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
81 print('use meshio C module')
84 from pymeshio import englishmap
85 from pymeshio import mmd as pmd
89 return sys.version_info[0]<3
94 from Blender import Mathutils
100 def setMaterialParams(material, m):
102 material.diffuse.r=m.R
103 material.diffuse.g=m.G
104 material.diffuse.b=m.B
105 material.diffuse.a=m.alpha
107 material.shinness=0 if m.spec<1e-5 else m.spec*10
108 material.specular.r=m.specR
109 material.specular.g=m.specG
110 material.specular.b=m.specB
112 material.ambient.r=m.mirR
113 material.ambient.g=m.mirG
114 material.ambient.b=m.mirB
116 material.flag=1 if m.enableSSS else 0
132 def setMaterialParams(material, m):
134 material.diffuse.r=m.diffuse_color[0]
135 material.diffuse.g=m.diffuse_color[1]
136 material.diffuse.b=m.diffuse_color[2]
137 material.diffuse.a=m.alpha
139 material.shinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
140 material.specular.r=m.specular_color[0]
141 material.specular.g=m.specular_color[1]
142 material.specular.b=m.specular_color[2]
144 material.ambient.r=m.mirror_color[0]
145 material.ambient.g=m.mirror_color[1]
146 material.ambient.b=m.mirror_color[2]
148 material.flag=1 if m.subsurface_scattering.enabled else 0
150 material.toon_index=7
153 return s.encode('cp932')
157 __slots__=['o', 'children']
158 def __init__(self, o):
163 ###############################################################################
164 # Blenderのメッシュをワンスキンメッシュ化する
165 ###############################################################################
166 def near(x, y, EPSILON=1e-5):
168 return d>=-EPSILON and d<=EPSILON
171 class VertexAttribute(object):
173 'nx', 'ny', 'nz', # normal
176 def __init__(self, nx, ny, nz, u, v):
184 return "<vkey: %f, %f, %f, %f, %f>" % (
185 self.nx, self.ny, self.nz, self.u, self.v)
188 return self.nx + self.ny + self.nz + self.u + self.v
190 def __eq__(self, rhs):
191 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
194 class VertexKey(object):
196 'obj_index', 'index',
199 def __init__(self, obj_index, index):
200 self.obj_index=obj_index
204 return "<vkey: %d, %d>" % (self.obj_index, self.index)
207 return self.index*100+self.obj_index
209 def __eq__(self, rhs):
210 return self.obj_index==rhs.obj_index and self.index==rhs.index
213 class VertexArray(object):
220 'attributes', # normal and uv
221 'b0', 'b1', 'weight',
226 # indexArrays split with each material
239 return "<VertexArray %d positions, %d indexArrays>" % (
240 len(self.positions), len(self.indexArrays))
244 self.positions, self.attributes,
245 self.b0, self.b1, self.weight)
248 keys=[key for key in self.indexArrays.keys()]
251 yield(key, self.indexArrays[key])
253 def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
254 key=VertexKey(obj_index, base_index)
255 attribute=VertexAttribute(
256 normal[0], normal[1], normal[2],
258 if key in self.vertexMap:
259 if attribute in self.vertexMap[key]:
260 return self.vertexMap[key][attribute]
262 return self.__addVertex(self.vertexMap[key],
263 pos, attribute, b0, b1, weight0)
266 self.vertexMap[key]=vertexMapKey
267 return self.__addVertex(vertexMapKey,
268 pos, attribute, b0, b1, weight0)
270 def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
271 index=len(self.positions)
272 vertexMapKey[attribute]=index
274 self.positions.append((pos.x, pos.y, pos.z))
276 self.attributes.append(attribute)
280 self.weight.append(weight0)
284 def getMappedIndex(self, obj_name, base_index):
285 return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
287 def addTriangle(self,
288 object_name, material,
289 base_index0, base_index1, base_index2,
295 weight0, weight1, weight2
297 if object_name in self.objectMap:
298 obj_index=self.objectMap[object_name]
300 obj_index=len(self.objectMap)
301 self.objectMap[object_name]=obj_index
302 index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
303 index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
304 index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
306 if not material in self.indexArrays:
307 self.indexArrays[material]=[]
308 self.indexArrays[material]+=[index0, index1, index2]
312 __slots__=['name', 'type', 'offsets']
313 def __init__(self, name, type):
318 def add(self, index, offset):
319 self.offsets.append((index, offset))
323 self.offsets.sort(lambda l, r: l[0]-r[0])
325 self.offsets.sort(key=lambda e: e[0])
328 return "<Morph %s>" % self.name
330 class IKSolver(object):
331 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
332 def __init__(self, target, effector, length, iterations, weight):
334 self.effector=effector
336 self.iterations=iterations
340 class OneSkinMesh(object):
341 __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
343 self.vertexArray=VertexArray()
349 return "<OneSkinMesh %s, morph:%d>" % (
353 def addMesh(self, obj):
354 if not bl.object.isVisible(obj):
358 self.__rigidbody(obj)
359 self.__constraint(obj)
361 def __getWeightMap(self, obj, mesh):
365 def setWeight(i, name, w):
368 if i in secondWeightMap:
370 if w<secondWeightMap[i][1]:
372 elif w<weightMap[i][1]:
374 secondWeightMap[i]=(name, w)
377 weightMap[i]=(name, w)
379 if w>weightMap[i][1]:
381 secondWeightMap[i]=weightMap[i]
382 weightMap[i]=(name, w)
384 secondWeightMap[i]=(name, w)
386 weightMap[i]=(name, w)
388 # ToDo bone weightと関係ないvertex groupを除外する
390 for name in bl.object.getVertexGroupNames(obj):
391 for i, w in mesh.getVertsFromGroup(name, 1):
392 setWeight(i, name, w)
394 for i, v in enumerate(mesh.verts):
397 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
399 setWeight(i, obj.vertex_groups[0].name, 1)
402 for i in xrange(len(mesh.verts)):
403 if i in secondWeightMap:
404 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
406 weightMap[i]=(weightMap[i][0], 1.0)
407 secondWeightMap[i]=("", 0)
409 print("no weight vertex")
411 secondWeightMap[i]=("", 0)
413 return weightMap, secondWeightMap
415 def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
417 for i, face in enumerate(mesh.faces):
418 faceVertexCount=bl.face.getVertexCount(face)
419 material=mesh.materials[bl.face.getMaterialIndex(face)]
420 v=[mesh.verts[index] for index in bl.face.getVertices(face)]
421 uv=bl.mesh.getFaceUV(
422 mesh, i, face, bl.face.getVertexCount(face))
424 if faceVertexCount==3:
426 self.vertexArray.addTriangle(
427 obj_name, material.name,
434 bl.vertex.getNormal(v[2]),
435 bl.vertex.getNormal(v[1]),
436 bl.vertex.getNormal(v[0]),
440 weightMap[v[2].index][0],
441 weightMap[v[1].index][0],
442 weightMap[v[0].index][0],
443 secondWeightMap[v[2].index][0],
444 secondWeightMap[v[1].index][0],
445 secondWeightMap[v[0].index][0],
446 weightMap[v[2].index][1],
447 weightMap[v[1].index][1],
448 weightMap[v[0].index][1]
450 elif faceVertexCount==4:
452 self.vertexArray.addTriangle(
453 obj_name, material.name,
460 bl.vertex.getNormal(v[2]),
461 bl.vertex.getNormal(v[1]),
462 bl.vertex.getNormal(v[0]),
466 weightMap[v[2].index][0],
467 weightMap[v[1].index][0],
468 weightMap[v[0].index][0],
469 secondWeightMap[v[2].index][0],
470 secondWeightMap[v[1].index][0],
471 secondWeightMap[v[0].index][0],
472 weightMap[v[2].index][1],
473 weightMap[v[1].index][1],
474 weightMap[v[0].index][1]
476 self.vertexArray.addTriangle(
477 obj_name, material.name,
484 bl.vertex.getNormal(v[0]),
485 bl.vertex.getNormal(v[3]),
486 bl.vertex.getNormal(v[2]),
490 weightMap[v[0].index][0],
491 weightMap[v[3].index][0],
492 weightMap[v[2].index][0],
493 secondWeightMap[v[0].index][0],
494 secondWeightMap[v[3].index][0],
495 secondWeightMap[v[2].index][0],
496 weightMap[v[0].index][1],
497 weightMap[v[3].index][1],
498 weightMap[v[2].index][1]
501 def __mesh(self, obj):
505 if RIGID_SHAPE_TYPE in obj:
507 if CONSTRAINT_A in obj:
510 #if not bl.modifier.hasType(obj, 'ARMATURE'):
513 bl.message("export: %s" % obj.name)
515 # メッシュのコピーを生成してオブジェクトの行列を適用する
516 copyMesh, copyObj=bl.object.duplicate(obj)
517 if len(copyMesh.verts)>0:
519 copyObj.scale=obj.scale
520 bpy.ops.object.scale_apply()
521 copyObj.rotation_euler=obj.rotation_euler
522 bpy.ops.object.rotation_apply()
523 copyObj.location=obj.location
524 bpy.ops.object.location_apply()
526 for m in [m for m in copyObj.modifiers]:
527 if m.type=='SOLIDFY':
529 elif m.type=='ARMATURE':
531 elif m.type=='MIRROR':
532 bpy.ops.object.modifier_apply(modifier=m.name)
536 weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
537 self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
538 bl.object.delete(copyObj)
540 def createEmptyBasicSkin(self):
541 self.__getOrCreateMorph('base', 0)
543 def __skin(self, obj):
544 if not bl.object.hasShapeKey(obj):
548 blenderMesh=bl.object.getData(obj)
552 vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
556 for b in bl.object.getShapeKeys(obj):
557 if b.name==BASE_SHAPE_NAME:
558 baseMorph=self.__getOrCreateMorph('base', 0)
563 v=bl.shapekey.getByIndex(b, index)
564 pos=[v[0], v[1], v[2]]
566 indices=self.vertexArray.getMappedIndex(obj.name, index)
567 for attribute, i in indices.items():
572 baseMorph.add(i, pos)
573 indexRelativeMap[i]=relativeIndex
578 print(basis.name, len(baseMorph.offsets))
580 if len(baseMorph.offsets)==0:
584 for b in bl.object.getShapeKeys(obj):
585 if b.name==BASE_SHAPE_NAME:
589 morph=self.__getOrCreateMorph(b.name, 4)
591 for index, src, dst in zip(
592 xrange(len(blenderMesh.verts)),
593 bl.shapekey.get(basis),
595 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
596 if offset[0]==0 and offset[1]==0 and offset[2]==0:
599 indices=self.vertexArray.getMappedIndex(obj.name, index)
600 for attribute, i in indices.items():
604 morph.add(indexRelativeMap[i], offset)
605 assert(len(morph.offsets)<len(baseMorph.offsets))
608 original=self.morphList[:]
610 for i, v in enumerate(englishmap.skinMap):
614 return len(englishmap.skinMap)
616 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
618 self.morphList.sort(key=getIndex)
620 def __rigidbody(self, obj):
623 if not RIGID_SHAPE_TYPE in obj:
625 self.rigidbodies.append(obj)
627 def __constraint(self, obj):
630 if not CONSTRAINT_A in obj:
632 self.constraints.append(obj)
634 def __getOrCreateMorph(self, name, type):
635 for m in self.morphList:
639 self.morphList.append(m)
642 def getVertexCount(self):
643 return len(self.vertexArray.positions)
647 __slots__=['index', 'name', 'ik_index',
648 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
649 def __init__(self, name, pos, tail, isConnect):
654 self.parent_index=None
657 self.isConnect=isConnect
660 def __eq__(self, rhs):
661 return self.index==rhs.index
664 return "<Bone %s %d>" % (self.name, self.type)
666 class BoneBuilder(object):
667 __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
674 def getBoneGroup(self, bone):
675 for i, g in enumerate(self.bone_groups):
679 print('no gorup', bone)
682 def build(self, armatureObj):
686 bl.message("build skeleton")
687 armature=bl.object.getData(armatureObj)
692 for g in bl.object.boneGroups(armatureObj):
693 self.bone_groups.append((g.name, []))
698 for b in armature.bones.values():
702 bl.bone.getHeadLocal(b),
703 bl.bone.getTailLocal(b),
706 self.__getBone(bone, b)
708 for b in armature.bones.values():
710 self.__checkConnection(b, None)
715 pose = bl.object.getPose(armatureObj)
716 for b in pose.bones.values():
720 self.__assignBoneGroup(b, b.bone_group)
721 for c in b.constraints:
722 if bl.constraint.isIKSolver(c):
726 target=self.__boneByName(bl.constraint.ikTarget(c))
733 link=self.__boneByName(b.name)
738 chainLength=bl.constraint.ikChainLen(c)
739 for i in range(chainLength):
741 chainBone=self.__boneByName(e.name)
743 chainBone.ik_index=target.index
746 IKSolver(target, link, chainLength,
747 int(bl.constraint.ikItration(c) * 0.1),
748 bl.constraint.ikRotationWeight(c)
758 for i, v in enumerate(englishmap.boneMap):
759 if v[0]==ik.target.name:
761 return len(englishmap.boneMap)
763 self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
765 self.ik_list.sort(key=getIndex)
767 def __assignBoneGroup(self, poseBone, boneGroup):
769 for g in self.bone_groups:
770 if g[0]==boneGroup.name:
771 g[1].append(poseBone.name)
773 def __checkConnection(self, b, p):
774 if bl.bone.isConnected(b):
775 parent=self.__boneByName(p.name)
776 parent.isConnect=True
779 self.__checkConnection(c, b)
785 boneMap=englishmap.boneMap
786 original=self.bones[:]
788 for i, k_v in enumerate(boneMap):
789 if k_v[0]==bone.name:
795 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
797 self.bones.sort(key=getIndex)
800 for i, b in enumerate(self.bones):
801 src=original.index(b)
804 b.index=sortMap[b.index]
806 b.parent_index=sortMap[b.parent_index]
808 b.tail_index=sortMap[b.tail_index]
810 b.ik_index=sortMap[b.ik_index]
818 if b.parent_index==None:
819 b.parent_index=0xFFFF
821 if b.type==6 or b.type==7:
823 parent=self.bones[b.parent_index]
824 #print('parnet', parent.name)
825 parent.tail_index=b.index
828 if b.tail_index==None:
833 def getIndex(self, bone):
834 for i, b in enumerate(self.bones):
839 def indexByName(self, name):
843 return self.getIndex(self.__boneByName(name))
845 def __boneByName(self, name):
846 return self.boneMap[name]
848 def __getBone(self, parent, b):
849 if len(b.children)==0:
853 for i, c in enumerate(b.children):
855 bl.bone.getHeadLocal(c),
856 bl.bone.getTailLocal(c),
857 bl.bone.isConnected(c))
860 bone.parent_index=parent.index
862 if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
863 parent.tail_index=bone.index
864 self.__getBone(bone, c)
866 def __addBone(self, bone):
867 bone.index=len(self.bones)
868 self.bones.append(bone)
869 self.boneMap[bone.name]=bone
872 class PmdExporter(object):
884 self.armatureObj=None
888 for o in bl.object.each():
889 object_node_map[o]=Node(o)
890 for o in bl.object.each():
891 node=object_node_map[o]
893 object_node_map[node.o.parent].children.append(node)
896 root=object_node_map[bl.object.getActive()]
898 self.englishName=o.name
899 self.englishComment=o[MMD_COMMENT] if MMD_COMMENT in o else 'blender export\n'
900 self.name=o[MMD_MB_NAME] if MMD_MB_NAME in o else 'Blenderエクスポート'
901 self.comment=o[MMD_MB_COMMENT] if MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
904 self.oneSkinMesh=OneSkinMesh()
905 self.__createOneSkinMesh(root)
906 bl.message(self.oneSkinMesh)
907 if len(self.oneSkinMesh.morphList)==0:
909 self.oneSkinMesh.createEmptyBasicSkin()
912 self.skeleton=BoneBuilder()
913 self.skeleton.build(self.armatureObj)
915 def __createOneSkinMesh(self, node):
916 ############################################################
917 # search armature modifier
918 ############################################################
919 for m in node.o.modifiers:
920 if bl.modifier.isType(m, 'ARMATURE'):
921 armatureObj=bl.modifier.getArmatureObject(m)
922 if not self.armatureObj:
923 self.armatureObj=armatureObj
924 elif self.armatureObj!=armatureObj:
925 print("warning! found multiple armature. ignored.",
928 if node.o.type.upper()=='MESH':
929 self.oneSkinMesh.addMesh(node.o)
931 for child in node.children:
932 self.__createOneSkinMesh(child)
934 def write(self, path):
936 io.setName(toCP932(self.name))
937 io.setComment(toCP932(self.comment))
941 for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
942 # convert right-handed z-up to left-handed y-up
947 v.normal.x=attribute.nx
948 v.normal.y=attribute.ny
949 v.normal.z=attribute.nz
951 v.uv.y=1.0-attribute.v # reverse vertical
952 v.bone0=self.skeleton.indexByName(b0)
953 v.bone1=self.skeleton.indexByName(b1)
954 v.weight0=int(100*weight)
955 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
958 vertexCount=self.oneSkinMesh.getVertexCount()
959 for material_name, indices in self.oneSkinMesh.vertexArray.each():
960 #print('material:', material_name)
961 m=bl.material.get(material_name)
963 material=io.addMaterial()
964 setMaterialParams(material, m)
966 material.vertex_count=len(indices)
967 material.toon_index=0
968 textures=[os.path.basename(path)
969 for path in bl.material.eachEnalbeTexturePath(m)]
971 material.setTexture(toCP932('*'.join(textures)))
973 material.setTexture(toCP932(""))
976 assert(i<vertexCount)
977 for i in xrange(0, len(indices), 3):
979 io.indices.append(indices[i])
980 io.indices.append(indices[i+1])
981 io.indices.append(indices[i+2])
985 for i, b in enumerate(self.skeleton.bones):
989 boneNameMap[b.name]=i
990 v=englishmap.getUnicodeBoneName(b.name)
994 cp932=v[1].encode('cp932')
995 assert(len(cp932)<20)
999 bone_english_name=toCP932(b.name)
1000 assert(len(bone_english_name)<20)
1001 bone.setEnglishName(bone_english_name)
1006 b.ik_index=self.skeleton.indexByName('eyes')
1011 bone.parent_index=b.parent_index
1012 bone.tail_index=b.tail_index
1013 bone.ik_index=b.ik_index
1015 # convert right-handed z-up to left-handed y-up
1016 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
1017 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
1018 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
1021 for ik in self.skeleton.ik_list:
1023 solver.index=self.skeleton.getIndex(ik.target)
1024 solver.target=self.skeleton.getIndex(ik.effector)
1025 solver.length=ik.length
1026 b=self.skeleton.bones[ik.effector.parent_index]
1027 for i in xrange(solver.length):
1028 solver.children.append(self.skeleton.getIndex(b))
1029 b=self.skeleton.bones[b.parent_index]
1030 solver.iterations=ik.iterations
1031 solver.weight=ik.weight
1034 for i, m in enumerate(self.oneSkinMesh.morphList):
1038 v=englishmap.getUnicodeSkinName(m.name)
1040 v=[m.name, m.name, 0]
1042 cp932=v[1].encode('cp932')
1043 morph.setName(cp932)
1044 morph.setEnglishName(m.name.encode('cp932'))
1047 for index, offset in m.offsets:
1048 # convert right-handed z-up to left-handed y-up
1049 morph.append(index, offset[0], offset[2], offset[1])
1050 morph.vertex_count=len(m.offsets)
1054 for i, m in enumerate(self.oneSkinMesh.morphList):
1056 io.face_list.append(i)
1057 for i, m in enumerate(self.oneSkinMesh.morphList):
1059 io.face_list.append(i)
1060 for i, m in enumerate(self.oneSkinMesh.morphList):
1062 io.face_list.append(i)
1063 for i, m in enumerate(self.oneSkinMesh.morphList):
1065 io.face_list.append(i)
1068 for g in self.skeleton.bone_groups:
1069 boneDisplayName=io.addBoneGroup()
1071 name=englishmap.getUnicodeBoneGroupName(g[0])
1074 boneDisplayName.setName(toCP932(name+'\n'))
1077 boneDisplayName.setEnglishName(toCP932(englishName+'\n'))
1080 for i, b in enumerate(self.skeleton.bones):
1083 if b.type in [6, 7]:
1085 io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1087 #assert(len(io.bones)==len(io.bone_display_list)+1)
1090 io.setEnglishName(toCP932(self.englishName))
1091 io.setEnglishComment(toCP932(self.englishComment))
1095 for o in bl.object.each():
1097 if o.name.startswith(TOON_TEXTURE_OBJECT):
1103 toonMesh=bl.object.getData(toonMeshObject)
1104 toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1106 t=bl.material.getTexture(toonMaterial, i)
1108 io.getToonTexture(i).setName(toCP932(t.name))
1110 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1113 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1117 for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1118 name=obj[RIGID_NAME] if RIGID_NAME in obj else obj.name
1120 rigidBody=io.addRigidBody()
1121 rigidBody.setName(name.encode('cp932'))
1122 rigidNameMap[name]=i
1123 boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1126 bone=self.skeleton.bones[0]
1128 bone=self.skeleton.bones[boneIndex]
1129 rigidBody.boneIndex=boneIndex
1130 #rigidBody.position.x=obj[RIGID_LOCATION][0]
1131 #rigidBody.position.y=obj[RIGID_LOCATION][1]
1132 #rigidBody.position.z=obj[RIGID_LOCATION][2]
1133 rigidBody.position.x=obj.location.x-bone.pos[0]
1134 rigidBody.position.y=obj.location.z-bone.pos[2]
1135 rigidBody.position.z=obj.location.y-bone.pos[1]
1136 rigidBody.rotation.x=-obj.rotation_euler[0]
1137 rigidBody.rotation.y=-obj.rotation_euler[2]
1138 rigidBody.rotation.z=-obj.rotation_euler[1]
1139 rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1140 rigidBody.group=obj[RIGID_GROUP]
1141 rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1142 rigidBody.weight=obj[RIGID_WEIGHT]
1143 rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1144 rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1145 rigidBody.restitution=obj[RIGID_RESTITUTION]
1146 rigidBody.friction=obj[RIGID_FRICTION]
1147 if obj[RIGID_SHAPE_TYPE]==0:
1148 rigidBody.shapeType=pmd.SHAPE_SPHERE
1149 rigidBody.w=obj.scale[0]
1150 elif obj[RIGID_SHAPE_TYPE]==1:
1151 rigidBody.shapeType=pmd.SHAPE_BOX
1152 rigidBody.w=obj.scale[0]
1153 rigidBody.d=obj.scale[1]
1154 rigidBody.h=obj.scale[2]
1155 elif obj[RIGID_SHAPE_TYPE]==2:
1156 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1157 rigidBody.w=obj.scale[0]
1158 rigidBody.h=obj.scale[2]
1161 for obj in self.oneSkinMesh.constraints:
1162 constraint=io.addConstraint()
1163 constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1164 constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1165 constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1166 constraint.pos.x=obj.location[0]
1167 constraint.pos.y=obj.location[2]
1168 constraint.pos.z=obj.location[1]
1169 constraint.rot.x=-obj.rotation_euler[0]
1170 constraint.rot.y=-obj.rotation_euler[2]
1171 constraint.rot.z=-obj.rotation_euler[1]
1172 constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1173 constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1174 constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1175 constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1176 constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1177 constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1178 constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1179 constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1180 constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1181 constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1182 constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1183 constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1184 constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1185 constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1186 constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1187 constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1188 constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1189 constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1192 bl.message('write: %s' % path)
1193 return io.write(path)
1196 def __execute(filename):
1197 active=bl.object.getActive()
1199 print("abort. no active object.")
1201 exporter=PmdExporter()
1204 exporter.write(filename)
1205 bl.object.activate(active)
1210 def execute_24(filename):
1211 bl.initialize('pmd_export', bpy.data.scenes.active)
1212 __execute(filename.decode(bl.INTERNAL_ENCODING))
1215 Blender.Window.FileSelector(
1217 'Export Metasequoia PMD',
1218 Blender.sys.makename(ext='.pmd'))
1222 def execute_25(filename, scene):
1223 bl.initialize('pmd_export', scene)
1228 class EXPORT_OT_pmd(bpy.types.Operator):
1229 '''Save a Metasequoia PMD file.'''
1230 bl_idname = "export_scene.pmd"
1231 bl_label = 'Export PMD'
1233 # List of operator properties, the attributes will be assigned
1234 # to the class instance from the operator settings before calling.
1235 filepath = bpy.props.StringProperty()
1236 filename = bpy.props.StringProperty()
1237 directory = bpy.props.StringProperty()
1239 def execute(self, context):
1241 self.properties.filepath,
1246 def invoke(self, context, event):
1248 wm.add_fileselect(self)
1249 return 'RUNNING_MODAL'
1252 def menu_func(self, context):
1253 default_path=bpy.data.filepath.replace(".blend", ".pmd")
1254 self.layout.operator(
1255 EXPORT_OT_pmd.bl_idname,
1256 text="Miku Miku Dance Model(.pmd)",
1258 ).filepath=default_path
1261 bpy.types.register(EXPORT_OT_pmd)
1262 bpy.types.INFO_MT_file_export.append(menu_func)
1265 bpy.types.unregister(EXPORT_OT_pmd)
1266 bpy.types.INFO_MT_file_export.remove(menu_func)
1268 if __name__ == "__main__":