Sometimes it is necessary to save data for creating a mesh (its vertices and polygon indices arrays) to text, for example, for further use in a script or addon.
We can export the mesh to one of the open formats, for example, to *.obj, but if we need only its vertexes and polygons data, we can use the following simple script:
1 2 3 4 5 6 7 8 9 10 11 |
import bpy save_to_file = 'd:/file.txt' vertices = [(vert.co.x, vert.co.y, vert.co.z) for vert in bpy.context.object.data.vertices] faces = [[vert for vert in polygon.vertices] for polygon in bpy.context.object.data.polygons] with open(save_to_file, 'w') as file: file.write('verts = ' + str(vertices) + '\n' + 'faces = ' + str(faces) + '\n') file.close() |
Here we set the file name for saving data, make two arrays with vertexes and polygons data and save them to the specified file.
For example, for the default cube we get the following result:
1 2 3 4 5 6 7 8 9 |
verts = [ (-1.0, -1.0, -1.0), (-1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, -1.0, -1.0), (1.0, -1.0, 1.0), (1.0, 1.0, -1.0), (1.0, 1.0, 1.0) ] faces = [ [0, 1, 3, 2], [2, 3, 7, 6], [6, 7, 5, 4], [4, 5, 1, 0], [2, 6, 4, 0], [7, 3, 1, 5] ] |
We can now use this saved data, for example, copying them to a script.
The following script after executing will create a new default cube in the scene:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
verts = [ (-1.0, -1.0, -1.0), (-1.0, -1.0, 1.0), (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, -1.0, -1.0), (1.0, -1.0, 1.0), (1.0, 1.0, -1.0), (1.0, 1.0, 1.0) ] faces = [ [0, 1, 3, 2], [2, 3, 7, 6], [6, 7, 5, 4], [4, 5, 1, 0], [2, 6, 4, 0], [7, 3, 1, 5] ] import bpy mesh_data = bpy.data.meshes.new("new_mesh") mesh_data.from_pydata(verts, [], faces) mesh_data.update() mesh = bpy.data.objects.new("new_mesh", mesh_data) bpy.context.scene.collection.objects.link(mesh) |
That would be nice if we could change the Index of the vertices in there. I don’t supose there is any way to change the Index, is it.
You can change indeces if you need. But this will result in mesh fully rebuild.