Wednesday, March 12, 2008

Blender Materials and Python

I spent some time tonight working with Blender on an illustration of DNA. At first, I thought it would be straightforward... I soon realized there were many challenges. The biggest was setting up the nucleotides. They have to be four different colors, representing the pair A and T, as well as C and G. The pairs need to go together. Since there were so many of them, I thought this was a good time to do a little Python. After poking around in the APIs, I found where I could set the Object's material. I ran my script and nothing seemed to happen. As it turns out, Blender can associate a material with an object or a mesh. By default it associates with a mesh and it seems that the mesh material takes precedence over the object material. A small change to the code and I got it working. Here's the program:

import Blender
from Blender import Material, Mesh

objects = Blender.Object.GetSelected()
mat = Material.Get("T_Nucleotide")

for curObj in objects:
n = curObj.getData()
n.materials = [mat]
curObj.layers = [5]

The code starts out with the import statements to use the Blender, Material, and Mesh modules. Next it gets all the selected objects (this way I could click on the ones I want to change). Then it sets a variable to the material I want to use. I loop through the list of objects getting the mesh data, then setting its materials. Note that the materials property is actually a list of materials, so I add the brackets around the material variable. I call update() so the screen is updated. Lastly, all the ones that were changed I move to layer 5. The layers property is list, this is a neat feature of Blender... unlike most graphics programs where an object can only reside on one layer at a time, in Blender you can set the object to appear on multiple layers. Turns out to be very useful.