Blender 2.49 Scripting - Anders Michel - E-Book

Blender 2.49 Scripting E-Book

Anders Michel

0,0
20,73 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In Detail

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

Approach

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.

Who this book is for

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:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 392

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Blender 2.49 Scripting
Credits
About the Author
About the Reviewer
Preface
What this book covers
What you need for this book
Who is this book for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Extending Blender with Python
The Blender API
A lot of power
Some batteries included
Check for a full Python distribution
Installing a full Python distribution
The interactive Python console
Exploring built-in modules, the help() function
Exploring built-in functions, the dir() function
Getting familiar with the built-in editor
An editor example
First steps: Hello world
Integrating a script in Blender's menus
Integrating a script in Blender's help system
Don't get confused, stay objective
Adding different types of object from a script
Adding a mesh object
Distributing scripts
The Blender API
The Blender module
Blender objects
The bpy module
Drawing on the screen
Utilities
Summary
2. Creating and Editing Objects
Creepy crawlies—a GUI to configure objects
Building the user interface
Creating bugs—some assembly required
Creating a user interface
Remembering choices
The full power of Blender graphics
Creating a new Mesh object
Transforming mesh topology
Code outline bridging edge loops
Dazzle your boss—bar charts in Blender style
The bar chart script
Weird faces—selecting and editing faces in meshes
Selecting warped (non-planar) quads
Code outline warp select
Selecting ultra sharp faces
Selecting vertices with many edges
Selecting poles
Selecting poles, again
Determining the volume of a mesh
Determining the centre of mass of a mesh
Some remarks about accuracy
Growing sunflowers—parenting and grouping objects
Groups
Parenting
Growing a sunflower from a seed
Duplication versus instantiation
Growing a sunflower
Summary
3. Vertex Groups and Materials
Vertex groups
A weighty issue
Code outline: leftright.py
Modifiers
Engraving
Converting a Text3d object to a mesh
Extruding an edge loop
Expanding an edge loop
Putting it all together: Engrave.py
Flying sparks
Calculating the local curvature
Code outline: curvature.py
Putting it all together: St. Elmo's fire
Bones
Tick-Tock
Code outline: clock.py
Get a bit of backbone boy!
Materials
Object materials versus ObData materials
Assigning materials to parts of an Object
Vertex colors versus face materials
Adding materials to our engraving
Summary
4. Pydrivers and Constraints
Getting to grips with animated properties
IPO
IPOchannels and IPOCurves
Constraints
Difference between drivers and constraints
Programming with constraints
Programming with IPOs
PyDrivers
PyConstraints
Setting the time—one to rule them all
Shortcuts
Overcoming limitations: pydrivers.py
Internal combustion—correlating complex changes
More power—combining multiple cylinders to an engine
Adding simple constraints
Defining complex constraints
The Blender constraint template
Do you find me attractive too?
Snapping to mesh vertices
Aligning along a vertex normal
Snap to vertices in a vertex group
Summary
5. Acting on Frame Changes
Animating the visibility of objects
Fading a material
Changing layers
Countdown—animating a timer with script links
I'll keep an eye on you
Code outline: AuraSpaceHandler.py
Using themes
Revisiting mesh—making an impression
The user interface
Calculating an impression
Summary
6. Shape Keys, IPOs, and Poses
A touchy subject—defining an IPO from scratch
Code outline: orbit.py
A lot to swallow—defining poses
Application of peristaltic.py to an armature
Get down with the beat—syncing shape keys to sound
Manipulating sound files
Code outline: Sound.py
Animating a mesh by a .wav file: the workflow
Summary
7. Creating Custom Shaders and Textures with Pynodes
The basics
From nodes to Pynodes
Regular tilings
Anti-aliasing
Indexing a texture by vector
A fresh breeze—textures with normals
Raindrops—animated Pynodes
Render-time parameters
What looks good, is good
Storing expensive results for reuse
Calculating normals
Putting it all together
Wuthering heights—a slope-dependent material
Determining the slope
World space versus camera space
Soap bubbles—a view-dependent shader
Summary
8. Rendering and Image Manipulation
A different view—combining multiple camera angles
Code outline—combine.py
Workflow—how to showcase your model
Now, strip—creating a film strip from an animation
Workflow—using strip.py
Rendering billboards
Workflow—using cardboard.py
Generating CAPTCHA challenges
Design of a CAPTCHA server
Summary
9. Expanding your Toolset
To the Web and beyond—publish a finished render with FTP
Spring cleaning—archive unused images
Extending the editor—searching with regular expressions
Extending the editor—interacting with Subversion
Committing a file to the repository
Updating a file from the repository
Working with a repository
The need for speed—using Psyco
Enabling Psyco
Summary
A. Links and Resources
General Blender-related forums and blogs
Python programming
Blender scripting
External packages used in this book
Other sources of information
B. Common Pitfalls
Read the API documents
The trouble with import
Installing a full Python distribution
C. Future Developments
Blender
Python
Index

Blender 2.49 Scripting

Michel J. Anders

Blender 2.49 Scripting

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]>)

Credits

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

About the Author

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.

About the Reviewer

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

Preface

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.

What this book covers

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.

What you need for this book

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).

Who is this book for

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.

Reader feedback

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.

Customer support

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.

Tip

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.

Errata

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

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.

Questions

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.

Getting familiar with the built-in editor

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.

An editor example

To get used to the editor, create a new text buffer by choosing Text | New and type in the following example lines:

import sys print sys.path

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).

Don't get confused, stay objective

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