OSDN Git Service

update for blender2.53.
[meshio/meshio.git] / swig / blender24 / 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.0"
11 __url__=()
12 __bpydoc__="""
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
15 1.0 20100530 implement, basic features.
16 """
17 import Blender
18 import os
19 import sys
20
21 from meshio import pmd, englishmap
22
23
24 # ファイルシステムの文字コード
25 # 改造版との共用のため
26 FS_ENCODING=sys.getfilesystemencoding()
27 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
28     INTERNAL_ENCODING='utf-8'
29 else:
30     INTERNAL_ENCODING=FS_ENCODING
31
32
33 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
34 EXTENSION = u'.pmd'
35
36
37 class Node(object):
38     __slots__=['o', 'children']
39     def __init__(self, o):
40         self.o=o
41         self.children=[]
42
43
44 ###############################################################################
45 # Blenderのメッシュをワンスキンメッシュ化する
46 ###############################################################################
47 def near(x, y, EPSILON=1e-5):
48     d=x-y
49     return d>=-EPSILON and d<=EPSILON
50
51
52 class VertexKey(object):
53     """
54     重複頂点の検索キー
55     """
56     __slots__=[
57             'x', 'y', 'z', # 位置
58             'nx', 'ny', 'nz', # 法線
59             'u', 'v', # uv
60             ]
61
62     def __init__(self, x, y, z, nx, ny, nz, u, v):
63         self.x=x
64         self.y=y
65         self.z=z
66         self.nx=nx
67         self.ny=ny
68         self.nz=nz
69         self.u=u
70         self.v=v
71
72     def __str__(self):
73         return "<vkey: %f, %f, %f, %f, %f, %f, %f, %f>" % (
74                 self.x, self.y, self.z, self.nx, self.ny, self.nz, self.u, self.v)
75
76     def __hash__(self):
77         #return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
78         return int((self.x+self.y+self.z)*100)
79
80     def __eq__(self, rhs):
81         #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z) and near(self.nx, rhs.nx) and near(self.ny, rhs.ny) and near(self.nz, rhs.nz) and near(self.u, rhs.u) and near(self.v, rhs.v)
82         #return near(self.x, rhs.x) and near(self.y, rhs.y) and near(self.z, rhs.z)
83         return self.x==rhs.x and self.y==rhs.y and self.z==rhs.z
84
85
86 class VertexArray(object):
87     """
88     頂点配列
89     """
90     def __init__(self):
91         # マテリアル毎に分割したインデックス配列
92         self.indexArrays={}
93         # 頂点属性
94         self.vertices=[]
95         self.normals=[]
96         self.uvs=[]
97         # skinning属性
98         self.b0=[]
99         self.b1=[]
100         self.weight=[]
101
102         self.vertexMap={}
103         self.indexMap={}
104
105     def __str__(self):
106         return "<VertexArray %d vertices, %d indexArrays>" % (
107                 len(self.vertices), len(self.indexArrays))
108
109     def zip(self):
110         return zip(
111                 self.vertices, self.normals, self.uvs,
112                 self.b0, self.b1, self.weight)
113
114     def __getIndex(self, base_index, pos, normal, uv, b0, b1, weight0):
115         """
116         頂点属性からその頂点のインデックスを得る
117         """
118         key=VertexKey(
119                 pos[0], pos[1], pos[2],
120                 normal[0], normal[1], normal[2],
121                 uv[0], uv[1])
122         if key in self.vertexMap:
123             # 同じ頂点を登録済み
124             index=self.vertexMap[key]
125         else:
126             index=len(self.vertices)
127             # 新規頂点
128             self.vertexMap[key]=index
129             # append...
130             self.vertices.append((pos.x, pos.y, pos.z))
131             self.normals.append((normal.x, normal.y, normal.z))
132             self.uvs.append((uv.x, uv.y))
133             self.b0.append(b0)
134             self.b1.append(b1)
135             self.weight.append(weight0)
136             
137         # indexのマッピングを保存する
138         if not base_index in self.indexMap:
139             self.indexMap[base_index]=set()
140         self.indexMap[base_index].add(index)
141
142         assert(index<=65535)
143         return index
144
145     def getMappedIndices(self, base_index):
146         return self.indexMap[base_index]
147
148     def addTriangle(self,
149             material,
150             base_index0, base_index1, base_index2,
151             pos0, pos1, pos2,
152             n0, n1, n2,
153             uv0, uv1, uv2,
154             b0_0, b0_1, b0_2,
155             b1_0, b1_1, b1_2,
156             weight0, weight1, weight2
157             ):
158         if not material in self.indexArrays:
159             self.indexArrays[material]=[]
160
161         index0=self.__getIndex(base_index0, pos0, n0, uv0, b0_0, b1_0, weight0)
162         index1=self.__getIndex(base_index1, pos1, n1, uv1, b0_1, b1_1, weight1)
163         index2=self.__getIndex(base_index2, pos2, n2, uv2, b0_2, b1_2, weight2)
164
165         self.indexArrays[material]+=[index0, index1, index2]
166
167
168 class Morph(object):
169     __slots__=['name', 'type', 'offsets']
170     def __init__(self, name, type):
171         self.name=name
172         self.type=type
173         self.offsets=[]
174
175     def add(self, index, offset):
176         self.offsets.append((index, offset))
177
178     def sort(self):
179         self.offsets.sort(lambda l, r: l[0]-r[0])
180
181     def __str__(self):
182         return "<Morph %s>" % self.name
183
184 class IKSolver(object):
185     __slots__=['target', 'effector', 'length', 'iterations', 'weight']
186     def __init__(self, target, effector, length, iterations, weight):
187         self.target=target
188         self.effector=effector
189         self.length=length
190         self.iterations=iterations
191         self.weight=weight
192
193
194 class OneSkinMesh(object):
195     __slots__=['vertexArray', 'morphList']
196     def __init__(self):
197         self.vertexArray=VertexArray()
198         self.morphList=[]
199
200     def __str__(self):
201         return "<OneSkinMesh %s, morph:%d>" % (
202                 self.vertexArray,
203                 len(self.morphList))
204
205     def addMesh(self, obj):
206         if obj.restrictDisplay:
207             # 非表示
208             return
209
210         print("export", obj.name)
211
212         ############################################################
213         # bone weight
214         ############################################################
215         mesh=obj.getData(mesh=True)
216         weightMap={}
217         secondWeightMap={}
218         for name in mesh.getVertGroupNames():
219             for i, w in mesh.getVertsFromGroup(name, 1):
220                 if w>0:
221                     if i in weightMap:
222                         if i in secondWeightMap:
223                             # 上位2つのweightを採用する
224                             if w<secondWeightMap[i]:
225                                 pass
226                             elif w<weightMap[i]:
227                                 # 2つ目を入れ替え
228                                 secondWeightMap[i]=(name, w)
229                             else:
230                                 # 1つ目を入れ替え
231                                 weightMap[i]=(name, w)
232                         else:
233                             if w>weightMap[i][1]:
234                                 # 多い方をweightMapに
235                                 secondWeightMap[i]=weightMap[i]
236                                 weightMap[i]=(name, w)
237                             else:
238                                 secondWeightMap[i]=(name, w)
239                     else:
240                         weightMap[i]=(name, w)
241
242         # 合計値が1になるようにする
243         for i in xrange(len(mesh.verts)):
244         #for i, name_weight in weightMap.items():
245             if i in secondWeightMap:
246                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
247             elif i in weightMap:
248                 weightMap[i]=(weightMap[i][0], 1.0)
249                 secondWeightMap[i]=("", 0)
250             else:
251                 print "no weight vertex"
252                 weightMap[i]=("", 0)
253                 secondWeightMap[i]=("", 0)
254                 
255
256         ############################################################
257         # faces
258         # 新たにメッシュを生成する
259         ############################################################
260         mesh=Blender.Mesh.New()
261         # not applied modifiers
262         mesh.getFromObject(obj.name, 1)
263         # apply object transform
264         mesh.transform(obj.getMatrix())
265         if len(mesh.verts)==0:
266             return
267
268         for face in mesh.faces:
269             faceVertexCount=len(face.v)
270             material=mesh.materials[face.mat]
271             if faceVertexCount==3:
272                 v0=face.v[0]
273                 v1=face.v[1]
274                 v2=face.v[2]
275                 # triangle
276                 self.vertexArray.addTriangle(
277                         material.name,
278                         v0.index, v1.index, v2.index,
279                         v0.co, v1.co, v2.co,
280                         # ToDo vertex normal
281                         #v0.no, v1.no, v2.no,
282                         face.no, face.no, face.no,
283                         face.uv[0], face.uv[1], face.uv[2],
284                         weightMap[v0.index][0],
285                         weightMap[v1.index][0],
286                         weightMap[v2.index][0],
287                         secondWeightMap[v0.index][0],
288                         secondWeightMap[v1.index][0],
289                         secondWeightMap[v2.index][0],
290                         weightMap[v0.index][1],
291                         weightMap[v1.index][1],
292                         weightMap[v2.index][1]
293                         )
294             elif faceVertexCount==4:
295                 v0=face.v[0]
296                 v1=face.v[1]
297                 v2=face.v[2]
298                 v3=face.v[3]
299                 # quadrangle
300                 self.vertexArray.addTriangle(
301                         material.name,
302                         v0.index, v1.index, v2.index,
303                         v0.co, v1.co, v2.co,
304                         #v0.no, v1.no, v2.no,
305                         face.no, face.no, face.no,
306                         face.uv[0], face.uv[1], face.uv[2],
307                         weightMap[v0.index][0],
308                         weightMap[v1.index][0],
309                         weightMap[v2.index][0],
310                         secondWeightMap[v0.index][0],
311                         secondWeightMap[v1.index][0],
312                         secondWeightMap[v2.index][0],
313                         weightMap[v0.index][1],
314                         weightMap[v1.index][1],
315                         weightMap[v2.index][1]
316                         )
317                 self.vertexArray.addTriangle(
318                         material.name,
319                         v2.index, v3.index, v0.index,
320                         v2.co, v3.co, v0.co,
321                         #v2.no, v3.no, v0.no,
322                         face.no, face.no, face.no,
323                         face.uv[2], face.uv[3], face.uv[0],
324                         weightMap[v2.index][0],
325                         weightMap[v3.index][0],
326                         weightMap[v0.index][0],
327                         secondWeightMap[v2.index][0],
328                         secondWeightMap[v3.index][0],
329                         secondWeightMap[v0.index][0],
330                         weightMap[v2.index][1],
331                         weightMap[v3.index][1],
332                         weightMap[v0.index][1]
333                         )
334
335         ############################################################
336         # skin
337         ############################################################
338         # base
339         indexRelativeMap={}
340         blenderMesh=obj.getData(mesh=True)
341         baseMorph=None
342         if blenderMesh.key:
343             for b in blenderMesh.key.blocks:
344                 if b.name=='Basis':
345                     print(b.name)
346                     baseMorph=self.__getOrCreateMorph('base', 0)
347                     relativeIndex=0
348                     basis=b
349                     for index in blenderMesh.getVertsFromGroup(
350                             MMD_SHAPE_GROUP_NAME):
351                         v=b.data[index]
352                         pos=[v[0], v[1], v[2]]
353                         indices=self.vertexArray.getMappedIndices(index)
354                         for i in indices:
355                             baseMorph.add(i, pos)
356                             indexRelativeMap[relativeIndex]=i
357                             relativeIndex+=1
358                     break
359             print(len(baseMorph.offsets))
360             baseMorph.sort()
361             assert(basis)
362
363             # shape keys
364             vg=obj.getData(mesh=True).getVertsFromGroup(
365                         MMD_SHAPE_GROUP_NAME)
366             for b in obj.getData(mesh=True).key.blocks:
367                 if b.name=='Basis':
368                     continue
369
370                 print(b.name)
371                 morph=self.__getOrCreateMorph(b.name, 4)
372                 for index, src, dst in zip(
373                         xrange(len(blenderMesh.verts)),
374                         basis.data,
375                         b.data):
376                     offset=[dst[0]-src[0], dst[1]-src[1], dst[2]-src[2]]
377                     if index in vg:
378                         indices=self.vertexArray.getMappedIndices(index)
379                         for i in indices:
380                             morph.add(indexRelativeMap[i], offset)
381                 assert(len(morph.offsets)==len(baseMorph.offsets))
382
383         # sort skinmap
384         if len(self.morphList)>1:
385             original=self.morphList[:]
386             def getIndex(morph):
387                 for i, v in enumerate(englishmap.skinMap):
388                     if v[0]==morph.name:
389                         return i
390                 #print(morph)
391                 return 0
392             self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
393
394     def __getOrCreateMorph(self, name, type):
395         for m in self.morphList:
396             if m.name==name:
397                 return m
398         m=Morph(name, type)
399         self.morphList.append(m)
400         return m
401
402     def getVertexCount(self):
403         return len(self.vertexArray.vertices)
404
405
406 class Bone(object):
407     __slots__=['index', 'name', 'ik_index',
408             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
409     def __init__(self, name, pos, tail):
410         self.index=-1
411         self.name=name
412         self.pos=pos
413         self.tail=tail
414         self.parent_index=None
415         self.tail_index=None
416         self.type=0
417         self.isConnect=False
418         self.ik_index=0
419
420     def __eq__(self, rhs):
421         return self.index==rhs.index
422
423     def __str__(self):
424         return "<Bone %s %d>" % (self.name, self.type)
425
426 class BoneBuilder(object):
427     __slots__=['bones', 'boneMap', 'ik_list']
428     def __init__(self):
429         self.bones=[]
430         self.boneMap={}
431         self.ik_list=[]
432
433     def build(self, armatureObj):
434         if not armatureObj:
435             return
436
437         print("gather bones")
438         armature=armatureObj.getData()
439         for b in armature.bones.values():
440             if b.name=='center':
441                 # root bone
442                 bone=Bone(b.name, 
443                         b.head['ARMATURESPACE'][0:3], 
444                         b.tail['ARMATURESPACE'][0:3])
445                 self.__addBone(bone)
446                 self.__getBone(bone, b)
447
448         for b in armature.bones.values():
449             if not b.parent and b.name!='center':
450                 # root bone
451                 bone=Bone(b.name, 
452                         b.head['ARMATURESPACE'][0:3], 
453                         b.tail['ARMATURESPACE'][0:3])
454                 self.__addBone(bone)
455                 self.__getBone(bone, b)
456
457         print("check connection")
458         for b in armature.bones.values():
459             if not b.parent:
460                 self.__checkConnection(b, None)
461
462         print("gather ik")
463         pose = armatureObj.getPose()
464         cSetting=Blender.Constraint.Settings
465         for b in pose.bones.values():
466             for c in b.constraints:
467                 if c.type==Blender.Constraint.Type.IKSOLVER:
468                     ####################
469                     # IK target
470                     ####################
471                     assert(c[cSetting.TARGET]==armatureObj)
472                     target=self.__boneByName(
473                             c[Blender.Constraint.Settings.BONE])
474                     target.type=2
475
476                     ####################
477                     # IK effector
478                     ####################
479                     # IK 接続先
480                     link=self.__boneByName(b.name)
481                     link.type=6
482
483                     # IK chain
484                     e=b.parent
485                     chainLength=c[cSetting.CHAINLEN]
486                     for i in range(chainLength):
487                         # IK影響下
488                         chainBone=self.__boneByName(e.name)
489                         chainBone.type=4
490                         chainBone.ik_index=target.index
491                         e=e.parent
492                     self.ik_list.append(
493                             IKSolver(target, link, chainLength, 
494                                 int(c[cSetting.ITERATIONS] * 0.1), 
495                                 c[cSetting.ROTWEIGHT]
496                                 ))
497
498     def __checkConnection(self, b, p):
499         if Blender.Armature.CONNECTED in b.options:
500             parent=self.__boneByName(p.name)
501             parent.isConnect=True
502
503         for c in b.children:
504             self.__checkConnection(c, b)
505
506     def sortBy(self, boneMap):
507         """
508         boneMap順に並べ替える
509         """
510         original=self.bones[:]
511         def getIndex(bone):
512             for i, k_v in enumerate(boneMap):
513                 if k_v[0]==bone.name:
514                     return i
515             print(bone)
516
517         self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
518         sortMap={}
519         for i, b in enumerate(self.bones):
520             src=original.index(b)
521             sortMap[src]=i
522         for b in self.bones:
523             b.index=sortMap[b.index]
524             if b.parent_index:
525                 b.parent_index=sortMap[b.parent_index]
526             if b.tail_index:
527                 b.tail_index=sortMap[b.tail_index]
528             if b.ik_index>0:
529                 b.ik_index=sortMap[b.ik_index]
530
531     def getIndex(self, bone):
532         for i, b in enumerate(self.bones):
533             if b==bone:
534                 return i
535         assert(false)
536
537     def indexByName(self, name):
538         return self.getIndex(self.__boneByName(name))
539
540     def __boneByName(self, name):
541         return self.bones[self.boneMap[name]]
542                     
543     def __getBone(self, parent, b):
544         if len(b.children)==0:
545             parent.type=7
546             return
547
548         for i, c in enumerate(b.children):
549             bone=Bone(c.name, 
550                     c.head['ARMATURESPACE'][0:3], 
551                     c.tail['ARMATURESPACE'][0:3])
552             self.__addBone(bone)
553             if parent:
554                 bone.parent_index=parent.index
555                 if i==0:
556                     parent.tail_index=bone.index
557             self.__getBone(bone, c)
558
559     def __addBone(self, bone):
560         bone.index=len(self.bones)
561         self.bones.append(bone)
562         self.boneMap[bone.name]=bone.index
563
564
565 class PmdExporter(object):
566
567     def __init__(self):
568         self.armatureObj=None
569
570     def setup(self, scene):
571         # 木構造を構築する
572         object_node_map={}
573         for o in scene.objects:
574             object_node_map[o]=Node(o)
575         for node in object_node_map.values():
576             if node.o.parent:
577                 object_node_map[node.o.parent].children.append(node)
578         # ルートを得る
579         root=object_node_map[scene.objects.active]
580
581         # ワンスキンメッシュを作る
582         self.oneSkinMesh=OneSkinMesh()
583         self.__createOneSkinMesh(root)
584         print(self.oneSkinMesh)
585         self.name=root.o.name
586
587         # skeleton
588         self.builder=BoneBuilder()
589         self.builder.build(self.armatureObj)
590         self.builder.sortBy(englishmap.boneMap)
591         def getIndex(ik):
592             for i, v in enumerate(englishmap.boneMap):
593                 if v[0]==ik.target.name:
594                     return i
595             return len(englishmap.boneMap)
596         self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
597
598     def __createOneSkinMesh(self, node):
599         ############################################################
600         # search armature modifier
601         ############################################################
602         for m in node.o.modifiers:
603             if m.name=="Armature":
604                 armatureObj=m[Blender.Modifier.Settings.OBJECT]
605                 if not self.armatureObj:
606                     self.armatureObj=armatureObj
607                 elif self.armatureObj!=armatureObj:
608                     print "warning! found multiple armature. ignored.", armatureObj.name
609
610         if node.o.getType()=='Mesh':
611             self.oneSkinMesh.addMesh(node.o)
612
613         for child in node.children:
614             self.__createOneSkinMesh(child)
615
616     def write(self, path):
617         print('write')
618         io=pmd.IO()
619         io.name=self.name
620         io.comment="blender export"
621         io.version=1.0
622
623         # 頂点
624         print('vertices')
625         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
626             # convert right-handed z-up to left-handed y-up
627             v=io.addVertex()
628             v.pos.x=pos[0]
629             v.pos.y=pos[2]
630             v.pos.z=pos[1]
631             v.normal.x=normal[0]
632             v.normal.y=normal[2]
633             v.normal.z=normal[1]
634             v.uv.x=uv[0]
635             v.uv.y=uv[1]
636             v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
637             v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
638             v.weight0=int(100*weight)
639             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
640
641         # 面とマテリアル
642         print('faces and materials')
643         vertexCount=self.oneSkinMesh.getVertexCount()
644         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
645             m=Blender.Material.Get(m)
646             # マテリアル
647             material=io.addMaterial()
648             material.diffuse.r=m.R
649             material.diffuse.g=m.G
650             material.diffuse.b=m.B
651             material.diffuse.a=m.alpha
652             material.sinness=0 if m.spec<1e-5 else m.spec*10
653             material.specular.r=m.specR
654             material.specular.g=m.specG
655             material.specular.b=m.specB
656             material.ambient.r=m.mirR
657             material.ambient.g=m.mirG
658             material.ambient.b=m.mirB
659             material.vertex_count=len(indices)
660             material.toon_index=0
661             material.flag=1 if m.enableSSS else 0
662             # ToDo
663             material.texture=""
664             # 面
665             for i in indices:
666                 assert(i<vertexCount)
667             for i in xrange(0, len(indices), 3):
668                 # reverse triangle
669                 io.indices.append(indices[i+2])
670                 io.indices.append(indices[i+1])
671                 io.indices.append(indices[i])
672
673                 #io.indices.append(indices[i])
674                 #io.indices.append(indices[i+1])
675                 #io.indices.append(indices[i+2])
676
677         # bones
678         print('bones')
679         for b in self.builder.bones:
680             if b.name.endswith("_t"):
681                 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
682                     # skip
683                     print "skip %s" % b.name
684                     continue
685
686             bone=io.addBone()
687
688             v=englishmap.getUnicodeBoneName(b.name)
689             assert(v)
690             cp932=v[1].encode('cp932')
691             bone_name="%s" % cp932
692             assert(len(bone_name)<20)
693             bone.name=bone_name
694
695             bone_english_name="%s" % b.name
696             assert(len(bone_english_name)<20)
697             bone.english_name=bone_english_name
698
699             if len(v)>=3:
700                 # has type
701                 if v[2]==5:
702                     b.ik_index=self.builder.indexByName('eyes')
703                 bone.type=v[2]
704             else:
705                 bone.type=b.type
706
707             # parent index
708             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
709
710             # tail index
711             if b.tail_index!=None:
712                 if bone.type==9:
713                     bone.tail_index=0
714                 else:
715                     bone.tail_index=b.tail_index
716             else:
717                 bone.tail_index=0
718
719             bone.ik_index=b.ik_index
720
721             # convert right-handed z-up to left-handed y-up
722             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
723             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
724             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
725
726         # IK
727         print('ik')
728         for ik in self.builder.ik_list:
729             solver=io.addIK()
730             solver.index=self.builder.getIndex(ik.target)
731             solver.target=self.builder.getIndex(ik.effector)
732             solver.length=ik.length
733             b=self.builder.bones[ik.effector.parent_index]
734             for i in xrange(solver.length):
735                 solver.children.append(self.builder.getIndex(b))
736                 b=self.builder.bones[b.parent_index]
737             solver.iterations=ik.iterations
738             solver.weight=ik.weight
739
740         # 表情
741         print('shape keys')
742         for i, m in enumerate(self.oneSkinMesh.morphList):
743             # morph
744             morph=io.addMorph()
745
746             v=englishmap.getUnicodeSkinName(m.name)
747             assert(v)
748             cp932=v[1].encode('cp932')
749             morph.name="%s\n" % cp932
750
751             morph.english_name="%s\n" % m.name
752             m.type=v[2]
753             morph.type=v[2]
754             for index, offset in m.offsets:
755                 # convert right-handed z-up to left-handed y-up
756                 morph.append(index, offset[0], offset[2], offset[1])
757             morph.vertex_count=len(m.offsets)
758
759         # 表情枠
760         print('display list')
761         # type==0はbase
762         for i, m in enumerate(self.oneSkinMesh.morphList):
763             if m.type==3:
764                 io.face_list.append(i)
765         for i, m in enumerate(self.oneSkinMesh.morphList):
766             if m.type==2:
767                 io.face_list.append(i)
768         for i, m in enumerate(self.oneSkinMesh.morphList):
769             if m.type==1:
770                 io.face_list.append(i)
771         for i, m in enumerate(self.oneSkinMesh.morphList):
772             if m.type==4:
773                 io.face_list.append(i)
774
775         # ボーン表示枠
776         print('bone display list')
777         def createBoneDisplayName(name, english):
778             boneDisplayName=io.addBoneDisplayName()
779             boneDisplayName.name=name.decode('utf-8').encode('cp932')
780             boneDisplayName.english_name=english
781         boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
782         boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
783         boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
784         boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
785         boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
786         boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
787         boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
788         for i, b in enumerate(self.builder.bones):
789             if i==0:
790                 continue
791             if b.type in [6, 7]:
792                 continue
793             io.addBoneDisplay(i, getBoneDisplayGroup(b))
794
795         # English
796         print('english')
797         io.english_name="blender export"
798         io.english_coment="blender export"
799
800         for i in range(10):
801             io.getToonTexture(i).name="toon%02d.bmp\n" % i
802
803         # 書き込み
804         return io.write(path)
805
806
807 def getBoneDisplayGroup(bone):
808     boneGroups=[
809             [ # IK
810                 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
811                 "toe IK_L", "toe IK_R", 
812                 ],
813             [ # 体(上)
814                 "upper body", "neck", "head", "eye_L", "eye_R",
815                 "necktie1", "necktie2", "necktie3", "eyes", 
816                 "eyelight_L", "eyelight_R",
817                 ],
818             [ # 髪
819                 "front hair1", "front hair2", "front hair3",
820                 "hair1_L", "hair2_L", "hair3_L", 
821                 "hair4_L", "hair5_L", "hair6_L",
822                 "hair1_R", "hair2_R", "hair3_R", 
823                 "hair4_R", "hair5_R", "hair6_R",
824                 ],
825             [ # 腕
826                 "shoulder_L", "arm_L", "arm twist_L", "elbow_L", 
827                 "wrist twist_L", "wrist_L", "sleeve_L", 
828                 "shoulder_R", "arm_R", "arm twist_R", "elbow_R", 
829                 "wrist twist_R", "wrist_R", "sleeve_R", 
830                 ],
831             [ # 指
832                 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
833                 "middle1_L", "middle2_L", "middle3_L",
834                 "third1_L", "third2_L", "third3_L",
835                 "little1_L", "little2_L", "little3_L",
836                 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
837                 "middle1_R", "middle2_R", "middle3_R",
838                 "third1_R", "third2_R", "third3_R",
839                 "little1_R", "little2_R", "little3_R",
840                 ],
841             [ # 体(下)
842                 "lower body",  "waist accessory", 
843                 "front skirt_L", "back skirt_L",
844                 "front skirt_R", "back skirt_R",
845                 ],
846             [ # 足
847                 "leg_L", "knee_L", "ankle_L",
848                 "leg_R", "knee_R", "ankle_R",
849                 ],
850             ]
851     index=1
852     for g in boneGroups:
853         if bone.name in g:
854             return index
855         index+=1
856     print(bone)
857     return -1
858
859 def export_pmd(filename):
860     filename=filename.decode(INTERNAL_ENCODING)
861
862     Blender.Window.WaitCursor(1) 
863     t = Blender.sys.time() 
864
865     if not filename.lower().endswith(EXTENSION):
866         filename += EXTENSION
867     print "pmd exporter: %s" % filename
868
869     exporter=PmdExporter()
870
871     # 情報収集
872     exporter.setup(Blender.Scene.GetCurrent())
873
874     # 出力
875     exporter.write(filename)
876
877     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
878     Blender.Redraw()
879     Blender.Window.WaitCursor(0) 
880  
881
882 Blender.Window.FileSelector(
883         export_pmd,
884         'Export Metasequoia PMD',
885         Blender.sys.makename(ext=EXTENSION))
886