OSDN Git Service

fix.
[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                     baseMorph=self.__getOrCreateMorph('base', 0)
378                     relativeIndex=0
379                     basis=b
380
381                     for index in bl.meshVertexGroup(obj, MMD_SHAPE_GROUP_NAME):
382                         v=bl.shapeKeyGet(b, index)
383                         pos=[v[0], v[1], v[2]]
384                         indices=self.vertexArray.getMappedIndices(index)
385                         for i in indices:
386                             baseMorph.add(i, pos)
387                             indexRelativeMap[i]=relativeIndex
388                             relativeIndex+=1
389
390                     break
391             assert(basis)
392             print(basis.name, len(baseMorph.offsets))
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 offset[0]==0 and offset[1]==0 and offset[2]==0:
411                             continue
412                         if index in vg:
413                             indices=self.vertexArray.getMappedIndices(index)
414                             for i in indices:
415                                 morph.add(indexRelativeMap[i], offset)
416
417                 # sort skinmap
418                 original=self.morphList[:]
419                 def getIndex(morph):
420                     for i, v in enumerate(englishmap.skinMap):
421                         if v[0]==morph.name:
422                             return i
423                     print(morph)
424                 if isBlender24():
425                     self.morphList.sort(lambda l, r: getIndex(l)-getIndex(r))
426                 else:
427                     self.morphList.sort(key=getIndex)
428
429     def __getOrCreateMorph(self, name, type):
430         for m in self.morphList:
431             if m.name==name:
432                 return m
433         m=Morph(name, type)
434         self.morphList.append(m)
435         return m
436
437     def getVertexCount(self):
438         return len(self.vertexArray.vertices)
439
440
441 class Bone(object):
442     __slots__=['index', 'name', 'ik_index',
443             'pos', 'tail', 'parent_index', 'tail_index', 'type', 'isConnect']
444     def __init__(self, name, pos, tail):
445         self.index=-1
446         self.name=name
447         self.pos=pos
448         self.tail=tail
449         self.parent_index=None
450         self.tail_index=None
451         self.type=0
452         self.isConnect=False
453         self.ik_index=0
454
455     def __eq__(self, rhs):
456         return self.index==rhs.index
457
458     def __str__(self):
459         return "<Bone %s %d>" % (self.name, self.type)
460
461 class BoneBuilder(object):
462     __slots__=['bones', 'boneMap', 'ik_list']
463     def __init__(self):
464         self.bones=[]
465         self.boneMap={}
466         self.ik_list=[]
467
468     def build(self, armatureObj):
469         if not armatureObj:
470             return
471
472         print("gather bones")
473         armature=bl.objectGetData(armatureObj)
474         for b in armature.bones.values():
475             if b.name=='center':
476                 # root bone
477                 bone=Bone(b.name, 
478                         bl.boneHeadLocal(b),
479                         bl.boneTailLocal(b))
480                 self.__addBone(bone)
481                 self.__getBone(bone, b)
482
483         for b in armature.bones.values():
484             if not b.parent and b.name!='center':
485                 # root bone
486                 bone=Bone(b.name, 
487                         bl.boneHeadLocal(b),
488                         bl.boneTailLocal(b))
489                 self.__addBone(bone)
490                 self.__getBone(bone, b)
491
492         print("check connection")
493         for b in armature.bones.values():
494             if not b.parent:
495                 self.__checkConnection(b, None)
496
497         print("gather ik")
498         pose = bl.objectGetPose(armatureObj)
499         for b in pose.bones.values():
500             for c in b.constraints:
501                 if bl.constraintIsIKSolver(c):
502                     ####################
503                     # IK target
504                     ####################
505                     target=self.__boneByName(bl.ikTarget(c))
506                     target.type=2
507
508                     ####################
509                     # IK effector
510                     ####################
511                     # IK 接続先
512                     link=self.__boneByName(b.name)
513                     link.type=6
514
515                     # IK chain
516                     e=b.parent
517                     chainLength=bl.ikChainLen(c)
518                     for i in range(chainLength):
519                         # IK影響下
520                         chainBone=self.__boneByName(e.name)
521                         chainBone.type=4
522                         chainBone.ik_index=target.index
523                         e=e.parent
524                     self.ik_list.append(
525                             IKSolver(target, link, chainLength, 
526                                 int(bl.ikItration(c) * 0.1), 
527                                 bl.ikRotationWeight(c)
528                                 ))
529
530     def __checkConnection(self, b, p):
531         if bl.boneIsConnected(b):
532             parent=self.__boneByName(p.name)
533             parent.isConnect=True
534
535         for c in b.children:
536             self.__checkConnection(c, b)
537
538     def sortBy(self, boneMap):
539         """
540         boneMap順に並べ替える
541         """
542         original=self.bones[:]
543         def getIndex(bone):
544             for i, k_v in enumerate(boneMap):
545                 if k_v[0]==bone.name:
546                     return i
547             print(bone)
548
549         if isBlender24():
550             self.bones.sort(lambda l, r: getIndex(l)-getIndex(r))
551         else:
552             self.bones.sort(key=getIndex)
553
554         sortMap={}
555         for i, b in enumerate(self.bones):
556             src=original.index(b)
557             sortMap[src]=i
558         for b in self.bones:
559             b.index=sortMap[b.index]
560             if b.parent_index:
561                 b.parent_index=sortMap[b.parent_index]
562             if b.tail_index:
563                 b.tail_index=sortMap[b.tail_index]
564             if b.ik_index>0:
565                 b.ik_index=sortMap[b.ik_index]
566
567     def getIndex(self, bone):
568         for i, b in enumerate(self.bones):
569             if b==bone:
570                 return i
571         assert(false)
572
573     def indexByName(self, name):
574         return self.getIndex(self.__boneByName(name))
575
576     def __boneByName(self, name):
577         return self.bones[self.boneMap[name]]
578                     
579     def __getBone(self, parent, b):
580         if len(b.children)==0:
581             parent.type=7
582             return
583
584         for i, c in enumerate(b.children):
585             bone=Bone(c.name, 
586                     bl.boneHeadLocal(c),
587                     bl.boneTailLocal(c))
588             self.__addBone(bone)
589             if parent:
590                 bone.parent_index=parent.index
591                 if i==0:
592                     parent.tail_index=bone.index
593             self.__getBone(bone, c)
594
595     def __addBone(self, bone):
596         bone.index=len(self.bones)
597         self.bones.append(bone)
598         self.boneMap[bone.name]=bone.index
599
600
601 class PmdExporter(object):
602
603     def setup(self, scene):
604         self.armatureObj=None
605         self.scene=scene
606
607         # 木構造を構築する
608         object_node_map={}
609         for o in scene.objects:
610             object_node_map[o]=Node(o)
611         for node in object_node_map.values():
612             if node.o.parent:
613                 object_node_map[node.o.parent].children.append(node)
614
615         # ルートを得る
616         root=object_node_map[scene.objects.active]
617
618         # ワンスキンメッシュを作る
619         self.oneSkinMesh=OneSkinMesh(scene)
620         self.__createOneSkinMesh(root)
621         print(self.oneSkinMesh)
622         self.name=root.o.name
623
624         # skeleton
625         self.builder=BoneBuilder()
626         self.builder.build(self.armatureObj)
627         self.builder.sortBy(englishmap.boneMap)
628         def getIndex(ik):
629             for i, v in enumerate(englishmap.boneMap):
630                 if v[0]==ik.target.name:
631                     return i
632             return len(englishmap.boneMap)
633         if isBlender24():
634             self.builder.ik_list.sort(lambda l, r: getIndex(l)-getIndex(r))
635         else:
636             self.builder.ik_list.sort(key=getIndex)
637
638     def __createOneSkinMesh(self, node):
639         print(node)
640         ############################################################
641         # search armature modifier
642         ############################################################
643         for m in node.o.modifiers:
644             if bl.modifierIsArmature(m):
645                 armatureObj=bl.armatureModifierGetObject(m)
646                 if not self.armatureObj:
647                     self.armatureObj=armatureObj
648                 elif self.armatureObj!=armatureObj:
649                     print("warning! found multiple armature. ignored.", armatureObj.name)
650
651         if node.o.type.upper()=='MESH':
652             self.oneSkinMesh.addMesh(node.o)
653
654         for child in node.children:
655             self.__createOneSkinMesh(child)
656
657     def write(self, path):
658         io=pmd.IO()
659         io.name=self.name
660         io.comment="blender export"
661         io.version=1.0
662
663         # 頂点
664         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
665             # convert right-handed z-up to left-handed y-up
666             v=io.addVertex()
667             v.pos.x=pos[0]
668             v.pos.y=pos[2]
669             v.pos.z=pos[1]
670             v.normal.x=normal[0]
671             v.normal.y=normal[2]
672             v.normal.z=normal[1]
673             v.uv.x=uv[0]
674             v.uv.y=uv[1]
675             v.bone0=self.builder.boneMap[b0] if b0 in self.builder.boneMap else 0
676             v.bone1=self.builder.boneMap[b1] if b1 in self.builder.boneMap else 0
677             v.weight0=int(100*weight)
678             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
679
680         # 面とマテリアル
681         vertexCount=self.oneSkinMesh.getVertexCount()
682         for material_name, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
683             m=bl.materialGet(self.scene, material_name)
684             # マテリアル
685             material=io.addMaterial()
686             if isBlender24():
687                 material.diffuse.r=m.R
688                 material.diffuse.g=m.G
689                 material.diffuse.b=m.B
690                 material.diffuse.a=m.alpha
691                 material.sinness=0 if m.spec<1e-5 else m.spec*10
692                 material.specular.r=m.specR
693                 material.specular.g=m.specG
694                 material.specular.b=m.specB
695                 material.ambient.r=m.mirR
696                 material.ambient.g=m.mirG
697                 material.ambient.b=m.mirB
698                 material.flag=1 if m.enableSSS else 0
699             else:
700                 material.diffuse.r=m.diffuse_color[0]
701                 material.diffuse.g=m.diffuse_color[1]
702                 material.diffuse.b=m.diffuse_color[2]
703                 material.diffuse.a=m.alpha
704                 material.sinness=0 if m.specular_hardness<1e-5 else m.specular_hardness*10
705                 material.specular.r=m.specular_color[0]
706                 material.specular.g=m.specular_color[1]
707                 material.specular.b=m.specular_color[2]
708                 material.ambient.r=m.mirror_color[0]
709                 material.ambient.g=m.mirror_color[1]
710                 material.ambient.b=m.mirror_color[2]
711                 material.flag=1 if m.subsurface_scattering.enabled else 0
712
713             material.vertex_count=len(indices)
714             material.toon_index=0
715             # ToDo
716             material.texture=""
717             # 面
718             for i in indices:
719                 assert(i<vertexCount)
720             for i in xrange(0, len(indices), 3):
721                 # reverse triangle
722                 io.indices.append(indices[i])
723                 io.indices.append(indices[i+1])
724                 io.indices.append(indices[i+2])
725
726         # bones
727         for b in self.builder.bones:
728             if b.name.endswith("_t"):
729                 if b.name.startswith("arm twist1_") or b.name.startswith("arm twist2_"):
730                     # skip
731                     print("skip %s" % b.name)
732                     continue
733
734             bone=io.addBone()
735
736             # name
737             v=englishmap.getUnicodeBoneName(b.name)
738             assert(v)
739             cp932=v[1].encode('cp932')
740             assert(len(cp932)<20)
741             bone.setName(cp932)
742
743             # english name
744             bone_english_name=b.name
745             assert(len(bone_english_name)<20)
746             bone.english_name=bone_english_name
747
748             if len(v)>=3:
749                 # has type
750                 if v[2]==5:
751                     b.ik_index=self.builder.indexByName('eyes')
752                 bone.type=v[2]
753             else:
754                 bone.type=b.type
755
756             # parent index
757             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
758
759             # tail index
760             if b.tail_index!=None:
761                 if bone.type==9:
762                     bone.tail_index=0
763                 else:
764                     bone.tail_index=b.tail_index
765             else:
766                 bone.tail_index=0
767
768             bone.ik_index=b.ik_index
769
770             # convert right-handed z-up to left-handed y-up
771             bone.pos.x=b.pos[0] if not near(b.pos[0], 0) else 0
772             bone.pos.y=b.pos[2] if not near(b.pos[2], 0) else 0
773             bone.pos.z=b.pos[1] if not near(b.pos[1], 0) else 0
774
775         # IK
776         for ik in self.builder.ik_list:
777             solver=io.addIK()
778             solver.index=self.builder.getIndex(ik.target)
779             solver.target=self.builder.getIndex(ik.effector)
780             solver.length=ik.length
781             b=self.builder.bones[ik.effector.parent_index]
782             for i in xrange(solver.length):
783                 solver.children.append(self.builder.getIndex(b))
784                 b=self.builder.bones[b.parent_index]
785             solver.iterations=ik.iterations
786             solver.weight=ik.weight
787
788         # 表情
789         for i, m in enumerate(self.oneSkinMesh.morphList):
790             # morph
791             morph=io.addMorph()
792
793             v=englishmap.getUnicodeSkinName(m.name)
794             assert(v)
795             cp932=v[1].encode('cp932')
796             morph.setName(cp932)
797             morph.setEnglishName(m.name.encode('cp932'))
798             m.type=v[2]
799             morph.type=v[2]
800             for index, offset in m.offsets:
801                 # convert right-handed z-up to left-handed y-up
802                 morph.append(index, offset[0], offset[2], offset[1])
803             morph.vertex_count=len(m.offsets)
804
805         # 表情枠
806         # type==0はbase
807         for i, m in enumerate(self.oneSkinMesh.morphList):
808             if m.type==3:
809                 io.face_list.append(i)
810         for i, m in enumerate(self.oneSkinMesh.morphList):
811             if m.type==2:
812                 io.face_list.append(i)
813         for i, m in enumerate(self.oneSkinMesh.morphList):
814             if m.type==1:
815                 io.face_list.append(i)
816         for i, m in enumerate(self.oneSkinMesh.morphList):
817             if m.type==4:
818                 io.face_list.append(i)
819
820         # ボーン表示枠
821         def createBoneDisplayName(name, english):
822             boneDisplayName=io.addBoneDisplayName()
823             if isBlender24():
824                 boneDisplayName.name=name.decode('utf-8').encode('cp932')
825                 boneDisplayName.english_name=english
826             else:
827                 boneDisplayName.setName(name.encode('cp932'))
828                 boneDisplayName.setEnglishName(english.encode('cp932'))
829         boneDisplayName=createBoneDisplayName("IK\n", "IK\n")
830         boneDisplayName=createBoneDisplayName("体(上)\n", "Body[u]\n")
831         boneDisplayName=createBoneDisplayName("髪\n", "Hair\n")
832         boneDisplayName=createBoneDisplayName("腕\n", "Arms\n")
833         boneDisplayName=createBoneDisplayName("指\n", "Fingers\n")
834         boneDisplayName=createBoneDisplayName("体(下)\n", "Body[l]\n")
835         boneDisplayName=createBoneDisplayName("足\n", "Legs\n")
836         for i, b in enumerate(self.builder.bones):
837             if i==0:
838                 continue
839             if b.type in [6, 7]:
840                 continue
841             io.addBoneDisplay(i, getBoneDisplayGroup(b))
842
843         # English
844         io.english_name="blender export"
845         io.english_coment="blender export"
846
847         for i in range(10):
848             io.getToonTexture(i).name="toon%02d.bmp\n" % i
849
850         # 書き込み
851         return io.write(path)
852
853
854 def getBoneDisplayGroup(bone):
855     boneGroups=[
856             [ # IK
857                 "necktie IK", "hair IK_L", "hair IK_R", "leg IK_L", "leg IK_R",
858                 "toe IK_L", "toe IK_R", 
859                 ],
860             [ # 体(上)
861                 "upper body", "neck", "head", "eye_L", "eye_R",
862                 "necktie1", "necktie2", "necktie3", "eyes", 
863                 "eyelight_L", "eyelight_R",
864                 ],
865             [ # 髪
866                 "front hair1", "front hair2", "front hair3",
867                 "hair1_L", "hair2_L", "hair3_L", 
868                 "hair4_L", "hair5_L", "hair6_L",
869                 "hair1_R", "hair2_R", "hair3_R", 
870                 "hair4_R", "hair5_R", "hair6_R",
871                 ],
872             [ # 腕
873                 "shoulder_L", "arm_L", "arm twist_L", "elbow_L", 
874                 "wrist twist_L", "wrist_L", "sleeve_L", 
875                 "shoulder_R", "arm_R", "arm twist_R", "elbow_R", 
876                 "wrist twist_R", "wrist_R", "sleeve_R", 
877                 ],
878             [ # 指
879                 "thumb1_L", "thumb2_L", "fore1_L", "fore2_L", "fore3_L",
880                 "middle1_L", "middle2_L", "middle3_L",
881                 "third1_L", "third2_L", "third3_L",
882                 "little1_L", "little2_L", "little3_L",
883                 "thumb1_R", "thumb2_R", "fore1_R", "fore2_R", "fore3_R",
884                 "middle1_R", "middle2_R", "middle3_R",
885                 "third1_R", "third2_R", "third3_R",
886                 "little1_R", "little2_R", "little3_R",
887                 ],
888             [ # 体(下)
889                 "lower body",  "waist accessory", 
890                 "front skirt_L", "back skirt_L",
891                 "front skirt_R", "back skirt_R",
892                 ],
893             [ # 足
894                 "leg_L", "knee_L", "ankle_L",
895                 "leg_R", "knee_R", "ankle_R",
896                 ],
897             ]
898     index=1
899     for g in boneGroups:
900         if bone.name in g:
901             return index
902         index+=1
903     print(bone)
904     return -1
905
906
907 def __execute(filename, scene):
908     if not scene.objects.active:
909         print("abort. no active object.")
910         return
911
912     exporter=PmdExporter()
913     exporter.setup(scene)
914     exporter.write(filename)
915
916
917 if isBlender24():
918     # for 2.4
919     def execute_24(filename):
920         filename=filename.decode(bl.INTERNAL_ENCODING)
921         print("pmd exporter: %s" % filename)
922
923         Blender.Window.WaitCursor(1) 
924         t = Blender.sys.time() 
925
926         scene = bpy.data.scenes.active
927         __execute(filename, scene)
928
929         print('finished in %.2f seconds' % (Blender.sys.time()-t))
930         Blender.Redraw()
931         Blender.Window.WaitCursor(0) 
932
933     Blender.Window.FileSelector(
934              execute_24,
935              'Export Metasequoia PMD',
936              Blender.sys.makename(ext='.pmd'))
937
938 else:
939     # for 2.5
940     def execute_25(*args):
941         __execute(*args)
942
943     # operator
944     class EXPORT_OT_pmd(bpy.types.Operator):
945         '''Save a Metasequoia PMD file.'''
946         bl_idname = "export_scene.pmd"
947         bl_label = 'Export PMD'
948
949         # List of operator properties, the attributes will be assigned
950         # to the class instance from the operator settings before calling.
951
952         path = StringProperty(
953                 name="File Path",
954                 description="File path used for exporting the PMD file",
955                 maxlen= 1024,
956                 default= ""
957                 )
958         filename = StringProperty(
959                 name="File Name", 
960                 description="Name of the file.")
961         directory = StringProperty(
962                 name="Directory", 
963                 description="Directory of the file.")
964
965         check_existing = BoolProperty(
966                 name="Check Existing",
967                 description="Check and warn on overwriting existing files",
968                 default=True,
969                 options=set('HIDDEN'))
970
971         def execute(self, context):
972             execute_25(
973                     self.properties.path, 
974                     context.scene
975                     )
976             return 'FINISHED'
977
978         def invoke(self, context, event):
979             wm=context.manager
980             wm.add_fileselect(self)
981             return 'RUNNING_MODAL'
982
983     # register menu
984     def menu_func(self, context): 
985         default_path=bpy.data.filename.replace(".blend", ".pmd")
986         self.layout.operator(
987                 EXPORT_OT_pmd.bl_idname, 
988                 text="Miku Miku Dance Model(.pmd)").path=default_path
989
990     def register():
991         bpy.types.register(EXPORT_OT_pmd)
992         bpy.types.INFO_MT_file_export.append(menu_func)
993
994     def unregister():
995         bpy.types.unregister(EXPORT_OT_pmd)
996         bpy.types.INFO_MT_file_export.remove(menu_func)
997
998     if __name__ == "__main__":
999         register()
1000