OSDN Git Service

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