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):
176 class IKSolver(object):
177 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
178 def __init__(self, target, effector, length, iterations, weight):
180 self.effector=effector
182 self.iterations=iterations
186 class OneSkinMesh(object):
187 __slots__=['armatureObj', 'vertexArray', 'morphList']
188 def __init__(self, root):
189 self.armatureObj=None
190 self.vertexArray=VertexArray()
195 return "<OneSkinMesh armature:%s, %s, morph:%d>" % (
196 self.armatureObj.name if self.armatureObj else None,
200 def __create(self, node):
201 if node.o.getType()=='Mesh':
202 self.__addMesh(node.o)
204 for child in node.children:
207 def __addMesh(self, obj):
208 if obj.restrictDisplay:
212 print("export", obj.name)
214 ############################################################
215 # search armature modifier
216 ############################################################
217 for m in obj.modifiers:
218 if m.name=="Armature":
219 armatureObj=m[Blender.Modifier.Settings.OBJECT]
220 if not self.armatureObj:
221 self.armatureObj=armatureObj
222 elif self.armatureObj!=armatureObj:
223 print "warning! found multiple armature. ignored.", armatureObj.name
225 ############################################################
227 ############################################################
228 mesh=obj.getData(mesh=True)
231 for name in mesh.getVertGroupNames():
232 for i, w in mesh.getVertsFromGroup(name, 1):
235 if i in secondWeightMap:
237 if w<secondWeightMap[i]:
241 secondWeightMap[i]=(name, w)
244 weightMap[i]=(name, w)
246 if w>weightMap[i][1]:
248 secondWeightMap[i]=weightMap[i]
249 weightMap[i]=(name, w)
251 secondWeightMap[i]=(name, w)
253 weightMap[i]=(name, w)
256 for i in xrange(len(mesh.verts)):
257 #for i, name_weight in weightMap.items():
258 if i in secondWeightMap:
259 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
261 weightMap[i]=(weightMap[i][0], 1.0)
262 secondWeightMap[i]=("", 0)
264 print "no weight vertex"
266 secondWeightMap[i]=("", 0)
269 ############################################################
272 ############################################################
273 mesh=Blender.Mesh.New()
274 # not applied modifiers
275 mesh.getFromObject(obj.name, 1)
276 # apply object transform
277 mesh.transform(obj.getMatrix())
278 if len(mesh.verts)==0:
281 for face in mesh.faces:
282 faceVertexCount=len(face.v)
283 material=mesh.materials[face.mat]
284 if faceVertexCount==3:
289 self.vertexArray.addTriangle(
291 v0.index, v1.index, v2.index,
294 #v0.no, v1.no, v2.no,
295 face.no, face.no, face.no,
296 face.uv[0], face.uv[1], face.uv[2],
297 weightMap[v0.index][0],
298 weightMap[v1.index][0],
299 weightMap[v2.index][0],
300 secondWeightMap[v0.index][0],
301 secondWeightMap[v1.index][0],
302 secondWeightMap[v2.index][0],
303 weightMap[v0.index][1],
304 weightMap[v1.index][1],
305 weightMap[v2.index][1]
307 elif faceVertexCount==4:
313 self.vertexArray.addTriangle(
315 v0.index, v1.index, v2.index,
317 #v0.no, v1.no, v2.no,
318 face.no, face.no, face.no,
319 face.uv[0], face.uv[1], face.uv[2],
320 weightMap[v0.index][0],
321 weightMap[v1.index][0],
322 weightMap[v2.index][0],
323 secondWeightMap[v0.index][0],
324 secondWeightMap[v1.index][0],
325 secondWeightMap[v2.index][0],
326 weightMap[v0.index][1],
327 weightMap[v1.index][1],
328 weightMap[v2.index][1]
330 self.vertexArray.addTriangle(
332 v2.index, v3.index, v0.index,
334 #v2.no, v3.no, v0.no,
335 face.no, face.no, face.no,
336 face.uv[2], face.uv[3], face.uv[0],
337 weightMap[v2.index][0],
338 weightMap[v3.index][0],
339 weightMap[v0.index][0],
340 secondWeightMap[v2.index][0],
341 secondWeightMap[v3.index][0],
342 secondWeightMap[v0.index][0],
343 weightMap[v2.index][1],
344 weightMap[v3.index][1],
345 weightMap[v0.index][1]
348 ############################################################
350 ############################################################
353 blenderMesh=obj.getData(mesh=True)
355 for b in blenderMesh.key.blocks:
358 morph=self.__getOrCreateMorph('base', 0)
361 for index in blenderMesh.getVertsFromGroup(
362 MMD_SHAPE_GROUP_NAME):
364 pos=[v[0], v[1], v[2]]
365 indices=self.vertexArray.getMappedIndices(index)
367 morph.indices.append(i)
368 morph.offsets.append(pos)
369 indexRelativeMap[i]=relativeIndex
376 for b in obj.getData(mesh=True).key.blocks:
381 morph=self.__getOrCreateMorph(b.name, 4)
382 for index in obj.getData(mesh=True).getVertsFromGroup(
383 MMD_SHAPE_GROUP_NAME):
384 #offset=[d-s for d, s in zip(
385 # b.data[index], basis.data[index])]
386 src=basis.data[index]
388 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
389 indices=self.vertexArray.getMappedIndices(index)
391 morph.indices.append(indexRelativeMap[i])
392 morph.offsets.append(offset)
394 def __getOrCreateMorph(self, name, type):
395 for m in self.morphList:
399 self.morphList.append(m)
402 def getVertexCount(self):
403 return len(self.vertexArray.vertices)
407 __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
408 def __init__(self, name, pos):
411 self.pos=[pos.x, pos.y, pos.z]
412 self.parent_index=None
417 return "<Bone %s %d>" % (self.name, self.type)
419 class BoneBuilder(object):
420 __slots__=['bones', 'boneMap', 'ik_list']
426 def build(self, armatureObj):
428 armature=armatureObj.getData()
429 for b in armature.bones.values():
432 bone=Bone(b.name, b.head['ARMATURESPACE'])
434 self.__getBone(bone, b)
436 pose = armatureObj.getPose()
437 cSetting=Blender.Constraint.Settings
438 for b in pose.bones.values():
439 for c in b.constraints:
440 if c.type==Blender.Constraint.Type.IKSOLVER:
445 link=self.__boneByName(b.name)
446 link_tail=self.bones[link.tail_index]
447 if link_tail.type==7:
448 # replace ...先 to IK接続先
453 chainLength=c[cSetting.CHAINLEN]
454 for i in range(chainLength):
456 self.__boneByName(e.name).type=4
462 assert(c[cSetting.TARGET]==armatureObj)
463 target=self.__boneByName(
464 c[Blender.Constraint.Settings.BONE])
468 IKSolver(target, link_tail, chainLength,
469 c[cSetting.ITERATIONS], c.influence))
471 def getIndex(self, bone):
472 for i, b in enumerate(self.bones):
477 def __boneByName(self, name):
478 return self.bones[self.boneMap[name]]
480 def __getBone(self, parent, b):
481 if not Blender.Armature.CONNECTED in b.options:
485 if len(b.children)==0:
487 bone=Bone(b.name+'_t', b.tail['ARMATURESPACE'])
491 bone.parent_index=parent.index
492 parent.tail_index=bone.index
495 for i, c in enumerate(b.children):
496 bone=Bone(c.name, c.head['ARMATURESPACE'])
499 bone.parent_index=parent.index
501 parent.tail_index=bone.index
502 self.__getBone(bone, c)
504 def __addBone(self, bone):
505 bone.index=len(self.bones)
506 self.bones.append(bone)
507 self.boneMap[bone.name]=bone.index
510 class PmdExporter(object):
512 def setup(self, scene):
515 for o in scene.objects:
516 object_node_map[o]=Node(o)
517 for node in object_node_map.values():
519 object_node_map[node.o.parent].children.append(node)
521 root=object_node_map[scene.objects.active]
524 self.oneSkinMesh=OneSkinMesh(root)
525 print(self.oneSkinMesh)
526 self.name=root.o.name
528 def write(self, path):
531 io.comment="blender export"
535 builder=BoneBuilder()
536 builder.build(self.oneSkinMesh.armatureObj)
539 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
540 # convert right-handed z-up to left-handed y-up
550 v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
551 v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
552 v.weight0=int(100*weight)
553 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
556 vertexCount=self.oneSkinMesh.getVertexCount()
557 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
558 m=Blender.Material.Get(m)
560 material=io.addMaterial()
561 material.diffuse.r=m.R
562 material.diffuse.g=m.G
563 material.diffuse.b=m.B
564 material.diffuse.a=m.alpha
565 material.sinness=m.spec
566 material.specular.r=m.specR
567 material.specular.g=m.specG
568 material.specular.b=m.specB
569 material.ambient.r=m.amb
570 material.ambient.g=m.amb
571 material.ambient.b=m.amb
572 material.vertex_count=len(indices)
573 material.toon_index=0
578 assert(i<vertexCount)
579 for i in xrange(0, len(indices), 3):
581 io.indices.append(indices[i+2])
582 io.indices.append(indices[i+1])
583 io.indices.append(indices[i])
585 #io.indices.append(indices[i])
586 #io.indices.append(indices[i+1])
587 #io.indices.append(indices[i+2])
590 for b in builder.bones:
593 unicode=englishmap.getUnicodeBoneName(b.name)
595 cp932=unicode.encode('cp932')
598 bone_name="%s\n" % cp932
599 assert(len(bone_name)<20)
602 bone_english_name="%s\n" % b.name
603 assert(len(bone_english_name)<20)
604 bone.english_name=bone_english_name
607 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
608 bone.tail_index=b.tail_index if b.tail_index!=None else 0
611 # convert right-handed z-up to left-handed y-up
617 for ik in builder.ik_list:
619 solver.index=builder.getIndex(ik.target)
620 solver.target=builder.getIndex(ik.effector)
621 solver.length=ik.length
622 b=builder.bones[ik.effector.parent_index]
623 for i in xrange(solver.length):
624 solver.children.append(builder.getIndex(b))
625 b=builder.bones[b.parent_index]
626 solver.iterations=ik.iterations
627 solver.weight=ik.weight
630 for i, m in enumerate(self.oneSkinMesh.morphList):
634 unicode=englishmap.getUnicodeSkinName(m.name)
636 cp932=unicode.encode('cp932')
639 morph.name="%s\n" % cp932
641 morph.english_name="%s\n" % m.name
643 for index, offset in zip(m.indices, m.offsets):
644 # convert right-handed z-up to left-handed y-up
645 morph.append(index, offset[0], offset[2], offset[1])
646 morph.vertex_count=len(m.indices)
650 io.face_list.append(i)
653 boneDisplayName=io.addBoneDisplayName()
654 boneDisplayName.name="bones\n"
655 boneDisplayName.english_name="bones\n"
657 for i, b in enumerate(builder.bones):
659 io.addBoneDisplay(i, displayIndex)
662 io.english_name="blender export model"
663 io.english_coment="blender export"
666 io.getToonTexture(i).name="toon%02d.bmp" % i
669 return io.write(path.encode(FS_ENCODING))
672 def export_pmd(filename):
673 filename=filename.decode(INTERNAL_ENCODING)
675 Blender.Window.WaitCursor(1)
676 t = Blender.sys.time()
678 if not filename.lower().endswith(EXTENSION):
679 filename += EXTENSION
680 print "pmd exporter: %s" % filename
682 exporter=PmdExporter()
685 exporter.setup(Blender.Scene.GetCurrent())
688 exporter.write(filename)
690 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
692 Blender.Window.WaitCursor(0)
695 Blender.Window.FileSelector(
697 'Export Metasequoia PMD',
698 Blender.sys.makename(ext=EXTENSION))