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.
29 2.2 20101005: update for Blender2.54.
33 'category': 'Import/Export',
34 'name': 'Export: MikuMikuDance Model Format (.pmd)',
38 'location': 'File > Export',
39 'description': 'Export to the MikuMikuDance Model Format (.pmd)',
40 'warning': '', # used for warning icon and text in addons panel
41 'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
42 'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
45 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
47 MMD_MB_COMMENT='mb_comment'
49 BASE_SHAPE_NAME='Basis'
50 RIGID_NAME='rigid_name'
51 RIGID_SHAPE_TYPE='rigid_shape_type'
52 RIGID_PROCESS_TYPE='rigid_process_type'
53 RIGID_BONE_NAME='rigid_bone_name'
54 #RIGID_LOCATION='rigid_loation'
55 RIGID_GROUP='ribid_group'
56 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
57 RIGID_WEIGHT='rigid_weight'
58 RIGID_LINEAR_DAMPING='rigid_linear_damping'
59 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
60 RIGID_RESTITUTION='rigid_restitution'
61 RIGID_FRICTION='rigid_friction'
62 CONSTRAINT_NAME='constraint_name'
63 CONSTRAINT_A='const_a'
64 CONSTRAINT_B='const_b'
65 CONSTRAINT_POS_MIN='const_pos_min'
66 CONSTRAINT_POS_MAX='const_pos_max'
67 CONSTRAINT_ROT_MIN='const_rot_min'
68 CONSTRAINT_ROT_MAX='const_rot_max'
69 CONSTRAINT_SPRING_POS='const_spring_pos'
70 CONSTRAINT_SPRING_ROT='const_spring_rot'
71 TOON_TEXTURE_OBJECT='ToonTextures'
74 ###############################################################################
76 ###############################################################################
82 from meshio import pmd, englishmap
83 print('use meshio C module')
86 from pymeshio import englishmap
87 from pymeshio import mmd as pmd
91 return sys.version_info[0]<3
96 from Blender import Mathutils
102 def setMaterialParams(material, m):
104 material.diffuse.r=m.R
105 material.diffuse.g=m.G
106 material.diffuse.b=m.B
107 material.diffuse.a=m.alpha
109 material.shinness=0 if m.spec<1e-5 else m.spec*10
110 material.specular.r=m.specR
111 material.specular.g=m.specG
112 material.specular.b=m.specB
114 material.ambient.r=m.mirR
115 material.ambient.g=m.mirG
116 material.ambient.b=m.mirB
118 material.flag=1 if m.enableSSS else 0
134 def setMaterialParams(material, m):
136 material.diffuse.r=m.diffuse_color[0]
137 material.diffuse.g=m.diffuse_color[1]
138 material.diffuse.b=m.diffuse_color[2]
139 material.diffuse.a=m.alpha
141 material.shinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
142 material.specular.r=m.specular_color[0]
143 material.specular.g=m.specular_color[1]
144 material.specular.b=m.specular_color[2]
146 material.ambient.r=m.mirror_color[0]
147 material.ambient.g=m.mirror_color[1]
148 material.ambient.b=m.mirror_color[2]
150 material.flag=1 if m.subsurface_scattering.enabled else 0
152 material.toon_index=7
155 return s.encode('cp932')
159 __slots__=['o', 'children']
160 def __init__(self, o):
165 ###############################################################################
166 # Blenderのメッシュをワンスキンメッシュ化する
167 ###############################################################################
168 def near(x, y, EPSILON=1e-5):
170 return d>=-EPSILON and d<=EPSILON
173 class VertexAttribute(object):
175 'nx', 'ny', 'nz', # normal
178 def __init__(self, nx, ny, nz, u, v):
186 return "<vkey: %f, %f, %f, %f, %f>" % (
187 self.nx, self.ny, self.nz, self.u, self.v)
190 return self.nx + self.ny + self.nz + self.u + self.v
192 def __eq__(self, rhs):
193 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
196 class VertexKey(object):
198 'obj_index', 'index',
201 def __init__(self, obj_index, index):
202 self.obj_index=obj_index
206 return "<vkey: %d, %d>" % (self.obj_index, self.index)
209 return self.index*100+self.obj_index
211 def __eq__(self, rhs):
212 return self.obj_index==rhs.obj_index and self.index==rhs.index
215 class VertexArray(object):
222 'attributes', # normal and uv
223 'b0', 'b1', 'weight',
228 # indexArrays split with each material
241 return "<VertexArray %d positions, %d indexArrays>" % (
242 len(self.positions), len(self.indexArrays))
246 self.positions, self.attributes,
247 self.b0, self.b1, self.weight)
250 keys=[key for key in self.indexArrays.keys()]
253 yield(key, self.indexArrays[key])
255 def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
256 key=VertexKey(obj_index, base_index)
257 attribute=VertexAttribute(
258 normal[0], normal[1], normal[2],
260 if key in self.vertexMap:
261 if attribute in self.vertexMap[key]:
262 return self.vertexMap[key][attribute]
264 return self.__addVertex(self.vertexMap[key],
265 pos, attribute, b0, b1, weight0)
268 self.vertexMap[key]=vertexMapKey
269 return self.__addVertex(vertexMapKey,
270 pos, attribute, b0, b1, weight0)
272 def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
273 index=len(self.positions)
274 vertexMapKey[attribute]=index
276 self.positions.append((pos.x, pos.y, pos.z))
278 self.attributes.append(attribute)
282 self.weight.append(weight0)
286 def getMappedIndex(self, obj_name, base_index):
287 return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
289 def addTriangle(self,
290 object_name, material,
291 base_index0, base_index1, base_index2,
297 weight0, weight1, weight2
299 if object_name in self.objectMap:
300 obj_index=self.objectMap[object_name]
302 obj_index=len(self.objectMap)
303 self.objectMap[object_name]=obj_index
304 index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
305 index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
306 index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
308 if not material in self.indexArrays:
309 self.indexArrays[material]=[]
310 self.indexArrays[material]+=[index0, index1, index2]
314 __slots__=['name', 'type', 'offsets']
315 def __init__(self, name, type):
320 def add(self, index, offset):
321 self.offsets.append((index, offset))
325 self.offsets.sort(lambda l, r: l[0]-r[0])
327 self.offsets.sort(key=lambda e: e[0])
330 return "<Morph %s>" % self.name
332 class IKSolver(object):
333 __slots__=['target', 'effector', 'length', 'iterations', 'weight']
334 def __init__(self, target, effector, length, iterations, weight):
336 self.effector=effector
338 self.iterations=iterations
342 class OneSkinMesh(object):
343 __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
345 self.vertexArray=VertexArray()
351 return "<OneSkinMesh %s, morph:%d>" % (
355 def addMesh(self, obj):
356 if not bl.object.isVisible(obj):
360 self.__rigidbody(obj)
361 self.__constraint(obj)
363 def __getWeightMap(self, obj, mesh):
367 def setWeight(i, name, w):
370 if i in secondWeightMap:
372 if w<secondWeightMap[i][1]:
374 elif w<weightMap[i][1]:
376 secondWeightMap[i]=(name, w)
379 weightMap[i]=(name, w)
381 if w>weightMap[i][1]:
383 secondWeightMap[i]=weightMap[i]
384 weightMap[i]=(name, w)
386 secondWeightMap[i]=(name, w)
388 weightMap[i]=(name, w)
390 # ToDo bone weightと関係ないvertex groupを除外する
392 for name in bl.object.getVertexGroupNames(obj):
393 for i, w in mesh.getVertsFromGroup(name, 1):
394 setWeight(i, name, w)
396 for i, v in enumerate(mesh.verts):
399 setWeight(i, obj.vertex_groups[g.group].name, g.weight)
401 setWeight(i, obj.vertex_groups[0].name, 1)
404 for i in xrange(len(mesh.verts)):
405 if i in secondWeightMap:
406 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
408 weightMap[i]=(weightMap[i][0], 1.0)
409 secondWeightMap[i]=("", 0)
411 print("no weight vertex")
413 secondWeightMap[i]=("", 0)
415 return weightMap, secondWeightMap
417 def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
419 for i, face in enumerate(mesh.faces):
420 faceVertexCount=bl.face.getVertexCount(face)
421 material=mesh.materials[bl.face.getMaterialIndex(face)]
422 v=[mesh.verts[index] for index in bl.face.getVertices(face)]
423 uv=bl.mesh.getFaceUV(
424 mesh, i, face, bl.face.getVertexCount(face))
426 if faceVertexCount==3:
428 self.vertexArray.addTriangle(
429 obj_name, material.name,
436 bl.vertex.getNormal(v[2]),
437 bl.vertex.getNormal(v[1]),
438 bl.vertex.getNormal(v[0]),
442 weightMap[v[2].index][0],
443 weightMap[v[1].index][0],
444 weightMap[v[0].index][0],
445 secondWeightMap[v[2].index][0],
446 secondWeightMap[v[1].index][0],
447 secondWeightMap[v[0].index][0],
448 weightMap[v[2].index][1],
449 weightMap[v[1].index][1],
450 weightMap[v[0].index][1]
452 elif faceVertexCount==4:
454 self.vertexArray.addTriangle(
455 obj_name, material.name,
462 bl.vertex.getNormal(v[2]),
463 bl.vertex.getNormal(v[1]),
464 bl.vertex.getNormal(v[0]),
468 weightMap[v[2].index][0],
469 weightMap[v[1].index][0],
470 weightMap[v[0].index][0],
471 secondWeightMap[v[2].index][0],
472 secondWeightMap[v[1].index][0],
473 secondWeightMap[v[0].index][0],
474 weightMap[v[2].index][1],
475 weightMap[v[1].index][1],
476 weightMap[v[0].index][1]
478 self.vertexArray.addTriangle(
479 obj_name, material.name,
486 bl.vertex.getNormal(v[0]),
487 bl.vertex.getNormal(v[3]),
488 bl.vertex.getNormal(v[2]),
492 weightMap[v[0].index][0],
493 weightMap[v[3].index][0],
494 weightMap[v[2].index][0],
495 secondWeightMap[v[0].index][0],
496 secondWeightMap[v[3].index][0],
497 secondWeightMap[v[2].index][0],
498 weightMap[v[0].index][1],
499 weightMap[v[3].index][1],
500 weightMap[v[2].index][1]
503 def __mesh(self, obj):
507 if RIGID_SHAPE_TYPE in obj:
509 if CONSTRAINT_A in obj:
512 #if not bl.modifier.hasType(obj, 'ARMATURE'):
515 bl.message("export: %s" % obj.name)
517 # メッシュのコピーを生成してオブジェクトの行列を適用する
518 copyMesh, copyObj=bl.object.duplicate(obj)
519 if len(copyMesh.verts)>0:
521 copyObj.scale=obj.scale
522 bpy.ops.object.scale_apply()
523 copyObj.rotation_euler=obj.rotation_euler
524 bpy.ops.object.rotation_apply()
525 copyObj.location=obj.location
526 bpy.ops.object.location_apply()
528 for m in [m for m in copyObj.modifiers]:
529 if m.type=='SOLIDFY':
531 elif m.type=='ARMATURE':
533 elif m.type=='MIRROR':
534 bpy.ops.object.modifier_apply(modifier=m.name)
538 weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
539 self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
540 bl.object.delete(copyObj)
542 def createEmptyBasicSkin(self):
543 self.__getOrCreateMorph('base', 0)
545 def __skin(self, obj):
546 if not bl.object.hasShapeKey(obj):
550 blenderMesh=bl.object.getData(obj)
554 vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
558 for b in bl.object.getShapeKeys(obj):
559 if b.name==BASE_SHAPE_NAME:
560 baseMorph=self.__getOrCreateMorph('base', 0)
565 v=bl.shapekey.getByIndex(b, index)
566 pos=[v[0], v[1], v[2]]
568 indices=self.vertexArray.getMappedIndex(obj.name, index)
569 for attribute, i in indices.items():
574 baseMorph.add(i, pos)
575 indexRelativeMap[i]=relativeIndex
580 print(basis.name, len(baseMorph.offsets))
582 if len(baseMorph.offsets)==0:
586 for b in bl.object.getShapeKeys(obj):
587 if b.name==BASE_SHAPE_NAME:
591 morph=self.__getOrCreateMorph(b.name, 4)
593 for index, src, dst in zip(
594 xrange(len(blenderMesh.verts)),
595 bl.shapekey.get(basis),
597 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
598 if offset[0]==0 and offset[1]==0 and offset[2]==0:
601 indices=self.vertexArray.getMappedIndex(obj.name, index)
602 for attribute, i in indices.items():
606 morph.add(indexRelativeMap[i], offset)
607 assert(len(morph.offsets)<len(baseMorph.offsets))
610 original=self.morphList[:]
612 for i, v in enumerate(englishmap.skinMap):
616 return len(englishmap.skinMap)
618 self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
620 self.morphList.sort(key=getIndex)
622 def __rigidbody(self, obj):
625 if not RIGID_SHAPE_TYPE in obj:
627 self.rigidbodies.append(obj)
629 def __constraint(self, obj):
632 if not CONSTRAINT_A in obj:
634 self.constraints.append(obj)
636 def __getOrCreateMorph(self, name, type):
637 for m in self.morphList:
641 self.morphList.append(m)
644 def getVertexCount(self):
645 return len(self.vertexArray.positions)
649 __slots__=['index', 'name', 'ik_index',
650 'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
651 def __init__(self, name, pos, tail, isConnect):
656 self.parent_index=None
659 self.isConnect=isConnect
662 def __eq__(self, rhs):
663 return self.index==rhs.index
666 return "<Bone %s %d>" % (self.name, self.type)
668 class BoneBuilder(object):
669 __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
676 def getBoneGroup(self, bone):
677 for i, g in enumerate(self.bone_groups):
681 print('no gorup', bone)
684 def build(self, armatureObj):
688 bl.message("build skeleton")
689 armature=bl.object.getData(armatureObj)
694 for g in bl.object.boneGroups(armatureObj):
695 self.bone_groups.append((g.name, []))
700 for b in armature.bones.values():
704 bl.bone.getHeadLocal(b),
705 bl.bone.getTailLocal(b),
708 self.__getBone(bone, b)
710 for b in armature.bones.values():
712 self.__checkConnection(b, None)
717 pose = bl.object.getPose(armatureObj)
718 for b in pose.bones.values():
722 self.__assignBoneGroup(b, b.bone_group)
723 for c in b.constraints:
724 if bl.constraint.isIKSolver(c):
728 target=self.__boneByName(bl.constraint.ikTarget(c))
735 link=self.__boneByName(b.name)
740 chainLength=bl.constraint.ikChainLen(c)
741 for i in range(chainLength):
743 chainBone=self.__boneByName(e.name)
745 chainBone.ik_index=target.index
748 IKSolver(target, link, chainLength,
749 int(bl.constraint.ikItration(c) * 0.1),
750 bl.constraint.ikRotationWeight(c)
760 for i, v in enumerate(englishmap.boneMap):
761 if v[0]==ik.target.name:
763 return len(englishmap.boneMap)
765 self.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
767 self.ik_list.sort(key=getIndex)
769 def __assignBoneGroup(self, poseBone, boneGroup):
771 for g in self.bone_groups:
772 if g[0]==boneGroup.name:
773 g[1].append(poseBone.name)
775 def __checkConnection(self, b, p):
776 if bl.bone.isConnected(b):
777 parent=self.__boneByName(p.name)
778 parent.isConnect=True
781 self.__checkConnection(c, b)
787 boneMap=englishmap.boneMap
788 original=self.bones[:]
790 for i, k_v in enumerate(boneMap):
791 if k_v[0]==bone.name:
797 self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
799 self.bones.sort(key=getIndex)
802 for i, b in enumerate(self.bones):
803 src=original.index(b)
806 b.index=sortMap[b.index]
808 b.parent_index=sortMap[b.parent_index]
810 b.tail_index=sortMap[b.tail_index]
812 b.ik_index=sortMap[b.ik_index]
820 if b.parent_index==None:
821 b.parent_index=0xFFFF
823 if b.type==6 or b.type==7:
825 parent=self.bones[b.parent_index]
826 #print('parnet', parent.name)
827 parent.tail_index=b.index
830 if b.tail_index==None:
835 def getIndex(self, bone):
836 for i, b in enumerate(self.bones):
841 def indexByName(self, name):
845 return self.getIndex(self.__boneByName(name))
847 def __boneByName(self, name):
848 return self.boneMap[name]
850 def __getBone(self, parent, b):
851 if len(b.children)==0:
855 for i, c in enumerate(b.children):
857 bl.bone.getHeadLocal(c),
858 bl.bone.getTailLocal(c),
859 bl.bone.isConnected(c))
862 bone.parent_index=parent.index
864 if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
865 parent.tail_index=bone.index
866 self.__getBone(bone, c)
868 def __addBone(self, bone):
869 bone.index=len(self.bones)
870 self.bones.append(bone)
871 self.boneMap[bone.name]=bone
874 class PmdExporter(object):
886 self.armatureObj=None
890 for o in bl.object.each():
891 object_node_map[o]=Node(o)
892 for o in bl.object.each():
893 node=object_node_map[o]
895 object_node_map[node.o.parent].children.append(node)
898 root=object_node_map[bl.object.getActive()]
900 self.englishName=o.name
901 self.englishComment=o[MMD_COMMENT] if MMD_COMMENT in o else 'blender export\n'
902 self.name=o[MMD_MB_NAME] if MMD_MB_NAME in o else 'Blenderエクスポート'
903 self.comment=o[MMD_MB_COMMENT] if MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
906 self.oneSkinMesh=OneSkinMesh()
907 self.__createOneSkinMesh(root)
908 bl.message(self.oneSkinMesh)
909 if len(self.oneSkinMesh.morphList)==0:
911 self.oneSkinMesh.createEmptyBasicSkin()
914 self.skeleton=BoneBuilder()
915 self.skeleton.build(self.armatureObj)
917 def __createOneSkinMesh(self, node):
918 ############################################################
919 # search armature modifier
920 ############################################################
921 for m in node.o.modifiers:
922 if bl.modifier.isType(m, 'ARMATURE'):
923 armatureObj=bl.modifier.getArmatureObject(m)
924 if not self.armatureObj:
925 self.armatureObj=armatureObj
926 elif self.armatureObj!=armatureObj:
927 print("warning! found multiple armature. ignored.",
930 if node.o.type.upper()=='MESH':
931 self.oneSkinMesh.addMesh(node.o)
933 for child in node.children:
934 self.__createOneSkinMesh(child)
936 def write(self, path):
938 io.setName(toCP932(self.name))
939 io.setComment(toCP932(self.comment))
943 for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
944 # convert right-handed z-up to left-handed y-up
949 v.normal.x=attribute.nx
950 v.normal.y=attribute.ny
951 v.normal.z=attribute.nz
953 v.uv.y=1.0-attribute.v # reverse vertical
954 v.bone0=self.skeleton.indexByName(b0)
955 v.bone1=self.skeleton.indexByName(b1)
956 v.weight0=int(100*weight)
957 v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
960 vertexCount=self.oneSkinMesh.getVertexCount()
961 for material_name, indices in self.oneSkinMesh.vertexArray.each():
962 #print('material:', material_name)
963 m=bl.material.get(material_name)
965 material=io.addMaterial()
966 setMaterialParams(material, m)
968 material.vertex_count=len(indices)
969 material.toon_index=0
970 textures=[os.path.basename(path)
971 for path in bl.material.eachEnalbeTexturePath(m)]
973 material.setTexture(toCP932('*'.join(textures)))
975 material.setTexture(toCP932(""))
978 assert(i<vertexCount)
979 for i in xrange(0, len(indices), 3):
981 io.indices.append(indices[i])
982 io.indices.append(indices[i+1])
983 io.indices.append(indices[i+2])
987 for i, b in enumerate(self.skeleton.bones):
991 boneNameMap[b.name]=i
992 v=englishmap.getUnicodeBoneName(b.name)
996 cp932=v[1].encode('cp932')
997 assert(len(cp932)<20)
1001 bone_english_name=toCP932(b.name)
1002 assert(len(bone_english_name)<20)
1003 bone.setEnglishName(bone_english_name)
1008 b.ik_index=self.skeleton.indexByName('eyes')
1013 bone.parent_index=b.parent_index
1014 bone.tail_index=b.tail_index
1015 bone.ik_index=b.ik_index
1017 # convert right-handed z-up to left-handed y-up
1018 bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
1019 bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
1020 bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
1023 for ik in self.skeleton.ik_list:
1025 solver.index=self.skeleton.getIndex(ik.target)
1026 solver.target=self.skeleton.getIndex(ik.effector)
1027 solver.length=ik.length
1028 b=self.skeleton.bones[ik.effector.parent_index]
1029 for i in xrange(solver.length):
1030 solver.children.append(self.skeleton.getIndex(b))
1031 b=self.skeleton.bones[b.parent_index]
1032 solver.iterations=ik.iterations
1033 solver.weight=ik.weight
1036 for i, m in enumerate(self.oneSkinMesh.morphList):
1040 v=englishmap.getUnicodeSkinName(m.name)
1042 v=[m.name, m.name, 0]
1044 cp932=v[1].encode('cp932')
1045 morph.setName(cp932)
1046 morph.setEnglishName(m.name.encode('cp932'))
1049 for index, offset in m.offsets:
1050 # convert right-handed z-up to left-handed y-up
1051 morph.append(index, offset[0], offset[2], offset[1])
1052 morph.vertex_count=len(m.offsets)
1056 for i, m in enumerate(self.oneSkinMesh.morphList):
1058 io.face_list.append(i)
1059 for i, m in enumerate(self.oneSkinMesh.morphList):
1061 io.face_list.append(i)
1062 for i, m in enumerate(self.oneSkinMesh.morphList):
1064 io.face_list.append(i)
1065 for i, m in enumerate(self.oneSkinMesh.morphList):
1067 io.face_list.append(i)
1070 for g in self.skeleton.bone_groups:
1071 boneDisplayName=io.addBoneGroup()
1073 name=englishmap.getUnicodeBoneGroupName(g[0])
1076 boneDisplayName.setName(toCP932(name+'\n'))
1079 boneDisplayName.setEnglishName(toCP932(englishName+'\n'))
1082 for i, b in enumerate(self.skeleton.bones):
1085 if b.type in [6, 7]:
1087 io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1089 #assert(len(io.bones)==len(io.bone_display_list)+1)
1092 io.setEnglishName(toCP932(self.englishName))
1093 io.setEnglishComment(toCP932(self.englishComment))
1097 for o in bl.object.each():
1099 if o.name.startswith(TOON_TEXTURE_OBJECT):
1105 toonMesh=bl.object.getData(toonMeshObject)
1106 toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1108 t=bl.material.getTexture(toonMaterial, i)
1110 io.getToonTexture(i).setName(toCP932(t.name))
1112 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1115 io.getToonTexture(i).setName(toCP932("toon%02d.bmp\n" % i))
1119 for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1120 name=obj[RIGID_NAME] if RIGID_NAME in obj else obj.name
1122 rigidBody=io.addRigidBody()
1123 rigidBody.setName(name.encode('cp932'))
1124 rigidNameMap[name]=i
1125 boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1128 bone=self.skeleton.bones[0]
1130 bone=self.skeleton.bones[boneIndex]
1131 rigidBody.boneIndex=boneIndex
1132 #rigidBody.position.x=obj[RIGID_LOCATION][0]
1133 #rigidBody.position.y=obj[RIGID_LOCATION][1]
1134 #rigidBody.position.z=obj[RIGID_LOCATION][2]
1135 rigidBody.position.x=obj.location.x-bone.pos[0]
1136 rigidBody.position.y=obj.location.z-bone.pos[2]
1137 rigidBody.position.z=obj.location.y-bone.pos[1]
1138 rigidBody.rotation.x=-obj.rotation_euler[0]
1139 rigidBody.rotation.y=-obj.rotation_euler[2]
1140 rigidBody.rotation.z=-obj.rotation_euler[1]
1141 rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1142 rigidBody.group=obj[RIGID_GROUP]
1143 rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1144 rigidBody.weight=obj[RIGID_WEIGHT]
1145 rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1146 rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1147 rigidBody.restitution=obj[RIGID_RESTITUTION]
1148 rigidBody.friction=obj[RIGID_FRICTION]
1149 if obj[RIGID_SHAPE_TYPE]==0:
1150 rigidBody.shapeType=pmd.SHAPE_SPHERE
1151 rigidBody.w=obj.scale[0]
1152 elif obj[RIGID_SHAPE_TYPE]==1:
1153 rigidBody.shapeType=pmd.SHAPE_BOX
1154 rigidBody.w=obj.scale[0]
1155 rigidBody.d=obj.scale[1]
1156 rigidBody.h=obj.scale[2]
1157 elif obj[RIGID_SHAPE_TYPE]==2:
1158 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1159 rigidBody.w=obj.scale[0]
1160 rigidBody.h=obj.scale[2]
1163 for obj in self.oneSkinMesh.constraints:
1164 constraint=io.addConstraint()
1165 constraint.setName(obj[CONSTRAINT_NAME].encode('cp932'))
1166 constraint.rigidA=rigidNameMap[obj[CONSTRAINT_A]]
1167 constraint.rigidB=rigidNameMap[obj[CONSTRAINT_B]]
1168 constraint.pos.x=obj.location[0]
1169 constraint.pos.y=obj.location[2]
1170 constraint.pos.z=obj.location[1]
1171 constraint.rot.x=-obj.rotation_euler[0]
1172 constraint.rot.y=-obj.rotation_euler[2]
1173 constraint.rot.z=-obj.rotation_euler[1]
1174 constraint.constraintPosMin.x=obj[CONSTRAINT_POS_MIN][0]
1175 constraint.constraintPosMin.y=obj[CONSTRAINT_POS_MIN][1]
1176 constraint.constraintPosMin.z=obj[CONSTRAINT_POS_MIN][2]
1177 constraint.constraintPosMax.x=obj[CONSTRAINT_POS_MAX][0]
1178 constraint.constraintPosMax.y=obj[CONSTRAINT_POS_MAX][1]
1179 constraint.constraintPosMax.z=obj[CONSTRAINT_POS_MAX][2]
1180 constraint.constraintRotMin.x=obj[CONSTRAINT_ROT_MIN][0]
1181 constraint.constraintRotMin.y=obj[CONSTRAINT_ROT_MIN][1]
1182 constraint.constraintRotMin.z=obj[CONSTRAINT_ROT_MIN][2]
1183 constraint.constraintRotMax.x=obj[CONSTRAINT_ROT_MAX][0]
1184 constraint.constraintRotMax.y=obj[CONSTRAINT_ROT_MAX][1]
1185 constraint.constraintRotMax.z=obj[CONSTRAINT_ROT_MAX][2]
1186 constraint.springPos.x=obj[CONSTRAINT_SPRING_POS][0]
1187 constraint.springPos.y=obj[CONSTRAINT_SPRING_POS][1]
1188 constraint.springPos.z=obj[CONSTRAINT_SPRING_POS][2]
1189 constraint.springRot.x=obj[CONSTRAINT_SPRING_ROT][0]
1190 constraint.springRot.y=obj[CONSTRAINT_SPRING_ROT][1]
1191 constraint.springRot.z=obj[CONSTRAINT_SPRING_ROT][2]
1194 bl.message('write: %s' % path)
1195 return io.write(path)
1198 def __execute(filename):
1199 active=bl.object.getActive()
1201 print("abort. no active object.")
1203 exporter=PmdExporter()
1206 exporter.write(filename)
1207 bl.object.activate(active)
1212 def execute_24(filename):
1213 bl.initialize('pmd_export', bpy.data.scenes.active)
1214 __execute(filename.decode(bl.INTERNAL_ENCODING))
1217 Blender.Window.FileSelector(
1219 'Export Metasequoia PMD',
1220 Blender.sys.makename(ext='.pmd'))
1224 def execute_25(filename, scene):
1225 bl.initialize('pmd_export', scene)
1230 class EXPORT_OT_pmd(bpy.types.Operator):
1231 '''Save a Metasequoia PMD file.'''
1232 bl_idname = "export_scene.pmd"
1233 bl_label = 'Export PMD'
1235 # List of operator properties, the attributes will be assigned
1236 # to the class instance from the operator settings before calling.
1237 filepath = bpy.props.StringProperty()
1238 filename = bpy.props.StringProperty()
1239 directory = bpy.props.StringProperty()
1241 def execute(self, context):
1243 self.properties.filepath,
1248 def invoke(self, context, event):
1249 wm=context.window_manager
1250 wm.add_fileselect(self)
1251 return 'RUNNING_MODAL'
1254 def menu_func(self, context):
1255 default_path=bpy.data.filepath.replace(".blend", ".pmd")
1256 self.layout.operator(
1257 EXPORT_OT_pmd.bl_idname,
1258 text="Miku Miku Dance Model(.pmd)",
1260 ).filepath=default_path
1263 bpy.types.INFO_MT_file_export.append(menu_func)
1266 bpy.types.INFO_MT_file_export.remove(menu_func)
1268 if __name__ == "__main__":