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.
21 1.2 20100616: implement rigid body.
22 1.3 20100619: fix rigid body, bone weight.
23 1.4 20100626: refactoring.
24 1.5 20100629: sphere map.
25 1.6 20100710: toon texture & bone group.
26 1.7 20100711: separate vertex with normal or uv.
27 2.0 20100724: update for Blender2.53.
28 2.1 20100731: add full python module.
32 'category': 'Import/Export',
33 'name': 'Export: MikuMikuDance Model Format (.pmd)',
37 'location': 'File > Export',
38 'description': 'Export to the MikuMikuDance Model Format (.pmd)',
39 'warning': '', # used for warning icon and text in addons panel
40 'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
43 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
45 MMD_MB_COMMENT='mb_comment'
47 BASE_SHAPE_NAME='Basis'
48 RIGID_NAME='rigid_name'
49 RIGID_SHAPE_TYPE='rigid_shape_type'
50 RIGID_PROCESS_TYPE='rigid_process_type'
51 RIGID_BONE_NAME='rigid_bone_name'
52 #RIGID_LOCATION='rigid_loation'
53 RIGID_GROUP='ribid_group'
54 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
55 RIGID_WEIGHT='rigid_weight'
56 RIGID_LINEAR_DAMPING='rigid_linear_damping'
57 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
58 RIGID_RESTITUTION='rigid_restitution'
59 RIGID_FRICTION='rigid_friction'
60 CONSTRAINT_NAME='constraint_name'
61 CONSTRAINT_A='const_a'
62 CONSTRAINT_B='const_b'
63 CONSTRAINT_POS_MIN='const_pos_min'
64 CONSTRAINT_POS_MAX='const_pos_max'
65 CONSTRAINT_ROT_MIN='const_rot_min'
66 CONSTRAINT_ROT_MAX='const_rot_max'
67 CONSTRAINT_SPRING_POS='const_spring_pos'
68 CONSTRAINT_SPRING_ROT='const_spring_rot'
69 TOON_TEXTURE_OBJECT='ToonTextures'
72 ###############################################################################
74 ###############################################################################
80 from meshio import pmd, englishmap
83 from pymeshio import englishmap
84 from pymeshio.mmd import PMDLoader as pmd
87 return sys.version_info[0]<3
92 from Blender import Mathutils
98 def setMaterialParams(material, m):
100 material.diffuse.r=m.R
101 material.diffuse.g=m.G
102 material.diffuse.b=m.B
103 material.diffuse.a=m.alpha
105 material.sinness=0 if m.spec<1e-5 else m.spec*10
106 material.specular.r=m.specR
107 material.specular.g=m.specG
108 material.specular.b=m.specB
110 material.ambient.r=m.mirR
111 material.ambient.g=m.mirG
112 material.ambient.b=m.mirB
114 material.flag=1 if m.enableSSS else 0
130 def setMaterialParams(material, m):
132 material.diffuse.r=m.diffuse_color[0]
133 material.diffuse.g=m.diffuse_color[1]
134 material.diffuse.b=m.diffuse_color[2]
135 material.diffuse.a=m.alpha
137 material.sinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
138 material.specular.r=m.specular_color[0]
139 material.specular.g=m.specular_color[1]
140 material.specular.b=m.specular_color[2]
142 material.ambient.r=m.mirror_color[0]
143 material.ambient.g=m.mirror_color[1]
144 material.ambient.b=m.mirror_color[2]
146 material.flag=1 if m.subsurface_scattering.enabled else 0
148 material.toon_index=7
151 return s.encode('cp932')
155 __slots__=['o', 'children']
156 def __init__(self, o):
161 ###############################################################################
162 # Blenderのメッシュをワンスキンメッシュ化する
163 ###############################################################################
164 def near(x, y, EPSILON=1e-5):
166 return d>=-EPSILON and d<=EPSILON
169 class VertexAttribute(object):
171 'nx', 'ny', 'nz', # normal
174 def __init__(self, nx, ny, nz, u, v):
182 return "<vkey: %f, %f, %f, %f, %f>" % (
183 self.nx, self.ny, self.nz, self.u, self.v)
186 return self.nx + self.ny + self.nz + self.u + self.v
188 def __eq__(self, rhs):
189 return self.nx==rhs.nx and self.ny==rhs.ny and self.nz==rhs.nz and self.u==rhs.u and self.v==rhs.v
192 class VertexKey(object):
194 'obj_index', 'index',
197 def __init__(self, obj_index, index):
198 self.obj_index=obj_index
202 return "<vkey: %d, %d>" % (self.obj_index, self.index)
205 return self.index*100+self.obj_index
207 def __eq__(self, rhs):
208 return self.obj_index==rhs.obj_index and self.index==rhs.index
211 class VertexArray(object):
218 'attributes', # normal and uv
219 'b0', 'b1', 'weight',
224 # indexArrays split with each material
237 return "<VertexArray %d positions, %d indexArrays>" % (
238 len(self.positions), len(self.indexArrays))
242 self.positions, self.attributes,
243 self.b0, self.b1, self.weight)
246 keys=[key for key in self.indexArrays.keys()]
249 yield(key, self.indexArrays[key])
251 def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
252 key=VertexKey(obj_index, base_index)
253 attribute=VertexAttribute(
254 normal[0], normal[1], normal[2],
256 if key in self.vertexMap:
257 if attribute in self.vertexMap[key]:
258 return self.vertexMap[key][attribute]
260 return self.__addVertex(self.vertexMap[key],
261 pos, attribute, b0, b1, weight0)
264 self.vertexMap[key]=vertexMapKey
265 return self.__addVertex(vertexMapKey,
266 pos, attribute, b0, b1, weight0)
268 def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
269 index=len(self.positions)
270 vertexMapKey[attribute]=index
272 self.positions.append((pos.x, pos.y, pos.z))
274 self.attributes.append(attribute)
278 self.weight.append(weight0)
282 def getMappedIndex(self, obj_name, base_index):
283 return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
285 def addTriangle(self,
286 object_name, material,
287 base_index0, base_index1, base_index2,
293 weight0, weight1, weight2
295 if object_name in self.objectMap:
296 obj_index=self.objectMap[object_name]
298 obj_index=len(self.objectMap)
299 self.objectMap[object_name]=obj_index
300 index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
301 index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
302 index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
304 if not material in self.indexArrays:
305 self.indexArrays[material]=[]
306 self.indexArrays[material]+=[index0, index1, index2]
310 __slots__=['name', 'type', 'offsets']
311 def __init__(self, name, type):
316 def add(self, index, offset):
317 self.offsets.append((index, offset))
321 self.offsets.sort(lambda l, r: l[0]-r[0])
323 self.offsets.sort(key=lambda e: e[0])
326 return "<Morph %s>" % self.name
328 class IKSolver(object):
329 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
330 def __init__(self, target, effector, length, iterations, weight):
332 self.effector=effector
334 self.iterations=iterations
338 class OneSkinMesh(object):
339 __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
341 self.vertexArray=VertexArray()
347 return "<OneSkinMesh %s, morph:%d>" % (
351 def addMesh(self, obj):
352 if not bl.object.isVisible(obj):
356 self.__rigidbody(obj)
357 self.__constraint(obj)
359 def __getWeightMap(self, obj, mesh):
363 def setWeight(i, name, w):
366 if i in secondWeightMap:
368 if w<secondWeightMap[i][1]:
370 elif w<weightMap[i][1]:
372 secondWeightMap[i]=(name, w)
375 weightMap[i]=(name, w)
377 if w>weightMap[i][1]:
379 secondWeightMap[i]=weightMap[i]
380 weightMap[i]=(name, w)
382 secondWeightMap[i]=(name, w)
384 weightMap[i]=(name, w)
386 # ToDo bone weightと関係ないvertex groupを除外する
388 for name in bl.object.getVertexGroupNames(obj):
389 for i, w in mesh.getVertsFromGroup(name, 1):
390 setWeight(i, name, w)
392 for i, v in enumerate(mesh.verts):
395 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
397 setWeight(i, obj.vertex_groups[0].name, 1)
400 for i in xrange(len(mesh.verts)):
401 if i in secondWeightMap:
402 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
404 weightMap[i]=(weightMap[i][0], 1.0)
405 secondWeightMap[i]=("", 0)
407 print("no weight vertex")
409 secondWeightMap[i]=("", 0)
411 return weightMap, secondWeightMap
413 def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
415 for i, face in enumerate(mesh.faces):
416 faceVertexCount=bl.face.getVertexCount(face)
417 material=mesh.materials[bl.face.getMaterialIndex(face)]
418 v=[mesh.verts[index] for index in bl.face.getVertices(face)]
419 uv=bl.mesh.getFaceUV(
420 mesh, i, face, bl.face.getVertexCount(face))
422 if faceVertexCount==3:
424 self.vertexArray.addTriangle(
425 obj_name, material.name,
432 bl.vertex.getNormal(v[2]),
433 bl.vertex.getNormal(v[1]),
434 bl.vertex.getNormal(v[0]),
438 weightMap[v[2].index][0],
439 weightMap[v[1].index][0],
440 weightMap[v[0].index][0],
441 secondWeightMap[v[2].index][0],
442 secondWeightMap[v[1].index][0],
443 secondWeightMap[v[0].index][0],
444 weightMap[v[2].index][1],
445 weightMap[v[1].index][1],
446 weightMap[v[0].index][1]
448 elif faceVertexCount==4:
450 self.vertexArray.addTriangle(
451 obj_name, material.name,
458 bl.vertex.getNormal(v[2]),
459 bl.vertex.getNormal(v[1]),
460 bl.vertex.getNormal(v[0]),
464 weightMap[v[2].index][0],
465 weightMap[v[1].index][0],
466 weightMap[v[0].index][0],
467 secondWeightMap[v[2].index][0],
468 secondWeightMap[v[1].index][0],
469 secondWeightMap[v[0].index][0],
470 weightMap[v[2].index][1],
471 weightMap[v[1].index][1],
472 weightMap[v[0].index][1]
474 self.vertexArray.addTriangle(
475 obj_name, material.name,
482 bl.vertex.getNormal(v[0]),
483 bl.vertex.getNormal(v[3]),
484 bl.vertex.getNormal(v[2]),
488 weightMap[v[0].index][0],
489 weightMap[v[3].index][0],
490 weightMap[v[2].index][0],
491 secondWeightMap[v[0].index][0],
492 secondWeightMap[v[3].index][0],
493 secondWeightMap[v[2].index][0],
494 weightMap[v[0].index][1],
495 weightMap[v[3].index][1],
496 weightMap[v[2].index][1]
499 def __mesh(self, obj):
503 if RIGID_SHAPE_TYPE in obj:
505 if CONSTRAINT_A in obj:
508 #if not bl.modifier.hasType(obj, 'ARMATURE'):
511 bl.message("export: %s" % obj.name)
513 # メッシュのコピーを生成してオブジェクトの行列を適用する
514 copyMesh, copyObj=bl.object.duplicate(obj)
515 if len(copyMesh.verts)>0:
517 copyObj.scale=obj.scale
518 bpy.ops.object.scale_apply()
519 copyObj.rotation_euler=obj.rotation_euler
520 bpy.ops.object.rotation_apply()
521 copyObj.location=obj.location
522 bpy.ops.object.location_apply()
524 for m in [m for m in copyObj.modifiers]:
525 if m.type=='SOLIDFY':
527 elif m.type=='ARMATURE':
529 elif m.type=='MIRROR':
530 bpy.ops.object.modifier_apply(modifier=m.name)
534 weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
535 self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
536 bl.object.delete(copyObj)
538 def createEmptyBasicSkin(self):
539 self.__getOrCreateMorph('base', 0)
541 def __skin(self, obj):
542 if not bl.object.hasShapeKey(obj):
546 blenderMesh=bl.object.getData(obj)
550 vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
554 for b in bl.object.getShapeKeys(obj):
555 if b.name==BASE_SHAPE_NAME:
556 baseMorph=self.__getOrCreateMorph('base', 0)
561 v=bl.shapekey.getByIndex(b, index)
562 pos=[v[0], v[1], v[2]]
564 indices=self.vertexArray.getMappedIndex(obj.name, index)
565 for attribute, i in indices.items():
570 baseMorph.add(i, pos)
571 indexRelativeMap[i]=relativeIndex
576 print(basis.name, len(baseMorph.offsets))
578 if len(baseMorph.offsets)==0:
582 for b in bl.object.getShapeKeys(obj):
583 if b.name==BASE_SHAPE_NAME:
587 morph=self.__getOrCreateMorph(b.name, 4)
589 for index, src, dst in zip(
590 xrange(len(blenderMesh.verts)),
591 bl.shapekey.get(basis),
593 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
594 if offset[0]==0 and offset[1]==0 and offset[2]==0:
597 indices=self.vertexArray.getMappedIndex(obj.name, index)
598 for attribute, i in indices.items():
602 morph.add(indexRelativeMap[i], offset)
603 assert(len(morph.offsets)<len(baseMorph.offsets))
606 original=self.morphList[:]
608 for i, v in enumerate(englishmap.skinMap):
612 return len(englishmap.skinMap)
614 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
616 self.morphList.sort(key=getIndex)
618 def __rigidbody(self, obj):
621 if not RIGID_SHAPE_TYPE in obj:
623 self.rigidbodies.append(obj)
625 def __constraint(self, obj):
628 if not CONSTRAINT_A in obj:
630 self.constraints.append(obj)
632 def __getOrCreateMorph(self, name, type):
633 for m in self.morphList:
637 self.morphList.append(m)
640 def getVertexCount(self):
641 return len(self.vertexArray.positions)
645 __slots__=['index', 'name', 'ik_index',
646 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
647 def __init__(self, name, pos, tail, isConnect):
652 self.parent_index=None
655 self.isConnect=isConnect
658 def __eq__(self, rhs):
659 return self.index==rhs.index
662 return "<Bone %s %d>" % (self.name, self.type)
664 class BoneBuilder(object):
665 __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
672 def getBoneGroup(self, bone):
673 for i, g in enumerate(self.bone_groups):
677 print('no gorup', bone)
680 def build(self, armatureObj):
684 bl.message("build skeleton")
685 armature=bl.object.getData(armatureObj)
690 for g in bl.object.boneGroups(armatureObj):
691 self.bone_groups.append((g.name, []))
696 for b in armature.bones.values():
700 bl.bone.getHeadLocal(b),
701 bl.bone.getTailLocal(b),
704 self.__getBone(bone, b)
706 for b in armature.bones.values():
708 self.__checkConnection(b, None)
713 pose = bl.object.getPose(armatureObj)
714 for b in pose.bones.values():
718 self.__assignBoneGroup(b, b.bone_group)
719 for c in b.constraints:
720 if bl.constraint.isIKSolver(c):
724 target=self.__boneByName(bl.constraint.ikTarget(c))
731 link=self.__boneByName(b.name)
736 chainLength=bl.constraint.ikChainLen(c)
737 for i in range(chainLength):
739 chainBone=self.__boneByName(e.name)
741 chainBone.ik_index=target.index
744 IKSolver(target, link, chainLength,
745 int(bl.constraint.ikItration(c) * 0.1),
746 bl.constraint.ikRotationWeight(c)
756 for i, v in enumerate(englishmap.boneMap):
757 if v[0]==ik.target.name:
759 return len(englishmap.boneMap)
761 self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
763 self.ik_list.sort(key=getIndex)
765 def __assignBoneGroup(self, poseBone, boneGroup):
767 for g in self.bone_groups:
768 if g[0]==boneGroup.name:
769 g[1].append(poseBone.name)
771 def __checkConnection(self, b, p):
772 if bl.bone.isConnected(b):
773 parent=self.__boneByName(p.name)
774 parent.isConnect=True
777 self.__checkConnection(c, b)
783 boneMap=englishmap.boneMap
784 original=self.bones[:]
786 for i, k_v in enumerate(boneMap):
787 if k_v[0]==bone.name:
793 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
795 self.bones.sort(key=getIndex)
798 for i, b in enumerate(self.bones):
799 src=original.index(b)
802 b.index=sortMap[b.index]
804 b.parent_index=sortMap[b.parent_index]
806 b.tail_index=sortMap[b.tail_index]
808 b.ik_index=sortMap[b.ik_index]
816 if b.parent_index==None:
817 b.parent_index=0xFFFF
819 if b.type==6 or b.type==7:
821 parent=self.bones[b.parent_index]
822 #print('parnet', parent.name)
823 parent.tail_index=b.index
826 if b.tail_index==None:
831 def getIndex(self, bone):
832 for i, b in enumerate(self.bones):
837 def indexByName(self, name):
841 return self.getIndex(self.__boneByName(name))
843 def __boneByName(self, name):
844 return self.boneMap[name]
846 def __getBone(self, parent, b):
847 if len(b.children)==0:
851 for i, c in enumerate(b.children):
853 bl.bone.getHeadLocal(c),
854 bl.bone.getTailLocal(c),
855 bl.bone.isConnected(c))
858 bone.parent_index=parent.index
860 if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
861 parent.tail_index=bone.index
862 self.__getBone(bone, c)
864 def __addBone(self, bone):
865 bone.index=len(self.bones)
866 self.bones.append(bone)
867 self.boneMap[bone.name]=bone
870 class PmdExporter(object):
882 self.armatureObj=None
886 for o in bl.object.each():
887 object_node_map[o]=Node(o)
888 for o in bl.object.each():
889 node=object_node_map[o]
891 object_node_map[node.o.parent].children.append(node)
894 root=object_node_map[bl.object.getActive()]
896 self.englishName=o.name
897 self.englishComment=o[MMD_COMMENT] if MMD_COMMENT in o else 'blender export\n'
898 self.name=o[MMD_MB_NAME] if MMD_MB_NAME in o else 'Blenderエクスポート'
899 self.comment=o[MMD_MB_COMMENT] if MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
902 self.oneSkinMesh=OneSkinMesh()
903 self.__createOneSkinMesh(root)
904 bl.message(self.oneSkinMesh)
905 if len(self.oneSkinMesh.morphList)==0:
907 self.oneSkinMesh.createEmptyBasicSkin()
910 self.skeleton=BoneBuilder()
911 self.skeleton.build(self.armatureObj)
913 def __createOneSkinMesh(self, node):
914 ############################################################
915 # search armature modifier
916 ############################################################
917 for m in node.o.modifiers:
918 if bl.modifier.isType(m, 'ARMATURE'):
919 armatureObj=bl.modifier.getArmatureObject(m)
920 if not self.armatureObj:
921 self.armatureObj=armatureObj
922 elif self.armatureObj!=armatureObj:
923 print("warning! found multiple armature. ignored.",
926 if node.o.type.upper()=='MESH':
927 self.oneSkinMesh.addMesh(node.o)
929 for child in node.children:
930 self.__createOneSkinMesh(child)
932 def write(self, path):
934 io.setName(toCP932(self.name))
935 io.setComment(toCP932(self.comment))
939 for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
940 # convert right-handed z-up to left-handed y-up
945 v.normal.x=attribute.nx
946 v.normal.y=attribute.ny
947 v.normal.z=attribute.nz
949 v.uv.y=1.0-attribute.v # reverse vertical
950 v.bone0=self.skeleton.indexByName(b0)
951 v.bone1=self.skeleton.indexByName(b1)
952 v.weight0=int(100*weight)
953 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
956 vertexCount=self.oneSkinMesh.getVertexCount()
957 for material_name, indices in self.oneSkinMesh.vertexArray.each():
958 #print('material:', material_name)
959 m=bl.material.get(material_name)
961 material=io.addMaterial()
962 setMaterialParams(material, m)
964 material.vertex_count=len(indices)
965 material.toon_index=0
966 textures=[os.path.basename(path)
967 for path in bl.material.eachEnalbeTexturePath(m)]
969 material.setTexture(toCP932('*'.join(textures)))
971 material.setTexture(toCP932(""))
974 assert(i<vertexCount)
975 for i in xrange(0, len(indices), 3):
977 io.indices.append(indices[i])
978 io.indices.append(indices[i+1])
979 io.indices.append(indices[i+2])
983 for i, b in enumerate(self.skeleton.bones):
987 boneNameMap[b.name]=i
988 v=englishmap.getUnicodeBoneName(b.name)
992 cp932=v[1].encode('cp932')
993 assert(len(cp932)<20)
997 bone_english_name=toCP932(b.name)
998 assert(len(bone_english_name)<20)
999 bone.setEnglishName(bone_english_name)
1004 b.ik_index=self.skeleton.indexByName('eyes')
1009 bone.parent_index=b.parent_index
1010 bone.tail_index=b.tail_index
1011 bone.ik_index=b.ik_index
1013 # convert right-handed z-up to left-handed y-up
1014 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
1015 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
1016 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
1019 for ik in self.skeleton.ik_list:
1021 solver.index=self.skeleton.getIndex(ik.target)
1022 solver.target=self.skeleton.getIndex(ik.effector)
1023 solver.length=ik.length
1024 b=self.skeleton.bones[ik.effector.parent_index]
1025 for i in xrange(solver.length):
1026 solver.children.append(self.skeleton.getIndex(b))
1027 b=self.skeleton.bones[b.parent_index]
1028 solver.iterations=ik.iterations
1029 solver.weight=ik.weight
1032 for i, m in enumerate(self.oneSkinMesh.morphList):
1036 v=englishmap.getUnicodeSkinName(m.name)
1038 v=[m.name, m.name, 0]
1040 cp932=v[1].encode('cp932')
1041 morph.setName(cp932)
1042 morph.setEnglishName(m.name.encode('cp932'))
1045 for index, offset in m.offsets:
1046 # convert right-handed z-up to left-handed y-up
1047 morph.append(index, offset[0], offset[2], offset[1])
1048 morph.vertex_count=len(m.offsets)
1052 for i, m in enumerate(self.oneSkinMesh.morphList):
1054 io.face_list.append(i)
1055 for i, m in enumerate(self.oneSkinMesh.morphList):
1057 io.face_list.append(i)
1058 for i, m in enumerate(self.oneSkinMesh.morphList):
1060 io.face_list.append(i)
1061 for i, m in enumerate(self.oneSkinMesh.morphList):
1063 io.face_list.append(i)
1066 for g in self.skeleton.bone_groups:
1067 boneDisplayName=io.addBoneGroup()
1069 name=englishmap.getUnicodeBoneGroupName(g[0])
1072 boneDisplayName.setName(toCP932(name+'\n'))
1075 boneDisplayName.setEnglishName(toCP932(englishName+'\n'))
1078 for i, b in enumerate(self.skeleton.bones):
1081 if b.type in [6, 7]:
1083 io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1085 #assert(len(io.bones)==len(io.bone_display_list)+1)
1088 io.setEnglishName(toCP932(self.englishName))
1089 io.setEnglishComment(toCP932(self.englishComment))
1093 for o in bl.object.each():
1095 if o.name.startswith(TOON_TEXTURE_OBJECT):
1101 toonMesh=bl.object.getData(toonMeshObject)
1102 toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1104 t=bl.material.getTexture(toonMaterial, i)
1106 io.getToonTexture(i).setName(toCP932(t.name))
1108 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1111 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1115 for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1116 name=obj[RIGID_NAME] if RIGID_NAME in obj else obj.name
1118 rigidBody=io.addRigidBody()
1119 rigidBody.setName(name.encode('cp932'))
1120 rigidNameMap[name]=i
1121 boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1124 bone=self.skeleton.bones[0]
1126 bone=self.skeleton.bones[boneIndex]
1127 rigidBody.boneIndex=boneIndex
1128 #rigidBody.position.x=obj[RIGID_LOCATION][0]
1129 #rigidBody.position.y=obj[RIGID_LOCATION][1]
1130 #rigidBody.position.z=obj[RIGID_LOCATION][2]
1131 rigidBody.position.x=obj.location.x-bone.pos[0]
1132 rigidBody.position.y=obj.location.z-bone.pos[2]
1133 rigidBody.position.z=obj.location.y-bone.pos[1]
1134 rigidBody.rotation.x=-obj.rotation_euler[0]
1135 rigidBody.rotation.y=-obj.rotation_euler[2]
1136 rigidBody.rotation.z=-obj.rotation_euler[1]
1137 rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1138 rigidBody.group=obj[RIGID_GROUP]
1139 rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1140 rigidBody.weight=obj[RIGID_WEIGHT]
1141 rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1142 rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1143 rigidBody.restitution=obj[RIGID_RESTITUTION]
1144 rigidBody.friction=obj[RIGID_FRICTION]
1145 if obj[RIGID_SHAPE_TYPE]==0:
1146 rigidBody.shapeType=pmd.SHAPE_SPHERE
1147 rigidBody.w=obj.scale[0]
1148 elif obj[RIGID_SHAPE_TYPE]==1:
1149 rigidBody.shapeType=pmd.SHAPE_BOX
1150 rigidBody.w=obj.scale[0]
1151 rigidBody.d=obj.scale[1]
1152 rigidBody.h=obj.scale[2]
1153 elif obj[RIGID_SHAPE_TYPE]==2:
1154 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1155 rigidBody.w=obj.scale[0]
1156 rigidBody.h=obj.scale[2]
1159 for obj in self.oneSkinMesh.constraints:
1160 constraint=io.addConstraint()
1161 constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1162 constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1163 constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1164 constraint.pos.x=obj.location[0]
1165 constraint.pos.y=obj.location[2]
1166 constraint.pos.z=obj.location[1]
1167 constraint.rot.x=-obj.rotation_euler[0]
1168 constraint.rot.y=-obj.rotation_euler[2]
1169 constraint.rot.z=-obj.rotation_euler[1]
1170 constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1171 constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1172 constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1173 constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1174 constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1175 constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1176 constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1177 constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1178 constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1179 constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1180 constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1181 constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1182 constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1183 constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1184 constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1185 constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1186 constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1187 constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1190 bl.message('write %s' % path)
1191 return io.write(path)
1194 def __execute(filename):
1195 active=bl.object.getActive()
1197 print("abort. no active object.")
1199 exporter=PmdExporter()
1202 exporter.write(filename)
1203 bl.object.activate(active)
1208 def execute_24(filename):
1209 bl.initialize('pmd_export', bpy.data.scenes.active)
1210 __execute(filename.decode(bl.INTERNAL_ENCODING))
1213 Blender.Window.FileSelector(
1215 'Export Metasequoia PMD',
1216 Blender.sys.makename(ext='.pmd'))
1220 def execute_25(filename, scene):
1221 bl.initialize('pmd_export', scene)
1226 class EXPORT_OT_pmd(bpy.types.Operator):
1227 '''Save a Metasequoia PMD file.'''
1228 bl_idname = "export_scene.pmd"
1229 bl_label = 'Export PMD'
1231 # List of operator properties, the attributes will be assigned
1232 # to the class instance from the operator settings before calling.
1233 filepath = bpy.props.StringProperty()
1234 filename = bpy.props.StringProperty()
1235 directory = bpy.props.StringProperty()
1237 def execute(self, context):
1239 self.properties.filepath,
1244 def invoke(self, context, event):
1246 wm.add_fileselect(self)
1247 return 'RUNNING_MODAL'
1250 def menu_func(self, context):
1251 default_path=bpy.data.filepath.replace(".blend", ".pmd")
1252 self.layout.operator(
1253 EXPORT_OT_pmd.bl_idname,
1254 text="Miku Miku Dance Model(.pmd)",
1256 ).filepath=default_path
1259 bpy.types.register(EXPORT_OT_pmd)
1260 bpy.types.INFO_MT_file_export.append(menu_func)
1263 bpy.types.unregister(EXPORT_OT_pmd)
1264 bpy.types.INFO_MT_file_export.remove(menu_func)
1266 if __name__ == "__main__":