Blender 3D: Noob to Pro/Advanced Tutorials/Python Scripting/Procedural object creation

Text BlocksEdit

A Blender document can contain text blocks, which are not the same as text objects in a 3D scene (though the former can be converted to the latter). Besides generating text objects, a text block can serve any purpose you like; for example, use it to pass workflow instructions to a colleague along with the document; display a copyright or help message in the initial layout that a user sees on opening the document; or hold a Python script that can be run by the user to perform some useful action related to the document.

Text blocks are edited in the Text Editor window. The Text Editor also provides commands to load the contents of a text block from an external file, or save it to an external file. And also execute the text as a Python script.

Your First ScriptEdit

Open a new, default Blender document. Split the 3D View in two vertically. Change the type of one side to a Text Editor window. In the header, you will see a small popup menu showing just a double-headed arrow; click on this, and it should show three items: “Text”, “ADD NEW” and “OPEN NEW”. “ADD NEW” creates a new, empty text block, while “OPEN NEW” creates a new text block by reading its contents from an external file. But “Text” is already the name of a default empty text block, so just use that; as soon as you select it, you should see a red insertion cursor appear at the top left, indicating that you can start typing.

Unlike the Interactive Python Console, nothing is automatically imported for you. So as in any other Python script, you need to mention every module you want to access.

Let us write a script that inserts a new mesh primitive into a Blender document, namely a tetrahedron. First we need to create a new mesh datablock, which we will name “Tetrahedron”:

NewMesh = Blender.Mesh.New("Tetrahedron")

Then we need to define the coordinates of the vertices; for a tetrahedron with edges of length 1 Blender unit, suitable values are (0, - \frac{1}{\sqrt{3}}, 0), (\frac{1}{2}, \frac{1}{2\sqrt{3}}, 0), (- \frac{1}{2}, \frac{1}{2\sqrt{3}}, 0) and (0, 0, \sqrt{\frac{2}{3}}). Or in Python:

NewMesh.verts.extend \
  (
    [
        (0, -1 / math.sqrt(3),0),
        (0.5, 1 / (2 * math.sqrt(3)), 0),
        (-0.5, 1 / (2 * math.sqrt(3)), 0),
        (0, 0, math.sqrt(2 / 3)),
    ]
  )

We also need to define the faces of the object; each face is defined by listing a sequence of indexes into the above array of vertices (you don’t need to bother about defining the edges; Blender will deduce them from the faces):

NewMesh.faces.extend \
  (
    [[0, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]]
  )

That suffices for the mesh, now we create an actual object datablock that will appear in the scene (which we also name “Tetrahedron”):

TheObj = Blender.Object.New("Mesh", "Tetrahedron")

Link it to the mesh we just made:

TheObj.link(NewMesh)

And to make the object appear in the scene, it has to be linked to it:

TheScene = Blender.Scene.GetCurrent()
TheScene.link(TheObj)

And finally, tell Blender that the scene has changed:

TheScene.update()

and to redraw the 3D view to show the updated scene:

Blender.Window.Redraw()

Put It All TogetherEdit

Your complete script should look like this, including the imports of the referenced math and Blender modules; note also the use of the directive to ensure that the “/” operator always returns a real, not an integer, result; this is good practice with Python 2.x, since it becomes mandatory behaviour beginning with Python 3.0.

from __future__ import division
import math
import Blender
 
NewMesh = Blender.Mesh.New("Tetrahedron")
NewMesh.verts.extend \
  (
    [
        (0, -1 / math.sqrt(3),0),
        (0.5, 1 / (2 * math.sqrt(3)), 0),
        (-0.5, 1 / (2 * math.sqrt(3)), 0),
        (0, 0, math.sqrt(2 / 3)),
    ]
  )
NewMesh.faces.extend \
  (
    [[0, 1, 2], [0, 1, 3], [1, 2, 3], [2, 0, 3]]
  )
TheObj = Blender.Object.New("Mesh", "Tetrahedron")
TheObj.link(NewMesh)
TheScene = Blender.Scene.GetCurrent()
TheScene.link(TheObj)
TheScene.update()
Blender.Window.Redraw()

In your 3D View, get rid of any default cube to avoid it obscuring things. Now come back to the Text Editor window showing the above script, and press  ALT + P  to execute it; you should see your new tetrahedron appear in the 3D view!

If You Hit An ErrorEdit

If there is any error running the script, Blender will display a cryptic message to let you know. For example, the following simple one-line script

raise RuntimeError("Uh-oh")

displays this message:

Blender249ScriptErrorMsg.png

To get more details you will have to look in Standard Error; on Linux/Unix systems, the message will appear in the terminal session if you invoked Blender from the command line; otherwise it will be appended to your ~/.xsessionerrors file if you launched Blender from a GUI. On Windows the message appears in the console window. By hunting around in the appropriate place, you should be able to find the full Python traceback:

Traceback (most recent call last):
  File "Text.001", line 1, in <module>
RuntimeError: Uh-oh
Last modified on 10 May 2011, at 04:36