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):
83 'nx', 'ny', 'nz', # 法線
87 def __init__(self, obj, index, x, y, z, nx, ny, nz, u, v):
100 return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
101 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
104 #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
105 return int((self.x+self.y+self.z)*100)
107 def __eq__(self, rhs):
108 #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)
109 #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
110 #return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
111 return self.obj==rhs.obj and self.index==rhs.index
114 class VertexArray(object):
119 # マテリアル毎に分割したインデックス配列
134 return "<VertexArray %d vertices, %d indexArrays>" % (
135 len(self.vertices), len(self.indexArrays))
139 self.vertices, self.normals, self.uvs,
140 self.b0, self.b1, self.weight)
142 def __getIndex(self, obj, base_index, pos, normal, uv, b0, b1, weight0):
148 pos[0], pos[1], pos[2],
149 normal[0], normal[1], normal[2],
151 if key in self.vertexMap:
153 index=self.vertexMap[key]
155 index=len(self.vertices)
157 self.vertexMap[key]=index
159 self.vertices.append((pos.x, pos.y, pos.z))
160 self.normals.append((normal.x, normal.y, normal.z))
161 self.uvs.append((uv[0], uv[1]))
164 self.weight.append(weight0)
167 if not base_index in self.indexMap:
168 self.indexMap[base_index]=set()
169 self.indexMap[base_index].add(index)
174 def getMappedIndices(self, base_index):
175 return self.indexMap[base_index]
177 def addTriangle(self,
179 base_index0, base_index1, base_index2,
185 weight0, weight1, weight2
187 if not material in self.indexArrays:
188 self.indexArrays[material]=[]
190 index0=self.__getIndex(obj, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
191 index1=self.__getIndex(obj, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
192 index2=self.__getIndex(obj, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
194 self.indexArrays[material]+=[index0, index1, index2]
198 __slots__=['name', 'type', 'offsets']
199 def __init__(self, name, type):
204 def add(self, index, offset):
205 self.offsets.append((index, offset))
209 self.offsets.sort(lambda l, r: l[0]-r[0])
211 self.offsets.sort(key=lambda e: e[0])
214 return "<Morph %s>" % self.name
216 class IKSolver(object):
217 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
218 def __init__(self, target, effector, length, iterations, weight):
220 self.effector=effector
222 self.iterations=iterations
226 class OneSkinMesh(object):
227 __slots__=['obj_index', 'scene', 'vertexArray', 'morphList']
228 def __init__(self, scene):
229 self.vertexArray=VertexArray()
235 return "<OneSkinMesh %s, morph:%d>" % (
239 def addMesh(self, obj):
240 if bl.objectIsVisible(obj):
244 print("export", obj.name)
247 weightMap=self.__mesh(obj)
252 def __mesh(self, obj):
253 mesh=bl.objectGetData(obj)
256 def setWeight(i, name, w):
259 if i in secondWeightMap:
261 if w<secondWeightMap[i]:
265 secondWeightMap[i]=(name, w)
268 weightMap[i]=(name, w)
270 if w>weightMap[i][1]:
272 secondWeightMap[i]=weightMap[i]
273 weightMap[i]=(name, w)
275 secondWeightMap[i]=(name, w)
277 weightMap[i]=(name, w)
280 for name in bl.meshVertexGroupNames(obj):
281 for i, w in mesh.getVertsFromGroup(name, 1):
282 setWeight(i, name, w)
284 for i, v in enumerate(mesh.verts):
286 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
289 for i in xrange(len(mesh.verts)):
290 #for i, name_weight in weightMap.items():
291 if i in secondWeightMap:
292 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
294 weightMap[i]=(weightMap[i][0], 1.0)
295 secondWeightMap[i]=("", 0)
297 print("no weight vertex")
299 secondWeightMap[i]=("", 0)
301 # メッシュのコピーを生成してオブジェクトの行列を適用する
302 copyMesh, copyObj=bl.objectDuplicate(self.scene, obj)
303 if len(copyMesh.verts)==0:
306 for i, face in enumerate(copyMesh.faces):
307 faceVertexCount=bl.faceVertexCount(face)
308 material=copyMesh.materials[bl.faceMaterialIndex(face)]
309 v=[copyMesh.verts[index] for index in bl.faceVertices(face)]
310 uv=bl.meshFaceUv(copyMesh, i, face)
311 if faceVertexCount==3:
313 self.vertexArray.addTriangle(
314 self.obj_index, material.name,
315 v[0].index, v[1].index, v[2].index,
316 v[0].co, v[1].co, v[2].co,
318 #v0.no, v1.no, v2.no,
323 weightMap[v[0].index][0],
324 weightMap[v[1].index][0],
325 weightMap[v[2].index][0],
326 secondWeightMap[v[0].index][0],
327 secondWeightMap[v[1].index][0],
328 secondWeightMap[v[2].index][0],
329 weightMap[v[0].index][1],
330 weightMap[v[1].index][1],
331 weightMap[v[2].index][1]
333 elif faceVertexCount==4:
335 self.vertexArray.addTriangle(
336 self.obj_index, material.name,
337 v[0].index, v[1].index, v[2].index,
338 v[0].co, v[1].co, v[2].co,
339 #v0.no, v1.no, v2.no,
344 weightMap[v[0].index][0],
345 weightMap[v[1].index][0],
346 weightMap[v[2].index][0],
347 secondWeightMap[v[0].index][0],
348 secondWeightMap[v[1].index][0],
349 secondWeightMap[v[2].index][0],
350 weightMap[v[0].index][1],
351 weightMap[v[1].index][1],
352 weightMap[v[2].index][1]
354 self.vertexArray.addTriangle(
355 self.obj_index, material.name,
356 v[2].index, v[3].index, v[0].index,
357 v[2].co, v[3].co, v[0].co,
358 #v2.no, v3.no, v0.no,
363 weightMap[v[2].index][0],
364 weightMap[v[3].index][0],
365 weightMap[v[0].index][0],
366 secondWeightMap[v[2].index][0],
367 secondWeightMap[v[3].index][0],
368 secondWeightMap[v[0].index][0],
369 weightMap[v[2].index][1],
370 weightMap[v[3].index][1],
371 weightMap[v[0].index][1]
373 bl.objectDelete(self.scene, copyObj)
376 def __skin(self, obj):
377 if not bl.objectHasShapeKey(obj):
381 blenderMesh=bl.objectGetData(obj)
385 vg=bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
389 for b in bl.objectShapeKeys(obj):
390 if b.name==BASE_SHAPE_NAME:
391 baseMorph=self.__getOrCreateMorph('base', 0)
396 v=bl.shapeKeyGet(b, index)
397 pos=[v[0], v[1], v[2]]
398 indices=self.vertexArray.getMappedIndices(index)
404 baseMorph.add(i, pos)
405 indexRelativeMap[i]=relativeIndex
410 print(basis.name, len(baseMorph.offsets))
412 if len(baseMorph.offsets)==0:
416 for b in bl.objectShapeKeys(obj):
417 if b.name==BASE_SHAPE_NAME:
421 morph=self.__getOrCreateMorph(b.name, 4)
423 for index, src, dst in zip(
424 xrange(len(blenderMesh.verts)),
427 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
428 if offset[0]==0 and offset[1]==0 and offset[2]==0:
431 indices=self.vertexArray.getMappedIndices(index)
436 morph.add(indexRelativeMap[i], offset)
439 original=self.morphList[:]
441 for i, v in enumerate(englishmap.skinMap):
446 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
448 self.morphList.sort(key=getIndex)
450 def __getOrCreateMorph(self, name, type):
451 for m in self.morphList:
455 self.morphList.append(m)
458 def getVertexCount(self):
459 return len(self.vertexArray.vertices)
463 __slots__=['index', 'name', 'ik_index',
464 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
465 def __init__(self, name, pos, tail):
470 self.parent_index=None
476 def __eq__(self, rhs):
477 return self.index==rhs.index
480 return "<Bone %s %d>" % (self.name, self.type)
482 class BoneBuilder(object):
483 __slots__=['bones', 'boneMap', 'ik_list']
489 def build(self, armatureObj):
493 print("gather bones")
494 armature=bl.objectGetData(armatureObj)
495 for b in armature.bones.values():
502 self.__getBone(bone, b)
504 for b in armature.bones.values():
505 if not b.parent and b.name!='center':
511 self.__getBone(bone, b)
513 print("check connection")
514 for b in armature.bones.values():
516 self.__checkConnection(b, None)
519 pose = bl.objectGetPose(armatureObj)
520 for b in pose.bones.values():
521 for c in b.constraints:
522 if bl.constraintIsIKSolver(c):
526 target=self.__boneByName(bl.ikTarget(c))
533 link=self.__boneByName(b.name)
538 chainLength=bl.ikChainLen(c)
539 for i in range(chainLength):
541 chainBone=self.__boneByName(e.name)
543 chainBone.ik_index=target.index
546 IKSolver(target, link, chainLength,
547 int(bl.ikItration(c) * 0.1),
548 bl.ikRotationWeight(c)
551 def __checkConnection(self, b, p):
552 if bl.boneIsConnected(b):
553 parent=self.__boneByName(p.name)
554 parent.isConnect=True
557 self.__checkConnection(c, b)
559 def sortBy(self, boneMap):
563 original=self.bones[:]
565 for i, k_v in enumerate(boneMap):
566 if k_v[0]==bone.name:
571 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
573 self.bones.sort(key=getIndex)
576 for i, b in enumerate(self.bones):
577 src=original.index(b)
580 b.index=sortMap[b.index]
582 b.parent_index=sortMap[b.parent_index]
584 b.tail_index=sortMap[b.tail_index]
586 b.ik_index=sortMap[b.ik_index]
588 def getIndex(self, bone):
589 for i, b in enumerate(self.bones):
594 def indexByName(self, name):
595 return self.getIndex(self.__boneByName(name))
597 def __boneByName(self, name):
598 return self.bones[self.boneMap[name]]
600 def __getBone(self, parent, b):
601 if len(b.children)==0:
605 for i, c in enumerate(b.children):
611 bone.parent_index=parent.index
613 parent.tail_index=bone.index
614 self.__getBone(bone, c)
616 def __addBone(self, bone):
617 bone.index=len(self.bones)
618 self.bones.append(bone)
619 self.boneMap[bone.name]=bone.index
622 class PmdExporter(object):
624 def setup(self, scene):
625 self.armatureObj=None
630 for o in scene.objects:
631 object_node_map[o]=Node(o)
632 for node in object_node_map.values():
634 object_node_map[node.o.parent].children.append(node)
637 root=object_node_map[scene.objects.active]
640 self.oneSkinMesh=OneSkinMesh(scene)
641 self.__createOneSkinMesh(root)
642 print(self.oneSkinMesh)
643 self.name=root.o.name
646 self.builder=BoneBuilder()
647 self.builder.build(self.armatureObj)
648 self.builder.sortBy(englishmap.boneMap)
650 for i, v in enumerate(englishmap.boneMap):
651 if v[0]==ik.target.name:
653 return len(englishmap.boneMap)
655 self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
657 self.builder.ik_list.sort(key=getIndex)
659 def __createOneSkinMesh(self, node):
661 ############################################################
662 # search armature modifier
663 ############################################################
664 for m in node.o.modifiers:
665 if bl.modifierIsArmature(m):
666 armatureObj=bl.armatureModifierGetObject(m)
667 if not self.armatureObj:
668 self.armatureObj=armatureObj
669 elif self.armatureObj!=armatureObj:
670 print("warning! found multiple armature. ignored.", armatureObj.name)
672 if node.o.type.upper()=='MESH':
673 self.oneSkinMesh.addMesh(node.o)
675 for child in node.children:
676 self.__createOneSkinMesh(child)
678 def write(self, path):
681 io.comment="blender export"
685 for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
686 # convert right-handed z-up to left-handed y-up
696 v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
697 v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
698 v.weight0=int(100*weight)
699 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
702 vertexCount=self.oneSkinMesh.getVertexCount()
703 for material_name, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
704 m=bl.materialGet(self.scene, material_name)
706 material=io.addMaterial()
708 material.diffuse.r=m.R
709 material.diffuse.g=m.G
710 material.diffuse.b=m.B
711 material.diffuse.a=m.alpha
712 material.sinness=0 if m.spec<1e-5 else m.spec*10
713 material.specular.r=m.specR
714 material.specular.g=m.specG
715 material.specular.b=m.specB
716 material.ambient.r=m.mirR
717 material.ambient.g=m.mirG
718 material.ambient.b=m.mirB
719 material.flag=1 if m.enableSSS else 0
721 material.diffuse.r=m.diffuse_color[0]
722 material.diffuse.g=m.diffuse_color[1]
723 material.diffuse.b=m.diffuse_color[2]
724 material.diffuse.a=m.alpha
725 material.sinness=0 if m.specular_hardness<1e-5 else m.specular_hardness*10
726 material.specular.r=m.specular_color[0]
727 material.specular.g=m.specular_color[1]
728 material.specular.b=m.specular_color[2]
729 material.ambient.r=m.mirror_color[0]
730 material.ambient.g=m.mirror_color[1]
731 material.ambient.b=m.mirror_color[2]
732 material.flag=1 if m.subsurface_scattering.enabled else 0
734 material.vertex_count=len(indices)
735 material.toon_index=0
740 assert(i<vertexCount)
741 for i in xrange(0, len(indices), 3):
743 io.indices.append(indices[i])
744 io.indices.append(indices[i+1])
745 io.indices.append(indices[i+2])
748 for b in self.builder.bones:
749 if b.name.endswith("_t"):
750 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
752 print("skip %s" % b.name)
758 v=englishmap.getUnicodeBoneName(b.name)
760 cp932=v[1].encode('cp932')
761 assert(len(cp932)<20)
765 bone_english_name=b.name
766 assert(len(bone_english_name)<20)
767 bone.english_name=bone_english_name
772 b.ik_index=self.builder.indexByName('eyes')
778 bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
781 if b.tail_index!=None:
785 bone.tail_index=b.tail_index
789 bone.ik_index=b.ik_index
791 # convert right-handed z-up to left-handed y-up
792 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
793 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
794 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
797 for ik in self.builder.ik_list:
799 solver.index=self.builder.getIndex(ik.target)
800 solver.target=self.builder.getIndex(ik.effector)
801 solver.length=ik.length
802 b=self.builder.bones[ik.effector.parent_index]
803 for i in xrange(solver.length):
804 solver.children.append(self.builder.getIndex(b))
805 b=self.builder.bones[b.parent_index]
806 solver.iterations=ik.iterations
807 solver.weight=ik.weight
810 for i, m in enumerate(self.oneSkinMesh.morphList):
814 v=englishmap.getUnicodeSkinName(m.name)
816 cp932=v[1].encode('cp932')
818 morph.setEnglishName(m.name.encode('cp932'))
821 for index, offset in m.offsets:
822 # convert right-handed z-up to left-handed y-up
823 morph.append(index, offset[0], offset[2], offset[1])
824 morph.vertex_count=len(m.offsets)
828 for i, m in enumerate(self.oneSkinMesh.morphList):
830 io.face_list.append(i)
831 for i, m in enumerate(self.oneSkinMesh.morphList):
833 io.face_list.append(i)
834 for i, m in enumerate(self.oneSkinMesh.morphList):
836 io.face_list.append(i)
837 for i, m in enumerate(self.oneSkinMesh.morphList):
839 io.face_list.append(i)
842 def createBoneDisplayName(name, english):
843 boneDisplayName=io.addBoneDisplayName()
845 boneDisplayName.name=name.decode('utf-8').encode('cp932')
846 boneDisplayName.english_name=english
848 boneDisplayName.setName(name.encode('cp932'))
849 boneDisplayName.setEnglishName(english.encode('cp932'))
850 boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
851 boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
852 boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
853 boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
854 boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
855 boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
856 boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
857 for i, b in enumerate(self.builder.bones):
862 io.addBoneDisplay(i, getBoneDisplayGroup(b))
865 io.english_name="blender export"
866 io.english_coment="blender export"
869 io.getToonTexture(i).name="toon%02d.bmp\n" % i
872 return io.write(path)
875 def getBoneDisplayGroup(bone):
878 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
879 "toe IK_L", "toe IK_R",
882 "upper body", "neck", "head", "eye_L", "eye_R",
883 "necktie1", "necktie2", "necktie3", "eyes",
884 "eyelight_L", "eyelight_R",
887 "front hair1", "front hair2", "front hair3",
888 "hair1_L", "hair2_L", "hair3_L",
889 "hair4_L", "hair5_L", "hair6_L",
890 "hair1_R", "hair2_R", "hair3_R",
891 "hair4_R", "hair5_R", "hair6_R",
894 "shoulder_L", "arm_L", "arm twist_L", "elbow_L",
895 "wrist twist_L", "wrist_L", "sleeve_L",
896 "shoulder_R", "arm_R", "arm twist_R", "elbow_R",
897 "wrist twist_R", "wrist_R", "sleeve_R",
900 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
901 "middle1_L", "middle2_L", "middle3_L",
902 "third1_L", "third2_L", "third3_L",
903 "little1_L", "little2_L", "little3_L",
904 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
905 "middle1_R", "middle2_R", "middle3_R",
906 "third1_R", "third2_R", "third3_R",
907 "little1_R", "little2_R", "little3_R",
910 "lower body", "waist accessory",
911 "front skirt_L", "back skirt_L",
912 "front skirt_R", "back skirt_R",
915 "leg_L", "knee_L", "ankle_L",
916 "leg_R", "knee_R", "ankle_R",
928 def __execute(filename, scene):
929 if not scene.objects.active:
930 print("abort. no active object.")
933 exporter=PmdExporter()
934 exporter.setup(scene)
935 exporter.write(filename)
940 def execute_24(filename):
941 filename=filename.decode(bl.INTERNAL_ENCODING)
942 print("pmd exporter: %s" % filename)
944 Blender.Window.WaitCursor(1)
945 t = Blender.sys.time()
947 scene = bpy.data.scenes.active
948 __execute(filename, scene)
950 print('finished in %.2f seconds' % (Blender.sys.time()-t))
952 Blender.Window.WaitCursor(0)
954 Blender.Window.FileSelector(
956 'Export Metasequoia PMD',
957 Blender.sys.makename(ext='.pmd'))
961 def execute_25(*args):
965 class EXPORT_OT_pmd(bpy.types.Operator):
966 '''Save a Metasequoia PMD file.'''
967 bl_idname = "export_scene.pmd"
968 bl_label = 'Export PMD'
970 # List of operator properties, the attributes will be assigned
971 # to the class instance from the operator settings before calling.
973 path = StringProperty(
975 description="File path used for exporting the PMD file",
979 filename = StringProperty(
981 description="Name of the file.")
982 directory = StringProperty(
984 description="Directory of the file.")
986 check_existing = BoolProperty(
987 name="Check Existing",
988 description="Check and warn on overwriting existing files",
990 options=set('HIDDEN'))
992 def execute(self, context):
994 self.properties.path,
999 def invoke(self, context, event):
1001 wm.add_fileselect(self)
1002 return 'RUNNING_MODAL'
1005 def menu_func(self, context):
1006 #default_path=bpy.data.filename.replace(".blend", ".pmd")
1007 self.layout.operator(
1008 EXPORT_OT_pmd.bl_idname,
1009 text="Miku Miku Dance Model(.pmd)")#.path=default_path
1012 bpy.types.register(EXPORT_OT_pmd)
1013 bpy.types.INFO_MT_file_export.append(menu_func)
1016 bpy.types.unregister(EXPORT_OT_pmd)
1017 bpy.types.INFO_MT_file_export.remove(menu_func)
1019 if __name__ == "__main__":