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 class IKSolver(object):
182 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
183 def __init__(self, target, effector, length, iterations, weight):
185 self.effector=effector
187 self.iterations=iterations
191 class OneSkinMesh(object):
192 __slots__=['vertexArray', 'morphList']
194 self.vertexArray=VertexArray()
198 return "<OneSkinMesh %s, morph:%d>" % (
202 def addMesh(self, obj):
203 if obj.restrictDisplay:
207 print("export", obj.name)
209 ############################################################
211 ############################################################
212 mesh=obj.getData(mesh=True)
215 for name in mesh.getVertGroupNames():
216 for i, w in mesh.getVertsFromGroup(name, 1):
219 if i in secondWeightMap:
221 if w<secondWeightMap[i]:
225 secondWeightMap[i]=(name, w)
228 weightMap[i]=(name, w)
230 if w>weightMap[i][1]:
232 secondWeightMap[i]=weightMap[i]
233 weightMap[i]=(name, w)
235 secondWeightMap[i]=(name, w)
237 weightMap[i]=(name, w)
240 for i in xrange(len(mesh.verts)):
241 #for i, name_weight in weightMap.items():
242 if i in secondWeightMap:
243 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
245 weightMap[i]=(weightMap[i][0], 1.0)
246 secondWeightMap[i]=("", 0)
248 print "no weight vertex"
250 secondWeightMap[i]=("", 0)
253 ############################################################
256 ############################################################
257 mesh=Blender.Mesh.New()
258 # not applied modifiers
259 mesh.getFromObject(obj.name, 1)
260 # apply object transform
261 mesh.transform(obj.getMatrix())
262 if len(mesh.verts)==0:
265 for face in mesh.faces:
266 faceVertexCount=len(face.v)
267 material=mesh.materials[face.mat]
268 if faceVertexCount==3:
273 self.vertexArray.addTriangle(
275 v0.index, v1.index, v2.index,
278 #v0.no, v1.no, v2.no,
279 face.no, face.no, face.no,
280 face.uv[0], face.uv[1], face.uv[2],
281 weightMap[v0.index][0],
282 weightMap[v1.index][0],
283 weightMap[v2.index][0],
284 secondWeightMap[v0.index][0],
285 secondWeightMap[v1.index][0],
286 secondWeightMap[v2.index][0],
287 weightMap[v0.index][1],
288 weightMap[v1.index][1],
289 weightMap[v2.index][1]
291 elif faceVertexCount==4:
297 self.vertexArray.addTriangle(
299 v0.index, v1.index, v2.index,
301 #v0.no, v1.no, v2.no,
302 face.no, face.no, face.no,
303 face.uv[0], face.uv[1], face.uv[2],
304 weightMap[v0.index][0],
305 weightMap[v1.index][0],
306 weightMap[v2.index][0],
307 secondWeightMap[v0.index][0],
308 secondWeightMap[v1.index][0],
309 secondWeightMap[v2.index][0],
310 weightMap[v0.index][1],
311 weightMap[v1.index][1],
312 weightMap[v2.index][1]
314 self.vertexArray.addTriangle(
316 v2.index, v3.index, v0.index,
318 #v2.no, v3.no, v0.no,
319 face.no, face.no, face.no,
320 face.uv[2], face.uv[3], face.uv[0],
321 weightMap[v2.index][0],
322 weightMap[v3.index][0],
323 weightMap[v0.index][0],
324 secondWeightMap[v2.index][0],
325 secondWeightMap[v3.index][0],
326 secondWeightMap[v0.index][0],
327 weightMap[v2.index][1],
328 weightMap[v3.index][1],
329 weightMap[v0.index][1]
332 ############################################################
334 ############################################################
337 blenderMesh=obj.getData(mesh=True)
340 for b in blenderMesh.key.blocks:
343 baseMorph=self.__getOrCreateMorph('base', 0)
346 for index in blenderMesh.getVertsFromGroup(
347 MMD_SHAPE_GROUP_NAME):
349 pos=[v[0], v[1], v[2]]
350 indices=self.vertexArray.getMappedIndices(index)
352 baseMorph.add(i, pos)
353 indexRelativeMap[i]=relativeIndex
356 print(len(baseMorph.offsets))
361 vg=obj.getData(mesh=True).getVertsFromGroup(
362 MMD_SHAPE_GROUP_NAME)
363 for b in obj.getData(mesh=True).key.blocks:
368 morph=self.__getOrCreateMorph(b.name, 4)
369 for index, src, dst in zip(
370 xrange(len(blenderMesh.verts)),
373 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
375 indices=self.vertexArray.getMappedIndices(index)
377 morph.add(indexRelativeMap[i], offset)
378 assert(len(morph.offsets)==len(baseMorph.offsets))
380 def __getOrCreateMorph(self, name, type):
381 for m in self.morphList:
385 self.morphList.append(m)
388 def getVertexCount(self):
389 return len(self.vertexArray.vertices)
393 __slots__=['index', 'name',
394 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
395 def __init__(self, name, pos, tail):
400 self.parent_index=None
405 def __eq__(self, rhs):
406 return self.index==rhs.index
409 return "<Bone %s %d>" % (self.name, self.type)
411 class BoneBuilder(object):
412 __slots__=['bones', 'boneMap', 'ik_list']
418 def build(self, armatureObj):
422 print("gather bones")
423 armature=armatureObj.getData()
424 for b in armature.bones.values():
428 b.head['ARMATURESPACE'][0:3],
429 b.tail['ARMATURESPACE'][0:3])
431 self.__getBone(bone, b)
433 for b in armature.bones.values():
434 if not b.parent and b.name!='center':
437 b.head['ARMATURESPACE'][0:3],
438 b.tail['ARMATURESPACE'][0:3])
440 self.__getBone(bone, b)
442 print("check connection")
443 for b in armature.bones.values():
445 self.__checkConnection(b, None)
455 bone=Bone(b.name+'_t', b.tail, None)
458 bone.parent_index=b.index
459 b.tail_index=bone.index
462 pose = armatureObj.getPose()
463 cSetting=Blender.Constraint.Settings
464 for b in pose.bones.values():
465 for c in b.constraints:
466 if c.type==Blender.Constraint.Type.IKSOLVER:
471 link=self.__boneByName(b.name)
472 link_tail=self.bones[link.tail_index]
473 if link_tail.type==7:
474 # replace ...先 to IK接続先
479 chainLength=c[cSetting.CHAINLEN]
480 for i in range(chainLength):
482 self.__boneByName(e.name).type=4
488 assert(c[cSetting.TARGET]==armatureObj)
489 target=self.__boneByName(
490 c[Blender.Constraint.Settings.BONE])
494 IKSolver(target, link_tail, chainLength,
495 c[cSetting.ITERATIONS], c.influence))
497 target_tail=self.bones[target.tail_index]
498 if target_tail.type!=7:
499 target_bone=armature.bones[target.name]
500 bone=Bone(target.name+'_t',
501 target_bone.tail['ARMATURESPACE'][0:3],
505 bone.parent_index=target.index
506 target.tail_index=bone.index
508 def __checkConnection(self, b, p):
509 if Blender.Armature.CONNECTED in b.options:
510 parent=self.__boneByName(p.name)
511 parent.isConnect=True
514 self.__checkConnection(c, b)
516 def sortBy(self, boneMap):
520 original=self.bones[:]
522 for i, k_v in enumerate(boneMap):
523 if k_v[0]==bone.name:
527 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
529 for i, b in enumerate(self.bones):
530 src=original.index(b)
533 b.index=sortMap[b.index]
535 b.parent_index=sortMap[b.parent_index]
537 b.tail_index=sortMap[b.tail_index]
539 def getIndex(self, bone):
540 for i, b in enumerate(self.bones):
545 def __boneByName(self, name):
546 return self.bones[self.boneMap[name]]
548 def __getBone(self, parent, b):
549 for i, c in enumerate(b.children):
551 c.head['ARMATURESPACE'][0:3],
552 c.tail['ARMATURESPACE'][0:3])
555 bone.parent_index=parent.index
557 parent.tail_index=bone.index
558 self.__getBone(bone, c)
560 def __addBone(self, bone):
561 bone.index=len(self.bones)
562 self.bones.append(bone)
563 self.boneMap[bone.name]=bone.index
566 class PmdExporter(object):
569 self.armatureObj=None
571 def setup(self, scene):
574 for o in scene.objects:
575 object_node_map[o]=Node(o)
576 for node in object_node_map.values():
578 object_node_map[node.o.parent].children.append(node)
580 root=object_node_map[scene.objects.active]
583 self.oneSkinMesh=OneSkinMesh()
584 self.__createOneSkinMesh(root)
585 print(self.oneSkinMesh)
586 self.name=root.o.name
589 self.builder=BoneBuilder()
590 self.builder.build(self.armatureObj)
591 self.builder.sortBy(englishmap.boneMap)
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\n" % cp932
683 assert(len(bone_name)<20)
686 bone_english_name="%s\n" % b.name
687 assert(len(bone_english_name)<20)
688 bone.english_name=bone_english_name
694 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
696 if b.tail_index!=None:
700 bone.tail_index=b.tail_index
705 # convert right-handed z-up to left-handed y-up
711 for ik in self.builder.ik_list:
713 solver.index=self.builder.getIndex(ik.target)
714 solver.target=self.builder.getIndex(ik.effector)
715 solver.length=ik.length
716 b=self.builder.bones[ik.effector.parent_index]
717 for i in xrange(solver.length):
718 solver.children.append(self.builder.getIndex(b))
719 b=self.builder.bones[b.parent_index]
720 solver.iterations=ik.iterations
721 solver.weight=ik.weight
724 for i, m in enumerate(self.oneSkinMesh.morphList):
728 unicode=englishmap.getUnicodeSkinName(m.name)
730 cp932=unicode.encode('cp932')
733 morph.name="%s\n" % cp932
735 morph.english_name="%s\n" % m.name
737 for index, offset in m.offsets:
738 # convert right-handed z-up to left-handed y-up
739 morph.append(index, offset[0], offset[2], offset[1])
740 morph.vertex_count=len(m.offsets)
744 io.face_list.append(i)
747 boneDisplayName=io.addBoneDisplayName()
748 boneDisplayName.name="bones\n"
749 boneDisplayName.english_name="bones\n"
751 for i, b in enumerate(self.builder.bones):
753 io.addBoneDisplay(i, displayIndex)
756 io.english_name="blender export"
757 io.english_coment="blender export"
760 io.getToonTexture(i).name="toon%02d.bmp\n" % i
763 return io.write(path.encode(FS_ENCODING))
766 def export_pmd(filename):
767 filename=filename.decode(INTERNAL_ENCODING)
769 Blender.Window.WaitCursor(1)
770 t = Blender.sys.time()
772 if not filename.lower().endswith(EXTENSION):
773 filename += EXTENSION
774 print "pmd exporter: %s" % filename
776 exporter=PmdExporter()
779 exporter.setup(Blender.Scene.GetCurrent())
782 exporter.write(filename)
784 print 'finished in %.2f seconds' % (Blender.sys.time()-t)
786 Blender.Window.WaitCursor(0)
789 Blender.Window.FileSelector(
791 'Export Metasequoia PMD',
792 Blender.sys.makename(ext=EXTENSION))