4 Name: 'MikuMikuDance model (.pmd)...'
7 Tooltip: 'Export PMD file for MikuMikuDance.'
9 __author__= ["ousttrue"]
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
20 from meshio import pmd, englishmap
25 FS_ENCODING=sys.getfilesystemencoding()
26 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
27 INTERNAL_ENCODING='utf-8'
29 INTERNAL_ENCODING=FS_ENCODING
32 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
37 __slots__=['o', 'children']
38 def __init__(self, o):
43 ###############################################################################
44 # Blenderのメッシュをワンスキンメッシュ化する
45 ###############################################################################
46 def near(x, y, EPSILON=1e-5):
48 return d>=-EPSILON and d<=EPSILON
51 class VertexKey(object):
57 'nx', 'ny', 'nz', # 法線
61 def __init__(self, x, y, z, nx, ny, nz, u, v):
72 return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
73 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
76 #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
77 return int((self.x+self.y+self.z)*100)
79 def __eq__(self, rhs):
80 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z) and near(self.nx, rhs.nx) and near(self.ny, rhs.ny) and near(self.nz, rhs.nz) and near(self.u, rhs.u) and near(self.v, rhs.v)
81 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
82 return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
85 class VertexArray(object):
105 return "<VertexArray %d vertices, %d indexArrays>" % (
106 len(self.vertices), len(self.indexArrays))
110 self.vertices, self.normals, self.uvs,
111 self.b0, self.b1, self.weight)
113 def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
118 pos[0], pos[1], pos[2],
119 normal[0], normal[1], normal[2],
121 if key in self.vertexMap:
123 index=self.vertexMap[key]
125 index=len(self.vertices)
127 self.vertexMap[key]=index
129 self.vertices.append((pos.x, pos.y, pos.z))
130 self.normals.append((normal.x, normal.y, normal.z))
131 self.uvs.append((uv.x, uv.y))
134 self.weight.append(weight0)
137 if not base_index in self.indexMap:
138 self.indexMap[base_index]=set()
139 self.indexMap[base_index].add(index)
144 def getMappedIndices(self, base_index):
145 return self.indexMap[base_index]
147 def addTriangle(self,
149 base_index0, base_index1, base_index2,
155 weight0, weight1, weight2
157 if not material in self.indexArrays:
158 self.indexArrays[material]=[]
160 index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
161 index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
162 index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
164 self.indexArrays[material]+=[index0, index1, index2]
168 __slots__=['name', 'type', 'indices', 'offsets']
169 def __init__(self, name, type):
175 class OneSkinMesh(object):
176 __slots__=['armatureObj', 'vertexArray', 'morphList']
177 def __init__(self, root):
178 self.armatureObj=None
179 self.vertexArray=VertexArray()
184 return "<OneSkinMesh armature:%s, %s, morph:%d>" % (
185 self.armatureObj.name if self.armatureObj else None,
189 def __create(self, node):
190 if node.o.getType()=='Mesh':
191 self.__addMesh(node.o)
193 for child in node.children:
196 def __addMesh(self, obj):
197 if obj.restrictDisplay:
201 print("export", obj.name)
203 ############################################################
204 # search armature modifier
205 ############################################################
206 for m in obj.modifiers:
207 if m.name=="Armature":
208 armatureObj=m[Blender.Modifier.Settings.OBJECT]
209 if not self.armatureObj:
210 self.armatureObj=armatureObj
211 elif self.armatureObj!=armatureObj:
212 print "warning! found multiple armature. ignored.", armatureObj.name
214 ############################################################
216 ############################################################
217 mesh=obj.getData(mesh=True)
220 for name in mesh.getVertGroupNames():
221 for i, w in mesh.getVertsFromGroup(name, 1):
224 if i in secondWeightMap:
226 if w<secondWeightMap[i]:
230 secondWeightMap[i]=(name, w)
233 weightMap[i]=(name, w)
235 if w>weightMap[i][1]:
237 secondWeightMap[i]=weightMap[i]
238 weightMap[i]=(name, w)
240 secondWeightMap[i]=(name, w)
242 weightMap[i]=(name, w)
245 for i in xrange(len(mesh.verts)):
246 #for i, name_weight in weightMap.items():
247 if i in secondWeightMap:
248 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
250 weightMap[i]=(weightMap[i][0], 1.0)
251 secondWeightMap[i]=("", 0)
253 print "no weight vertex"
255 secondWeightMap[i]=("", 0)
258 ############################################################
261 ############################################################
262 mesh=Blender.Mesh.New()
263 # not applied modifiers
264 mesh.getFromObject(obj.name, 1)
265 # apply object transform
266 mesh.transform(obj.getMatrix())
267 if len(mesh.verts)==0:
270 for face in mesh.faces:
271 faceVertexCount=len(face.v)
272 material=mesh.materials[face.mat]
273 if faceVertexCount==3:
278 self.vertexArray.addTriangle(
280 v0.index, v1.index, v2.index,
283 #v0.no, v1.no, v2.no,
284 face.no, face.no, face.no,
285 face.uv[0], face.uv[1], face.uv[2],
286 weightMap[v0.index][0],
287 weightMap[v1.index][0],
288 weightMap[v2.index][0],
289 secondWeightMap[v0.index][0],
290 secondWeightMap[v1.index][0],
291 secondWeightMap[v2.index][0],
292 weightMap[v0.index][1],
293 weightMap[v1.index][1],
294 weightMap[v2.index][1]
296 elif faceVertexCount==4:
302 self.vertexArray.addTriangle(
304 v0.index, v1.index, v2.index,
306 #v0.no, v1.no, v2.no,
307 face.no, face.no, face.no,
308 face.uv[0], face.uv[1], face.uv[2],
309 weightMap[v0.index][0],
310 weightMap[v1.index][0],
311 weightMap[v2.index][0],
312 secondWeightMap[v0.index][0],
313 secondWeightMap[v1.index][0],
314 secondWeightMap[v2.index][0],
315 weightMap[v0.index][1],
316 weightMap[v1.index][1],
317 weightMap[v2.index][1]
319 self.vertexArray.addTriangle(
321 v2.index, v3.index, v0.index,
323 #v2.no, v3.no, v0.no,
324 face.no, face.no, face.no,
325 face.uv[2], face.uv[3], face.uv[0],
326 weightMap[v2.index][0],
327 weightMap[v3.index][0],
328 weightMap[v0.index][0],
329 secondWeightMap[v2.index][0],
330 secondWeightMap[v3.index][0],
331 secondWeightMap[v0.index][0],
332 weightMap[v2.index][1],
333 weightMap[v3.index][1],
334 weightMap[v0.index][1]
337 ############################################################
339 ############################################################
342 blenderMesh=obj.getData(mesh=True)
344 for b in blenderMesh.key.blocks:
347 morph=self.__getOrCreateMorph('base', 0)
350 for index in blenderMesh.getVertsFromGroup(
351 MMD_SHAPE_GROUP_NAME):
353 pos=[v[0], v[1], v[2]]
354 indices=self.vertexArray.getMappedIndices(index)
356 morph.indices.append(i)
357 morph.offsets.append(pos)
358 indexRelativeMap[i]=relativeIndex
365 for b in obj.getData(mesh=True).key.blocks:
370 morph=self.__getOrCreateMorph(b.name, 4)
371 for index in obj.getData(mesh=True).getVertsFromGroup(
372 MMD_SHAPE_GROUP_NAME):
373 #offset=[d-s for d, s in zip(
374 # b.data[index], basis.data[index])]
375 src=basis.data[index]
377 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
378 indices=self.vertexArray.getMappedIndices(index)
380 morph.indices.append(indexRelativeMap[i])
381 morph.offsets.append(offset)
383 def __getOrCreateMorph(self, name, type):
384 for m in self.morphList:
388 self.morphList.append(m)
391 def getVertexCount(self):
392 return len(self.vertexArray.vertices)
396 __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
397 def __init__(self, name, pos):
400 self.pos=[pos.x, pos.y, pos.z]
401 self.parent_index=None
406 return "<Bone %s %d>" % (self.name, self.type)
408 class BoneBuilder(object):
409 __slots__=['bones', 'boneMap', 'ik_list']
415 def build(self, armatureObj):
417 armature=armatureObj.getData()
418 for b in armature.bones.values():
421 bone=Bone(b.name, b.head['ARMATURESPACE'])
423 self.__getBone(bone, b)
425 pose = armatureObj.getPose()
426 for b in pose.bones.values():
427 for c in b.constraints:
428 if c.type==Blender.Constraint.Type.IKSOLVER:
431 for i in range(c[Blender.Constraint.Settings.CHAINLEN]):
433 self.__boneByName(e.name).type=4
436 assert(c[Blender.Constraint.Settings.TARGET]==armatureObj)
438 c[Blender.Constraint.Settings.BONE]).type=2
440 link=self.__boneByName(b.name)
441 link_tail=self.bones[link.tail_index]
442 if link_tail.type==7:
447 def __boneByName(self, name):
448 return self.bones[self.boneMap[name]]
450 def __getBone(self, parent, b):
451 if not Blender.Armature.CONNECTED in b.options:
455 if len(b.children)==0:
457 bone=Bone(b.name+'_tail', b.tail['ARMATURESPACE'])
461 bone.parent_index=parent.index
462 parent.tail_index=bone.index
465 for i, c in enumerate(b.children):
466 bone=Bone(c.name, c.head['ARMATURESPACE'])
469 bone.parent_index=parent.index
471 parent.tail_index=bone.index
472 self.__getBone(bone, c)
474 def __addBone(self, bone):
475 bone.index=len(self.bones)
476 self.bones.append(bone)
477 self.boneMap[bone.name]=bone.index
480 class PmdExporter(object):
482 def setup(self, scene):
485 for o in scene.objects:
486 object_node_map[o]=Node(o)
487 for node in object_node_map.values():
489 object_node_map[node.o.parent].children.append(node)
491 root=object_node_map[scene.objects.active]
494 self.oneSkinMesh=OneSkinMesh(root)
495 print(self.oneSkinMesh)
496 self.name=root.o.name
498 def write(self, path):
501 io.comment="blender export"
505 builder=BoneBuilder()
506 builder.build(self.oneSkinMesh.armatureObj)
507 for b in builder.bones:
511 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
512 bone.tail_index=b.tail_index if b.tail_index!=None else 0
515 # convert right-handed z-up to left-handed y-up
521 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
522 # convert right-handed z-up to left-handed y-up
532 v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
533 v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
534 v.weight0=int(100*weight)
535 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
538 vertexCount=self.oneSkinMesh.getVertexCount()
539 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
540 m=Blender.Material.Get(m)
542 material=io.addMaterial()
543 material.diffuse.r=m.R
544 material.diffuse.g=m.G
545 material.diffuse.b=m.B
546 material.diffuse.a=m.alpha
547 material.sinness=m.spec
548 material.specular.r=m.specR
549 material.specular.g=m.specG
550 material.specular.b=m.specB
551 material.ambient.r=m.amb
552 material.ambient.g=m.amb
553 material.ambient.b=m.amb
554 material.vertex_count=len(indices)
555 material.toon_index=0
560 assert(i<vertexCount)
561 for i in xrange(0, len(indices), 3):
563 io.indices.append(indices[i+2])
564 io.indices.append(indices[i+1])
565 io.indices.append(indices[i])
567 #io.indices.append(indices[i])
568 #io.indices.append(indices[i+1])
569 #io.indices.append(indices[i+2])
572 for m in self.oneSkinMesh.morphList:
577 for index, offset in zip(m.indices, m.offsets):
578 # convert right-handed z-up to left-handed y-up
579 morph.append(index, offset[0], offset[2], offset[1])
580 morph.vertex_count=len(m.indices)
583 return io.write(path.encode(FS_ENCODING))
586 def export_pmd(filename):
587 filename=filename.decode(INTERNAL_ENCODING)
589 Blender.Window.WaitCursor(1)
590 t = Blender.sys.time()
592 if not filename.lower().endswith(EXTENSION):
593 filename += EXTENSION
594 print "pmd exporter: %s" % filename
596 exporter=PmdExporter()
599 exporter.setup(Blender.Scene.GetCurrent())
602 exporter.write(filename)
604 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
606 Blender.Window.WaitCursor(0)
609 Blender.Window.FileSelector(
611 'Export Metasequoia PMD',
612 Blender.sys.makename(ext=EXTENSION))