OSDN Git Service

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