OSDN Git Service

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