OSDN Git Service

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