OSDN Git Service

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