20,73 €
Blender 3D is a popular, open source modeling package that can produce photo-realistic 3D images and animations. Automating tasks and extending the functionality of an extensive application like Blender will streamline your workflow and make the impossible possible. However, implementing scripts may be daunting.
This book takes a practical step-by-step approach to implementing Python scripts that cover almost all areas of Blender. It clearly outlines each problem and focuses on straightforward, easy-to-understand code, highlighting the common pitfalls and Blender idiosyncrasies. It guides you from the installation process and the creation of a simple object to elaborate, fully rigged models with vertex groups and materials all the way to extending Blender's built-in editor. It also teaches how to implement a simple web server inside Blender to serve rendered images. This book will take you from a clear problem description to a fully functional program. The focus is on finding your way in Blender's vast array of possibilities and getting things done without losing too much time on programming details. Each script is carefully explained to provide insight that can be reused in other projects.
This practical book will help you gain control over all the aspects of Blender using the Python programming language
The focus of the book is on practical problems and how to solve them in Python. The examples given are useful programs that try to solve real-world needs. Each chapter revolves around a single concept giving several examples gradually growing in difficulty. Each section analyses the problem first before diving into coding and gives extensive background information to enable the reader to generalize from the specific problem to a wider range of challenges. The sample code is provided as fully working examples with all key issues extensively highlighted. All sample programs are clear and concise yet nothing essential is left out and the programming style focuses on readability rather than on stylistic rigor or efficiency.
This book is for users comfortable with Blender as a modeling and rendering tool who want to expand their skills to include Blender scripting to automate laborious tasks and achieve results otherwise impossible. Blender experience is essential as is some experience in Python programming.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 392
Veröffentlichungsjahr: 2010
Copyright © 2010 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: April 2010
Production Reference: 1230410
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 9781849510400
www.packtpub.com
Cover Image by Vinayak Chittar (<[email protected]>)
Author
Michel Anders
Reviewer
Pang Lih-Hern
Acquisition Editor
Sarah Cullington
Development Editor
Mehul Shetty
Technical Editor
Namita Sahni
Indexers
Hemangini Bari
Rekha Nair
Editorial Team Leader
Akshara Aware
Project Team Leader
Lata Basantani
Project Coordinator
Shubhanjan Chatterjee
Proofreader
Jeff Orloff
Graphics
Geetanjali Sawant
Production Coordinator
Melwyn D'sa
Cover Work
Melwyn D'sa
Michel Anders, after completing his chemistry and physics studies, where he spent more time on computer simulations than on real world experiments, he realized that his real interests lay with IT and Internet technology. He has worked as an IT manager for several different companies, including an Internet provider and a hospital.
Currently he manages the R&D department of Aia Software—a leading developer of document composition software. He lives happily on a small, converted farm with his partner, 3 cats, and 12 goats.
He has been using Blender since version 2.32, although he will be the first one to acknowledge his artwork is naive at best. He loves to help people with Blender and Python-related questions and may be contacted as "varkenvarken" on blenderartists.org.
First, I would like to thank all the wonderful people at Packt Publishing. Without their help this book would not have been written. Also, I would like to thank my partner and my colleagues at work for putting up with my endless talks about Blender. Finally, I'd like to thank all those people in the Blender community who have together made Blender such a wonderful application.
Pang Lih-Hern is a computer game engine programmer with five years of industry experience. He started programming when he was 12, learning the quick Basic language. After graduating with a degree in Software Engineering and Games Design from Multimedia University Malaysia he started his freelancing endeavor that eventually lead him to be part of the core technical team of John Galt Games (Malaysia). He was part of the decision making group in designing and implementing the company's proprietary game engine. Lih-Hern is also actively involved in the open source front, often submitting fixes and features for the popular open source Ogre3D engine. One notable contribution is the Parallel Split Shadow Map feature that enhances the shadow rendering of a 3D scene. He is also a strong advocate of Blender and is currently holding the position of maintaining the Blender exporter to Ogre3D's mesh format.
After leaving John Galt Games (Malaysia), Lih-Hern co-founded Liquid Rock Games with his fellow artist partner Yap Chun Fei. The goal was to create innovative AAA quality games without the need for huge budget cost by the means of using open source technology and tools such as Blender, Gimp, and Ogre3D. As of now, Liquid Rock Games is in the process of developing its first racing title named Aftershock—an online multiplayer post-apocalyptic racing game. The game's artwork is modeled and textured using Blender and Gimp, showing the capability of such tools in the commercial market.
First of all, I would like to thank the publisher, Packt publishing, for giving me the opportunity to review this book. I would also like to thank my family and the co-partner of my company for allowing me the spare time and support to review this book. I hope that the readers will benefit from this book and be inspired to produce more amazing useful tools for Blender.
For Clementine
Blender is no doubt the most powerful, and versatile, open source 3D package available. Its power comes close to, or even surpasses, many professional packages. Blender's built-in Python interpreter plays an important role in tapping this power and allows artists to extend the functionality even further. Yet, mastering a scripting language and getting familiar with the many possibilities that Blender offers through its Python API can be a daunting venture.
This book will show how to get the most out of Blender by showing practical solutions to many realistic problems. Each example is a complete working script, which is explained step-by-step in a very detailed manner.
Chapter 1, Extending Blender with Python, gives you an overview of what can and cannot be accomplished with Python in Blender. It teaches you how to install a full Python distribution and how to use the built-in editor. You also learn how to write and run a simple Python script and how to integrate it in Blender's menu system.
Chapter 2, Creating and Editing Objects, introduces objects and meshes and you will see how to manipulate them programmatically. Specifically, you learn how to create configurable mesh objects, design a graphical user interface, and how to make your script store user choices for later reuse. You also learn how to select vertices and faces in a mesh, parent an object to another, and how to create groups. Finally, this chapter shows how to run Blender from the command line, render in the background, and how to process command-line parameters.
Chapter 3, Vertex Groups and Materials, tells you about the many uses of vertex groups and how versatile they can be. You get to know how to define vertex groups and how to assign vertices to a vertex group. You will also learn how you can use those vertex groups for modifiers and armatures. You also look into the application of different materials to different faces and how to assign vertex colors to vertices.
Chapter 4, Pydrivers and Constraints, shows how you can associate built-in constraints with Blender objects and how to define complex relationships between animated properties by using the so-called pydrivers. You also define new complex constraints that may be used just like the built-in constraints. Specifically, you see how to drive one IPO from another by a Python expression, how to work around some limitations inherent in pydrivers, and how to restrict the motion of objects and bones by adding constraints. This chapter teaches you how to write a constraint in Python that will snap an object to the closest vertex on another object.
Chapter 5, Acting on Frame Changes, focuses on writing scripts that may be used to act on certain events. You can learn what script links and space handlers are and how they can be used to perform activities on each frame change in an animation. You also see how to associate additional information with an object, how to use script links to make an object appear or disappear by changing its layout or changing its transparency, and how to implement a scheme to associate a different mesh with an object on each frame. Finally, you can look into ways to augment the functionality of the 3D view.
Chapter 6, Shape Keys, IPOs, and Poses, discovers that there is more to IPOs that can prove useful in animated scenes. Although IPOs were introduced in Chapter 4, here you learn how to define IPOs on all kinds of objects, associate shape keys with a mesh, and how to define IPOs for those shape keys. You also look into posing armatures and combining poses into actions.
Chapter 7, Creating Custom Shaders and Textures with Pynodes, introduces Pynodes and you get to know how they enable you to define completely new textures and materials. You learn how to write Pynodes that create simple color patterns, Pynodes that produce patterns with normals, and you also learn how to animate Pynodes. This chapter also explains about Pynodes that produce height and slope-dependent materials and even create shaders that react to the angle of incident light.
Chapter 8, Rendering and Image Manipulation, turns to the rendering process as a whole. You can automate this rendering process, combine the resulting images in various ways, and even turn Blender into a specialized web server. Specifically, you learn how to automate the rendering process, create multiple views for product presentations, and create billboards from complex objects. You get to know about ways to enhance Blender with some external libraries to manipulate images, including render results.
Chapter 9, Expanding your Toolset, is less about rendering and more about making life easier for the day-to-day use of Blender by extending its functionality. In this chapter, you learn how to list and archive assets such as image maps, publish a rendered image automatically with FTP, extend the functionality of the built-in editor with regular expression searches, speed up computations by using Psyco—a just-in-time compiler, and add version control to your scripts with Subversion.
Appendix A, Links and Resources, gives you a list of most resources used in this book along with some generally useful information.
Appendix B, Common Pitfalls, highlights some of the common questions that pop up more often than others as do some mistakes.
Appendix C, Future Developments, is the final appendix that tries to show what the future holds in store and how this may affect you as both Blender and Python are constantly developed further.
All examples in the book use Blender 2.49 (available at www.blender.org) and its built-in Python 2.6.x language. Many examples assume that you have a full Python (www.python.org) distribution. In Chapter 1, Extending Blender with Python, you are shown how to install a full distribution—if you don't have one already. Blender and Python are platform independent and all examples should run equally well on Windows, Linux, and Mac. Some additional modules are used as well and suitable download instructions are provided where appropriate. All examples can be downloaded from the publisher's website (http://www.packtpub.com).
This book is for users comfortable with Blender as a modeling and rendering tool and who want to expand their skills to include Blender scripting to automate laborious tasks and achieve results otherwise impossible. Blender experience is essential as is some experience in Python programming.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code for the book
Visit https://www.packtpub.com//sites/default/files/downloads/0400_Code.zip to directly download the example code.
The downloadable files contain instructions on how to use them.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
It is possible to use any editor (that you like) to write Python scripts and then import the scripts as text files but Blender's built-in text editor will probably be adequate for all programming needs. It features conveniences such as syntax highlighting, line numbering, and automatic indentation, and gives you the possibility to run a script directly from the editor. The ability to run a script directly from the editor is a definite boon when debugging because of the direct feedback that you get when encountering an error. You will not only get an informative message but the offending line will also be highlighted in the editor.
What is more, the editor comes with many plug-ins of which the automatic suggestion of members and the documentation viewer are very convenient for programmers. And of course, it is possible to write additional plug-ins yourself.
You can select the built-in editor by choosing Text Editor from the Windows menu:
When you start up you are presented with an almost empty area except for a strip of buttons at the bottom:
We can select the default empty text buffer TX:Text or create a new empty text by selecting ADD NEW from the drop-down menu available when we click on the Menu button.
The default name for this new text will be TX:Text.001, but you may change it to something more meaningful by clicking on the name and changing it. Note that if you would like to save this text to an external file (with Text|SaveAs...) the name of the text is distinct from the filename (although in general it is a good idea to keep these the same to avoid confusion). It is not mandatory to save texts as external files; texts are Blender objects that are saved together with all other information when you save your .blend file.
External files may be opened as texts by selecting OPEN NEW from the Menu button drop-down instead of ADD NEW. If for some reason an external file and an associated text are out of sync when Blender is started, an out of sync button is displayed. When clicked, it displays a number of options to resolve the issue.
Once a new or existing text is selected, the menu bar at the bottom of the screen is updated with some additional menu options:
The Textfilemenu gives access to options to open or save a file or to run the script in the editor. It also presents a number of template scripts that may be used as a basis for your own scripts. If you select one of these templates a new text buffer is created with a copy of the selected template.
The Editmenu contains cut-and-paste functionality as well as options to search and replace text or jump to a chosen line number.
The Format menu has options to indent and unindent selected text as well as options to convert whitespace. The latter option can be very helpful when the Python interpreter complains about unexpected indentation levels although there seems nothing amiss with your file. If that happens you possibly have mixed tabs and spaces in way that confuse Python (as they are different as far as the interpreter is concerned) and a possible way out is to convert selected text to spaces first and then back to tabs. This way mixed spaces and tabs will be used in a uniform way again.
To get used to the editor, create a new text buffer by choosing Text | New and type in the following example lines:
Most keys on the keyboard will behave in a familiar way, including Delete, Backspace, and Enter. The shortcut keys for cutting, pasting, and copying are listed in the Edit menu as Alt + X, Alt + V, and Alt + C respectively but the Ctrl key equivalents Ctrl + X, Ctrl + V, and Ctrl + C (familiar to Windows users) work just as well. A full keyboard map can be consulted on the Blender wiki, http://wiki.blender.org/index.php/Doc:Manual/Extensions/Python/Text_editor
Selecting portions of the text can be achieved by clicking and dragging the mouse, but you can also select text by moving the text cursor around while pressing the Shift key.
Text will be uncolored by default, but reading scripts can be made a lot easier on the eye by enabling syntax highlighting. Clicking on the little AB button will toggle this (it will be black and white when syntax highlighting is off and colored when on.) Like many aspects of Blender, text colors can be customized in the themes section of the User Preferences window.
Another feature that is very convenient to enable, especially when debugging scripts, is line numbering. (You might write a faultless code in one go, but unfortunately yours truly is less of a genius.) Every Python error message that will be shown will have a filename and a line number, and the offending line will be highlighted. But the lines of the calling function(s), if any, will not be highlighted although their line numbers will be shown in the error message, so having line numbers enabled will enable you to quickly locate the calling context of the trouble spot. Line numbering is enabled by clicking on the lines button.
Running a script is done by pressing Alt + P. Nothing is displayed in the editor when there are no errors encountered, but the output will be shown on the console (that is, the DOSBox or X terminal Blender started from, not the Python interactive console that we encountered earlier).
As you may have noticed the word object is used in two different (possibly confusing) ways. In Blender almost anything is referred to as an Object. A Lamp for instance is an Object, but so is a Cube or a Camera. Objects are things that can be manipulated by the user and have for example a position and a rotation.
In fact, things are a little bit more structured (or complicated, as some people say): any Blender object contains a reference to a more specific object called the datablock. When you add a Cube object to an empty scene you will have a generic object at some location. That object will be called
