OSDN Git Service

fix mqo_import smoothing, mirroring.
[meshio/meshio.git] / swig / blender / bl25.py
1 # coding: utf-8
2 import bpy
3 import mathutils
4
5 import os
6 import sys
7 import time
8 import functools
9
10\e$B%U%!%$%k%7%9%F%`$NJ8;z%3!<%I\e(B
11\e$B2~B$HG$H$N6&MQ$N$?$a\e(B
12 FS_ENCODING=sys.getfilesystemencoding()
13 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
14     INTERNAL_ENCODING='utf-8'
15 else:
16     INTERNAL_ENCODING=FS_ENCODING
17
18
19 ###############################################################################
20 # ProgressBar
21 ###############################################################################
22 class ProgressBar(object):
23     def __init__(self, base):
24         print("#### %s ####" % base)
25         self.base=base
26         self.start=time.time() 
27         self.set('<start>', 0)
28
29     def advance(self, message, progress):
30         self.progress+=float(progress)
31         self._print(message)
32
33     def set(self, message, progress):
34         self.progress=float(progress)
35         self._print(message)
36
37     def _print(self, message):
38         print(message)
39         message="%s: %s" % (self.base, message)
40         #Blender.Window.DrawProgressBar(self.progress, message)
41
42     def finish(self):
43         self.progress=1.0
44         message='finished in %.2f sec' % (time.time()-self.start)
45         self.set(message, 1.0)
46
47 def progress_start(base):
48     global progressBar
49     progressBar=ProgressBar(base)
50
51 def progress_finish():
52     global progressBar
53     progressBar.finish()
54
55 def progress_print(message, progress=0.05):
56     global progressBar
57     progressBar.advance(message, progress)
58
59 def progress_set(message, progress):
60     global progressBar
61     progressBar.set(message, progress)
62
63
64 ###############################################################################
65 class Writer(object):
66     def __init__(self, path, encoding):
67         self.io=open(path, "wb")
68         self.encoding=encoding
69
70     def write(self, s):
71         self.io.write(s.encode(self.encoding))
72
73     def flush(self):
74         self.io.flush()
75
76     def close(self):
77         self.io.close()
78
79 ###############################################################################
80 def createEmptyObject(scene, name):
81     empty=bpy.data.objects.new(name, None)
82     scene.objects.link(empty)
83     return empty
84
85 def createMaterial(name):
86     material = bpy.data.materials.new(name)
87     return material
88
89 def createMqoMaterial(m):
90     material = bpy.data.materials.new(m.getName())
91     material.diffuse_color=[m.color.r, m.color.g, m.color.b]
92     material.alpha=m.color.a
93     material.diffuse_intensity=m.diffuse
94     return material
95
96 def createPmdMaterial(m):
97     material = bpy.data.materials.new("Material")
98     material.diffuse_shader='TOON'
99     material.specular_shader='TOON'
100     material.diffuse_color=([m.diffuse.r, m.diffuse.g, m.diffuse.b])
101     material.alpha=m.diffuse.a
102     material.specular_hardness=int(m.shinness)
103     material.specular_color=([m.specular.r, m.specular.g, m.specular.b])
104     material.mirror_color=([m.ambient.r, m.ambient.g, m.ambient.b])
105     material.subsurface_scattering.enabled=True if m.flag==1 else False
106     return material
107
108 def createTexture(path):
109     texture=bpy.data.textures.new(os.path.basename(path))
110     texture.type='IMAGE'
111     texture=texture.recast_type()
112     image=bpy.data.images.load(path)
113     texture.image=image
114     texture.mipmap = True
115     texture.interpolation = True
116     texture.use_alpha = True
117     return texture, image
118
119
120 def materialAddTexture(material, texture):
121     #material.add_texture(texture, "UV", {"COLOR", "ALPHA"})
122     material.add_texture(texture, "UV", "COLOR")
123
124
125 def meshAddMaterial(mesh, material):
126     mesh.add_material(material)
127
128
129 def createMesh(scene, name):
130     mesh=bpy.data.meshes.new("Mesh")
131     mesh_object= bpy.data.objects.new(name, mesh)
132     scene.objects.link(mesh_object)
133     return mesh, mesh_object
134
135
136 def objectMakeParent(parent, child):
137     child.parent=parent
138
139 def objectAddMirrorModifier(mesh_object):
140     return mesh_object.modifiers.new("Modifier", "MIRROR")
141
142 def meshAddMqoGeometry(mesh_object, o, materials, imageMap, scale):
143     mesh=mesh_object.data
144     # count triangle and quadrangle
145     faceCount=0
146     for f in o.faces:
147         if f.index_count==3 or f.index_count==4:
148             faceCount+=1
149     mesh.add_geometry(len(o.vertices), 0, faceCount)
150
151     # add vertex
152     unpackedVertices=[]
153     for v in o.vertices:
154         # convert right-handed y-up to right-handed z-up
155         unpackedVertices.extend(
156                 (scale*v.x, scale*-v.z, scale*v.y))
157     mesh.verts.foreach_set("co", unpackedVertices)
158
159     # add face
160     unpackedFaces = []
161     usedMaterial=set()
162
163     def getFace(f):
164         face = []
165         for i in range(f.index_count):
166             face.append(f.getIndex(i))
167         return face
168
169     for f in o.faces:
170         face=getFace(f)
171         if len(face) != 3 and len(face) != 4:
172             print("{0} vertices in face.".format(len(face)))
173             continue
174
175         if len(face) == 4:
176             if face[3] == 0:
177                 # rotate indices if the 4th is 0
178                 face = [face[3], face[0], face[1], face[2]]
179         elif len(face) == 3:
180             if face[2] == 0:
181                 # rotate indices if the 3rd is 0
182                 face = [face[2], face[0], face[1], 0]
183             else:
184                 face.append(0)
185
186         unpackedFaces.extend(face)
187         usedMaterial.add(f.material_index)
188     try:
189         mesh.faces.foreach_set("verts_raw", unpackedFaces)
190     except:
191         #print([getFace(f) for f in o.faces])
192         print("fail to mesh.faces.foreach_set")
193         return
194
195     # add material
196     meshMaterialMap={}
197     materialIndex=0
198     for i in usedMaterial:
199         mesh.add_material(materials[i])
200         meshMaterialMap[i]=materialIndex
201         materialIndex+=1
202
203     # each face
204     mesh.add_uv_texture()
205     for mqo_face, blender_face, uv_face in zip(
206             o.faces, mesh.faces, mesh.uv_textures[0].data):
207         if mqo_face.index_count<3:
208             continue
209         blender_face.material_index=meshMaterialMap[mqo_face.material_index]
210         if mqo_face.index_count>=3:
211             uv_face.uv1=[mqo_face.getUV(0).x, 1.0-mqo_face.getUV(0).y]
212             uv_face.uv2=[mqo_face.getUV(1).x, 1.0-mqo_face.getUV(1).y]
213             uv_face.uv3=[mqo_face.getUV(2).x, 1.0-mqo_face.getUV(2).y]
214             if mqo_face.index_count==4:
215                 uv_face.uv4=[
216                         mqo_face.getUV(3).x, 1.0-mqo_face.getUV(3).y]
217         if materials[mqo_face.material_index] in imageMap:
218             uv_face.image=imageMap[mqo_face.material_index]
219             uv_face.tex=True
220
221     mesh.update()
222
223 def getTexture(m, dirname):
224     tex=""
225     aplane=""
226     # texture
227     for slot in m.texture_slots:
228         if slot and slot.texture:
229             texture=slot.texture
230             if  texture.type=="IMAGE":
231                 image=texture.image
232                 if not image:
233                     continue
234                 imagePath=image.filename
235                 if len(dirname)>0 and imagePath.startswith(dirname):
236                     # \e$BAjBP%Q%9$KJQ49$9$k\e(B
237                     imagePath=imagePath[len(dirname)+1:len(imagePath)]
238                 #imagePath=Blender.sys.expandpath(
239                 #        imagePath).replace("\\", '/')
240                 if slot.map_colordiff:
241                     tex=" tex(\"%s\")" % imagePath
242                 elif slot.map_alpha:
243                     aplane=" aplane(\"%s\")" % imagePath
244     return tex, aplane
245
246 def objectDuplicate(scene, obj):
247     bpy.ops.object.select_all(action='DESELECT')
248     obj.selected=True
249     scene.objects.active=obj
250     bpy.ops.object.duplicate()
251     dumy=scene.objects.active
252     bpy.ops.object.rotation_apply()
253     bpy.ops.object.scale_apply()
254     bpy.ops.object.location_apply()
255     return dumy.data, dumy
256
257 def objectDelete(scene, obj):
258     scene.objects.unlink(obj)
259
260 def faceVertexCount(face):
261     return len(face.verts)
262
263 def faceVertices(face):
264     return face.verts[:]
265
266 def meshHasUV(mesh):
267     return mesh.active_uv_texture
268
269 def faceHasUV(mesh, i, face):
270     return mesh.active_uv_texture.data[i]
271
272 def faceGetUV(mesh, i, faces, count):
273     uvFace=mesh.active_uv_texture.data[i]
274     if count==3:
275         return (uvFace.uv1, uvFace.uv2, uvFace.uv3)
276     elif count==4:
277         return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4)
278     else:
279         print(count)
280         assert(False)
281
282 def materialToMqo(m):
283     return "\"%s\" shader(3) col(%f %f %f %f)" % (
284             m.name, 
285             m.diffuse_color[0], m.diffuse_color[1], m.diffuse_color[2], 
286             m.alpha)
287
288 def faceMaterialIndex(face):
289     return face.material_index
290
291 def objectGetData(o):
292     return o.data
293
294 def objectAddArmatureModifier(o, armature_object):
295     mod=o.modifiers.new("Modifier", "ARMATURE")
296     mod.object = armature_object
297     mod.use_bone_envelopes=False
298
299 def objectSelect(o):
300     o.selected=True
301
302 def objectGetPose(o):
303     return o.pose
304
305 def poseBoneLimit(n, b):
306     if n.endswith("_t"):
307         return
308     if n.startswith("knee_"):
309         b.ik_dof_y=False
310         b.ik_dof_z=False
311         b.ik_dof_x=True
312         b.ik_limit_x=True
313         b.ik_min_x=0
314         b.ik_max_x=180
315     elif n.startswith("ankle_"):
316         #b.ik_dof_y=False
317         pass
318
319 def enterEditMode():
320     bpy.ops.object.mode_set(mode='EDIT', toggle=False)
321
322 def exitEditMode():
323     bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
324
325 def objectDeselectAll():
326     bpy.ops.object.select_all(action='DESELECT')
327
328 def objectActivate(scene, o):
329     o.selected=True 
330     scene.objects.active=o
331
332 def objectGetActive(scene):
333     return scene.objects.active
334
335 def meshAddVertexGroup(meshObject, name):
336     meshObject.add_vertex_group(name)
337
338 def vertexSetNormal(mvert, normal):
339     mvert.normal=mathutils.Vector(normal)
340
341 def meshUseVertexUv(mesh):
342     pass
343
344 def vertexSetUv(mvert, uv):
345     pass
346
347 def meshAssignVertexGroup(meshObject, name, index, weight):
348     meshObject.add_vertex_to_group(index, 
349                 meshObject.vertex_groups[name], weight, 'ADD')
350
351 def meshCreateVerteicesAndFaces(mesh, vertices, faces):
352     vertexCount=int(len(vertices)/3)
353     faceCount=int(len(faces)/4)
354     mesh.add_geometry(vertexCount, 0, faceCount)
355     mesh.verts.foreach_set("co", vertices)
356     mesh.faces.foreach_set("verts_raw", faces)
357     assert(len(mesh.verts)==vertexCount)
358
359 def meshAddUV(mesh):
360     mesh.add_uv_texture()
361
362 def meshVertsDelete(mesh, remove_vertices):
363     enterEditMode()
364     bpy.ops.mesh.select_all(action='DESELECT')
365     exitEditMode()
366
367     for i in remove_vertices:
368         mesh.verts[i].selected=True
369
370     enterEditMode()
371     bpy.ops.mesh.delete(type='VERT')
372     exitEditMode()
373
374 def createArmature(scene):
375     armature = bpy.data.armatures.new('Armature')
376     armature_object=bpy.data.objects.new('Armature', armature)
377     scene.objects.link(armature_object)
378
379     armature_object.x_ray=True
380     armature.draw_names=True
381     armature.drawtype='OCTAHEDRAL'
382     armature.deform_envelope=False
383     armature.deform_vertexgroups=True
384     armature.x_axis_mirror=True
385
386     return armature, armature_object
387
388 def armatureMakeEditable(scene, armature_object):
389     # select only armature object and set edit mode
390     scene.objects.active=armature_object
391     bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
392     bpy.ops.object.mode_set(mode='EDIT', toggle=False)
393
394 def createIkConstraint(armature_object, p_bone, effector_name, ik):
395     constraint = p_bone.constraints.new('IK')
396     constraint.chain_length=len(ik.children)
397     constraint.target=armature_object
398     constraint.subtarget=effector_name
399     constraint.use_tail=False
400     # not used. place folder when export.
401     constraint.weight=ik.weight
402     constraint.iterations=ik.iterations * 10
403     return constraint
404
405 def createArmatureBone(armature, name):
406     return armature.edit_bones.new(name)
407
408 def boneSetConnected(bone):
409     bone.connected=True
410
411 def createVector(x, y, z):
412     return mathutils.Vector([x, y, z])
413
414 def armatureUpdate(armature):
415     pass
416
417 def boneLayerMask(bone, layers):
418     layer=[]
419     for i in range(32):
420         try:
421             layer.append(True if layers[i]!=0 else False)
422         except IndexError:
423             layer.append(False)
424     bone.layer=layer
425
426 def objectLayerMask(object, layers):
427     layer=[]
428     for i in range(20):
429         try:
430             layer.append(True if layers[i]!=0 else False)
431         except IndexError:
432             layer.append(False)
433     object.layers=layer
434
435 def objectPinShape(o):
436     o.shape_key_lock=True
437
438 def objectAddShapeKey(o, name):
439     return o.add_shape_key(name)
440
441 def objectActivateShapeKey(o, index):
442     o.active_shape_key_index=index
443
444 def shapeKeyAssign(shapeKey, index, pos):
445     shapeKey.data[index].co=pos
446
447 def objectIsVisible(obj):
448     return obj.restrict_view
449
450 def meshVertexGroupNames(meshObject):
451     for g in meshObject.vertex_groups:
452         yield g.name
453
454 def faceNormal(face):
455     return face.normal
456
457 def meshFaceUv(mesh, i, face):
458     return mesh.uv_textures[0].data[i].uv
459
460 def armatureModifierGetObject(m):
461     return m.object
462
463 def objectHasShapeKey(o):
464     return o.data.shape_keys
465
466 def objectShapeKeys(o):
467     return o.data.shape_keys.keys
468
469 def meshVertexGroup(meshObject, name):
470     indices=[]
471     for i, v in enumerate(meshObject.data.verts):
472         for g in v.groups:
473             if meshObject.vertex_groups[g.group].name==name:
474                 indices.append(i)
475     return indices
476
477 def materialGet(scene, material_name):
478     return bpy.data.materials[material_name]
479
480 def modifierIsArmature(m):
481     return m.type=="ARMATURE"
482
483 def boneHeadLocal(b):
484     return b.head_local[0:3]
485
486 def boneTailLocal(b):
487     return b.tail_local[0:3]
488
489 def boneIsConnected(b):
490     return b.connected
491
492 def constraintIsIKSolver(c):
493     return c.type=='IK'
494
495 def ikChainLen(c):
496     return c.chain_length
497
498 def ikTarget(c):
499     return c.subtarget
500
501 def ikItration(c):
502     return c.iterations
503
504 def ikRotationWeight(c):
505     return c.weight
506
507 def shapeKeyGet(b, index):
508     return b.data[index].co
509
510 def shapeKeys(b):
511     for k in b.data:
512         yield k.co
513
514 def VtoV(v):
515     return mathutils.Vector([v.x, v.y, v.z])
516
517 def meshSetSmooth(mesh, smoothing):
518     mesh.autosmooth_angle=int(smoothing)
519     mesh.autosmooth=True
520     mesh.calc_normals()
521