Creating a Red Sphere in Blender with Python

Motivation:

In order to do any of the following:

  • 3D-printing
  • Video Game Design
  • Molecular Modeling
  • 3D Molecular simulations

You might want to learn a 3D modeling software.  Money being always of scarce supply for educators I look towards the free and open-source Blender software.

My goal in this project was to create a simple red-sphere with python, as a step towards creating molecular models (red-sphere would be an oxygen atom).  Using a 3D simulator could also make it easier to create a better or interactive diagram for intrinsically 3D ideas: solar system models, Electromagnetism models, or molecular interaction models (we could save time otherwise spent explaining away ambiguities/mis-interpretations in 2D on-paper or on white-board representations).

Python is probably the lowest barrier-to-entry language right now too, so hopefully people will not be afraid of trying it.

Download Blender:

This is the easiest part, here is a link to their website: http://downloadblender.com/

Watch Orientation Video:

This is a 30 minute video that makes the whole thing less scary: http://blendtuts.com/2010/06/blender-25-interface.html

Coding:

Opening up a text editor and pasting this in will allow you to make your first sphere.

Call the file sphere.py , and save it in a folder easy to find via the terminal.


#!/usr/local/bin/python2.7
import bpy

#color changing code from http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Materials_and_textures

def makeMaterial(name, diffuse, specular, alpha):

mat = bpy.data.materials.new(name)
mat.diffuse_color = diffuse
mat.diffuse_shader = ‘LAMBERT’
mat.diffuse_intensity = 1.0
mat.specular_color = specular
mat.specular_shader = ‘COOKTORR’
mat.specular_intensity = 0.5
mat.alpha = alpha
mat.ambient = 1
return mat

def setMaterial(ob, mat):

me = ob.data

me.materials.append(mat)

#cleaning the scene from http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Interface
bpy.ops.object.select_by_type(type=’MESH’)
bpy.ops.object.delete()

red = makeMaterial(‘Red’,(1,0,0),(1,1,1),1)
origin = (0,0,0)
bpy.ops.mesh.primitive_uv_sphere_add(location=origin)
bpy.ops.transform.translate(value=(1,0,0))
setMaterial(bpy.context.object, red)

Running the Command

Find the script in the terminal and cd into that folder, then type:

blender –python sphere.py

Image

Image

This should create a lone sphere in the center of the Blender scene.   Now you can tweak the code and add a for loop to create an entire molecule, or a snapshot of our solar system, or print some size sphere via a 3D printer.

Epilogue

While Blender is open source and free to use, you will need more tutorials before making your own video game or animated film.  That being said, you are pretty close

(see Animation Tutorial)*tutorial under construction

(see Video Game Tutorial)*tutorial under construction