bl_info = {
"name": "Export Mesh to JSON",
"category": "Import-Export"
}
import bpy
import json
class MeshToJSON(bpy.types.Operator):
bl_idname = 'import_export.mesh2json'
bl_label = 'Export Mesh to JSON'
bl_options = {'REGISTER'}
bl_category = 'Import-Export'
def execute(self, context):
mesh = bpy.context.active_object
mesh_json = {
'vertex_positions': [],
'num_vertices_in_each_face': [],
'vertex_position_indices': [],
'vertex_normals': [],
'vertex_normal_indices': [],
'armature_name': None,
'vertex_group_indices': [],
'vertex_group_weights': [],
'num_groups_for_each_vertex': []
}
if mesh.parent != None and mesh.parent.type == 'ARMATURE':
mesh_json['armature_name'] = mesh.parent.name
index = 0
for face in mesh.data.polygons:
num_vertices_in_face = len(face.vertices)
mesh_json['num_vertices_in_each_face'].append(num_vertices_in_face)
for i in range(num_vertices_in_face):
mesh_json['vertex_position_indices'].append(face.vertices[i])
mesh_json['vertex_normal_indices'].append(index)
mesh_json['vertex_normals'].append(face.normal.x)
mesh_json['vertex_normals'].append(face.normal.y)
mesh_json['vertex_normals'].append(face.normal.z)
index += 1
for vert in mesh.data.vertices:
mesh_json['vertex_positions'].append(vert.co.x)
mesh_json['vertex_positions'].append(vert.co.y)
mesh_json['vertex_positions'].append(vert.co.z)
num_groups = len(list(vert.groups))
for group in vert.groups:
mesh_json['vertex_group_indices'].append(group.group)
mesh_json['vertex_group_weights'].append(group.weight)
if mesh_json['armature_name'] != None:
mesh_json['num_groups_for_each_vertex'].append(num_groups)
if mesh_json['armature_name'] == None:
mesh_json['vertex_group_indices'] = None
mesh_json['vertex_group_weights'] = None
mesh_json['num_groups_for_each_vertex'] = None
print("START_MESH_JSON " + bpy.data.filepath + " " + mesh.name)
print(json.dumps(mesh_json))
print("END_MESH_JSON " + bpy.data.filepath + " " + mesh.name)
return {'FINISHED'}
def register():
bpy.utils.register_class(MeshToJSON)
def unregister():
bpy.utils.unregister_class(MeshToJSON)
if __name__ == "__main__":
register()