OSDN Git Service

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