import bpy
import json
#读取jSON文件,将数据写入改文件
file_handle = open('C:/write.json','w')
#选择的物体
me = bpy.context.object.data
#选择物体的uv
uv_layer = me.uv_layers.active.data
#uv贴图的图的宽高
image_w = bpy.data.images['planar.jpg'].size[0]
image_h = bpy.data.images['planar.jpg'].size[1]
json_str = []
#每个多边形都引用循环数组中的一个切片,这样,多边形不会直接存储顶点或角数据(例如 UV),而只是对
#多边形使用的循环的引用
#循环选中物体的多边形,根据索引查找顶点及其对应的uv坐标,并根据图片大小计算对应的纹理坐标
for poly in me.polygons:
# range is used here to show how the polygons reference loops,
# for convenience 'poly.loop_indices' can be used instead.
for loop_index in range(poly.loop_start, poly.loop_start + poly.loop_total):
if len(uv_layer) >0:
#加此判断是因为本人uv只贴了一部分图
px = me.vertices[me.loops[loop_index].vertex_index].co.x
py = me.vertices[me.loops[loop_index].vertex_index].co.y
pz = me.vertices[me.loops[loop_index].vertex_index].co.z
uvx = uv_layer[loop_index].uv.x
uvy = uv_layer[loop_index].uv.y
json_item = {
"point":{
"x":px,
"y":py,
"z":pz
},
"uv":{
"x":uvx * image_w,
"y":uvy * image_h
}
}
json_str.append(json_item)
将数据以写入json文件
json.dump(json_str,file_handle)
file_handle.close()
文中的polygons,poly.loop_start, poly.loop_start + poly.loop_total可至官网查询具体解释
https://docs.blender.org/api/current/bpy.types.Mesh.html#bpy.types.Mesh