4 Name: 'MikuMikuDance model (.pmd)...'
7 Tooltip: 'Import PMD file for MikuMikuDance.'
9 __author__= ["ousttrue"]
15 This script imports a pmd into Blender for editing.
17 0.1 20091126: first implement.
18 0.2 20091209: implement IK.
19 0.3 20091210: implement morph target.
20 0.4 20100305: use english name.
21 0.5 20100408: cleanup not used vertices.
22 0.6 20100416: fix fornt face. texture load fail safe. add progress.
23 0.7 20100506: C extension.
24 0.8 20100521: add shape_key group.
25 1.0 20100530: add invisilbe bone tail(armature layer 2).
26 1.1 20100608: integrate 2.4 and 2.5.
27 1.2 20100616: implement rigid body.
28 1.3 20100619: fix for various models.
29 1.4 20100623: fix constraint name.
30 1.5 20100626: refactoring.
31 1.6 20100629: sphere map.
32 1.7 20100703: implement bone group.
33 1.8 20100710: implement toon texture.
34 1.9 20100718: keep model name, comment.
35 2.0 20100724: update for Blender2.53.
36 2.1 20100731: add full python module.
37 2.2 20101005: update for Blender2.54.
38 2.3 20101228: update for Blender2.55.
39 2.4 20110429: update for Blender2.57b.
40 2.5 20110522: implement RigidBody and Constraint.
43 'category': 'Import/Export',
44 'name': 'Import: MikuMikuDance Model Format (.pmd)',
48 'location': 'File > Import',
49 'description': 'Import from the MikuMikuDance Model Format (.pmd)',
50 'warning': '', # used for warning icon and text in addons panel
51 'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
52 'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
55 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
57 MMD_MB_COMMENT='mb_comment'
59 BASE_SHAPE_NAME='Basis'
60 RIGID_NAME='rigid_name'
61 RIGID_SHAPE_TYPE='rigid_shape_type'
62 RIGID_PROCESS_TYPE='rigid_process_type'
63 RIGID_BONE_NAME='rigid_bone_name'
64 #RIGID_LOCATION='rigid_loation'
65 RIGID_GROUP='ribid_group'
66 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
67 RIGID_WEIGHT='rigid_weight'
68 RIGID_LINEAR_DAMPING='rigid_linear_damping'
69 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
70 RIGID_RESTITUTION='rigid_restitution'
71 RIGID_FRICTION='rigid_friction'
72 CONSTRAINT_NAME='constraint_name'
73 CONSTRAINT_A='const_a'
74 CONSTRAINT_B='const_b'
75 CONSTRAINT_POS_MIN='const_pos_min'
76 CONSTRAINT_POS_MAX='const_pos_max'
77 CONSTRAINT_ROT_MIN='const_rot_min'
78 CONSTRAINT_ROT_MAX='const_rot_max'
79 CONSTRAINT_SPRING_POS='const_spring_pos'
80 CONSTRAINT_SPRING_ROT='const_spring_rot'
81 TOON_TEXTURE_OBJECT='ToonTextures'
84 ###############################################################################
86 ###############################################################################
93 from meshio import pmd, englishmap
94 print('use meshio C module')
97 from .pymeshio import englishmap
98 #from .pymeshio import mmd as pmd
100 from .pymeshio import pmd
107 from . import bl25 as bl
111 def createPmdMaterial(m, index):
112 material = bpy.data.materials.new("Material")
114 material.diffuse_shader='FRESNEL'
115 material.diffuse_color=([m.diffuse.r, m.diffuse.g, m.diffuse.b])
116 material.alpha=m.diffuse.a
118 material.specular_shader='TOON'
119 material.specular_color=([m.specular.r, m.specular.g, m.specular.b])
120 material.specular_toon_size=int(m.shinness)
122 material.mirror_color=([m.ambient.r, m.ambient.g, m.ambient.b])
124 material.subsurface_scattering.use=True if m.flag==1 else False
126 material.name="m_%02d" % index
127 material.preview_render_type='FLAT'
128 material.use_transparency=True
131 def poseBoneLimit(n, b):
134 if n.startswith("knee_"):
139 b.use_ik_limit_x=True
142 elif n.startswith("ankle_"):
146 def setSphereMap(material, index, blend_type='MULTIPLY'):
147 slot=material.texture_slots[index]
148 slot.texture_coords='NORMAL'
149 slot.mapping='SPHERE'
150 slot.blend_type=blend_type
153 ###############################################################################
155 return bl.createVector(v.x, v.y, v.z)
158 def convert_coord(pos):
160 Left handed y-up to Right handed z-up
162 return (pos.x, pos.z, pos.y)
165 def to_radian(degree):
166 return math.pi * degree / 180
169 def get_bone_name(l, index):
171 return l.bones[0]._name
173 if index < len(l.bones):
174 name=englishmap.getEnglishBoneName(l.bones[index]._name)
177 return l.bones[index]._name
178 print('invalid bone index', index)
179 return l.bones[0]._name
182 def get_group_name(g):
183 group_name=englishmap.getEnglishBoneGroupName(g._name.strip())
185 group_name=g._name.strip()
189 def __importToonTextures(io, tex_dir):
190 mesh, meshObject=bl.mesh.create(TOON_TEXTURE_OBJECT)
191 material=bl.material.create(TOON_TEXTURE_OBJECT)
192 bl.mesh.addMaterial(mesh, material)
193 for toon in (io.toon_textures._toon_textures[i] for i in range(10)):
194 path=os.path.join(tex_dir, toon)
195 texture, image=bl.texture.create(path)
196 bl.material.addTexture(material, texture, False)
197 return meshObject, material
200 def __importShape(obj, l, vertex_map):
201 if len(l.morph_list)==0:
205 bl.object.pinShape(obj, True)
209 for s in l.morph_list:
213 # create vertex group
214 bl.object.addVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
219 bl.object.assignVertexGroup(
220 obj, MMD_SHAPE_GROUP_NAME, vertex_map[i], 0)
226 baseShapeBlock=bl.object.addShapeKey(obj, BASE_SHAPE_NAME)
228 mesh=bl.object.getData(obj)
232 for s in l.morph_list:
237 name=englishmap.getEnglishSkinName(s._name)
242 new_shape_key=bl.object.addShapeKey(obj, name)
244 for index, offset in zip(s.indices, s.pos_list):
246 vertex_index=vertex_map[base.indices[index]]
247 bl.shapekey.assign(new_shape_key, vertex_index,
248 mesh.vertices[vertex_index].co+
249 bl.createVector(*convert_coord(offset)))
250 except IndexError as msg:
252 print(index, len(base.indices), len(vertex_map))
253 print(len(mesh.vertices))
254 print(base.indices[index])
258 #print 'this mesh not has shape vertices'
262 bl.object.setActivateShapeKey(obj, 0)
265 def __build(armature, b, p, parent):
266 name=englishmap.getEnglishBoneName(b._name)
270 bone=bl.armature.createBone(armature, name)
272 if parent and (b.tail_index==0 or b.type==6 or b.type==7 or b.type==9):
274 bone.head = bl.createVector(*convert_coord(b.pos))
275 bone.tail=bone.head+bl.createVector(0, 1, 0)
277 if bone.name=="center_t":
278 # センターボーンは(0, 1, 0)の方向を向いていないと具合が悪い
279 parent.tail=parent.head+bl.createVector(0, 1, 0)
280 bone.head=parent.tail
281 bone.tail=bone.head+bl.createVector(0, 1, 0)
283 if parent.tail==bone.head:
286 print('diffurence with parent.tail and head', name)
289 bl.bone.setConnected(bone)
291 bl.bone.setLayerMask(bone, [0, 1])
294 bone.head = bl.createVector(*convert_coord(b.pos))
295 bone.tail = bl.createVector(*convert_coord(b.tail))
298 if parent.tail==bone.head:
299 bl.bone.setConnected(bone)
301 if bone.head==bone.tail:
302 bone.tail=bone.head+bl.createVector(0, 1, 0)
305 __build(armature, c, b, bone)
308 def __importArmature(l):
309 armature, armature_object=bl.armature.create()
312 bl.armature.makeEditable(armature_object)
315 __build(armature, b, None, None)
316 bl.armature.update(armature)
320 pose = bl.object.getPose(armature_object)
322 target=l.bones[ik.target]
323 name = englishmap.getEnglishBoneName(target._name)
326 p_bone = pose.bones[name]
328 print('not found', name)
330 if len(ik.children) >= 16:
331 print('over MAX_CHAINLEN', ik, len(ik.children))
333 effector_name=englishmap.getEnglishBoneName(
334 l.bones[ik.index]._name)
335 if not effector_name:
336 effector_name=l.bones[ik.index]._name
338 constraint=bl.armature.createIkConstraint(armature_object,
339 p_bone, effector_name, ik)
341 bl.armature.makeEditable(armature_object)
342 bl.armature.update(armature)
346 for i, g in enumerate(l.bone_group_list):
347 name=get_group_name(g)
348 bl.object.createBoneGroup(armature_object, name, "THEME%02d" % (i+1))
350 # assign bone to group
351 for b_index, g_index in l.bone_display_list:
354 bone_name=englishmap.getEnglishBoneName(b._name)
358 g=l.bone_group_list[g_index-1]
359 group_name=get_group_name(g)
362 pose.bones[bone_name].bone_group=pose.bone_groups[group_name]
366 return armature_object
369 def __import16MaerialAndMesh(meshObject, l,
370 material_order, face_map, tex_dir, toon_material):
372 mesh=bl.object.getData(meshObject)
373 ############################################################
375 ############################################################
376 bl.progress_print('create materials')
382 for material_index in material_order:
384 m=l.materials[material_index]
385 mesh_material_map[material_index]=index
389 material=createPmdMaterial(m, material_index)
392 texture_name=m._texture
394 for i, t in enumerate(texture_name.split('*')):
396 texture=textureMap[t]
398 path=os.path.join(tex_dir, t)
399 texture, image=bl.texture.create(path)
400 textureMap[texture_name]=texture
401 imageMap[material_index]=image
402 texture_index=bl.material.addTexture(material, texture)
403 if t.endswith('sph'):
405 setSphereMap(material, texture_index)
406 elif t.endswith('spa'):
408 setSphereMap(material, texture_index, 'ADD')
411 toon_index=bl.material.addTexture(
413 bl.material.getTexture(
415 0 if m.toon_index==0xFF else m.toon_index
419 bl.mesh.addMaterial(mesh, material)
423 ############################################################
425 ############################################################
426 bl.progress_print('create vertices')
429 for v in l.each_vertex():
430 vertices.append(convert_coord(v.pos))
432 ############################################################
434 ############################################################
435 bl.progress_print('create faces')
438 mesh_face_materials=[]
441 for material_index in material_order:
442 face_offset=face_map[material_index]
443 m=l.materials[material_index]
444 material_faces=l.indices[face_offset:face_offset+m.vertex_count]
446 def degenerate(i0, i1, i2):
450 return i0==i1 or i1==i2 or i2==i0
452 for j in xrange(0, len(material_faces), 3):
454 i1=material_faces[j+1]
455 i2=material_faces[j+2]
457 triangle=[i2, i1, i0]
458 if degenerate(*triangle):
460 mesh_face_indices.append(triangle[0:3])
461 mesh_face_materials.append(material_index)
462 used_vertices.add(i0)
463 used_vertices.add(i1)
464 used_vertices.add(i2)
466 ############################################################
467 # create vertices & faces
468 ############################################################
469 bl.mesh.addGeometry(mesh, vertices, mesh_face_indices)
471 ############################################################
473 ############################################################
474 # create vertex group
476 for v in l.each_vertex():
477 vertex_groups[v.bone0]=True
478 vertex_groups[v.bone1]=True
479 for i in vertex_groups.keys():
480 bl.object.addVertexGroup(meshObject, get_bone_name(l, i))
483 bl.mesh.useVertexUV(mesh)
484 for i, v, mvert in zip(xrange(len(l.vertices)),
485 l.each_vertex(), mesh.vertices):
487 bl.vertex.setNormal(mvert, convert_coord(v.normal))
489 w1=float(v.weight0)/100.0
491 bl.object.assignVertexGroup(meshObject, get_bone_name(l, v.bone0),
493 bl.object.assignVertexGroup(meshObject, get_bone_name(l, v.bone1),
496 ############################################################
498 ############################################################
501 for i, (face, material_index) in enumerate(
502 zip(mesh.faces, mesh_face_materials)):
504 index=mesh_material_map[material_index]
505 except KeyError as message:
506 print(message, mesh_material_map, m)
508 bl.face.setMaterial(face, index)
509 material=mesh.materials[index]
511 if bl.material.hasTexture(material):
512 uv_array=[l.getUV(i) for i in bl.face.getIndices(face)]
513 bl.mesh.setFaceUV(mesh, i, face,
515 [(uv.x, 1.0-uv.y) for uv in uv_array],
516 imageMap.get(index, None))
519 bl.face.setSmooth(face, True)
523 ############################################################
524 # clean up not used vertices
525 ############################################################
526 bl.progress_print('clean up vertices not used')
529 for i, v in enumerate(l.each_vertex()):
530 if i in used_vertices:
531 vertex_map[i]=len(vertex_map)
533 remove_vertices.append(i)
535 bl.mesh.vertsDelete(mesh, remove_vertices)
537 bl.progress_print('%s created' % mesh.name)
541 def __importMaterialAndMesh(io, tex_dir, toon_material):
543 @param l[in] mmd.PMDLoader
546 ############################################################
547 # shpaeキーで使われるマテリアル優先的に前に並べる
548 ############################################################
549 # shapeキーで使われる頂点インデックスを集める
550 shape_key_used_vertices=set()
551 if len(io.morph_list)>0:
554 for s in io.morph_list:
561 for index in base.indices:
562 shape_key_used_vertices.add(index)
564 # マテリアルに含まれる頂点がshape_keyに含まれるか否か?
565 def isMaterialUsedInShape(offset, m):
566 for i in xrange(offset, offset+m.vertex_count):
567 if io.indices[i] in shape_key_used_vertices:
570 material_with_shape=set()
572 # 各マテリアルの開始頂点インデックスを記録する
575 for i, m in enumerate(io.materials):
576 face_map[i]=face_count
577 if isMaterialUsedInShape(face_count, m):
578 material_with_shape.add(i)
579 face_count+=m.vertex_count
581 # shapeキーで使われる頂点のあるマテリアル
582 material_with_shape=list(material_with_shape)
583 material_with_shape.sort()
585 # shapeキーに使われていないマテリアル
586 material_without_shape=[]
587 for i in range(len(io.materials)):
588 if not i in material_with_shape:
589 material_without_shape.append(i)
592 def __splitList(l, length):
593 for i in range(0, len(l), length):
596 def __importMeshAndShape(material16, name):
597 mesh, meshObject=bl.mesh.create(name)
600 bl.object.deselectAll()
601 bl.object.activate(meshObject)
603 # shapeキーで使われる順に並べなおしたマテリアル16個分の
605 vertex_map=__import16MaerialAndMesh(
606 meshObject, io, material16, face_map, tex_dir, toon_material)
609 __importShape(meshObject, io, vertex_map)
614 mesh_objects=[__importMeshAndShape(material16, 'with_shape')
615 for material16 in __splitList(material_with_shape, 16)]
617 mesh_objects+=[__importMeshAndShape(material16, 'mesh')
618 for material16 in __splitList(material_without_shape, 16)]
623 def __importConstraints(io):
624 print("create constraint")
625 container=bl.object.createEmpty('Constraints')
627 True, False, False, False, False, False, False, False, False, False,
628 False, False, False, False, False, False, False, False, False, False,
630 material=bl.material.create('constraint')
631 material.diffuse_color=(1, 0, 0)
633 for i, c in enumerate(io.constraints):
634 bpy.ops.mesh.primitive_uv_sphere_add(
638 location=(c.pos.x, c.pos.z, c.pos.y),
641 meshObject=bl.object.getActive()
642 constraintMeshes.append(meshObject)
643 mesh=bl.object.getData(meshObject)
644 bl.mesh.addMaterial(mesh, material)
645 meshObject.name='c_%d' % i
646 #meshObject.draw_transparent=True
647 #meshObject.draw_wire=True
648 meshObject.draw_type='SOLID'
650 meshObject.rotation_euler=(-rot.x, -rot.z, -rot.y)
652 meshObject[CONSTRAINT_NAME]=c._name
653 meshObject[CONSTRAINT_A]=io.rigidbodies[c.rigidA]._name
654 meshObject[CONSTRAINT_B]=io.rigidbodies[c.rigidB]._name
655 meshObject[CONSTRAINT_POS_MIN]=VtoV(c.constraintPosMin)
656 meshObject[CONSTRAINT_POS_MAX]=VtoV(c.constraintPosMax)
657 meshObject[CONSTRAINT_ROT_MIN]=VtoV(c.constraintRotMin)
658 meshObject[CONSTRAINT_ROT_MAX]=VtoV(c.constraintRotMax)
659 meshObject[CONSTRAINT_SPRING_POS]=VtoV(c.springPos)
660 meshObject[CONSTRAINT_SPRING_ROT]=VtoV(c.springRot)
662 for meshObject in reversed(constraintMeshes):
663 bl.object.makeParent(container, meshObject)
668 def __importRigidBodies(io):
669 print("create rigid bodies")
671 container=bl.object.createEmpty('RigidBodies')
673 True, False, False, False, False, False, False, False, False, False,
674 False, False, False, False, False, False, False, False, False, False,
676 material=bl.material.create('rigidBody')
678 for i, rigid in enumerate(io.rigidbodies):
679 if rigid.boneIndex==0xFFFF:
683 bone=io.bones[rigid.boneIndex]
684 pos=bone.pos+rigid.position
686 if rigid.shapeType==pmd.SHAPE_SPHERE:
687 bpy.ops.mesh.primitive_ico_sphere_add(
688 location=(pos.x, pos.z, pos.y),
691 bpy.ops.transform.resize(
692 value=(rigid.w, rigid.w, rigid.w))
693 elif rigid.shapeType==pmd.SHAPE_BOX:
694 bpy.ops.mesh.primitive_cube_add(
695 location=(pos.x, pos.z, pos.y),
698 bpy.ops.transform.resize(
699 value=(rigid.w, rigid.d, rigid.h))
700 elif rigid.shapeType==pmd.SHAPE_CAPSULE:
701 bpy.ops.mesh.primitive_cylinder_add(
702 location=(pos.x, pos.z, pos.y),
705 bpy.ops.transform.resize(
706 value=(rigid.w, rigid.w, rigid.h))
710 meshObject=bl.object.getActive()
711 mesh=bl.object.getData(meshObject)
712 rigidMeshes.append(meshObject)
713 bl.mesh.addMaterial(mesh, material)
714 meshObject.name='r_%d' % i
715 meshObject[RIGID_NAME]=rigid._name
716 #meshObject.draw_transparent=True
717 #meshObject.draw_wire=True
718 meshObject.draw_type='WIRE'
720 meshObject.rotation_euler=(-rot.x, -rot.z, -rot.y)
723 meshObject[RIGID_SHAPE_TYPE]=rigid.shapeType
724 meshObject[RIGID_PROCESS_TYPE]=rigid.processType
726 bone_name = englishmap.getEnglishBoneName(bone._name)
729 meshObject[RIGID_BONE_NAME]=bone_name
731 meshObject[RIGID_GROUP]=rigid.group
732 meshObject[RIGID_INTERSECTION_GROUP]=rigid.target
733 meshObject[RIGID_WEIGHT]=rigid.weight
734 meshObject[RIGID_LINEAR_DAMPING]=rigid.linearDamping
735 meshObject[RIGID_ANGULAR_DAMPING]=rigid.angularDamping
736 meshObject[RIGID_RESTITUTION]=rigid.restitution
737 meshObject[RIGID_FRICTION]=rigid.friction
739 for meshObject in reversed(rigidMeshes):
740 bl.object.makeParent(container, meshObject)
745 def _execute(filepath=""):
747 load pmd file to context.
751 bl.progress_set('load %s' % filepath, 0.0)
754 if not io.read(filepath):
755 bl.message("fail to load %s" % filepath)
757 bl.progress_set('loaded', 0.1)
760 model_name=io._english_name
761 if len(model_name)==0:
763 root=bl.object.createEmpty(model_name)
764 root[MMD_MB_NAME]=io._name
765 root[MMD_MB_COMMENT]=io._comment
766 root[MMD_COMMENT]=io._english_comment
769 tex_dir=os.path.dirname(filepath)
770 toonTextures, toonMaterial=__importToonTextures(io, tex_dir)
771 bl.object.makeParent(root, toonTextures)
774 mesh_objects=__importMaterialAndMesh(io, tex_dir, toonMaterial)
775 for o in mesh_objects:
776 bl.object.makeParent(root, o)
779 armature_object=__importArmature(io)
781 bl.object.makeParent(root, armature_object)
782 armature = bl.object.getData(armature_object)
784 # add armature modifier
785 for o in mesh_objects:
786 bl.modifier.addArmature(o, armature_object)
789 for n, b in bl.object.getPose(armature_object).bones.items():
792 # import rigid bodies
793 rigidBodies=__importRigidBodies(io)
795 bl.object.makeParent(root, rigidBodies)
798 constraints=__importConstraints(io)
800 bl.object.makeParent(root, constraints)
802 bl.object.activate(root)