Friday, June 1, 2012

The two most useful Blender tips for Python programmers

I've been dealing with Python and Blender a fair lot. I haven't even reached a mature level on both, but i have found that there's two tips that would have made my life easier when i started.

The two most important tips are:



  • Use the Python console code completion. It's amazing how much info you can get from it. When you type something and hit Ctrl+Space blender tries to autocomplete whatever you have written, and it is smart at it. Look at the screenshot and you will see there are a lot of members in green. The ones that end on parentheses are functions and the ones that don't are plain members. If you don't have the Blender API handy you can even put the name of a functionand press Ctrl+Space again and you'll see a little help text of it. It's pretty handy.

  • If you can't find how to access certain function or property of the Blender UI via code completion or API reference, you can ALWAYS see the tooltip of what are you trying to acomplish and it will show you the API route to that property. For example, see the screenshot to the right, if you would like to know in what unit type is the focal length of a camera, you just got to put the cursor over the aforementioned property on the UI and a Tooltip will popup with the information right to the "Python" keyword. This is extremely useful for those hard to find properties and saves you a LOT of time when trying to export or modify something on Blender.

If anyone else thinks there is another essential tip, shout it on the comments box down below. :-

Extracting UV Maps

Someone asked on G+ "how blender stores the UV maps?" and i told him i would write about it, so this inspired me to begin writing this blog.

In fact, i'll try to dump the little knowledge i have acquired creating my own exporter (Blender Machete) in the coming weeks so everyone trying to use the Blender API can benefit from what i've learnt.

On to the question: How blender stores the UV maps?

It's easy: Each UV Layer is stored on an array called uv_textures in the Mesh class. So, for a given object Obj  you could do the following:


As you can see, we're obtaining the corresponding mesh of the object and then iterating over the UV layers. In each iteration we append to uvs the mapped values from the UV.

Enumerating each interesting line:

  • Line 6: for each face in the mesh
  • Line 7: use the index of that face to extract the UV from the layer data (layer.data)
  • Line 8: and then take each component of the UV coordinate (two floats) and store it on our array.
Finally, each element in the 'uvs' array is an array for each vertex that you can pass directly on a Vertex Buffer Object in OpenGL as the UVs.

Pretty simple, isn't it?