4 Name: 'MikuMikuDance model (.pmd)...'
7 Tooltip: 'Export PMD file for MikuMikuDance.'
9 __author__= ["ousttrue"]
15 This script exports a pmd model.
17 0.1 20100318: first implementation.
18 0.2 20100519: refactoring. use C extension.
19 1.0 20100530: implement, basic features.
20 1.1 20100612: integrate 2.4 and 2.5.
23 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
24 BASE_SHAPE_NAME='Basis'
27 ###############################################################################
29 ###############################################################################
36 from meshio import pmd, englishmap
39 return sys.version_info[0]<3
44 from Blender import Mathutils
52 from bpy.props import *
62 __slots__=['o', 'children']
63 def __init__(self, o):
68 ###############################################################################
69 # Blenderのメッシュをワンスキンメッシュ化する
70 ###############################################################################
71 def near(x, y, EPSILON=1e-5):
73 return d>=-EPSILON and d<=EPSILON
76 class VertexKey(object):
82 'nx', 'ny', 'nz', # 法線
86 def __init__(self, x, y, z, nx, ny, nz, u, v):
97 return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
98 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
101 #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
102 return int((self.x+self.y+self.z)*100)
104 def __eq__(self, rhs):
105 #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)
106 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
107 return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
110 class VertexArray(object):
115 # マテリアル毎に分割したインデックス配列
130 return "<VertexArray %d vertices, %d indexArrays>" % (
131 len(self.vertices), len(self.indexArrays))
135 self.vertices, self.normals, self.uvs,
136 self.b0, self.b1, self.weight)
138 def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
143 pos[0], pos[1], pos[2],
144 normal[0], normal[1], normal[2],
146 if key in self.vertexMap:
148 index=self.vertexMap[key]
150 index=len(self.vertices)
152 self.vertexMap[key]=index
154 self.vertices.append((pos.x, pos.y, pos.z))
155 self.normals.append((normal.x, normal.y, normal.z))
156 self.uvs.append((uv[0], uv[1]))
159 self.weight.append(weight0)
162 if not base_index in self.indexMap:
163 self.indexMap[base_index]=set()
164 self.indexMap[base_index].add(index)
169 def getMappedIndices(self, base_index):
170 return self.indexMap[base_index]
172 def addTriangle(self,
174 base_index0, base_index1, base_index2,
180 weight0, weight1, weight2
182 if not material in self.indexArrays:
183 self.indexArrays[material]=[]
185 index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
186 index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
187 index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
189 self.indexArrays[material]+=[index0, index1, index2]
193 __slots__=['name', 'type', 'offsets']
194 def __init__(self, name, type):
199 def add(self, index, offset):
200 self.offsets.append((index, offset))
204 self.offsets.sort(lambda l, r: l[0]-r[0])
206 self.offsets.sort(key=lambda e: e[0])
209 return "<Morph %s>" % self.name
211 class IKSolver(object):
212 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
213 def __init__(self, target, effector, length, iterations, weight):
215 self.effector=effector
217 self.iterations=iterations
221 class OneSkinMesh(object):
222 __slots__=['scene', 'vertexArray', 'morphList']
223 def __init__(self, scene):
224 self.vertexArray=VertexArray()
229 return "<OneSkinMesh %s, morph:%d>" % (
233 def addMesh(self, obj):
234 if bl.objectIsVisible(obj):
238 print("export", obj.name)
240 ############################################################
242 ############################################################
243 mesh=bl.objectGetData(obj)
246 def setWeight(i, name, w):
249 if i in secondWeightMap:
251 if w<secondWeightMap[i]:
255 secondWeightMap[i]=(name, w)
258 weightMap[i]=(name, w)
260 if w>weightMap[i][1]:
262 secondWeightMap[i]=weightMap[i]
263 weightMap[i]=(name, w)
265 secondWeightMap[i]=(name, w)
267 weightMap[i]=(name, w)
270 for name in bl.meshVertexGroupNames(obj):
271 for i, w in mesh.getVertsFromGroup(name, 1):
272 setWeight(i, name, w)
274 for i, v in enumerate(mesh.verts):
276 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
279 for i in xrange(len(mesh.verts)):
280 #for i, name_weight in weightMap.items():
281 if i in secondWeightMap:
282 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
284 weightMap[i]=(weightMap[i][0], 1.0)
285 secondWeightMap[i]=("", 0)
287 print("no weight vertex")
289 secondWeightMap[i]=("", 0)
291 ############################################################
292 # メッシュのコピーを生成してオブジェクトの行列を適用する
293 ############################################################
294 copyMesh, copyObj=bl.objectDuplicate(self.scene, obj)
295 if len(copyMesh.verts)==0:
298 for i, face in enumerate(copyMesh.faces):
299 faceVertexCount=bl.faceVertexCount(face)
300 material=copyMesh.materials[bl.faceMaterialIndex(face)]
301 v=[copyMesh.verts[index] for index in bl.faceVertices(face)]
302 uv=bl.meshFaceUv(copyMesh, i, face)
303 if faceVertexCount==3:
305 self.vertexArray.addTriangle(
307 v[0].index, v[1].index, v[2].index,
308 v[0].co, v[1].co, v[2].co,
310 #v0.no, v1.no, v2.no,
315 weightMap[v[0].index][0],
316 weightMap[v[1].index][0],
317 weightMap[v[2].index][0],
318 secondWeightMap[v[0].index][0],
319 secondWeightMap[v[1].index][0],
320 secondWeightMap[v[2].index][0],
321 weightMap[v[0].index][1],
322 weightMap[v[1].index][1],
323 weightMap[v[2].index][1]
325 elif faceVertexCount==4:
327 self.vertexArray.addTriangle(
329 v[0].index, v[1].index, v[2].index,
330 v[0].co, v[1].co, v[2].co,
331 #v0.no, v1.no, v2.no,
336 weightMap[v[0].index][0],
337 weightMap[v[1].index][0],
338 weightMap[v[2].index][0],
339 secondWeightMap[v[0].index][0],
340 secondWeightMap[v[1].index][0],
341 secondWeightMap[v[2].index][0],
342 weightMap[v[0].index][1],
343 weightMap[v[1].index][1],
344 weightMap[v[2].index][1]
346 self.vertexArray.addTriangle(
348 v[2].index, v[3].index, v[0].index,
349 v[2].co, v[3].co, v[0].co,
350 #v2.no, v3.no, v0.no,
355 weightMap[v[2].index][0],
356 weightMap[v[3].index][0],
357 weightMap[v[0].index][0],
358 secondWeightMap[v[2].index][0],
359 secondWeightMap[v[3].index][0],
360 secondWeightMap[v[0].index][0],
361 weightMap[v[2].index][1],
362 weightMap[v[3].index][1],
363 weightMap[v[0].index][1]
365 bl.objectDelete(self.scene, copyObj)
367 ############################################################
369 ############################################################
371 blenderMesh=bl.objectGetData(obj)
373 if bl.objectHasShapeKey(obj):
375 for b in bl.objectShapeKeys(obj):
378 baseMorph=self.__getOrCreateMorph('base', 0)
382 for index in bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME):
384 pos=[v[0], v[1], v[2]]
385 indices=self.vertexArray.getMappedIndices(index)
387 baseMorph.add(i, pos)
388 indexRelativeMap[i]=relativeIndex
394 if(len(baseMorph.offsets)>0):
398 vg=obj.getData(mesh=True).getVertsFromGroup(
399 MMD_SHAPE_GROUP_NAME)
400 for b in obj.getData(mesh=True).key.blocks:
405 morph=self.__getOrCreateMorph(b.name, 4)
406 for index, src, dst in zip(
407 xrange(len(blenderMesh.verts)),
410 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
412 indices=self.vertexArray.getMappedIndices(index)
414 morph.add(indexRelativeMap[i], offset)
415 assert(len(morph.offsets)==len(baseMorph.offsets))
418 original=self.morphList[:]
420 for i, v in enumerate(englishmap.skinMap):
425 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
427 self.morphList.sort(key=getIndex)
429 def __getOrCreateMorph(self, name, type):
430 for m in self.morphList:
434 self.morphList.append(m)
437 def getVertexCount(self):
438 return len(self.vertexArray.vertices)
442 __slots__=['index', 'name', 'ik_index',
443 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
444 def __init__(self, name, pos, tail):
449 self.parent_index=None
455 def __eq__(self, rhs):
456 return self.index==rhs.index
459 return "<Bone %s %d>" % (self.name, self.type)
461 class BoneBuilder(object):
462 __slots__=['bones', 'boneMap', 'ik_list']
468 def build(self, armatureObj):
472 print("gather bones")
473 armature=armatureObj.getData()
474 for b in armature.bones.values():
478 b.head['ARMATURESPACE'][0:3],
479 b.tail['ARMATURESPACE'][0:3])
481 self.__getBone(bone, b)
483 for b in armature.bones.values():
484 if not b.parent and b.name!='center':
487 b.head['ARMATURESPACE'][0:3],
488 b.tail['ARMATURESPACE'][0:3])
490 self.__getBone(bone, b)
492 print("check connection")
493 for b in armature.bones.values():
495 self.__checkConnection(b, None)
498 pose = armatureObj.getPose()
499 cSetting=Blender.Constraint.Settings
500 for b in pose.bones.values():
501 for c in b.constraints:
502 if c.type==Blender.Constraint.Type.IKSOLVER:
506 assert(c[cSetting.TARGET]==armatureObj)
507 target=self.__boneByName(
508 c[Blender.Constraint.Settings.BONE])
515 link=self.__boneByName(b.name)
520 chainLength=c[cSetting.CHAINLEN]
521 for i in range(chainLength):
523 chainBone=self.__boneByName(e.name)
525 chainBone.ik_index=target.index
528 IKSolver(target, link, chainLength,
529 int(c[cSetting.ITERATIONS] * 0.1),
530 c[cSetting.ROTWEIGHT]
533 def __checkConnection(self, b, p):
534 if Blender.Armature.CONNECTED in b.options:
535 parent=self.__boneByName(p.name)
536 parent.isConnect=True
539 self.__checkConnection(c, b)
541 def sortBy(self, boneMap):
545 original=self.bones[:]
547 for i, k_v in enumerate(boneMap):
548 if k_v[0]==bone.name:
553 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
555 self.bones.sort(key=getIndex)
558 for i, b in enumerate(self.bones):
559 src=original.index(b)
562 b.index=sortMap[b.index]
564 b.parent_index=sortMap[b.parent_index]
566 b.tail_index=sortMap[b.tail_index]
568 b.ik_index=sortMap[b.ik_index]
570 def getIndex(self, bone):
571 for i, b in enumerate(self.bones):
576 def indexByName(self, name):
577 return self.getIndex(self.__boneByName(name))
579 def __boneByName(self, name):
580 return self.bones[self.boneMap[name]]
582 def __getBone(self, parent, b):
583 if len(b.children)==0:
587 for i, c in enumerate(b.children):
589 c.head['ARMATURESPACE'][0:3],
590 c.tail['ARMATURESPACE'][0:3])
593 bone.parent_index=parent.index
595 parent.tail_index=bone.index
596 self.__getBone(bone, c)
598 def __addBone(self, bone):
599 bone.index=len(self.bones)
600 self.bones.append(bone)
601 self.boneMap[bone.name]=bone.index
604 class PmdExporter(object):
606 def setup(self, scene):
607 self.armatureObj=None
612 for o in scene.objects:
613 object_node_map[o]=Node(o)
614 for node in object_node_map.values():
616 object_node_map[node.o.parent].children.append(node)
618 root=object_node_map[scene.objects.active]
621 self.oneSkinMesh=OneSkinMesh(scene)
622 self.__createOneSkinMesh(root)
623 print(self.oneSkinMesh)
624 self.name=root.o.name
627 self.builder=BoneBuilder()
628 self.builder.build(self.armatureObj)
629 self.builder.sortBy(englishmap.boneMap)
631 for i, v in enumerate(englishmap.boneMap):
632 if v[0]==ik.target.name:
634 return len(englishmap.boneMap)
636 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
638 self.builder.ik_list.sort(key=getIndex)
640 def __createOneSkinMesh(self, node):
641 ############################################################
642 # search armature modifier
643 ############################################################
644 for m in node.o.modifiers:
645 if m.name=="Armature":
646 armatureObj=bl.armatureModifierGetObject(m)
647 if not self.armatureObj:
648 self.armatureObj=armatureObj
649 elif self.armatureObj!=armatureObj:
650 print("warning! found multiple armature. ignored.", armatureObj.name)
652 if node.o.type.upper()=='MESH':
653 self.oneSkinMesh.addMesh(node.o)
655 for child in node.children:
656 self.__createOneSkinMesh(child)
658 def write(self, path):
661 io.comment="blender export"
665 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
666 # convert right-handed z-up to left-handed y-up
676 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
677 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
678 v.weight0=int(100*weight)
679 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
682 vertexCount=self.oneSkinMesh.getVertexCount()
683 for material_name, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
684 m=bl.materialGet(self.scene, material_name)
686 material=io.addMaterial()
688 material.diffuse.r=m.R
689 material.diffuse.g=m.G
690 material.diffuse.b=m.B
691 material.diffuse.a=m.alpha
692 material.sinness=0 if m.spec<1e-5 else m.spec*10
693 material.specular.r=m.specR
694 material.specular.g=m.specG
695 material.specular.b=m.specB
696 material.ambient.r=m.mirR
697 material.ambient.g=m.mirG
698 material.ambient.b=m.mirB
699 material.flag=1 if m.enableSSS else 0
701 material.diffuse.r=m.diffuse_color[0]
702 material.diffuse.g=m.diffuse_color[1]
703 material.diffuse.b=m.diffuse_color[2]
704 material.diffuse.a=m.alpha
705 material.sinness=0 if m.specular_hardness<1e-5 else m.specular_hardness*10
706 material.specular.r=m.specular_color[0]
707 material.specular.g=m.specular_color[1]
708 material.specular.b=m.specular_color[2]
709 material.ambient.r=m.mirror_color[0]
710 material.ambient.g=m.mirror_color[1]
711 material.ambient.b=m.mirror_color[2]
712 material.flag=1 if m.subsurface_scattering.enabled else 0
714 material.vertex_count=len(indices)
715 material.toon_index=0
720 assert(i<vertexCount)
721 for i in xrange(0, len(indices), 3):
723 io.indices.append(indices[i+2])
724 io.indices.append(indices[i+1])
725 io.indices.append(indices[i])
727 #io.indices.append(indices[i])
728 #io.indices.append(indices[i+1])
729 #io.indices.append(indices[i+2])
732 for b in self.builder.bones:
733 if b.name.endswith("_t"):
734 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
736 print("skip %s" % b.name)
741 v=englishmap.getUnicodeBoneName(b.name)
743 cp932=v[1].encode('cp932')
744 bone_name="%s" % cp932
745 assert(len(bone_name)<20)
748 bone_english_name="%s" % b.name
749 assert(len(bone_english_name)<20)
750 bone.english_name=bone_english_name
755 b.ik_index=self.builder.indexByName('eyes')
761 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
764 if b.tail_index!=None:
768 bone.tail_index=b.tail_index
772 bone.ik_index=b.ik_index
774 # convert right-handed z-up to left-handed y-up
775 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
776 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
777 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
780 for ik in self.builder.ik_list:
782 solver.index=self.builder.getIndex(ik.target)
783 solver.target=self.builder.getIndex(ik.effector)
784 solver.length=ik.length
785 b=self.builder.bones[ik.effector.parent_index]
786 for i in xrange(solver.length):
787 solver.children.append(self.builder.getIndex(b))
788 b=self.builder.bones[b.parent_index]
789 solver.iterations=ik.iterations
790 solver.weight=ik.weight
793 for i, m in enumerate(self.oneSkinMesh.morphList):
797 v=englishmap.getUnicodeSkinName(m.name)
799 cp932=v[1].encode('cp932')
800 morph.name="%s\n" % cp932
802 morph.english_name="%s\n" % m.name
805 for index, offset in m.offsets:
806 # convert right-handed z-up to left-handed y-up
807 morph.append(index, offset[0], offset[2], offset[1])
808 morph.vertex_count=len(m.offsets)
812 for i, m in enumerate(self.oneSkinMesh.morphList):
814 io.face_list.append(i)
815 for i, m in enumerate(self.oneSkinMesh.morphList):
817 io.face_list.append(i)
818 for i, m in enumerate(self.oneSkinMesh.morphList):
820 io.face_list.append(i)
821 for i, m in enumerate(self.oneSkinMesh.morphList):
823 io.face_list.append(i)
826 def createBoneDisplayName(name, english):
827 boneDisplayName=io.addBoneDisplayName()
829 boneDisplayName.name=name.decode('utf-8').encode('cp932')
830 boneDisplayName.english_name=english
833 boneDisplayName.name=english
834 boneDisplayName.english_name=english
835 boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
836 boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
837 boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
838 boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
839 boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
840 boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
841 boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
842 for i, b in enumerate(self.builder.bones):
847 io.addBoneDisplay(i, getBoneDisplayGroup(b))
850 io.english_name="blender export"
851 io.english_coment="blender export"
854 io.getToonTexture(i).name="toon%02d.bmp\n" % i
857 return io.write(path)
860 def getBoneDisplayGroup(bone):
863 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
864 "toe IK_L", "toe IK_R",
867 "upper body", "neck", "head", "eye_L", "eye_R",
868 "necktie1", "necktie2", "necktie3", "eyes",
869 "eyelight_L", "eyelight_R",
872 "front hair1", "front hair2", "front hair3",
873 "hair1_L", "hair2_L", "hair3_L",
874 "hair4_L", "hair5_L", "hair6_L",
875 "hair1_R", "hair2_R", "hair3_R",
876 "hair4_R", "hair5_R", "hair6_R",
879 "shoulder_L", "arm_L", "arm twist_L", "elbow_L",
880 "wrist twist_L", "wrist_L", "sleeve_L",
881 "shoulder_R", "arm_R", "arm twist_R", "elbow_R",
882 "wrist twist_R", "wrist_R", "sleeve_R",
885 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
886 "middle1_L", "middle2_L", "middle3_L",
887 "third1_L", "third2_L", "third3_L",
888 "little1_L", "little2_L", "little3_L",
889 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
890 "middle1_R", "middle2_R", "middle3_R",
891 "third1_R", "third2_R", "third3_R",
892 "little1_R", "little2_R", "little3_R",
895 "lower body", "waist accessory",
896 "front skirt_L", "back skirt_L",
897 "front skirt_R", "back skirt_R",
900 "leg_L", "knee_L", "ankle_L",
901 "leg_R", "knee_R", "ankle_R",
913 def __execute(filename, scene):
914 exporter=PmdExporter()
915 exporter.setup(scene)
916 exporter.write(filename)
921 def execute_24(filename):
922 filename=filename.decode(bl.INTERNAL_ENCODING)
923 print("pmd exporter: %s" % filename)
925 Blender.Window.WaitCursor(1)
926 t = Blender.sys.time()
928 scene = bpy.data.scenes.active
929 __execute(filename, scene)
931 print('finished in %.2f seconds' % (Blender.sys.time()-t))
933 Blender.Window.WaitCursor(0)
935 Blender.Window.FileSelector(
937 'Export Metasequoia PMD',
938 Blender.sys.makename(ext='.pmd'))
942 def execute_25(*args):
946 class EXPORT_OT_pmd(bpy.types.Operator):
947 '''Save a Metasequoia PMD file.'''
948 bl_idname = "export_scene.pmd"
949 bl_label = 'Export PMD'
951 # List of operator properties, the attributes will be assigned
952 # to the class instance from the operator settings before calling.
954 path = StringProperty(
956 description="File path used for exporting the PMD file",
960 filename = StringProperty(
962 description="Name of the file.")
963 directory = StringProperty(
965 description="Directory of the file.")
967 check_existing = BoolProperty(
968 name="Check Existing",
969 description="Check and warn on overwriting existing files",
971 options=set('HIDDEN'))
973 def execute(self, context):
975 self.properties.path,
980 def invoke(self, context, event):
982 wm.add_fileselect(self)
983 return 'RUNNING_MODAL'
986 def menu_func(self, context):
987 default_path=bpy.data.filename.replace(".blend", ".pmd")
988 self.layout.operator(
989 EXPORT_OT_pmd.bl_idname,
990 text="Miku Miku Dance Model(.pmd)").path=default_path
993 bpy.types.register(EXPORT_OT_pmd)
994 bpy.types.INFO_MT_file_export.append(menu_func)
997 bpy.types.unregister(EXPORT_OT_pmd)
998 bpy.types.INFO_MT_file_export.remove(menu_func)
1000 if __name__ == "__main__":