OSDN Git Service

20ea6f4277457d8bc3aac8383fb8e1a2270e2e25
[meshio/meshio.git] / swig / blender24 / 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__= "0.2"
11 __url__=()
12 __bpydoc__="""
13 0.1 20100318 first implementation.
14 0.2 20100519 refactoring. use C extension.
15 """
16 import Blender
17 import os
18 import sys
19
20 from meshio import pmd, englishmap
21
22
23 # ファイルシステムの文字コード
24 # 改造版との共用のため
25 FS_ENCODING=sys.getfilesystemencoding()
26 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
27     INTERNAL_ENCODING='utf-8'
28 else:
29     INTERNAL_ENCODING=FS_ENCODING
30
31
32 EXTENSION = u'.pmd'
33
34
35 class Node(object):
36     __slots__=['o', 'children']
37     def __init__(self, o):
38         self.o=o
39         self.children=[]
40
41
42 ###############################################################################
43 # Blenderのメッシュをワンスキンメッシュ化する
44 ###############################################################################
45 def near(x, y, EPSILON=1e-5):
46     d=x-y
47     return d>=-EPSILON and d<=EPSILON
48
49
50 class VertexKey(object):
51     """
52     重複頂点の検索キー
53     """
54     __slots__=[
55             'x', 'y', 'z', # 位置
56             'nx', 'ny', 'nz', # 法線
57             'u', 'v', # uv
58             ]
59
60     def __init__(self, x, y, z, nx, ny, nz, u, v):
61         self.x=x
62         self.y=y
63         self.z=z
64         self.nx=nx
65         self.ny=ny
66         self.nz=nz
67         self.u=u
68         self.v=v
69
70     def __hash__(self):
71         return int((self.x+self.y+self.z+self.nx+self.ny+self.nz+self.u+self.v)*100)
72
73     def __eq__(self, rhs):
74         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)
75
76
77 class VertexArray(object):
78     """
79     頂点配列
80     """
81     def __init__(self):
82         # マテリアル毎に分割したインデックス配列
83         self.indexArrays={}
84         # 頂点属性
85         self.vertices=[]
86         self.normals=[]
87         self.uvs=[]
88         # skinning属性
89         self.b0=[]
90         self.b1=[]
91         self.weight=[]
92
93         self.vertexMap={}
94
95     def __str__(self):
96         return "<VertexArray %d vertices, %d indexArrays>" % (
97                 len(self.vertices), len(self.indexArrays))
98
99     def zip(self):
100         return zip(
101                 self.vertices, self.normals, self.uvs,
102                 self.b0, self.b1, self.weight)
103
104     def getIndex(self, pos, normal, uv, b0, b1, weight0):
105         """
106         頂点属性からその頂点のインデックスを得る
107         """
108         key=VertexKey(
109                 pos[0], pos[1], pos[2],
110                 normal[0], normal[1], normal[2],
111                 uv[0], uv[1])
112         if not key in self.vertexMap:
113             self.vertexMap[key]=len(self.vertices)
114             self.vertices.append((pos.x, pos.y, pos.z))
115             self.normals.append((normal.x, normal.y, normal.z))
116             self.uvs.append((uv.x, uv.y))
117             # ToDo
118             self.b0.append(b0)
119             self.b1.append(b1)
120             self.weight.append(weight0)
121         return self.vertexMap[key]
122
123     def addTriangle(self,
124             material,
125             pos0, pos1, pos2,
126             n0, n1, n2,
127             uv0, uv1, uv2,
128             b0_0, b0_1, b0_2,
129             b1_0, b1_1, b1_2,
130             weight0, weight1, weight2
131             ):
132         if not material in self.indexArrays:
133             self.indexArrays[material]=[]
134
135         index0=self.getIndex(pos0, n0, uv0, b0_0, b1_0, weight0)
136         index1=self.getIndex(pos1, n1, uv1, b0_1, b1_1, weight1)
137         index2=self.getIndex(pos2, n2, uv2, b0_2, b1_2, weight2)
138
139         self.indexArrays[material]+=[index0, index1, index2]
140
141
142 class OneSkinMesh(object):
143     __slots__=['armatureObj', 'vertexArray']
144     def __init__(self, root):
145         self.armatureObj=None
146         self.vertexArray=VertexArray()
147         self.__create(root)
148
149     def __str__(self):
150         return "<OneSkinMesh armature:%s, %s>" % (
151                 self.armatureObj.name if self.armatureObj else None, 
152                 self.vertexArray)
153
154     def __create(self, node):
155         if node.o.getType()=='Mesh':
156             self.__addMesh(node.o)
157
158         for child in node.children:
159             self.__create(child)
160
161     def __addMesh(self, obj):
162         if obj.restrictDisplay:
163             # 非表示
164             return
165
166         print("export", obj.name)
167
168         ############################################################
169         # search armature modifier
170         ############################################################
171         for m in obj.modifiers:
172             if m.name=="Armature":
173                 armatureObj=m[Blender.Modifier.Settings.OBJECT]
174                 if not self.armatureObj:
175                     self.armatureObj=armatureObj
176                 elif self.armatureObj!=armatureObj:
177                     print "warning! found multiple armature. ignored.", armatureObj.name
178
179         ############################################################
180         # bone weight
181         ############################################################
182         mesh=obj.getData(mesh=True)
183         weightMap={}
184         secondWeightMap={}
185         for name in mesh.getVertGroupNames():
186             for i, w in mesh.getVertsFromGroup(name, 1):
187                 if w>0:
188                     if i in weightMap:
189                         if i in secondWeightMap:
190                             # 上位2つのweightを採用する
191                             if w<secondWeightMap[i]:
192                                 pass
193                             elif w<weightMap[i]:
194                                 # 2つ目を入れ替え
195                                 secondWeightMap[i]=(name, w)
196                             else:
197                                 # 1つ目を入れ替え
198                                 weightMap[i]=(name, w)
199                         else:
200                             if w>weightMap[i][1]:
201                                 # 多い方をweightMapに
202                                 secondWeightMap[i]=weightMap[i]
203                                 weightMap[i]=(name, w)
204                             else:
205                                 secondWeightMap[i]=(name, w)
206                     else:
207                         weightMap[i]=(name, w)
208
209         # 合計値が1になるようにする
210         for i in xrange(len(mesh.verts)):
211         #for i, name_weight in weightMap.items():
212             if i in secondWeightMap:
213                 secondWeightMap[i]=(secondWeightMap[i][0], 1.0-weightMap[i][1])
214             elif i in weightMap:
215                 weightMap[i]=(weightMap[i][0], 1.0)
216                 secondWeightMap[i]=("", 0)
217             else:
218                 print "no weight vertex"
219                 weightMap[i]=("", 0)
220                 secondWeightMap[i]=("", 0)
221                 
222
223         ############################################################
224         # faces
225         # 新たにメッシュを生成する
226         ############################################################
227         mesh=Blender.Mesh.New()
228         # not applied modifiers
229         mesh.getFromObject(obj.name, 1)
230         # apply object transform
231         mesh.transform(obj.getMatrix())
232         if len(mesh.verts)==0:
233             return
234
235         for face in mesh.faces:
236             faceVertexCount=len(face.v)
237             material=mesh.materials[face.mat]
238             if faceVertexCount==3:
239                 v0=face.v[0]
240                 v1=face.v[1]
241                 v2=face.v[2]
242                 # triangle
243                 self.vertexArray.addTriangle(
244                         material.name,
245                         v0.co, v1.co, v2.co,
246                         v0.no, v1.no, v2.no,
247                         face.uv[0], face.uv[1], face.uv[2],
248                         weightMap[v0.index][0],
249                         weightMap[v1.index][0],
250                         weightMap[v2.index][0],
251                         secondWeightMap[v0.index][0],
252                         secondWeightMap[v1.index][0],
253                         secondWeightMap[v2.index][0],
254                         weightMap[v0.index][1],
255                         weightMap[v1.index][1],
256                         weightMap[v2.index][1]
257                         )
258             elif faceVertexCount==4:
259                 v0=face.v[0]
260                 v1=face.v[1]
261                 v2=face.v[2]
262                 v3=face.v[3]
263                 # quadrangle
264                 self.vertexArray.addTriangle(
265                         material.name,
266                         v0.co, v1.co, v2.co,
267                         v0.no, v1.no, v2.no,
268                         face.uv[0], face.uv[1], face.uv[2],
269                         weightMap[v0.index][0],
270                         weightMap[v1.index][0],
271                         weightMap[v2.index][0],
272                         secondWeightMap[v0.index][0],
273                         secondWeightMap[v1.index][0],
274                         secondWeightMap[v2.index][0],
275                         weightMap[v0.index][1],
276                         weightMap[v1.index][1],
277                         weightMap[v2.index][1]
278                         )
279                 self.vertexArray.addTriangle(
280                         material.name,
281                         v2.co, v3.co, v0.co,
282                         v2.no, v3.no, v0.no,
283                         face.uv[2], face.uv[3], face.uv[0],
284                         weightMap[v2.index][0],
285                         weightMap[v3.index][0],
286                         weightMap[v0.index][0],
287                         secondWeightMap[v2.index][0],
288                         secondWeightMap[v3.index][0],
289                         secondWeightMap[v0.index][0],
290                         weightMap[v2.index][1],
291                         weightMap[v3.index][1],
292                         weightMap[v0.index][1]
293                         )
294
295     def getVertexCount(self):
296         return len(self.vertexArray.vertices)
297
298
299 class Bone(object):
300     __slots__=['index', 'name', 'pos', 'parent_index', 'tail_index', 'type']
301     def __init__(self, name, pos):
302         self.index=-1
303         self.name=name
304         self.pos=[pos.x, pos.y, pos.z]
305         self.parent_index=None
306         self.tail_index=None
307         self.type=0
308
309     def __str__(self):
310         return "<Bone %s %d>" % (self.name, self.type)
311
312 class BoneBuilder(object):
313     __slots__=['bones', 'boneMap', 'ik_list']
314     def __init__(self):
315         self.bones=[]
316         self.boneMap={}
317         self.ik_list=[]
318
319     def build(self, armatureObj):
320         if armatureObj:
321             armature=armatureObj.getData()
322             for b in armature.bones.values():
323                 if not b.parent:
324                     # root bone
325                     bone=Bone(b.name, b.head['ARMATURESPACE'])
326                     self.__addBone(bone)
327                     self.__getBone(bone, b)
328
329         pose = armatureObj.getPose()
330         for b in pose.bones.values():
331             for c in b.constraints:
332                 if c.type==Blender.Constraint.Type.IKSOLVER:
333                     # IK effector
334                     e=b
335                     for i in range(c[Blender.Constraint.Settings.CHAINLEN]):
336                         # IK影響下
337                         self.__boneByName(e.name).type=4
338                         e=e.parent
339                     # IK target
340                     assert(c[Blender.Constraint.Settings.TARGET]==armatureObj)
341                     self.__boneByName(
342                             c[Blender.Constraint.Settings.BONE]).type=2
343                     # IK 接続先
344                     link=self.__boneByName(b.name)
345                     link_tail=self.bones[link.tail_index]
346                     if link_tail.type==7:
347                         # IK接続先
348                         link_tail.type=6
349                         
350
351     def __boneByName(self, name):
352         return self.bones[self.boneMap[name]]
353                     
354     def __getBone(self, parent, b):
355         if not Blender.Armature.CONNECTED in b.options:
356             #print b, b.options
357             pass
358
359         if len(b.children)==0:
360             # 末端の非表示ボーン
361             bone=Bone(b.name+'_tail', b.tail['ARMATURESPACE'])
362             bone.type=7
363             self.__addBone(bone)
364             assert(parent)
365             bone.parent_index=parent.index
366             parent.tail_index=bone.index
367             return
368
369         for i, c in enumerate(b.children):
370             bone=Bone(c.name, c.head['ARMATURESPACE'])
371             self.__addBone(bone)
372             if parent:
373                 bone.parent_index=parent.index
374                 if i==0:
375                     parent.tail_index=bone.index
376             self.__getBone(bone, c)
377
378     def __addBone(self, bone):
379         bone.index=len(self.bones)
380         self.bones.append(bone)
381         self.boneMap[bone.name]=bone.index
382
383
384 class PmdExporter(object):
385
386     def setup(self, scene):
387         # 木構造を構築する
388         object_node_map={}
389         for o in scene.objects:
390             object_node_map[o]=Node(o)
391         for node in object_node_map.values():
392             if node.o.parent:
393                 object_node_map[node.o.parent].children.append(node)
394         # ルートを得る
395         root=object_node_map[scene.objects.active]
396
397         # ワンスキンメッシュを作る
398         self.oneSkinMesh=OneSkinMesh(root)
399         print(self.oneSkinMesh)
400         self.name=root.o.name
401
402     def write(self, path):
403         io=pmd.IO()
404         io.name=self.name
405         io.comment="blender export"
406         io.version=1.0
407
408         # bones
409         builder=BoneBuilder()
410         builder.build(self.oneSkinMesh.armatureObj)
411         for b in builder.bones:
412             bone=io.addBone()
413             bone.name=b.name
414             bone.type=b.type
415             bone.parent_index=b.parent_index if b.parent_index!=None else 0xFFFF
416             bone.tail_index=b.tail_index if b.tail_index!=None else 0
417             # ToDo
418             bone.ik_index=0xFFFF
419             # convert right-handed z-up to left-handed y-up
420             bone.pos.x=b.pos[0]
421             bone.pos.y=b.pos[2]
422             bone.pos.z=b.pos[1]
423
424         # 頂点
425         for pos, normal, uv, b0, b1, weight in self.oneSkinMesh.vertexArray.zip():
426             # convert right-handed z-up to left-handed y-up
427             v=io.addVertex()
428             v.pos.x=pos[0]
429             v.pos.y=pos[2]
430             v.pos.z=pos[1]
431             v.normal.x=normal[0]
432             v.normal.y=normal[2]
433             v.normal.z=normal[1]
434             v.uv.x=uv[0]
435             v.uv.y=uv[1]
436             v.bone0=builder.boneMap[b0] if b0 in builder.boneMap else 0
437             v.bone1=builder.boneMap[b1] if b1 in builder.boneMap else 0
438             v.weight0=int(100*weight)
439             v.edge_flag=0 # edge flag, 0: enable edge, 1: not edge
440
441         # 面とマテリアル
442         vertexCount=self.oneSkinMesh.getVertexCount()
443         for m, indices in self.oneSkinMesh.vertexArray.indexArrays.items():
444             print(m, len(indices))
445             m=Blender.Material.Get(m)
446             # マテリアル
447             material=io.addMaterial()
448             material.diffuse.r=m.R
449             material.diffuse.g=m.G
450             material.diffuse.b=m.B
451             material.diffuse.a=m.alpha
452             material.sinness=m.spec
453             material.specular.r=m.specR
454             material.specular.g=m.specG
455             material.specular.b=m.specB
456             material.ambient.r=m.amb
457             material.ambient.g=m.amb
458             material.ambient.b=m.amb
459             material.vertex_count=len(indices)
460             material.toon_index=0
461             # ToDo
462             material.texture=""
463             # 面
464             for i in indices:
465                 assert(i<vertexCount)
466             for i in xrange(0, len(indices), 3):
467                 # reverse triangle
468                 io.indices.append(indices[i+2])
469                 io.indices.append(indices[i+1])
470                 io.indices.append(indices[i])
471
472                 #io.indices.append(indices[i])
473                 #io.indices.append(indices[i+1])
474                 #io.indices.append(indices[i+2])
475
476         # 書き込み
477         return io.write(path.encode(FS_ENCODING))
478
479
480 def export_pmd(filename):
481     filename=filename.decode(INTERNAL_ENCODING)
482
483     Blender.Window.WaitCursor(1) 
484     t = Blender.sys.time() 
485
486     if not filename.lower().endswith(EXTENSION):
487         filename += EXTENSION
488     print "pmd exporter: %s" % filename
489
490     exporter=PmdExporter()
491
492     # 情報収集
493     exporter.setup(Blender.Scene.GetCurrent())
494
495     # 出力
496     exporter.write(filename)
497
498     print 'finished in %.2f seconds' % (Blender.sys.time()-t) 
499     Blender.Redraw()
500     Blender.Window.WaitCursor(0) 
501  
502
503 Blender.Window.FileSelector(
504         export_pmd,
505         'Export Metasequoia PMD',
506         Blender.sys.makename(ext=EXTENSION))
507