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.
15 1.0 20100530 implement, basic features.
21 from meshio import pmd, englishmap
26 FS_ENCODING=sys.getfilesystemencoding()
27 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
28 INTERNAL_ENCODING='utf-8'
30 INTERNAL_ENCODING=FS_ENCODING
33 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
38 __slots__=['o', 'children']
39 def __init__(self, o):
44 ###############################################################################
45 # Blenderのメッシュをワンスキンメッシュ化する
46 ###############################################################################
47 def near(x, y, EPSILON=1e-5):
49 return d>=-EPSILON and d<=EPSILON
52 class VertexKey(object):
58 'nx', 'ny', 'nz', # 法線
62 def __init__(self, x, y, z, nx, ny, nz, u, v):
73 return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
74 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
77 #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
78 return int((self.x+self.y+self.z)*100)
80 def __eq__(self, rhs):
81 #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)
82 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
83 return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
86 class VertexArray(object):
106 return "<VertexArray %d vertices, %d indexArrays>" % (
107 len(self.vertices), len(self.indexArrays))
111 self.vertices, self.normals, self.uvs,
112 self.b0, self.b1, self.weight)
114 def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
119 pos[0], pos[1], pos[2],
120 normal[0], normal[1], normal[2],
122 if key in self.vertexMap:
124 index=self.vertexMap[key]
126 index=len(self.vertices)
128 self.vertexMap[key]=index
130 self.vertices.append((pos.x, pos.y, pos.z))
131 self.normals.append((normal.x, normal.y, normal.z))
132 self.uvs.append((uv.x, uv.y))
135 self.weight.append(weight0)
138 if not base_index in self.indexMap:
139 self.indexMap[base_index]=set()
140 self.indexMap[base_index].add(index)
145 def getMappedIndices(self, base_index):
146 return self.indexMap[base_index]
148 def addTriangle(self,
150 base_index0, base_index1, base_index2,
156 weight0, weight1, weight2
158 if not material in self.indexArrays:
159 self.indexArrays[material]=[]
161 index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
162 index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
163 index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
165 self.indexArrays[material]+=[index0, index1, index2]
169 __slots__=['name', 'type', 'offsets']
170 def __init__(self, name, type):
175 def add(self, index, offset):
176 self.offsets.append((index, offset))
179 self.offsets.sort(lambda l, r: l[0]-r[0])
182 return "<Morph %s>" % self.name
184 class IKSolver(object):
185 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
186 def __init__(self, target, effector, length, iterations, weight):
188 self.effector=effector
190 self.iterations=iterations
194 class OneSkinMesh(object):
195 __slots__=['vertexArray', 'morphList']
197 self.vertexArray=VertexArray()
201 return "<OneSkinMesh %s, morph:%d>" % (
205 def addMesh(self, obj):
206 if obj.restrictDisplay:
210 print("export", obj.name)
212 ############################################################
214 ############################################################
215 mesh=obj.getData(mesh=True)
218 for name in mesh.getVertGroupNames():
219 for i, w in mesh.getVertsFromGroup(name, 1):
222 if i in secondWeightMap:
224 if w<secondWeightMap[i]:
228 secondWeightMap[i]=(name, w)
231 weightMap[i]=(name, w)
233 if w>weightMap[i][1]:
235 secondWeightMap[i]=weightMap[i]
236 weightMap[i]=(name, w)
238 secondWeightMap[i]=(name, w)
240 weightMap[i]=(name, w)
243 for i in xrange(len(mesh.verts)):
244 #for i, name_weight in weightMap.items():
245 if i in secondWeightMap:
246 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
248 weightMap[i]=(weightMap[i][0], 1.0)
249 secondWeightMap[i]=("", 0)
251 print "no weight vertex"
253 secondWeightMap[i]=("", 0)
256 ############################################################
259 ############################################################
260 mesh=Blender.Mesh.New()
261 # not applied modifiers
262 mesh.getFromObject(obj.name, 1)
263 # apply object transform
264 mesh.transform(obj.getMatrix())
265 if len(mesh.verts)==0:
268 for face in mesh.faces:
269 faceVertexCount=len(face.v)
270 material=mesh.materials[face.mat]
271 if faceVertexCount==3:
276 self.vertexArray.addTriangle(
278 v0.index, v1.index, v2.index,
281 #v0.no, v1.no, v2.no,
282 face.no, face.no, face.no,
283 face.uv[0], face.uv[1], face.uv[2],
284 weightMap[v0.index][0],
285 weightMap[v1.index][0],
286 weightMap[v2.index][0],
287 secondWeightMap[v0.index][0],
288 secondWeightMap[v1.index][0],
289 secondWeightMap[v2.index][0],
290 weightMap[v0.index][1],
291 weightMap[v1.index][1],
292 weightMap[v2.index][1]
294 elif faceVertexCount==4:
300 self.vertexArray.addTriangle(
302 v0.index, v1.index, v2.index,
304 #v0.no, v1.no, v2.no,
305 face.no, face.no, face.no,
306 face.uv[0], face.uv[1], face.uv[2],
307 weightMap[v0.index][0],
308 weightMap[v1.index][0],
309 weightMap[v2.index][0],
310 secondWeightMap[v0.index][0],
311 secondWeightMap[v1.index][0],
312 secondWeightMap[v2.index][0],
313 weightMap[v0.index][1],
314 weightMap[v1.index][1],
315 weightMap[v2.index][1]
317 self.vertexArray.addTriangle(
319 v2.index, v3.index, v0.index,
321 #v2.no, v3.no, v0.no,
322 face.no, face.no, face.no,
323 face.uv[2], face.uv[3], face.uv[0],
324 weightMap[v2.index][0],
325 weightMap[v3.index][0],
326 weightMap[v0.index][0],
327 secondWeightMap[v2.index][0],
328 secondWeightMap[v3.index][0],
329 secondWeightMap[v0.index][0],
330 weightMap[v2.index][1],
331 weightMap[v3.index][1],
332 weightMap[v0.index][1]
335 ############################################################
337 ############################################################
340 blenderMesh=obj.getData(mesh=True)
343 for b in blenderMesh.key.blocks:
346 baseMorph=self.__getOrCreateMorph('base', 0)
349 for index in blenderMesh.getVertsFromGroup(
350 MMD_SHAPE_GROUP_NAME):
352 pos=[v[0], v[1], v[2]]
353 indices=self.vertexArray.getMappedIndices(index)
355 baseMorph.add(i, pos)
356 indexRelativeMap[relativeIndex]=i
359 print(len(baseMorph.offsets))
364 vg=obj.getData(mesh=True).getVertsFromGroup(
365 MMD_SHAPE_GROUP_NAME)
366 for b in obj.getData(mesh=True).key.blocks:
371 morph=self.__getOrCreateMorph(b.name, 4)
372 for index, src, dst in zip(
373 xrange(len(blenderMesh.verts)),
376 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
378 indices=self.vertexArray.getMappedIndices(index)
380 morph.add(indexRelativeMap[i], offset)
381 assert(len(morph.offsets)==len(baseMorph.offsets))
384 if len(self.morphList)>1:
385 original=self.morphList[:]
387 for i, v in enumerate(englishmap.skinMap):
392 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
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', 'ik_index',
408 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
409 def __init__(self, name, pos, tail):
414 self.parent_index=None
420 def __eq__(self, rhs):
421 return self.index==rhs.index
424 return "<Bone %s %d>" % (self.name, self.type)
426 class BoneBuilder(object):
427 __slots__=['bones', 'boneMap', 'ik_list']
433 def build(self, armatureObj):
437 print("gather bones")
438 armature=armatureObj.getData()
439 for b in armature.bones.values():
443 b.head['ARMATURESPACE'][0:3],
444 b.tail['ARMATURESPACE'][0:3])
446 self.__getBone(bone, b)
448 for b in armature.bones.values():
449 if not b.parent and b.name!='center':
452 b.head['ARMATURESPACE'][0:3],
453 b.tail['ARMATURESPACE'][0:3])
455 self.__getBone(bone, b)
457 print("check connection")
458 for b in armature.bones.values():
460 self.__checkConnection(b, None)
463 pose = armatureObj.getPose()
464 cSetting=Blender.Constraint.Settings
465 for b in pose.bones.values():
466 for c in b.constraints:
467 if c.type==Blender.Constraint.Type.IKSOLVER:
471 assert(c[cSetting.TARGET]==armatureObj)
472 target=self.__boneByName(
473 c[Blender.Constraint.Settings.BONE])
480 link=self.__boneByName(b.name)
485 chainLength=c[cSetting.CHAINLEN]
486 for i in range(chainLength):
488 chainBone=self.__boneByName(e.name)
490 chainBone.ik_index=target.index
493 IKSolver(target, link, chainLength,
494 int(c[cSetting.ITERATIONS] * 0.1),
495 c[cSetting.ROTWEIGHT]
498 def __checkConnection(self, b, p):
499 if Blender.Armature.CONNECTED in b.options:
500 parent=self.__boneByName(p.name)
501 parent.isConnect=True
504 self.__checkConnection(c, b)
506 def sortBy(self, boneMap):
510 original=self.bones[:]
512 for i, k_v in enumerate(boneMap):
513 if k_v[0]==bone.name:
517 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
519 for i, b in enumerate(self.bones):
520 src=original.index(b)
523 b.index=sortMap[b.index]
525 b.parent_index=sortMap[b.parent_index]
527 b.tail_index=sortMap[b.tail_index]
529 b.ik_index=sortMap[b.ik_index]
531 def getIndex(self, bone):
532 for i, b in enumerate(self.bones):
537 def indexByName(self, name):
538 return self.getIndex(self.__boneByName(name))
540 def __boneByName(self, name):
541 return self.bones[self.boneMap[name]]
543 def __getBone(self, parent, b):
544 if len(b.children)==0:
548 for i, c in enumerate(b.children):
550 c.head['ARMATURESPACE'][0:3],
551 c.tail['ARMATURESPACE'][0:3])
554 bone.parent_index=parent.index
556 parent.tail_index=bone.index
557 self.__getBone(bone, c)
559 def __addBone(self, bone):
560 bone.index=len(self.bones)
561 self.bones.append(bone)
562 self.boneMap[bone.name]=bone.index
565 class PmdExporter(object):
568 self.armatureObj=None
570 def setup(self, scene):
573 for o in scene.objects:
574 object_node_map[o]=Node(o)
575 for node in object_node_map.values():
577 object_node_map[node.o.parent].children.append(node)
579 root=object_node_map[scene.objects.active]
582 self.oneSkinMesh=OneSkinMesh()
583 self.__createOneSkinMesh(root)
584 print(self.oneSkinMesh)
585 self.name=root.o.name
588 self.builder=BoneBuilder()
589 self.builder.build(self.armatureObj)
590 self.builder.sortBy(englishmap.boneMap)
592 for i, v in enumerate(englishmap.boneMap):
593 if v[0]==ik.target.name:
595 return len(englishmap.boneMap)
596 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
598 def __createOneSkinMesh(self, node):
599 ############################################################
600 # search armature modifier
601 ############################################################
602 for m in node.o.modifiers:
603 if m.name=="Armature":
604 armatureObj=m[Blender.Modifier.Settings.OBJECT]
605 if not self.armatureObj:
606 self.armatureObj=armatureObj
607 elif self.armatureObj!=armatureObj:
608 print "warning! found multiple armature. ignored.", armatureObj.name
610 if node.o.getType()=='Mesh':
611 self.oneSkinMesh.addMesh(node.o)
613 for child in node.children:
614 self.__createOneSkinMesh(child)
616 def write(self, path):
620 io.comment="blender export"
625 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
626 # convert right-handed z-up to left-handed y-up
636 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
637 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
638 v.weight0=int(100*weight)
639 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
642 print('faces and materials')
643 vertexCount=self.oneSkinMesh.getVertexCount()
644 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
645 m=Blender.Material.Get(m)
647 material=io.addMaterial()
648 material.diffuse.r=m.R
649 material.diffuse.g=m.G
650 material.diffuse.b=m.B
651 material.diffuse.a=m.alpha
652 material.sinness=0 if m.spec<1e-5 else m.spec*10
653 material.specular.r=m.specR
654 material.specular.g=m.specG
655 material.specular.b=m.specB
656 material.ambient.r=m.mirR
657 material.ambient.g=m.mirG
658 material.ambient.b=m.mirB
659 material.vertex_count=len(indices)
660 material.toon_index=0
661 material.flag=1 if m.enableSSS else 0
666 assert(i<vertexCount)
667 for i in xrange(0, len(indices), 3):
669 io.indices.append(indices[i+2])
670 io.indices.append(indices[i+1])
671 io.indices.append(indices[i])
673 #io.indices.append(indices[i])
674 #io.indices.append(indices[i+1])
675 #io.indices.append(indices[i+2])
679 for b in self.builder.bones:
680 if b.name.endswith("_t"):
681 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
683 print "skip %s" % b.name
688 v=englishmap.getUnicodeBoneName(b.name)
690 cp932=v[1].encode('cp932')
691 bone_name="%s" % cp932
692 assert(len(bone_name)<20)
695 bone_english_name="%s" % b.name
696 assert(len(bone_english_name)<20)
697 bone.english_name=bone_english_name
702 b.ik_index=self.builder.indexByName('eyes')
708 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
711 if b.tail_index!=None:
715 bone.tail_index=b.tail_index
719 bone.ik_index=b.ik_index
721 # convert right-handed z-up to left-handed y-up
722 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
723 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
724 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
728 for ik in self.builder.ik_list:
730 solver.index=self.builder.getIndex(ik.target)
731 solver.target=self.builder.getIndex(ik.effector)
732 solver.length=ik.length
733 b=self.builder.bones[ik.effector.parent_index]
734 for i in xrange(solver.length):
735 solver.children.append(self.builder.getIndex(b))
736 b=self.builder.bones[b.parent_index]
737 solver.iterations=ik.iterations
738 solver.weight=ik.weight
742 for i, m in enumerate(self.oneSkinMesh.morphList):
746 v=englishmap.getUnicodeSkinName(m.name)
748 cp932=v[1].encode('cp932')
749 morph.name="%s\n" % cp932
751 morph.english_name="%s\n" % m.name
754 for index, offset in m.offsets:
755 # convert right-handed z-up to left-handed y-up
756 morph.append(index, offset[0], offset[2], offset[1])
757 morph.vertex_count=len(m.offsets)
760 print('display list')
762 for i, m in enumerate(self.oneSkinMesh.morphList):
764 io.face_list.append(i)
765 for i, m in enumerate(self.oneSkinMesh.morphList):
767 io.face_list.append(i)
768 for i, m in enumerate(self.oneSkinMesh.morphList):
770 io.face_list.append(i)
771 for i, m in enumerate(self.oneSkinMesh.morphList):
773 io.face_list.append(i)
776 print('bone display list')
777 def createBoneDisplayName(name, english):
778 boneDisplayName=io.addBoneDisplayName()
779 boneDisplayName.name=name.decode('utf-8').encode('cp932')
780 boneDisplayName.english_name=english
781 boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
782 boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
783 boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
784 boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
785 boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
786 boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
787 boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
788 for i, b in enumerate(self.builder.bones):
793 io.addBoneDisplay(i, getBoneDisplayGroup(b))
797 io.english_name="blender export"
798 io.english_coment="blender export"
801 io.getToonTexture(i).name="toon%02d.bmp\n" % i
804 return io.write(path)
807 def getBoneDisplayGroup(bone):
810 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
811 "toe IK_L", "toe IK_R",
814 "upper body", "neck", "head", "eye_L", "eye_R",
815 "necktie1", "necktie2", "necktie3", "eyes",
816 "eyelight_L", "eyelight_R",
819 "front hair1", "front hair2", "front hair3",
820 "hair1_L", "hair2_L", "hair3_L",
821 "hair4_L", "hair5_L", "hair6_L",
822 "hair1_R", "hair2_R", "hair3_R",
823 "hair4_R", "hair5_R", "hair6_R",
826 "shoulder_L", "arm_L", "arm twist_L", "elbow_L",
827 "wrist twist_L", "wrist_L", "sleeve_L",
828 "shoulder_R", "arm_R", "arm twist_R", "elbow_R",
829 "wrist twist_R", "wrist_R", "sleeve_R",
832 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
833 "middle1_L", "middle2_L", "middle3_L",
834 "third1_L", "third2_L", "third3_L",
835 "little1_L", "little2_L", "little3_L",
836 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
837 "middle1_R", "middle2_R", "middle3_R",
838 "third1_R", "third2_R", "third3_R",
839 "little1_R", "little2_R", "little3_R",
842 "lower body", "waist accessory",
843 "front skirt_L", "back skirt_L",
844 "front skirt_R", "back skirt_R",
847 "leg_L", "knee_L", "ankle_L",
848 "leg_R", "knee_R", "ankle_R",
859 def export_pmd(filename):
860 filename=filename.decode(INTERNAL_ENCODING)
862 Blender.Window.WaitCursor(1)
863 t = Blender.sys.time()
865 if not filename.lower().endswith(EXTENSION):
866 filename += EXTENSION
867 print "pmd exporter: %s" % filename
869 exporter=PmdExporter()
872 exporter.setup(Blender.Scene.GetCurrent())
875 exporter.write(filename)
877 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
879 Blender.Window.WaitCursor(0)
882 Blender.Window.FileSelector(
884 'Export Metasequoia PMD',
885 Blender.sys.makename(ext=EXTENSION))