OSDN Git Service

fix normal
[meshio/pymeshio.git] / blender25-meshio / export_pmd.py
1 #!BPY
2 # coding: utf-8
3 """
4  Name: 'MikuMikuDance model (.pmd)...'
5  Blender: 248
6  Group: 'Export'
7  Tooltip: 'Export PMD file for MikuMikuDance.'
8 """
9 __author__= ["ousttrue"]
10 __version__= "2.5"
11 __url__=()
12 __bpydoc__="""
13 pmd Importer
14
15 This script exports a pmd model.
16
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.
30 2.3 20101228: update for Blender2.55.
31 2.4 20110429: update for Blender2.57b.
32 2.5 20110522: implement RigidBody and Constraint.
33 """
34
35 bl_addon_info = {
36         'category': 'Import/Export',
37         'name': 'Export: MikuMikuDance Model Format (.pmd)',
38         'author': 'ousttrue',
39         'version': (2, 2),
40         'blender': (2, 5, 3),
41         'location': 'File > Export',
42         'description': 'Export to the MikuMikuDance Model Format (.pmd)',
43         'warning': '', # used for warning icon and text in addons panel
44         'wiki_url': 'http://sourceforge.jp/projects/meshio/wiki/FrontPage',
45         'tracker_url': 'http://sourceforge.jp/ticket/newticket.php?group_id=5081',
46         }
47
48 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
49 MMD_MB_NAME='mb_name'
50 MMD_MB_COMMENT='mb_comment'
51 MMD_COMMENT='comment'
52 BASE_SHAPE_NAME='Basis'
53 RIGID_NAME='rigid_name'
54 RIGID_SHAPE_TYPE='rigid_shape_type'
55 RIGID_PROCESS_TYPE='rigid_process_type'
56 RIGID_BONE_NAME='rigid_bone_name'
57 #RIGID_LOCATION='rigid_loation'
58 RIGID_GROUP='ribid_group'
59 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
60 RIGID_WEIGHT='rigid_weight'
61 RIGID_LINEAR_DAMPING='rigid_linear_damping'
62 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
63 RIGID_RESTITUTION='rigid_restitution'
64 RIGID_FRICTION='rigid_friction'
65 CONSTRAINT_NAME='constraint_name'
66 CONSTRAINT_A='const_a'
67 CONSTRAINT_B='const_b'
68 CONSTRAINT_POS_MIN='const_pos_min'
69 CONSTRAINT_POS_MAX='const_pos_max'
70 CONSTRAINT_ROT_MIN='const_rot_min'
71 CONSTRAINT_ROT_MAX='const_rot_max'
72 CONSTRAINT_SPRING_POS='const_spring_pos'
73 CONSTRAINT_SPRING_ROT='const_spring_rot'
74 TOON_TEXTURE_OBJECT='ToonTextures'
75
76
77 ###############################################################################
78 # import
79 ###############################################################################
80 import os
81 import sys
82
83 try:
84     # C extension
85     from meshio import pmd, englishmap
86     print('use meshio C module')
87 except ImportError:
88     # full python
89     from .pymeshio import englishmap
90     from .pymeshio import pmd
91
92
93 # for 2.5
94 import bpy
95 import mathutils
96
97 # wrapper
98 from . import bl25 as bl
99
100 xrange=range
101
102 def setMaterialParams(material, m):
103     # diffuse
104     material.diffuse.r=m.diffuse_color[0]
105     material.diffuse.g=m.diffuse_color[1]
106     material.diffuse.b=m.diffuse_color[2]
107     material.diffuse.a=m.alpha
108     # specular
109     material.shinness=0 if m.specular_toon_size<1e-5 else m.specular_hardness*10
110     material.specular.r=m.specular_color[0]
111     material.specular.g=m.specular_color[1]
112     material.specular.b=m.specular_color[2]
113     # ambient
114     material.ambient.r=m.mirror_color[0]
115     material.ambient.g=m.mirror_color[1]
116     material.ambient.b=m.mirror_color[2]
117     # flag
118     material.flag=1 if m.subsurface_scattering.use else 0
119     # toon
120     material.toon_index=0
121
122 def toCP932(s):
123     return s.encode('cp932')
124
125
126 class Node(object):
127     __slots__=['o', 'children']
128     def __init__(self, o):
129         self.o=o
130         self.children=[]
131
132
133 ###############################################################################
134 # Blenderのメッシュをワンスキンメッシュ化する
135 ###############################################################################
136 def near(x, y, EPSILON=1e-5):
137     d=x-y
138     return d>=-EPSILON and d<=EPSILON
139
140
141 class VertexAttribute(object):
142     __slots__=[
143             'nx', 'ny', 'nz', # normal
144             'u', 'v', # uv
145             ]
146     def __init__(self, nx, ny, nz, u, v):
147         self.nx=nx
148         self.ny=ny
149         self.nz=nz
150         self.u=u
151         self.v=v
152
153     def __str__(self):
154         return "<vkey: %f, %f, %f, %f, %f>" % (
155                 self.nx, self.ny, self.nz, self.u, self.v)
156
157     def __hash__(self):
158         return int(100*(self.nx + self.ny + self.nz + self.u + self.v))
159
160     def __eq__(self, rhs):
161         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
162
163
164 class VertexKey(object):
165     __slots__=[
166             'obj_index', 'index',
167             ]
168
169     def __init__(self, obj_index, index):
170         self.obj_index=obj_index
171         self.index=index
172
173     def __str__(self):
174         return "<vkey: %d, %d>" % (self.obj_index, self.index)
175
176     def __hash__(self):
177         return self.index*100+self.obj_index
178
179     def __eq__(self, rhs):
180         return self.obj_index==rhs.obj_index and self.index==rhs.index
181
182
183 class VertexArray(object):
184     """
185     頂点配列
186     """
187     __slots__=[
188             'indexArrays',
189             'positions',
190             'attributes', # normal and uv
191             'b0', 'b1', 'weight',
192             'vertexMap',
193             'objectMap',
194             ]
195     def __init__(self):
196         # indexArrays split with each material
197         self.indexArrays={}
198
199         self.positions=[]
200         self.attributes=[]
201         self.b0=[]
202         self.b1=[]
203         self.weight=[]
204
205         self.vertexMap={}
206         self.objectMap={}
207
208     def __str__(self):
209         return "<VertexArray %d positions, %d indexArrays>" % (
210                 len(self.positions), len(self.indexArrays))
211
212     def zip(self):
213         return zip(
214                 self.positions, self.attributes,
215                 self.b0, self.b1, self.weight)
216
217     def each(self):
218         keys=[key for key in self.indexArrays.keys()]
219         keys.sort()
220         for key in keys:
221             yield(key, self.indexArrays[key])
222
223     def __addOrGetIndex(self, obj_index, base_index, pos, normal, uv, b0, b1, weight0):
224         key=VertexKey(obj_index, base_index)
225         attribute=VertexAttribute( 
226                 normal[0], normal[1], normal[2],
227                 uv[0], uv[1])
228         if key in self.vertexMap:
229             if attribute in self.vertexMap[key]:
230                 return self.vertexMap[key][attribute]
231             else:
232                 return self.__addVertex(self.vertexMap[key],
233                         pos, attribute, b0, b1, weight0)
234         else:
235             vertexMapKey={}
236             self.vertexMap[key]=vertexMapKey
237             return self.__addVertex(vertexMapKey,
238                     pos, attribute, b0, b1, weight0)
239
240     def __addVertex(self, vertexMapKey, pos, attribute, b0, b1, weight0):
241         index=len(self.positions)
242         vertexMapKey[attribute]=index
243         # position
244         self.positions.append((pos.x, pos.y, pos.z))
245         # unique attribute
246         self.attributes.append(attribute)
247         # shared attribute
248         self.b0.append(b0)
249         self.b1.append(b1)
250         self.weight.append(weight0)
251         assert(index<=65535)
252         return index
253             
254     def getMappedIndex(self, obj_name, base_index):
255         return self.vertexMap[VertexKey(self.objectMap[obj_name], base_index)]
256
257     def addTriangle(self,
258             object_name, material,
259             base_index0, base_index1, base_index2,
260             pos0, pos1, pos2,
261             n0, n1, n2,
262             uv0, uv1, uv2,
263             b0_0, b0_1, b0_2,
264             b1_0, b1_1, b1_2,
265             weight0, weight1, weight2
266             ):
267         if object_name in self.objectMap:
268             obj_index=self.objectMap[object_name]
269         else:
270             obj_index=len(self.objectMap)
271             self.objectMap[object_name]=obj_index
272         index0=self.__addOrGetIndex(obj_index, base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
273         index1=self.__addOrGetIndex(obj_index, base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
274         index2=self.__addOrGetIndex(obj_index, base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
275
276         if not material in self.indexArrays:
277             self.indexArrays[material]=[]
278         self.indexArrays[material]+=[index0, index1, index2]
279
280
281 class Morph(object):
282     __slots__=['name', 'type', 'offsets']
283     def __init__(self, name, type):
284         self.name=name
285         self.type=type
286         self.offsets=[]
287
288     def add(self, index, offset):
289         self.offsets.append((index, offset))
290
291     def sort(self):
292         self.offsets.sort(key=lambda e: e[0])
293
294     def __str__(self):
295         return "<Morph %s>" % self.name
296
297 class IKSolver(object):
298     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
299     def __init__(self, target, effector, length, iterations, weight):
300         self.target=target
301         self.effector=effector
302         self.length=length
303         self.iterations=iterations
304         self.weight=weight
305
306
307 class SSS(object):
308     def __init__(self):
309         self.use=1
310
311
312 class DefaultMatrial(object):
313     def __init__(self):
314         self.name='default'
315         # diffuse
316         self.diffuse_color=[1, 1, 1]
317         self.alpha=1
318         # specular
319         self.specular_toon_size=0
320         self.specular_hardness=5
321         self.specular_color=[1, 1, 1]
322         # ambient
323         self.mirror_color=[1, 1, 1]
324         # flag
325         self.subsurface_scattering=SSS()
326         # texture
327         self.texture_slots=[]
328
329
330 class OneSkinMesh(object):
331     __slots__=['vertexArray', 'morphList', 'rigidbodies', 'constraints', ]
332     def __init__(self):
333         self.vertexArray=VertexArray()
334         self.morphList=[]
335         self.rigidbodies=[]
336         self.constraints=[]
337
338     def __str__(self):
339         return "<OneSkinMesh %s, morph:%d>" % (
340                 self.vertexArray,
341                 len(self.morphList))
342
343     def addMesh(self, obj):
344         if not bl.object.isVisible(obj):
345             return
346         self.__mesh(obj)
347         self.__skin(obj)
348         self.__rigidbody(obj)
349         self.__constraint(obj)
350
351     def __getWeightMap(self, obj, mesh):
352         # bone weight
353         weightMap={}
354         secondWeightMap={}
355         def setWeight(i, name, w):
356             if w>0:
357                 if i in weightMap:
358                     if i in secondWeightMap:
359                         # 上位2つのweightを採用する
360                         if w<secondWeightMap[i][1]:
361                             pass
362                         elif w<weightMap[i][1]:
363                             # 2つ目を入れ替え
364                             secondWeightMap[i]=(name, w)
365                         else:
366                             # 1つ目を入れ替え
367                             weightMap[i]=(name, w)
368                     else:
369                         if w>weightMap[i][1]:
370                             # 多い方をweightMapに
371                             secondWeightMap[i]=weightMap[i]
372                             weightMap[i]=(name, w)
373                         else:
374                             secondWeightMap[i]=(name, w)
375                 else:
376                     weightMap[i]=(name, w)
377
378         # ToDo bone weightと関係ないvertex groupを除外する
379         for i, v in enumerate(mesh.vertices):
380             if len(v.groups)>0:
381                 for g in v.groups:
382                     setWeight(i, obj.vertex_groups[g.group].name, g.weight)
383             else:
384                 try:
385                     setWeight(i, obj.vertex_groups[0].name, 1)
386                 except:
387                     # no vertex_groups
388                     pass
389
390         # 合計値が1になるようにする
391         for i in xrange(len(mesh.vertices)):
392             if i in secondWeightMap:
393                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
394             elif i in weightMap:
395                 weightMap[i]=(weightMap[i][0], 1.0)
396                 secondWeightMap[i]=("", 0)
397             else:
398                 print("no weight vertex")
399                 weightMap[i]=("", 0)
400                 secondWeightMap[i]=("", 0)
401
402         return weightMap, secondWeightMap
403
404     def __processFaces(self, obj_name, mesh, weightMap, secondWeightMap):
405         default_material=DefaultMatrial()
406         # 各面の処理
407         for i, face in enumerate(mesh.faces):
408             faceVertexCount=bl.face.getVertexCount(face)
409             try:
410                 material=mesh.materials[bl.face.getMaterialIndex(face)]
411             except IndexError as e:
412                 material=default_material
413             v=[mesh.vertices[index] for index in bl.face.getVertices(face)]
414             uv=bl.mesh.getFaceUV(
415                     mesh, i, face, bl.face.getVertexCount(face))
416             # flip triangle
417             if faceVertexCount==3:
418                 # triangle
419                 self.vertexArray.addTriangle(
420                         obj_name, material.name,
421                         v[2].index, 
422                         v[1].index, 
423                         v[0].index,
424                         v[2].co, 
425                         v[1].co, 
426                         v[0].co,
427                         bl.vertex.getNormal(v[2]), 
428                         bl.vertex.getNormal(v[1]), 
429                         bl.vertex.getNormal(v[0]),
430                         uv[2], 
431                         uv[1], 
432                         uv[0],
433                         weightMap[v[2].index][0],
434                         weightMap[v[1].index][0],
435                         weightMap[v[0].index][0],
436                         secondWeightMap[v[2].index][0],
437                         secondWeightMap[v[1].index][0],
438                         secondWeightMap[v[0].index][0],
439                         weightMap[v[2].index][1],
440                         weightMap[v[1].index][1],
441                         weightMap[v[0].index][1]
442                         )
443             elif faceVertexCount==4:
444                 # quadrangle
445                 self.vertexArray.addTriangle(
446                         obj_name, material.name,
447                         v[2].index, 
448                         v[1].index, 
449                         v[0].index,
450                         v[2].co, 
451                         v[1].co, 
452                         v[0].co,
453                         bl.vertex.getNormal(v[2]), 
454                         bl.vertex.getNormal(v[1]), 
455                         bl.vertex.getNormal(v[0]), 
456                         uv[2], 
457                         uv[1], 
458                         uv[0],
459                         weightMap[v[2].index][0],
460                         weightMap[v[1].index][0],
461                         weightMap[v[0].index][0],
462                         secondWeightMap[v[2].index][0],
463                         secondWeightMap[v[1].index][0],
464                         secondWeightMap[v[0].index][0],
465                         weightMap[v[2].index][1],
466                         weightMap[v[1].index][1],
467                         weightMap[v[0].index][1]
468                         )
469                 self.vertexArray.addTriangle(
470                         obj_name, material.name,
471                         v[0].index, 
472                         v[3].index, 
473                         v[2].index,
474                         v[0].co, 
475                         v[3].co, 
476                         v[2].co,
477                         bl.vertex.getNormal(v[0]), 
478                         bl.vertex.getNormal(v[3]), 
479                         bl.vertex.getNormal(v[2]), 
480                         uv[0], 
481                         uv[3], 
482                         uv[2],
483                         weightMap[v[0].index][0],
484                         weightMap[v[3].index][0],
485                         weightMap[v[2].index][0],
486                         secondWeightMap[v[0].index][0],
487                         secondWeightMap[v[3].index][0],
488                         secondWeightMap[v[2].index][0],
489                         weightMap[v[0].index][1],
490                         weightMap[v[3].index][1],
491                         weightMap[v[2].index][1]
492                         )
493
494     def __mesh(self, obj):
495         if RIGID_SHAPE_TYPE in obj:
496             return
497         if CONSTRAINT_A in obj:
498             return
499
500         bl.message("export: %s" % obj.name)
501
502         # メッシュのコピーを生成してオブジェクトの行列を適用する
503         copyMesh, copyObj=bl.object.duplicate(obj)
504         if len(copyMesh.vertices)>0:
505             # apply transform
506             """
507             try:
508                 # svn 36722
509                 copyObj.scale=obj.scale
510                 bpy.ops.object.transform_apply(scale=True)
511                 copyObj.rotation_euler=obj.rotation_euler
512                 bpy.ops.object.transform_apply(rotation=True)
513                 copyObj.location=obj.location
514                 bpy.ops.object.transform_apply(location=True)
515             except AttributeError as e:
516                 # 2.57b
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()
523             """
524             copyMesh.transform(obj.matrix_world)
525
526             # apply modifier
527             for m in [m for m in copyObj.modifiers]:
528                 if m.type=='SOLIDFY':
529                     continue
530                 elif m.type=='ARMATURE':
531                     continue
532                 elif m.type=='MIRROR':
533                     bpy.ops.object.modifier_apply(modifier=m.name)
534                 else:
535                     print(m.type)
536
537             weightMap, secondWeightMap=self.__getWeightMap(copyObj, copyMesh)
538             self.__processFaces(obj.name, copyMesh, weightMap, secondWeightMap)
539         bl.object.delete(copyObj)
540
541     def createEmptyBasicSkin(self):
542         self.__getOrCreateMorph('base', 0)
543
544     def __skin(self, obj):
545         if not bl.object.hasShapeKey(obj):
546             return
547
548         indexRelativeMap={}
549         blenderMesh=bl.object.getData(obj)
550         baseMorph=None
551
552         # shape keys
553         vg=bl.object.getVertexGroup(obj, MMD_SHAPE_GROUP_NAME)
554
555         # base
556         used=set()
557         for b in bl.object.getShapeKeys(obj):
558             if b.name==BASE_SHAPE_NAME:
559                 baseMorph=self.__getOrCreateMorph('base', 0)
560                 basis=b
561
562                 relativeIndex=0
563                 for index in vg:
564                     v=bl.shapekey.getByIndex(b, index)
565                     pos=[v[0], v[1], v[2]]
566
567                     indices=self.vertexArray.getMappedIndex(obj.name, index)
568                     for attribute, i in indices.items():
569                         if i in used:
570                             continue
571                         used.add(i)
572
573                         baseMorph.add(i, pos)
574                         indexRelativeMap[i]=relativeIndex
575                         relativeIndex+=1
576
577                 break
578         assert(basis)
579         #print(basis.name, len(baseMorph.offsets))
580
581         if len(baseMorph.offsets)==0:
582             return
583
584         # shape keys
585         for b in bl.object.getShapeKeys(obj):
586             if b.name==BASE_SHAPE_NAME:
587                 continue
588
589             #print(b.name)
590             morph=self.__getOrCreateMorph(b.name, 4)
591             used=set()
592             for index, src, dst in zip(
593                     xrange(len(blenderMesh.vertices)),
594                     bl.shapekey.get(basis),
595                     bl.shapekey.get(b)):
596                 offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
597                 if offset[0]==0 and offset[1]==0 and offset[2]==0:
598                     continue
599                 if index in vg:
600                     indices=self.vertexArray.getMappedIndex(obj.name, index)
601                     for attribute, i in indices.items():
602                         if i in used:
603                             continue
604                         used.add(i) 
605                         morph.add(indexRelativeMap[i], offset)
606             assert(len(morph.offsets)<len(baseMorph.offsets))
607
608         # sort skinmap
609         original=self.morphList[:]
610         def getIndex(morph):
611             for i, v in enumerate(englishmap.skinMap):
612                 if v[0]==morph.name:
613                     return i
614             #print(morph)
615             return len(englishmap.skinMap)
616         self.morphList.sort(key=getIndex)
617
618     def __rigidbody(self, obj):
619         if not RIGID_SHAPE_TYPE in obj:
620             return
621         self.rigidbodies.append(obj)
622
623     def __constraint(self, obj):
624         if not CONSTRAINT_A in obj:
625             return
626         self.constraints.append(obj)
627
628     def __getOrCreateMorph(self, name, type):
629         for m in self.morphList:
630             if m.name==name:
631                 return m
632         m=Morph(name, type)
633         self.morphList.append(m)
634         return m
635
636     def getVertexCount(self):
637         return len(self.vertexArray.positions)
638
639
640 class Bone(object):
641     __slots__=['index', 'name', 'ik_index',
642             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
643     def __init__(self, name, pos, tail, isConnect):
644         self.index=-1
645         self.name=name
646         self.pos=pos
647         self.tail=tail
648         self.parent_index=None
649         self.tail_index=None
650         self.type=0
651         self.isConnect=isConnect
652         self.ik_index=0
653
654     def __eq__(self, rhs):
655         return self.index==rhs.index
656
657     def __str__(self):
658         return "<Bone %s %d>" % (self.name, self.type)
659
660 class BoneBuilder(object):
661     __slots__=['bones', 'boneMap', 'ik_list', 'bone_groups',]
662     def __init__(self):
663         self.bones=[]
664         self.boneMap={}
665         self.ik_list=[]
666         self.bone_groups=[]
667
668     def getBoneGroup(self, bone):
669         for i, g in enumerate(self.bone_groups):
670             for b in g[1]:
671                 if b==bone.name:
672                     return i+1
673         print('no gorup', bone)
674         return 0
675
676     def build(self, armatureObj):
677         if not armatureObj:
678             return
679
680         bl.message("build skeleton")
681         armature=bl.object.getData(armatureObj)
682
683         ####################
684         # bone group
685         ####################
686         for g in bl.object.boneGroups(armatureObj):
687             self.bone_groups.append((g.name, []))
688
689         ####################
690         # get bones
691         ####################
692         for b in armature.bones.values():
693             if not b.parent:
694                 # root bone
695                 bone=Bone(b.name, 
696                         bl.bone.getHeadLocal(b),
697                         bl.bone.getTailLocal(b),
698                         False)
699                 self.__addBone(bone)
700                 self.__getBone(bone, b)
701
702         for b in armature.bones.values():
703             if not b.parent:
704                 self.__checkConnection(b, None)
705
706         ####################
707         # get IK
708         ####################
709         pose = bl.object.getPose(armatureObj)
710         for b in pose.bones.values():
711             ####################
712             # assing bone group
713             ####################
714             self.__assignBoneGroup(b, b.bone_group)
715             for c in b.constraints:
716                 if bl.constraint.isIKSolver(c):
717                     ####################
718                     # IK target
719                     ####################
720                     target=self.__boneByName(bl.constraint.ikTarget(c))
721                     target.type=2
722
723                     ####################
724                     # IK effector
725                     ####################
726                     # IK 接続先
727                     link=self.__boneByName(b.name)
728                     link.type=6
729
730                     # IK chain
731                     e=b.parent
732                     chainLength=bl.constraint.ikChainLen(c)
733                     for i in range(chainLength):
734                         # IK影響下
735                         chainBone=self.__boneByName(e.name)
736                         chainBone.type=4
737                         chainBone.ik_index=target.index
738                         e=e.parent
739                     self.ik_list.append(
740                             IKSolver(target, link, chainLength, 
741                                 int(bl.constraint.ikItration(c) * 0.1), 
742                                 bl.constraint.ikRotationWeight(c)
743                                 ))
744
745         ####################
746
747         # boneのsort
748         self._sortBy()
749         self._fix()
750         # IKのsort
751         def getIndex(ik):
752             for i, v in enumerate(englishmap.boneMap):
753                 if v[0]==ik.target.name:
754                     return i
755             return len(englishmap.boneMap)
756         self.ik_list.sort(key=getIndex)
757
758     def __assignBoneGroup(self, poseBone, boneGroup):
759         if boneGroup:
760             for g in self.bone_groups:
761                 if g[0]==boneGroup.name:
762                     g[1].append(poseBone.name)
763
764     def __checkConnection(self, b, p):
765         if bl.bone.isConnected(b):
766             parent=self.__boneByName(p.name)
767             parent.isConnect=True
768
769         for c in b.children:
770             self.__checkConnection(c, b)
771
772     def _sortBy(self):
773         """
774         boneMap順に並べ替える
775         """
776         boneMap=englishmap.boneMap
777         original=self.bones[:]
778         def getIndex(bone):
779             for i, k_v in enumerate(boneMap):
780                 if k_v[0]==bone.name:
781                     return i
782             print(bone)
783             return len(boneMap)
784
785         self.bones.sort(key=getIndex)
786
787         sortMap={}
788         for i, b in enumerate(self.bones):
789             src=original.index(b)
790             sortMap[src]=i
791         for b in self.bones:
792             b.index=sortMap[b.index]
793             if b.parent_index:
794                 b.parent_index=sortMap[b.parent_index]
795             if b.tail_index:
796                 b.tail_index=sortMap[b.tail_index]
797             if b.ik_index>0:
798                 b.ik_index=sortMap[b.ik_index]
799
800     def _fix(self):
801         """
802         調整
803         """
804         for b in self.bones:
805             # parent index
806             if b.parent_index==None:
807                 b.parent_index=0xFFFF
808             else:
809                 if b.type==6 or b.type==7:
810                     # fix tail bone
811                     parent=self.bones[b.parent_index]
812                     #print('parnet', parent.name)
813                     parent.tail_index=b.index
814
815         for b in self.bones:
816             if b.tail_index==None:
817                 b.tail_index=0
818             elif b.type==9:
819                 b.tail_index==0
820
821     def getIndex(self, bone):
822         for i, b in enumerate(self.bones):
823             if b==bone:
824                 return i
825         assert(false)
826
827     def indexByName(self, name):
828         if name=='':
829             return 0
830         else:
831             try:
832                 return self.getIndex(self.__boneByName(name))
833             except:
834                 return 0
835
836     def __boneByName(self, name):
837         return self.boneMap[name]
838
839     def __getBone(self, parent, b):
840         if len(b.children)==0:
841             parent.type=7
842             return
843
844         for i, c in enumerate(b.children):
845             bone=Bone(c.name, 
846                     bl.bone.getHeadLocal(c),
847                     bl.bone.getTailLocal(c),
848                     bl.bone.isConnected(c))
849             self.__addBone(bone)
850             if parent:
851                 bone.parent_index=parent.index
852                 #if i==0:
853                 if bone.isConnect or (not parent.tail_index and parent.tail==bone.pos):
854                     parent.tail_index=bone.index
855             self.__getBone(bone, c)
856
857     def __addBone(self, bone):
858         bone.index=len(self.bones)
859         self.bones.append(bone)
860         self.boneMap[bone.name]=bone
861
862
863 class PmdExporter(object):
864
865     __slots__=[
866             'armatureObj',
867             'oneSkinMesh',
868             'englishName',
869             'englishComment',
870             'name',
871             'comment',
872             'skeleton',
873             ]
874     def setup(self):
875         self.armatureObj=None
876
877         # 木構造を構築する
878         object_node_map={}
879         for o in bl.object.each():
880             object_node_map[o]=Node(o)
881         for o in bl.object.each():
882             node=object_node_map[o]
883             if node.o.parent:
884                 object_node_map[node.o.parent].children.append(node)
885
886         # ルートを得る
887         root=object_node_map[bl.object.getActive()]
888         o=root.o
889         self.englishName=o.name
890         self.englishComment=o[MMD_COMMENT] if MMD_COMMENT in o else 'blender export\n'
891         self.name=o[MMD_MB_NAME] if MMD_MB_NAME in o else 'Blenderエクスポート'
892         self.comment=o[MMD_MB_COMMENT] if MMD_MB_COMMENT in o else 'Blnderエクスポート\n'
893
894         # ワンスキンメッシュを作る
895         self.oneSkinMesh=OneSkinMesh()
896         self.__createOneSkinMesh(root)
897         bl.message(self.oneSkinMesh)
898         if len(self.oneSkinMesh.morphList)==0:
899             # create emtpy skin
900             self.oneSkinMesh.createEmptyBasicSkin()
901
902         # skeleton
903         self.skeleton=BoneBuilder()
904         self.skeleton.build(self.armatureObj)
905
906     def __createOneSkinMesh(self, node):
907         ############################################################
908         # search armature modifier
909         ############################################################
910         for m in node.o.modifiers:
911             if bl.modifier.isType(m, 'ARMATURE'):
912                 armatureObj=bl.modifier.getArmatureObject(m)
913                 if not self.armatureObj:
914                     self.armatureObj=armatureObj
915                 elif self.armatureObj!=armatureObj:
916                     print("warning! found multiple armature. ignored.", 
917                             armatureObj.name)
918
919         if node.o.type.upper()=='MESH':
920             self.oneSkinMesh.addMesh(node.o)
921
922         for child in node.children:
923             self.__createOneSkinMesh(child)
924
925     def write(self, path):
926         io=pmd.IO()
927         io.name=self.name
928         io.comment=self.comment
929         io.version=1.0
930
931         # 頂点
932         for pos, attribute, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
933             # convert right-handed z-up to left-handed y-up
934             v=io.addVertex()
935             v.pos.x=pos[0]
936             v.pos.y=pos[2]
937             v.pos.z=pos[1]
938             # convert right-handed z-up to left-handed y-up
939             v.normal.x=attribute.nx
940             v.normal.y=attribute.nz
941             v.normal.z=attribute.ny
942             v.uv.x=attribute.u
943             v.uv.y=1.0-attribute.v # reverse vertical
944             v.bone0=self.skeleton.indexByName(b0)
945             v.bone1=self.skeleton.indexByName(b1)
946             v.weight0=int(100*weight)
947             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
948
949         # 面とマテリアル
950         vertexCount=self.oneSkinMesh.getVertexCount()
951         for material_name, indices in self.oneSkinMesh.vertexArray.each():
952             #print('material:', material_name)
953             try:
954                 m=bl.material.get(material_name)
955             except KeyError as e:
956                 m=DefaultMatrial()
957             # マテリアル
958             material=io.addMaterial()
959             setMaterialParams(material, m)
960
961             material.vertex_count=len(indices)
962             def get_texture_name(texture):
963                 pos=texture.replace("\\", "/").rfind("/")
964                 if pos==-1:
965                     return texture
966                 else:
967                     return texture[pos+1:]
968             textures=[get_texture_name(path)
969                 for path in bl.material.eachEnalbeTexturePath(m)]
970             print(textures)
971             if len(textures)>0:
972                 material.texture='*'.join(textures)
973             else:
974                 material.texture=""
975             # 面
976             for i in indices:
977                 assert(i<vertexCount)
978             for i in xrange(0, len(indices), 3):
979                 # reverse triangle
980                 io.indices.append(indices[i])
981                 io.indices.append(indices[i+1])
982                 io.indices.append(indices[i+2])
983
984         # bones
985         boneNameMap={}
986         for i, b in enumerate(self.skeleton.bones):
987             bone=io.addBone()
988
989             # name
990             boneNameMap[b.name]=i
991             v=englishmap.getUnicodeBoneName(b.name)
992             if not v:
993                 v=[b.name, b.name]
994             assert(v)
995             bone.name=v[1]
996
997             # english name
998             bone_english_name=toCP932(b.name)
999             if len(bone_english_name)>=20:
1000                 print(bone_english_name)
1001                 #assert(len(bone_english_name)<20)
1002             bone.english_name=bone_english_name
1003
1004             if len(v)>=3:
1005                 # has type
1006                 if v[2]==5:
1007                     b.ik_index=self.skeleton.indexByName('eyes')
1008                 bone.type=v[2]
1009             else:
1010                 bone.type=b.type
1011
1012             bone.parent_index=b.parent_index
1013             bone.tail_index=b.tail_index
1014             bone.ik_index=b.ik_index
1015
1016             # convert right-handed z-up to left-handed y-up
1017             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
1018             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
1019             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
1020
1021         # IK
1022         for ik in self.skeleton.ik_list:
1023             solver=io.addIK()
1024             solver.index=self.skeleton.getIndex(ik.target)
1025             solver.target=self.skeleton.getIndex(ik.effector)
1026             solver.length=ik.length
1027             b=self.skeleton.bones[ik.effector.parent_index]
1028             for i in xrange(solver.length):
1029                 solver.children.append(self.skeleton.getIndex(b))
1030                 b=self.skeleton.bones[b.parent_index]
1031             solver.iterations=ik.iterations
1032             solver.weight=ik.weight
1033
1034         # 表情
1035         for i, m in enumerate(self.oneSkinMesh.morphList):
1036             # morph
1037             morph=io.addMorph()
1038
1039             v=englishmap.getUnicodeSkinName(m.name)
1040             if not v:
1041                 v=[m.name, m.name, 0]
1042             assert(v)
1043             morph.name=v[1]
1044             morph.english_name=m.name
1045             m.type=v[2]
1046             morph.type=v[2]
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)
1051
1052         # 表情枠
1053         # type==0はbase
1054         for i, m in enumerate(self.oneSkinMesh.morphList):
1055             if m.type==3:
1056                 io.face_list.append(i)
1057         for i, m in enumerate(self.oneSkinMesh.morphList):
1058             if m.type==2:
1059                 io.face_list.append(i)
1060         for i, m in enumerate(self.oneSkinMesh.morphList):
1061             if m.type==1:
1062                 io.face_list.append(i)
1063         for i, m in enumerate(self.oneSkinMesh.morphList):
1064             if m.type==4:
1065                 io.face_list.append(i)
1066
1067         # ボーングループ
1068         for g in self.skeleton.bone_groups:
1069             boneDisplayName=io.addBoneGroup()
1070             # name
1071             name=englishmap.getUnicodeBoneGroupName(g[0])
1072             if not name:
1073                 name=g[0]
1074             boneDisplayName.name=name+'\n'
1075             # english
1076             englishName=g[0]
1077             boneDisplayName.english_name=englishName+'\n'
1078
1079         # ボーングループメンバー
1080         for i, b in enumerate(self.skeleton.bones):
1081             if i==0:
1082                continue
1083             if b.type in [6, 7]:
1084                continue
1085             io.addBoneDisplay(i, self.skeleton.getBoneGroup(b))
1086
1087         #assert(len(io.bones)==len(io.bone_display_list)+1)
1088
1089         # English
1090         io.english_name=self.englishName
1091         io.english_comment=self.englishComment
1092
1093         # toon
1094         toonMeshObject=None
1095         for o in bl.object.each():
1096             try:
1097                 if o.name.startswith(TOON_TEXTURE_OBJECT):
1098                     toonMeshObject=o
1099             except:
1100                 p(o.name)
1101             break
1102         if toonMeshObject:
1103             toonMesh=bl.object.getData(toonMeshObject)
1104             toonMaterial=bl.mesh.getMaterial(toonMesh, 0)
1105             for i in range(10):
1106                 t=bl.material.getTexture(toonMaterial, i)
1107                 if t:
1108                     io.toon_textures[i]="%s" % t.name
1109                 else:
1110                     io.toon_textures[i]="toon%02d.bmp" % (i+1)
1111         else:
1112             for i in range(10):
1113                 io.toon_textures[i]="toon%02d.bmp" % (i+1)
1114
1115         # rigid body
1116         rigidNameMap={}
1117         for i, obj in enumerate(self.oneSkinMesh.rigidbodies):
1118             name=obj[RIGID_NAME] if RIGID_NAME in obj else obj.name
1119             #print(name)
1120             rigidBody=pmd.RigidBody(name)
1121             rigidNameMap[name]=i
1122             boneIndex=boneNameMap[obj[RIGID_BONE_NAME]]
1123             if boneIndex==0:
1124                 boneIndex=0xFFFF
1125                 bone=self.skeleton.bones[0]
1126             else:
1127                 bone=self.skeleton.bones[boneIndex]
1128             rigidBody.boneIndex=boneIndex
1129             #rigidBody.position.x=obj[RIGID_LOCATION][0]
1130             #rigidBody.position.y=obj[RIGID_LOCATION][1]
1131             #rigidBody.position.z=obj[RIGID_LOCATION][2]
1132             rigidBody.position.x=obj.location.x-bone.pos[0]
1133             rigidBody.position.y=obj.location.z-bone.pos[2]
1134             rigidBody.position.z=obj.location.y-bone.pos[1]
1135             rigidBody.rotation.x=-obj.rotation_euler[0]
1136             rigidBody.rotation.y=-obj.rotation_euler[2]
1137             rigidBody.rotation.z=-obj.rotation_euler[1]
1138             rigidBody.processType=obj[RIGID_PROCESS_TYPE]
1139             rigidBody.group=obj[RIGID_GROUP]
1140             rigidBody.target=obj[RIGID_INTERSECTION_GROUP]
1141             rigidBody.weight=obj[RIGID_WEIGHT]
1142             rigidBody.linearDamping=obj[RIGID_LINEAR_DAMPING]
1143             rigidBody.angularDamping=obj[RIGID_ANGULAR_DAMPING]
1144             rigidBody.restitution=obj[RIGID_RESTITUTION]
1145             rigidBody.friction=obj[RIGID_FRICTION]
1146             if obj[RIGID_SHAPE_TYPE]==0:
1147                 rigidBody.shapeType=pmd.SHAPE_SPHERE
1148                 rigidBody.w=obj.scale[0]
1149                 rigidBody.d=0
1150                 rigidBody.h=0
1151             elif obj[RIGID_SHAPE_TYPE]==1:
1152                 rigidBody.shapeType=pmd.SHAPE_BOX
1153                 rigidBody.w=obj.scale[0]
1154                 rigidBody.d=obj.scale[1]
1155                 rigidBody.h=obj.scale[2]
1156             elif obj[RIGID_SHAPE_TYPE]==2:
1157                 rigidBody.shapeType=pmd.SHAPE_CAPSULE
1158                 rigidBody.w=obj.scale[0]
1159                 rigidBody.h=obj.scale[2]
1160                 rigidBody.d=0
1161             io.rigidbodies.append(rigidBody)
1162
1163         # constraint
1164         for obj in self.oneSkinMesh.constraints:
1165             constraint=pmd.Constraint(obj[CONSTRAINT_NAME])
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]
1192             io.constraints.append(constraint)
1193
1194         # 書き込み
1195         bl.message('write: %s' % path)
1196         return io.write(path)
1197
1198
1199 def _execute(filepath=''):
1200     active=bl.object.getActive()
1201     if not active:
1202         print("abort. no active object.")
1203         return
1204     exporter=PmdExporter()
1205     exporter.setup()
1206     print(exporter)
1207     exporter.write(filepath)
1208     bl.object.activate(active)
1209
1210