OSDN Git Service

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