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', 'offsets']
169 def __init__(self, name, type):
174 def add(self, index, offset):
175 self.offsets.append((index, offset))
178 self.offsets.sort(lambda l, r: l[0]-r[0])
181 return "<Morph %s>" % self.name
183 class IKSolver(object):
184 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
185 def __init__(self, target, effector, length, iterations, weight):
187 self.effector=effector
189 self.iterations=iterations
193 class OneSkinMesh(object):
194 __slots__=['vertexArray', 'morphList']
196 self.vertexArray=VertexArray()
200 return "<OneSkinMesh %s, morph:%d>" % (
204 def addMesh(self, obj):
205 if obj.restrictDisplay:
209 print("export", obj.name)
211 ############################################################
213 ############################################################
214 mesh=obj.getData(mesh=True)
217 for name in mesh.getVertGroupNames():
218 for i, w in mesh.getVertsFromGroup(name, 1):
221 if i in secondWeightMap:
223 if w<secondWeightMap[i]:
227 secondWeightMap[i]=(name, w)
230 weightMap[i]=(name, w)
232 if w>weightMap[i][1]:
234 secondWeightMap[i]=weightMap[i]
235 weightMap[i]=(name, w)
237 secondWeightMap[i]=(name, w)
239 weightMap[i]=(name, w)
242 for i in xrange(len(mesh.verts)):
243 #for i, name_weight in weightMap.items():
244 if i in secondWeightMap:
245 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
247 weightMap[i]=(weightMap[i][0], 1.0)
248 secondWeightMap[i]=("", 0)
250 print "no weight vertex"
252 secondWeightMap[i]=("", 0)
255 ############################################################
258 ############################################################
259 mesh=Blender.Mesh.New()
260 # not applied modifiers
261 mesh.getFromObject(obj.name, 1)
262 # apply object transform
263 mesh.transform(obj.getMatrix())
264 if len(mesh.verts)==0:
267 for face in mesh.faces:
268 faceVertexCount=len(face.v)
269 material=mesh.materials[face.mat]
270 if faceVertexCount==3:
275 self.vertexArray.addTriangle(
277 v0.index, v1.index, v2.index,
280 #v0.no, v1.no, v2.no,
281 face.no, face.no, face.no,
282 face.uv[0], face.uv[1], face.uv[2],
283 weightMap[v0.index][0],
284 weightMap[v1.index][0],
285 weightMap[v2.index][0],
286 secondWeightMap[v0.index][0],
287 secondWeightMap[v1.index][0],
288 secondWeightMap[v2.index][0],
289 weightMap[v0.index][1],
290 weightMap[v1.index][1],
291 weightMap[v2.index][1]
293 elif faceVertexCount==4:
299 self.vertexArray.addTriangle(
301 v0.index, v1.index, v2.index,
303 #v0.no, v1.no, v2.no,
304 face.no, face.no, face.no,
305 face.uv[0], face.uv[1], face.uv[2],
306 weightMap[v0.index][0],
307 weightMap[v1.index][0],
308 weightMap[v2.index][0],
309 secondWeightMap[v0.index][0],
310 secondWeightMap[v1.index][0],
311 secondWeightMap[v2.index][0],
312 weightMap[v0.index][1],
313 weightMap[v1.index][1],
314 weightMap[v2.index][1]
316 self.vertexArray.addTriangle(
318 v2.index, v3.index, v0.index,
320 #v2.no, v3.no, v0.no,
321 face.no, face.no, face.no,
322 face.uv[2], face.uv[3], face.uv[0],
323 weightMap[v2.index][0],
324 weightMap[v3.index][0],
325 weightMap[v0.index][0],
326 secondWeightMap[v2.index][0],
327 secondWeightMap[v3.index][0],
328 secondWeightMap[v0.index][0],
329 weightMap[v2.index][1],
330 weightMap[v3.index][1],
331 weightMap[v0.index][1]
334 ############################################################
336 ############################################################
339 blenderMesh=obj.getData(mesh=True)
342 for b in blenderMesh.key.blocks:
345 baseMorph=self.__getOrCreateMorph('base', 0)
348 for index in blenderMesh.getVertsFromGroup(
349 MMD_SHAPE_GROUP_NAME):
351 pos=[v[0], v[1], v[2]]
352 indices=self.vertexArray.getMappedIndices(index)
354 baseMorph.add(i, pos)
355 indexRelativeMap[i]=relativeIndex
358 print(len(baseMorph.offsets))
363 vg=obj.getData(mesh=True).getVertsFromGroup(
364 MMD_SHAPE_GROUP_NAME)
365 for b in obj.getData(mesh=True).key.blocks:
370 morph=self.__getOrCreateMorph(b.name, 4)
371 for index, src, dst in zip(
372 xrange(len(blenderMesh.verts)),
375 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
377 indices=self.vertexArray.getMappedIndices(index)
379 morph.add(indexRelativeMap[i], offset)
380 assert(len(morph.offsets)==len(baseMorph.offsets))
383 original=self.morphList[:]
385 for i, v in enumerate(englishmap.skinMap):
389 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
391 def __getOrCreateMorph(self, name, type):
392 for m in self.morphList:
396 self.morphList.append(m)
399 def getVertexCount(self):
400 return len(self.vertexArray.vertices)
404 __slots__=['index', 'name', 'ik_index',
405 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
406 def __init__(self, name, pos, tail):
411 self.parent_index=None
417 def __eq__(self, rhs):
418 return self.index==rhs.index
421 return "<Bone %s %d>" % (self.name, self.type)
423 class BoneBuilder(object):
424 __slots__=['bones', 'boneMap', 'ik_list']
430 def build(self, armatureObj):
434 print("gather bones")
435 armature=armatureObj.getData()
436 for b in armature.bones.values():
440 b.head['ARMATURESPACE'][0:3],
441 b.tail['ARMATURESPACE'][0:3])
443 self.__getBone(bone, b)
445 for b in armature.bones.values():
446 if not b.parent and b.name!='center':
449 b.head['ARMATURESPACE'][0:3],
450 b.tail['ARMATURESPACE'][0:3])
452 self.__getBone(bone, b)
454 print("check connection")
455 for b in armature.bones.values():
457 self.__checkConnection(b, None)
460 pose = armatureObj.getPose()
461 cSetting=Blender.Constraint.Settings
462 for b in pose.bones.values():
463 for c in b.constraints:
464 if c.type==Blender.Constraint.Type.IKSOLVER:
468 assert(c[cSetting.TARGET]==armatureObj)
469 target=self.__boneByName(
470 c[Blender.Constraint.Settings.BONE])
477 link=self.__boneByName(b.name)
482 chainLength=c[cSetting.CHAINLEN]
483 for i in range(chainLength):
485 chainBone=self.__boneByName(e.name)
487 chainBone.ik_index=target.index
490 IKSolver(target, link, chainLength,
491 c[cSetting.ITERATIONS], c.influence))
493 def __checkConnection(self, b, p):
494 if Blender.Armature.CONNECTED in b.options:
495 parent=self.__boneByName(p.name)
496 parent.isConnect=True
499 self.__checkConnection(c, b)
501 def sortBy(self, boneMap):
505 original=self.bones[:]
507 for i, k_v in enumerate(boneMap):
508 if k_v[0]==bone.name:
512 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
514 for i, b in enumerate(self.bones):
515 src=original.index(b)
518 b.index=sortMap[b.index]
520 b.parent_index=sortMap[b.parent_index]
522 b.tail_index=sortMap[b.tail_index]
524 b.ik_index=sortMap[b.ik_index]
526 def getIndex(self, bone):
527 for i, b in enumerate(self.bones):
532 def indexByName(self, name):
533 return self.getIndex(self.__boneByName(name))
535 def __boneByName(self, name):
536 return self.bones[self.boneMap[name]]
538 def __getBone(self, parent, b):
539 if len(b.children)==0:
543 for i, c in enumerate(b.children):
545 c.head['ARMATURESPACE'][0:3],
546 c.tail['ARMATURESPACE'][0:3])
549 bone.parent_index=parent.index
551 parent.tail_index=bone.index
552 self.__getBone(bone, c)
554 def __addBone(self, bone):
555 bone.index=len(self.bones)
556 self.bones.append(bone)
557 self.boneMap[bone.name]=bone.index
560 class PmdExporter(object):
563 self.armatureObj=None
565 def setup(self, scene):
568 for o in scene.objects:
569 object_node_map[o]=Node(o)
570 for node in object_node_map.values():
572 object_node_map[node.o.parent].children.append(node)
574 root=object_node_map[scene.objects.active]
577 self.oneSkinMesh=OneSkinMesh()
578 self.__createOneSkinMesh(root)
579 print(self.oneSkinMesh)
580 self.name=root.o.name
583 self.builder=BoneBuilder()
584 self.builder.build(self.armatureObj)
585 self.builder.sortBy(englishmap.boneMap)
587 for i, v in enumerate(englishmap.boneMap):
588 if v[0]==ik.target.name:
590 return len(englishmap.boneMap)
591 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
593 def __createOneSkinMesh(self, node):
594 ############################################################
595 # search armature modifier
596 ############################################################
597 for m in node.o.modifiers:
598 if m.name=="Armature":
599 armatureObj=m[Blender.Modifier.Settings.OBJECT]
600 if not self.armatureObj:
601 self.armatureObj=armatureObj
602 elif self.armatureObj!=armatureObj:
603 print "warning! found multiple armature. ignored.", armatureObj.name
605 if node.o.getType()=='Mesh':
606 self.oneSkinMesh.addMesh(node.o)
608 for child in node.children:
609 self.__createOneSkinMesh(child)
611 def write(self, path):
614 io.comment="blender export"
618 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
619 # convert right-handed z-up to left-handed y-up
629 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
630 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
631 v.weight0=int(100*weight)
632 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
635 vertexCount=self.oneSkinMesh.getVertexCount()
636 for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
637 m=Blender.Material.Get(m)
639 material=io.addMaterial()
640 material.diffuse.r=m.R
641 material.diffuse.g=m.G
642 material.diffuse.b=m.B
643 material.diffuse.a=m.alpha
644 material.sinness=0 if m.spec<1e-5 else m.spec*10
645 material.specular.r=m.specR
646 material.specular.g=m.specG
647 material.specular.b=m.specB
648 material.ambient.r=m.mirR
649 material.ambient.g=m.mirG
650 material.ambient.b=m.mirB
651 material.vertex_count=len(indices)
652 material.toon_index=0
653 material.flag=1 if m.enableSSS else 0
658 assert(i<vertexCount)
659 for i in xrange(0, len(indices), 3):
661 io.indices.append(indices[i+2])
662 io.indices.append(indices[i+1])
663 io.indices.append(indices[i])
665 #io.indices.append(indices[i])
666 #io.indices.append(indices[i+1])
667 #io.indices.append(indices[i+2])
670 for b in self.builder.bones:
671 if b.name.endswith("_t"):
672 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
674 print "skip %s" % b.name
679 v=englishmap.getUnicodeBoneName(b.name)
681 cp932=v[1].encode('cp932')
682 bone_name="%s" % cp932
683 assert(len(bone_name)<20)
686 bone_english_name="%s" % b.name
687 assert(len(bone_english_name)<20)
688 bone.english_name=bone_english_name
693 b.ik_index=self.builder.indexByName('eyes')
699 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
702 if b.tail_index!=None:
706 bone.tail_index=b.tail_index
710 bone.ik_index=b.ik_index
712 # convert right-handed z-up to left-handed y-up
713 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
714 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
715 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
718 for ik in self.builder.ik_list:
720 solver.index=self.builder.getIndex(ik.target)
721 solver.target=self.builder.getIndex(ik.effector)
722 solver.length=ik.length
723 b=self.builder.bones[ik.effector.parent_index]
724 for i in xrange(solver.length):
725 solver.children.append(self.builder.getIndex(b))
726 b=self.builder.bones[b.parent_index]
727 solver.iterations=ik.iterations
728 solver.weight=ik.weight
731 for i, m in enumerate(self.oneSkinMesh.morphList):
735 v=englishmap.getUnicodeSkinName(m.name)
737 cp932=v[1].encode('cp932')
738 morph.name="%s\n" % cp932
740 morph.english_name="%s\n" % m.name
742 for index, offset in m.offsets:
743 # convert right-handed z-up to left-handed y-up
744 morph.append(index, offset[0], offset[2], offset[1])
745 morph.vertex_count=len(m.offsets)
749 io.face_list.append(i)
752 boneDisplayName=io.addBoneDisplayName()
753 boneDisplayName.name="bones\n"
754 boneDisplayName.english_name="bones\n"
756 for i, b in enumerate(self.builder.bones):
758 io.addBoneDisplay(i, displayIndex)
761 io.english_name="blender export"
762 io.english_coment="blender export"
765 io.getToonTexture(i).name="toon%02d.bmp\n" % i
768 return io.write(path.encode(FS_ENCODING))
771 def export_pmd(filename):
772 filename=filename.decode(INTERNAL_ENCODING)
774 Blender.Window.WaitCursor(1)
775 t = Blender.sys.time()
777 if not filename.lower().endswith(EXTENSION):
778 filename += EXTENSION
779 print "pmd exporter: %s" % filename
781 exporter=PmdExporter()
784 exporter.setup(Blender.Scene.GetCurrent())
787 exporter.write(filename)
789 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
791 Blender.Window.WaitCursor(0)
794 Blender.Window.FileSelector(
796 'Export Metasequoia PMD',
797 Blender.sys.makename(ext=EXTENSION))