OSDN Git Service

c7353ec7c7c3c70fc6fb24d5f7ffe7d3d6d2dcd5
[meshio/pymeshio.git] / blender26-meshio / bl.py
1 # coding: utf-8
2 import os
3 import sys
4 import time
5 import functools
6
7 try:
8     import bpy
9     import mathutils
10 except:
11     pass
12
13 FS_ENCODING=sys.getfilesystemencoding()
14 if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"):
15     INTERNAL_ENCODING='utf-8'
16 else:
17     INTERNAL_ENCODING=FS_ENCODING
18
19 def register():
20     pass
21
22 def unregister():
23     pass
24
25 SCENE=None
26 def initialize(name, scene):
27     global SCENE
28     SCENE=scene
29     progress_start(name)
30
31 def finalize():
32     scene.update(SCENE)
33     progress_finish()
34
35 def message(msg):
36     print(msg)
37
38 def enterEditMode():
39     bpy.ops.object.mode_set(mode='EDIT', toggle=False)
40
41 def enterObjectMode():
42     bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
43
44 def enterPoseMode():
45     bpy.ops.object.mode_set(mode='POSE', toggle=False)
46
47 def createVector(x, y, z):
48     return mathutils.Vector([x, y, z])
49
50
51 class Writer(object):
52     '''
53     io wrapper
54     '''
55     def __init__(self, path, encoding):
56         self.io=open(path, "wb")
57         self.encoding=encoding
58
59     def write(self, s):
60         self.io.write(s.encode(self.encoding))
61
62     def flush(self):
63         self.io.flush()
64
65     def close(self):
66         self.io.close()
67
68
69 progressBar=None
70 class ProgressBar(object):
71     '''
72     progress bar wrapper
73     '''
74     def __init__(self, base):
75         print("#### %s ####" % base)
76         self.base=base
77         self.start=time.time() 
78         self.set('<start>', 0)
79
80     def advance(self, message, progress):
81         self.progress+=float(progress)
82         self._print(message)
83
84     def set(self, message, progress):
85         self.progress=float(progress)
86         self._print(message)
87
88     def _print(self, message):
89         print(message)
90         message="%s: %s" % (self.base, message)
91         #Blender.Window.DrawProgressBar(self.progress, message)
92
93     def finish(self):
94         self.progress=1.0
95         message='finished in %.2f sec' % (time.time()-self.start)
96         self.set(message, 1.0)
97
98 def progress_start(base):
99     global progressBar
100     print("#### progressBar ####")
101     progressBar=ProgressBar(base)
102
103 def progress_finish():
104     global progressBar
105     progressBar.finish()
106
107 def progress_print(message, progress=0.05):
108     global progressBar
109     progressBar.advance(message, progress)
110
111 def progress_set(message, progress):
112     global progressBar
113     progressBar.set(message, progress)
114
115
116 class scene:
117     @staticmethod
118     def get():
119         global SCENE
120         return SCENE
121
122     def update(scene):
123         scene.update()
124
125
126 class object:
127     @staticmethod
128     def createEmpty(name):
129         global SCENE
130         empty=bpy.data.objects.new(name, None)
131         SCENE.objects.link(empty)
132         return empty
133
134     @staticmethod
135     def each():
136         for o in SCENE.objects:
137             yield o
138
139     @staticmethod
140     def makeParent(parent, child):
141         child.parent=parent
142
143     @staticmethod
144     def duplicate(o):
145         global SCENE
146         bpy.ops.object.select_all(action='DESELECT')
147         o.select=True
148         SCENE.objects.active=o
149         bpy.ops.object.duplicate()
150         dumy=SCENE.objects.active
151         #bpy.ops.object.rotation_apply()
152         #bpy.ops.object.scale_apply()
153         #bpy.ops.object.location_apply()
154         return dumy.data, dumy
155
156     @staticmethod
157     def delete(o):
158         global SCENE
159         SCENE.objects.unlink(o)
160
161     @staticmethod
162     def getData(o):
163         return o.data
164
165     @staticmethod
166     def select(o):
167         o.select=True
168
169     @staticmethod
170     def activate(o):
171         global SCENE
172         o.select=True 
173         SCENE.objects.active=o
174
175     @staticmethod
176     def getActive():
177         global SCENE 
178         return SCENE.objects.active
179
180     @staticmethod
181     def deselectAll():
182         bpy.ops.object.select_all(action='DESELECT')
183
184     @staticmethod
185     def setLayerMask(object, layers):
186         layer=[]
187         for i in range(20):
188             try:
189                 layer.append(True if layers[i]!=0 else False)
190             except IndexError:
191                 layer.append(False)
192         object.layers=layer
193
194     @staticmethod
195     def isVisible(o):
196         return False if o.hide else True
197
198     @staticmethod
199     def getShapeKeys(o):
200         return o.data.shape_keys.key_blocks
201
202     @staticmethod
203     def addShapeKey(o, name):
204         try:
205             return o.shape_key_add(name)
206         except:
207             return o.add_shape_key(name)
208
209     @staticmethod
210     def hasShapeKey(o):
211         return o.data.shape_keys
212
213     @staticmethod
214     def pinShape(o, enable):
215         o.show_only_shape_key=enable
216
217     @staticmethod
218     def setActivateShapeKey(o, index):
219         o.active_shape_key_index=index
220
221     @staticmethod
222     def getPose(o):
223         return o.pose
224
225     @staticmethod
226     def getVertexGroup(o, name):
227         indices=[]
228         for i, v in enumerate(o.data.vertices):
229             for g in v.groups:
230                 if o.vertex_groups[g.group].name==name:
231                     indices.append(i)
232         return indices
233
234     @staticmethod
235     def getVertexGroupNames(o):
236         for g in o.vertex_groups:
237             yield g.name
238
239     @staticmethod
240     def addVertexGroup(o, name):
241         o.vertex_groups.new(name)
242
243     @staticmethod
244     def assignVertexGroup(o, name, index, weight):
245         o.vertex_groups[name].add([index], weight, 'ADD')
246
247     @staticmethod
248     def createBoneGroup(o, name, color_set='DEFAULT'):
249         # create group
250         object.activate(o)
251         enterPoseMode()
252         bpy.ops.pose.group_add()
253         # set name
254         pose=object.getPose(o)
255         g=pose.bone_groups.active
256         g.name=name
257         g.color_set=color_set
258
259     @staticmethod
260     def boneGroups(o):
261         return object.getPose(o).bone_groups
262
263
264 class modifier:
265     @staticmethod
266     def addMirror(mesh_object):
267         return mesh_object.modifiers.new("Modifier", "MIRROR")
268
269     @staticmethod
270     def addArmature(mesh_object, armature_object):
271         mod=mesh_object.modifiers.new("Modifier", "ARMATURE")
272         mod.object = armature_object
273         mod.use_bone_envelopes=False
274
275     @staticmethod
276     def hasType(mesh_object, type_name):
277         for mod in mesh_object.modifiers:
278                 if mod.type==type_name.upper():
279                     return True
280
281     @staticmethod
282     def isType(m, type_name):
283         return m.type==type_name.upper()
284
285     @staticmethod
286     def getArmatureObject(m):
287         return m.object
288
289
290 class shapekey:
291     @staticmethod
292     def assign(shapeKey, index, pos):
293         shapeKey.data[index].co=pos
294
295     @staticmethod
296     def getByIndex(b, index):
297         return b.data[index].co
298
299     @staticmethod
300     def get(b):
301         for k in b.data:
302             yield k.co
303
304
305 class texture:
306     @staticmethod
307     def create(path):
308         texture=bpy.data.textures.new(os.path.basename(path), 'IMAGE')
309         texture.use_mipmap=True
310         texture.use_interpolation=True
311         texture.use_alpha=True
312         try:
313             image=bpy.data.images.load(path)
314         except RuntimeError:
315             image=bpy.data.images.new('Image', width=16, height=16)
316         texture.image=image
317         return texture, image
318
319     @staticmethod
320     def getPath(t):
321         if  t.type=="IMAGE":
322             image=t.image
323             if image:
324                 return image.filepath
325
326
327 class material:
328     @staticmethod
329     def create(name):
330         return bpy.data.materials.new(name)
331
332     @staticmethod
333     def get(material_name):
334         return bpy.data.materials[material_name]
335
336     @staticmethod
337     def addTexture(material, texture, enable=True):
338         # search free slot
339         index=None
340         for i, slot in enumerate(material.texture_slots):
341             if not slot:
342                 index=i
343                 break
344         if index==None:
345             return
346         #
347         #material.add_texture(texture, "UV", "COLOR")
348         #slot=material.texture_slots.add()
349         slot=material.texture_slots.create(index)
350         slot.texture=texture
351         slot.texture_coords='UV'
352         slot.blend_type='MULTIPLY'
353         slot.use_map_alpha=True
354         slot.use=enable
355         return index
356
357     @staticmethod
358     def getTexture(m, index):
359         return m.texture_slots[index].texture
360
361     @staticmethod
362     def hasTexture(m):
363         return m.texture_slots[0]
364
365     @staticmethod
366     def setUseTexture(m, index, enable):
367         m.use_textures[index]=enable
368
369     @staticmethod
370     def eachTexturePath(m):
371         for slot in m.texture_slots:
372             if slot and slot.texture:
373                 texture=slot.texture
374                 if  texture.type=="IMAGE":
375                     image=texture.image
376                     if not image:
377                         continue
378                     yield image.filepath
379
380     @staticmethod
381     def eachEnalbeTexturePath(m):
382         for i, slot in enumerate(m.texture_slots):
383             if m.use_textures[i] and slot and slot.texture:
384                 texture=slot.texture
385                 if  texture.type=="IMAGE":
386                     image=texture.image
387                     if not image:
388                         continue
389                     yield image.filepath
390
391
392 class mesh:
393     @staticmethod
394     def create(name):
395         global SCENE
396         mesh=bpy.data.meshes.new("Mesh")
397         mesh_object= bpy.data.objects.new(name, mesh)
398         SCENE.objects.link(mesh_object)
399         return mesh, mesh_object
400
401     @staticmethod
402     def addGeometry(mesh, vertices, faces):
403         mesh.from_pydata(vertices, [], faces)
404         """
405         mesh.add_geometry(len(vertices), 0, len(faces))
406         # add vertex
407         unpackedVertices=[]
408         for v in vertices:
409             unpackedVertices.extend(v)
410         mesh.vertices.foreach_set("co", unpackedVertices)
411         # add face
412         unpackedFaces = []
413         for face in faces:
414             if len(face) == 4:
415                 if face[3] == 0:
416                     # rotate indices if the 4th is 0
417                     face = [face[3], face[0], face[1], face[2]]
418             elif len(face) == 3:
419                 if face[2] == 0:
420                     # rotate indices if the 3rd is 0
421                     face = [face[2], face[0], face[1], 0]
422                 else:
423                     face.append(0)
424             unpackedFaces.extend(face)
425         mesh.faces.foreach_set("verts_raw", unpackedFaces)
426         """
427         assert(len(vertices)==len(mesh.vertices))
428         assert(len(faces)==len(mesh.faces))
429
430     @staticmethod
431     def hasUV(mesh):
432         return len(mesh.uv_textures)>0
433
434     @staticmethod
435     def useVertexUV(mesh):
436         pass
437
438     @staticmethod
439     def addUV(mesh):
440         mesh.uv_textures.new()
441
442     @staticmethod
443     def hasFaceUV(mesh, i, face):
444         active_uv_texture=None
445         for t in mesh.uv_textures:
446             if t.active:
447                 active_uv_texture=t
448                 break
449         return active_uv_texture and active_uv_texture.data[i]
450
451     @staticmethod
452     def getFaceUV(mesh, i, faces, count=3):
453         active_uv_texture=None
454         for t in mesh.uv_textures:
455             if t.active:
456                 active_uv_texture=t
457                 break
458         if active_uv_texture and active_uv_texture.data[i]:
459             uvFace=active_uv_texture.data[i]
460             if count==3:
461                 return (uvFace.uv1, uvFace.uv2, uvFace.uv3)
462             elif count==4:
463                 return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4)
464             else:
465                 print(count)
466                 assert(False)
467         else:
468             return ((0, 0), (0, 0), (0, 0), (0, 0))
469
470     @staticmethod
471     def setFaceUV(m, i, face, uv_array, image):
472         uv_face=m.uv_textures[0].data[i]
473         uv_face.uv=uv_array
474         if image:
475             uv_face.image=image
476             #uv_face.use_image=True
477
478     @staticmethod
479     def vertsDelete(m, remove_vertices):
480         enterEditMode()
481         bpy.ops.mesh.select_all(action='DESELECT')
482         enterObjectMode()
483
484         for i in remove_vertices:
485             m.vertices[i].select=True
486
487         enterEditMode()
488         bpy.ops.mesh.delete(type='VERT')
489         enterObjectMode()
490
491     @staticmethod
492     def setSmooth(m, smoothing):
493         m.auto_smooth_angle=int(smoothing)
494         m.use_auto_smooth=True
495
496     @staticmethod
497     def recalcNormals(mesh_object):
498         bpy.ops.object.select_all(action='DESELECT')
499         object.activate(mesh_object)
500         enterEditMode()
501         bpy.ops.mesh.normals_make_consistent()
502         enterObjectMode()
503
504     @staticmethod
505     def flipNormals(m):
506         m.flipNormals()
507
508     @staticmethod
509     def addMaterial(m, material):
510         m.materials.append(material)
511
512     @staticmethod
513     def getMaterial(m, index):
514         return m.materials[index]
515
516
517 class vertex:
518     @staticmethod
519     def setNormal(v, normal):
520         v.normal=mathutils.Vector(normal)
521
522     @staticmethod
523     def getNormal(v):
524         return v.normal
525
526     @staticmethod
527     def setUv(v, uv):
528         # sticky ?
529         pass
530
531
532 class face:
533     @staticmethod
534     def getVertexCount(face):
535         return len(face.vertices)
536
537     @staticmethod
538     def getVertices(face):
539         return face.vertices[:]
540
541     @staticmethod
542     def getIndices(face, count=3):
543         if count==3:
544             return [face.vertices[0], face.vertices[1], face.vertices[2]]
545         elif count==4:
546             return [face.vertices[0], face.vertices[1], face.vertices[2], face.vertices[3]]
547         else:
548             assert(False)
549
550     @staticmethod
551     def setMaterial(face, material_index):
552         face.material_index=material_index
553
554     @staticmethod
555     def getMaterialIndex(face):
556         return face.material_index
557
558     @staticmethod
559     def setNormal(face, normal):
560         face.normal=normal
561
562     @staticmethod
563     def getNormal(face):
564         return face.normal
565
566     @staticmethod
567     def setSmooth(face, isSmooth):
568         face.use_smooth=True if isSmooth else False
569
570
571 class armature:
572     @staticmethod
573     def create():
574         global SCENE
575         armature = bpy.data.armatures.new('Armature')
576         armature_object=bpy.data.objects.new('Armature', armature)
577         SCENE.objects.link(armature_object)
578
579         armature_object.show_x_ray=True
580         armature.show_names=True
581         #armature.draw_type='OCTAHEDRAL'
582         armature.draw_type='STICK'
583         armature.use_deform_envelopes=False
584         armature.use_deform_vertex_groups=True
585         armature.use_mirror_x=True
586
587         return armature, armature_object
588
589     @staticmethod
590     def makeEditable(armature_object):
591         global SCENE
592         # select only armature object and set edit mode
593         SCENE.objects.active=armature_object
594         bpy.ops.object.mode_set(mode='OBJECT', toggle=False)
595         bpy.ops.object.mode_set(mode='EDIT', toggle=False)
596
597     @staticmethod
598     def createIkConstraint(armature_object, p_bone, effector_name, ik):
599         constraint = p_bone.constraints.new('IK')
600         constraint.chain_count=len(ik.children)
601         constraint.target=armature_object
602         constraint.subtarget=effector_name
603         constraint.use_tail=False
604         # not used. place folder when export.
605         constraint.weight=ik.weight
606         constraint.iterations=ik.iterations * 10
607         return constraint
608
609     @staticmethod
610     def createBone(armature, name):
611         return armature.edit_bones.new(name)
612
613     @staticmethod
614     def update(armature):
615         pass
616
617
618 class bone:
619     @staticmethod
620     def setConnected(bone):
621         bone.use_connect=True
622
623     @staticmethod
624     def isConnected(bone):
625         return bone.use_connect
626
627     @staticmethod
628     def setLayerMask(bone, layers):
629         layer=[]
630         for i in range(32):
631             try:
632                 layer.append(True if layers[i]!=0 else False)
633             except IndexError:
634                 layer.append(False)
635         bone.layers=layer
636
637     @staticmethod
638     def getHeadLocal(b):
639         return b.head_local[0:3]
640
641     @staticmethod
642     def getTailLocal(b):
643         return b.tail_local[0:3]
644
645
646 class constraint:
647     @staticmethod
648     def ikChainLen(c):
649         return c.chain_count
650
651     @staticmethod
652     def ikTarget(c):
653         return c.subtarget
654
655     @staticmethod
656     def ikItration(c):
657         return c.iterations
658
659     @staticmethod
660     def ikRotationWeight(c):
661         return c.weight
662
663     @staticmethod
664     def isIKSolver(c):
665         return c.type=='IK'
666
667 MMD_SHAPE_GROUP_NAME='_MMD_SHAPE'
668 MMD_MB_NAME='mb_name'
669 MMD_MB_COMMENT='mb_comment'
670 MMD_COMMENT='comment'
671 BASE_SHAPE_NAME='Basis'
672 RIGID_NAME='rigid_name'
673 RIGID_SHAPE_TYPE='rigid_shape_type'
674 RIGID_PROCESS_TYPE='rigid_process_type'
675 RIGID_BONE_NAME='rigid_bone_name'
676 RIGID_GROUP='ribid_group'
677 RIGID_INTERSECTION_GROUP='rigid_intersection_group'
678 RIGID_WEIGHT='rigid_weight'
679 RIGID_LINEAR_DAMPING='rigid_linear_damping'
680 RIGID_ANGULAR_DAMPING='rigid_angular_damping'
681 RIGID_RESTITUTION='rigid_restitution'
682 RIGID_FRICTION='rigid_friction'
683 CONSTRAINT_NAME='const_name'
684 CONSTRAINT_A='const_a'
685 CONSTRAINT_B='const_b'
686 CONSTRAINT_POS_MIN='const_pos_min'
687 CONSTRAINT_POS_MAX='const_pos_max'
688 CONSTRAINT_ROT_MIN='const_rot_min'
689 CONSTRAINT_ROT_MAX='const_rot_max'
690 CONSTRAINT_SPRING_POS='const_spring_pos'
691 CONSTRAINT_SPRING_ROT='const_spring_rot'
692 TOON_TEXTURE_OBJECT='ToonTextures'
693