OSDN Git Service

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