OSDN Git Service

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