Musings of a Fondue

Blender X Python

Did you know Blender uses Python?!

I had created a shape on Blender and wanted to export its vertices for use in another program. Not sure how to go about it, I Googled for ideas and came across this StackExchange answer.

It was a small Python script that did just that. And, I understood it!? And even tweaked it!


# have to be in object mode

# get vertices
#   http://blender.stackexchange.com/a/1316

import bpy
obj = bpy.context.active_object

verts = [vert.co for vert in obj.data.vertices]

# coordinates as tuples
p_verts = [vert.to_tuple() for vert in verts]
print(p_verts)

# get faces
#   http://blender.stackexchange.com/a/3658

faces = [face.vertices[:] for face in obj.data.polygons]
print(faces)


# Optional - tuple to array
for e in range( len(faces) ):
    faces[e] = list( faces[e] )

for e in range( len(p_verts) ):
    p_verts[e] = list( p_verts[e] )
    for i in range(3):
        p_verts[e][i] = round( p_verts[e][i], 3 )

# Optional - output to txt file
with open('c:/.../.../desktop/thefile.txt', mode='w', encoding='utf-8') as f:
    f.write("verts")
    f.write( str(p_verts) )
    f.write("\n")
    f.write("faces")
    f.write( str(faces) )

how about that

After getting the vertices, I was able to use them on Khan Academy:

Not only can you interface with Blender using Python - Blender itself is written in Python!

This might be a cliche, but once you learn the basics of programming the applications are endless. So do it!

Comments