From: ousttrue Date: Sat, 26 Jun 2010 00:56:38 +0000 (+0900) Subject: refactoring. X-Git-Url: http://git.osdn.net/view?a=commitdiff_plain;h=49e6bf278e016039253ecfc21cd0999c49a4ac5d;p=meshio%2Fmeshio.git refactoring. --- diff --git a/swig/blender/bl24.py b/swig/blender/bl24.py old mode 100644 new mode 100755 index d433fd4..0bdd6e7 --- a/swig/blender/bl24.py +++ b/swig/blender/bl24.py @@ -1,10 +1,13 @@ # coding: utf-8 import sys import os -import Blender -from Blender import Mathutils -import bpy +try: + import Blender + from Blender import Mathutils + import bpy +except: + pass # ファイルシステムの文字コード # 改造版との共用のため @@ -14,12 +17,50 @@ if os.path.exists(os.path.dirname(sys.argv[0])+"/utf8"): else: INTERNAL_ENCODING=FS_ENCODING +SCENE=None +def initialize(name, scene): + global SCENE + SCENE=scene + progress_start(name) + # set object mode + mode_edit = Blender.Window.EditMode() + if mode_edit: + Blender.Window.EditMode(0) + +def finalize(): + scene.update(SCENE) + progress_finish() + # restore edit mode + #if mode_edit: + # Blender.Window.EditMode(1) + +def message(msg): + res=Blender.Draw.PupMenu(msg + "%t|OK") + print(res) + +def enterEditMode(): + Blender.Window.EditMode(1) + +def exitEditMode(): + Blender.Window.EditMode(0) + +def createVector(x, y, z): + return Mathutils.Vector(x, y, z) + -############################################################################### -# Writer -############################################################################### class Writer(object): + ''' + io wrapper + ''' + __slots__=[ + 'io', 'encoding', + ] def __init__(self, path, encoding): + ''' + path: file path to open + encoding: text encoding to write + + ''' self.io=open(path, "wb") self.encoding=encoding @@ -33,15 +74,17 @@ class Writer(object): self.io.close() -############################################################################### -# ProgressBar -############################################################################### class ProgressBar(object): + ''' + progress bar wrapper + ''' + __slots__=['base', 'start', 'progress',] def __init__(self, base): print("#### %s ####" % base) self.base=base self.start=Blender.sys.time() self.set('', 0) + Blender.Window.WaitCursor(1) def advance(self, message, progress): self.progress+=float(progress) @@ -62,7 +105,8 @@ class ProgressBar(object): self.progress=1.0 message='finished in %.2f sec' % (Blender.sys.time()-self.start) self.set(message, 1.0) - + Blender.Window.WaitCursor(0) + Blender.Redraw() def progress_start(base): global progressBar @@ -81,375 +125,419 @@ def progress_set(message, progress): progressBar.set(message, progress) -############################################################################### -def createEmptyObject(scene, name): - empty=scene.objects.new("Empty") - empty.setName(name) - return empty - -def createMaterial(name): - material = Blender.Material.New(name) - return material - -def createMqoMaterial(m): - material = Blender.Material.New(m.getName().encode(INTERNAL_ENCODING)) - material.mode |= Blender.Material.Modes.SHADELESS - material.rgbCol = [m.color.r, m.color.g, m.color.b] - material.alpha = m.color.a - material.amb = m.ambient - material.spec = m.specular - material.hard = int(255 * m.power) - return material - -def createPmdMaterial(m): - material=Blender.Material.New() - material.setDiffuseShader(Blender.Material.Shaders.DIFFUSE_TOON) - material.setRef(1) - material.diffuseSize = 3.14/2 - material.setDiffuseSmooth(0) - material.setSpecShader(Blender.Material.Shaders.SPEC_TOON) - material.setSpecSize(0) - material.setSpec(0) - material.setRGBCol([m.diffuse.r, m.diffuse.g, m.diffuse.b]) - material.setAlpha(m.diffuse.a) - material.setSpec(m.shinness*0.1) - material.setSpecCol([m.specular.r, m.specular.g, m.specular.b]) - material.setMirCol([m.ambient.r, m.ambient.g, m.ambient.b]) - material.enableSSS=True if m.flag==1 else False - return material - -def createTexture(path): - image = Blender.Image.Load(path.encode(INTERNAL_ENCODING)) - texture = Blender.Texture.New(path.encode(INTERNAL_ENCODING)) - texture.type = Blender.Texture.Types.IMAGE - texture.image = image - texture.tex.imageFlags|=Blender.Texture.ImageFlags.USEALPHA - return texture, image - -def materialAddTexture(material, texture): - material.mode = material.mode | Blender.Material.Modes.TEXFACE - material.setTexture(0, texture, Blender.Texture.TexCo.UV) - -def materialHasTexture(material): - return len(material.getTextures())>0 - -def createMesh(scene, name): - mesh = Blender.Mesh.New() - mesh_object=scene.objects.new(mesh, name.encode(INTERNAL_ENCODING)) - return mesh, mesh_object - - -def objectMakeParent(parent, child): - parent.makeParent([child]) - - -def meshAddMaterial(mesh, material): - mesh.materials+=[material] - - -def meshAddGeometry(mesh, vertices, faces): - mesh.verts.extend(vertices) - new_faces=mesh.faces.extend(faces, - #ignoreDups=True, - indexList=True) - mesh.update() - -def objectAddMirrorModifier(mesh_object): - return mesh_object.modifiers.append(Blender.Modifier.Types.MIRROR) - -def faceSetNormal(face, normal): - face.no=normal - -def getTexture(m, dirname): - tex="" - aplane="" - # texture - for texture in m.getTextures(): - if texture and texture.tex and texture.tex.getImage(): - image=texture.tex.getImage() - if not image: - continue - imagePath=Blender.sys.expandpath(image.getFilename()) - if len(dirname)>0 and imagePath.startswith(dirname): - # 相対パスに変換する - imagePath=imagePath[len(dirname)+1:len(imagePath)] - if texture.mtCol>0: - tex=" tex(\"%s\")" % imagePath - elif texture.mtAlpha>0: - aplane=" aplane(\"%s\")" % imagePath - return tex, aplane - -def objectDuplicate(scene, obj): - mesh, dumy=createMesh(scene, obj.name.decode(INTERNAL_ENCODING)) - # not apply modifiers - mesh.getFromObject(obj.name, 1) - # apply matrix - dumy.setMatrix(obj.matrixWorld) - return mesh, dumy - -def objectDelete(scene, obj): - scene.objects.unlink(obj) - -def faceVertexCount(face): - return len(face.v) - -def faceVertices(face): - # flip - return [v.index for v in reversed(face.v)] - -def meshHasUV(mesh): - return mesh.faceUV - -def faceHasUV(mesh, i, face): - return len(face.uv)>0 - -def faceGetUV(mesh, i, face, count): - # flip - return reversed(face.uv) - -def faceSetMaterial(face, material_index): - face.mat=material_index - -def faceSetSmooth(face, isSmooth): - face.smooth=1 if isSmooth else 0 - -def faceSetUv(face, uv_array): - face.uv=uv_array - -def materialToMqo(m): - return "\"%s\" shader(3) col(%f %f %f %f)" % ( - m.name, m.rgbCol[0], m.rgbCol[1], m.rgbCol[2], m.alpha) - -def faceMaterialIndex(face): - return face.mat - -def objectGetData(o): - return o.getData(mesh=True) - -def objectAddArmatureModifier(o, armature_object): - mod=o.modifiers.append(Blender.Modifier.Types.ARMATURE) - mod[Blender.Modifier.Settings.OBJECT] = armature_object - mod[Blender.Modifier.Settings.ENVELOPES] = False - -def objectSelect(o): - o.select(True) - -def objectGetPose(o): - return o.getPose() - -def poseBoneLimit(n, b): - if n.endswith("_t"): - return - if n.startswith("knee_"): - b.lockYRot=True - b.lockZRot=True - b.limitX=True - b.limitMin=[0, 0, 0] - b.limitMax=[180, 0, 0] - elif n.startswith("ankle_"): - b.lockYRot=True - -def enterEditMode(): - Blender.Window.EditMode(1) - -def exitEditMode(): - Blender.Window.EditMode(0) - -def objectDeselectAll(): - for o in bpy.data.scenes.active.objects: - o.select(False) - -def objectActivate(scene, o): - o.select(True ) - scene.objects.active=o - -def objectGetActive(scene): - return scene.objects.active - -def meshAddVertexGroup(meshObject, name): - meshObject.getData(mesh=True).addVertGroup(name) - -def meshUseVertexUv(mesh): - mesh.vertexUV = 1 - -def vertexSetNormal(mvert, normal): - mvert.no=Mathutils.Vector(*normal) - -def vertexSetUv(mvert, uv): - mvert.uvco=uv - -def meshAssignVertexGroup(meshObject, name, index, weight): - meshObject.getData(mesh=True).assignVertsToGroup(name, - [index], weight, Blender.Mesh.AssignModes.ADD) - -def meshAddUV(mesh): - mesh.addUVLayer('NewUV') - -def meshVertsDelete(mesh, remove_vertices): - mesh.verts.delete(remove_vertices) - -def createArmature(scene): - armature = Blender.Armature.New() - armature_object = scene.objects.new(armature) - - # set XRAY - armature_object.drawMode = ( - armature_object.drawMode | Blender.Object.DrawModes.XRAY) - # armature settings - armature.drawType = Blender.Armature.OCTAHEDRON - armature.drawNames=True - armature.envelopes = False - armature.vertexGroups = True - armature.mirrorEdit = True - - return armature, armature_object - -def armatureMakeEditable(scene, armature_object): - # create armature - armature_object.getData().makeEditable() - -def createIkConstraint(armature_object, p_bone, effector_name, ik): - cSetting = Blender.Constraint.Settings - # IK solver - constraint = p_bone.constraints.append(Blender.Constraint.Type.IKSOLVER) - constraint[cSetting.CHAINLEN]=len(ik.children) - constraint[cSetting.TARGET]=armature_object - constraint[cSetting.USETIP]=False - constraint[cSetting.BONE]=effector_name - # not used. place folder when export. - constraint[cSetting.ROTWEIGHT]=ik.weight - constraint[cSetting.ITERATIONS]=ik.iterations * 10 - return constraint - -def createArmatureBone(armature, name): - bone=Blender.Armature.Editbone() - bone.name=name.encode(INTERNAL_ENCODING) - armature.bones[name]=bone - return bone - -def boneSetConnected(bone): - bone.options+=[Blender.Armature.CONNECTED] - -def createVector(x, y, z): - return Mathutils.Vector(x, y, z) - -def armatureUpdate(armature): - armature.update() - -def boneLayerMask(bone, layers): - mask=0 - for i, enable in enumerate(layers): - if enable!=0: - mask+=(1<0 + + @staticmethod + def getTexturePath(m, dirname): + tex="" + aplane="" + # texture + for texture in m.getTextures(): + if texture and texture.tex and texture.tex.getImage(): + image=texture.tex.getImage() + if not image: + continue + imagePath=Blender.sys.expandpath(image.getFilename()) + if len(dirname)>0 and imagePath.startswith(dirname): + # 相対パスに変換する + imagePath=imagePath[len(dirname)+1:len(imagePath)] + if texture.mtCol>0: + tex=" tex(\"%s\")" % imagePath + elif texture.mtAlpha>0: + aplane=" aplane(\"%s\")" % imagePath + return tex, aplane + + +class mesh: + @staticmethod + def create(name): + global SCENE + m=Blender.Mesh.New() + o=SCENE.objects.new(m, name.encode(INTERNAL_ENCODING)) + return m, o + + @staticmethod + def addGeometry(m, vertices, faces): + m.verts.extend(vertices) + new_faces=m.faces.extend(faces, + #ignoreDups=True, + indexList=True) + m.update() + + @staticmethod + def hasUV(m): + return m.faceUV + + @staticmethod + def useVertexUV(m): + m.vertexUV = 1 + + @staticmethod + def addUV(m): + m.addUVLayer('NewUV') + + @staticmethod + def hasFaceUV(m, i, face): + return len(face.uv)>0 + + @staticmethod + def getFaceUV(m, i, face, count=3): + return face.uv + + @staticmethod + def setFaceUV(m, i, face, uv_array, image): + face.uv=[Mathutils.Vector(uv[0], uv[1]) for uv in uv_array] + if image: + face.image=image + + @staticmethod + def vertsDelete(m, remove_vertices): + m.verts.delete(remove_vertices) + + @staticmethod + def setSmooth(m, smoothing): + m.mode |= Blender.Mesh.Modes.AUTOSMOOTH + m.degr=int(smoothing) + #m.smooth() + + @staticmethod + def recalcNormals(mesh_object): + m=mesh_object.getData(mesh=True) + m.calcNormals() + + @staticmethod + def flipNormals(m): + m.flipNormals() + + @staticmethod + def addMaterial(m, material): + m.materials+=[material] + + +class vertex: + @staticmethod + def setNormal(mvert, normal): + mvert.no=Mathutils.Vector(*normal) + + @staticmethod + def setUv(mvert, uv): + mvert.uvco=uv + + +class face: + @staticmethod + def getVertexCount(face): + return len(face.v) + + @staticmethod + def getVertices(face): + return [v.index for v in face.v] + + @staticmethod + def getIndices(face): + return [face.verts[0].index, face.verts[1].index, face.verts[2].index] + + @staticmethod + def setMaterial(face, material_index): + face.mat=material_index + + @staticmethod + def getMaterialIndex(face): + return face.mat + + @staticmethod + def setNormal(face, normal): + face.no=normal + + @staticmethod + def getNormal(face): + return face.no + + @staticmethod + def setSmooth(face, isSmooth): + face.smooth=1 if isSmooth else 0 + + +class armature: + @staticmethod + def create(): + global SCENE + armature = Blender.Armature.New() + armature_object = SCENE.objects.new(armature) + + # set XRAY + armature_object.drawMode = ( + armature_object.drawMode | Blender.Object.DrawModes.XRAY) + # armature settings + armature.drawType = Blender.Armature.OCTAHEDRON + armature.drawNames=True + armature.envelopes = False + armature.vertexGroups = True + armature.mirrorEdit = True + + return armature, armature_object + + @staticmethod + def makeEditable(armature_object): + # create armature + armature_object.getData().makeEditable() + + @staticmethod + def createIkConstraint(armature_object, p_bone, effector_name, ik): + cSetting = Blender.Constraint.Settings + # IK solver + constraint = p_bone.constraints.append(Blender.Constraint.Type.IKSOLVER) + constraint[cSetting.CHAINLEN]=len(ik.children) + constraint[cSetting.TARGET]=armature_object + constraint[cSetting.USETIP]=False + constraint[cSetting.BONE]=effector_name + # not used. place folder when export. + constraint[cSetting.ROTWEIGHT]=ik.weight + constraint[cSetting.ITERATIONS]=ik.iterations * 10 + return constraint + + @staticmethod + def createBone(armature_object, name): + bone=Blender.Armature.Editbone() + bone.name=name.encode(INTERNAL_ENCODING) + armature_object.bones[name]=bone + return bone + + @staticmethod + def update(armature): + armature.update() + + +class bone: + @staticmethod + def setConnected(bone): + bone.options+=[Blender.Armature.CONNECTED] + + @staticmethod + def isConnected(b): + return Blender.Armature.CONNECTED in b.options + + @staticmethod + def setLayerMask(bone, layers): + mask=0 + for i, enable in enumerate(layers): + if enable!=0: + mask+=(1<0 and imagePath.startswith(dirname): - # $BAjBP%Q%9$KJQ49$9$k(B - imagePath=imagePath[len(dirname)+1:len(imagePath)] - #imagePath=Blender.sys.expandpath( - # imagePath).replace("\\", '/') - if slot.map_colordiff: - tex=" tex(\"%s\")" % imagePath - elif slot.map_alpha: - aplane=" aplane(\"%s\")" % imagePath - return tex, aplane - -def objectDuplicate(scene, obj): - bpy.ops.object.select_all(action='DESELECT') - obj.selected=True - scene.objects.active=obj - bpy.ops.object.duplicate() - dumy=scene.objects.active - bpy.ops.object.rotation_apply() - bpy.ops.object.scale_apply() - bpy.ops.object.location_apply() - return dumy.data, dumy - -def objectDelete(scene, obj): - scene.objects.unlink(obj) - -def faceVertexCount(face): - return len(face.verts) - -def faceVertices(face): - return face.verts[:] - -def meshHasUV(mesh): - return mesh.active_uv_texture - -def faceHasUV(mesh, i, face): - return mesh.active_uv_texture.data[i] - -def faceGetUV(mesh, i, faces, count): - uvFace=mesh.active_uv_texture.data[i] - if count==3: - return (uvFace.uv1, uvFace.uv2, uvFace.uv3) - elif count==4: - return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4) - else: - print(count) - assert(False) - -def materialToMqo(m): - return "\"%s\" shader(3) col(%f %f %f %f)" % ( - m.name, - m.diffuse_color[0], m.diffuse_color[1], m.diffuse_color[2], - m.alpha) - -def faceMaterialIndex(face): - return face.material_index - -def objectGetData(o): - return o.data - -def objectAddArmatureModifier(o, armature_object): - mod=o.modifiers.new("Modifier", "ARMATURE") - mod.object = armature_object - mod.use_bone_envelopes=False - -def objectSelect(o): - o.selected=True - -def objectGetPose(o): - return o.pose - -def poseBoneLimit(n, b): - if n.endswith("_t"): - return - if n.startswith("knee_"): - b.ik_dof_y=False - b.ik_dof_z=False - b.ik_dof_x=True - b.ik_limit_x=True - b.ik_min_x=0 - b.ik_max_x=180 - elif n.startswith("ankle_"): - #b.ik_dof_y=False +class scene: + @staticmethod + def update(scene): + scene.update() + + +class object: + @staticmethod + def createEmpty(name): + global SCENE + empty=bpy.data.objects.new(name, None) + SCENE.objects.link(empty) + return empty + + @staticmethod + def makeParent(parent, child): + child.parent=parent + + @staticmethod + def duplicate(o): + global SCENE + bpy.ops.object.select_all(action='DESELECT') + o.selected=True + SCENE.objects.active=o + bpy.ops.object.duplicate() + dumy=SCENE.objects.active + #bpy.ops.object.rotation_apply() + #bpy.ops.object.scale_apply() + #bpy.ops.object.location_apply() + return dumy.data, dumy + + @staticmethod + def delete(o): + global SCENE + SCENE.objects.unlink(o) + + @staticmethod + def getData(o): + return o.data + + @staticmethod + def select(o): + o.selected=True + + @staticmethod + def activate(o): + global SCENE + o.selected=True + SCENE.objects.active=o + + @staticmethod + def getActive(): + global SCENE + return SCENE.objects.active + + @staticmethod + def deselectAll(): + bpy.ops.object.select_all(action='DESELECT') + + @staticmethod + def setLayerMask(object, layers): + layer=[] + for i in range(20): + try: + layer.append(True if layers[i]!=0 else False) + except IndexError: + layer.append(False) + object.layers=layer + + @staticmethod + def isVisible(o): + return o.restrict_view + + @staticmethod + def getShapeKeys(o): + return o.data.shape_keys.keys + + @staticmethod + def addShapeKey(o, name): + return o.add_shape_key(name) + + @staticmethod + def hasShapeKey(o): + return o.data.shape_keys + + @staticmethod + def pinShape(o, enable): + o.shape_key_lock=enable + + @staticmethod + def setActivateShapeKey(o, index): + o.active_shape_key_index=index + + @staticmethod + def getPose(o): + return o.pose + + @staticmethod + def getVertexGroup(o, name): + indices=[] + for i, v in enumerate(o.data.verts): + for g in v.groups: + if o.vertex_groups[g.group].name==name: + indices.append(i) + return indices + + @staticmethod + def getVertexGroupNames(o): + for g in o.vertex_groups: + yield g.name + + @staticmethod + def addVertexGroup(o, name): + o.add_vertex_group(name) + + @staticmethod + def assignVertexGroup(o, name, index, weight): + o.add_vertex_to_group(index, + o.vertex_groups[name], weight, 'ADD') + + +class modifier: + @staticmethod + def addMirror(mesh_object): + return mesh_object.modifiers.new("Modifier", "MIRROR") + + @staticmethod + def addArmature(mesh_object, armature_object): + mod=mesh_object.modifiers.new("Modifier", "ARMATURE") + mod.object = armature_object + mod.use_bone_envelopes=False + + @staticmethod + def hasType(mesh_object, type_name): + for mod in mesh_object.modifiers: + if mod.type==type_name.upper(): + return True + + @staticmethod + def isType(m, type_name): + return m.type==type_name.upper() + + @staticmethod + def getArmatureObject(m): + return m.object + + +class shapekey: + @staticmethod + def assign(shapeKey, index, pos): + shapeKey.data[index].co=pos + + @staticmethod + def getByIndex(b, index): + return b.data[index].co + + @staticmethod + def get(b): + for k in b.data: + yield k.co + + +class texture: + @staticmethod + def create(path): + texture=bpy.data.textures.new(os.path.basename(path)) + texture.type='IMAGE' + texture=texture.recast_type() + image=bpy.data.images.load(path) + texture.image=image + texture.mipmap = True + texture.interpolation = True + texture.use_alpha = True + return texture, image + + +class material: + @staticmethod + def create(name): + return bpy.data.materials.new(name) + + @staticmethod + def get(material_name): + return bpy.data.materials[material_name] + + @staticmethod + def addTexture(material, texture): + #material.add_texture(texture, "UV", {"COLOR", "ALPHA"}) + material.add_texture(texture, "UV", "COLOR") + + @staticmethod + def hasTexture(material): + return material.texture_slots[0] + + @staticmethod + def getTexturePath(m, dirname): + tex="" + aplane="" + # texture + for slot in m.texture_slots: + if slot and slot.texture: + texture=slot.texture + if texture.type=="IMAGE": + image=texture.image + if not image: + continue + imagePath=image.filename + if len(dirname)>0 and imagePath.startswith(dirname): + # $BAjBP%Q%9$KJQ49$9$k(B + imagePath=imagePath[len(dirname)+1:len(imagePath)] + #imagePath=Blender.sys.expandpath( + # imagePath).replace("\\", '/') + if slot.map_colordiff: + tex=" tex(\"%s\")" % imagePath + elif slot.map_alpha: + aplane=" aplane(\"%s\")" % imagePath + return tex, aplane + + +class mesh: + @staticmethod + def create(name): + global SCENE + mesh=bpy.data.meshes.new("Mesh") + mesh_object= bpy.data.objects.new(name, mesh) + SCENE.objects.link(mesh_object) + return mesh, mesh_object + + @staticmethod + def addGeometry(mesh, vertices, faces): + mesh.from_pydata(vertices, [], faces) + """ + mesh.add_geometry(len(vertices), 0, len(faces)) + # add vertex + unpackedVertices=[] + for v in vertices: + unpackedVertices.extend(v) + mesh.verts.foreach_set("co", unpackedVertices) + # add face + unpackedFaces = [] + for face in faces: + if len(face) == 4: + if face[3] == 0: + # rotate indices if the 4th is 0 + face = [face[3], face[0], face[1], face[2]] + elif len(face) == 3: + if face[2] == 0: + # rotate indices if the 3rd is 0 + face = [face[2], face[0], face[1], 0] + else: + face.append(0) + unpackedFaces.extend(face) + mesh.faces.foreach_set("verts_raw", unpackedFaces) + """ + assert(len(vertices)==len(mesh.verts)) + assert(len(faces)==len(mesh.faces)) + + @staticmethod + def hasUV(mesh): + return mesh.active_uv_texture + + @staticmethod + def useVertexUV(mesh): pass -def enterEditMode(): - bpy.ops.object.mode_set(mode='EDIT', toggle=False) - -def exitEditMode(): - bpy.ops.object.mode_set(mode='OBJECT', toggle=False) - -def objectDeselectAll(): - bpy.ops.object.select_all(action='DESELECT') - -def objectActivate(scene, o): - o.selected=True - scene.objects.active=o - -def objectGetActive(scene): - return scene.objects.active - -def meshAddVertexGroup(meshObject, name): - meshObject.add_vertex_group(name) - -def vertexSetNormal(mvert, normal): - mvert.normal=mathutils.Vector(normal) - -def faceSetNormal(face, normal): - face.normal=normal - -def meshUseVertexUv(mesh): - pass - -def vertexSetUv(mvert, uv): - pass - -def meshAssignVertexGroup(meshObject, name, index, weight): - meshObject.add_vertex_to_group(index, - meshObject.vertex_groups[name], weight, 'ADD') - -def meshAddUV(mesh): - mesh.add_uv_texture() - -def meshVertsDelete(mesh, remove_vertices): - enterEditMode() - bpy.ops.mesh.select_all(action='DESELECT') - exitEditMode() - - for i in remove_vertices: - mesh.verts[i].selected=True - - enterEditMode() - bpy.ops.mesh.delete(type='VERT') - exitEditMode() - -def createArmature(scene): - armature = bpy.data.armatures.new('Armature') - armature_object=bpy.data.objects.new('Armature', armature) - scene.objects.link(armature_object) - - armature_object.x_ray=True - armature.draw_names=True - armature.drawtype='OCTAHEDRAL' - armature.deform_envelope=False - armature.deform_vertexgroups=True - armature.x_axis_mirror=True - - return armature, armature_object - -def armatureMakeEditable(scene, armature_object): - # select only armature object and set edit mode - scene.objects.active=armature_object - bpy.ops.object.mode_set(mode='OBJECT', toggle=False) - bpy.ops.object.mode_set(mode='EDIT', toggle=False) - -def createIkConstraint(armature_object, p_bone, effector_name, ik): - constraint = p_bone.constraints.new('IK') - constraint.chain_length=len(ik.children) - constraint.target=armature_object - constraint.subtarget=effector_name - constraint.use_tail=False - # not used. place folder when export. - constraint.weight=ik.weight - constraint.iterations=ik.iterations * 10 - return constraint - -def createArmatureBone(armature, name): - return armature.edit_bones.new(name) - -def boneSetConnected(bone): - bone.connected=True - -def createVector(x, y, z): - return mathutils.Vector([x, y, z]) - -def armatureUpdate(armature): - pass - -def boneLayerMask(bone, layers): - layer=[] - for i in range(32): - try: - layer.append(True if layers[i]!=0 else False) - except IndexError: - layer.append(False) - bone.layer=layer - -def objectLayerMask(object, layers): - layer=[] - for i in range(20): - try: - layer.append(True if layers[i]!=0 else False) - except IndexError: - layer.append(False) - object.layers=layer - -def objectPinShape(o): - o.shape_key_lock=True - -def objectAddShapeKey(o, name): - return o.add_shape_key(name) - -def objectActivateShapeKey(o, index): - o.active_shape_key_index=index - -def shapeKeyAssign(shapeKey, index, pos): - shapeKey.data[index].co=pos - -def objectIsVisible(obj): - return obj.restrict_view - -def meshVertexGroupNames(meshObject): - for g in meshObject.vertex_groups: - yield g.name - -def faceNormal(face): - return face.normal - -def meshFaceUv(mesh, i, face): - return mesh.uv_textures[0].data[i].uv - -def armatureModifierGetObject(m): - return m.object - -def objectHasShapeKey(o): - return o.data.shape_keys - -def objectShapeKeys(o): - return o.data.shape_keys.keys - -def meshVertexGroup(meshObject, name): - indices=[] - for i, v in enumerate(meshObject.data.verts): - for g in v.groups: - if meshObject.vertex_groups[g.group].name==name: - indices.append(i) - return indices - -def materialGet(scene, material_name): - return bpy.data.materials[material_name] - -def modifierIsArmature(m): - return m.type=="ARMATURE" - -def boneHeadLocal(b): - return b.head_local[0:3] - -def boneTailLocal(b): - return b.tail_local[0:3] + @staticmethod + def addUV(mesh): + mesh.add_uv_texture() + + @staticmethod + def hasFaceUV(mesh, i, face): + return mesh.active_uv_texture.data[i] + + @staticmethod + def getFaceUV(mesh, i, faces, count=3): + uvFace=mesh.active_uv_texture.data[i] + if count==3: + return (uvFace.uv1, uvFace.uv2, uvFace.uv3) + elif count==4: + return (uvFace.uv1, uvFace.uv2, uvFace.uv3, uvFace.uv4) + else: + print(count) + assert(False) + + @staticmethod + def setFaceUV(mesh, i, face, uv_array, image): + uv_face=mesh.uv_textures[0].data[i] + uv_face.uv=uv_array + if image: + uv_face.image=image + uv_face.tex=True + + @staticmethod + def vertsDelete(mesh, remove_vertices): + enterEditMode() + bpy.ops.mesh.select_all(action='DESELECT') + exitEditMode() + + for i in remove_vertices: + mesh.verts[i].selected=True + + enterEditMode() + bpy.ops.mesh.delete(type='VERT') + exitEditMode() + + @staticmethod + def setSmooth(mesh, smoothing): + mesh.autosmooth_angle=int(smoothing) + mesh.autosmooth=True + + @staticmethod + def recalcNormals(mesh_object): + bpy.ops.object.select_all(action='DESELECT') + object.activate(mesh_object) + enterEditMode() + bpy.ops.mesh.normals_make_consistent() + exitEditMode() + + @staticmethod + def flipNormals(mesh): + mesh.flipNormals() + + @staticmethod + def addMaterial(mesh, material): + mesh.add_material(material) + + +class vertex: + @staticmethod + def setNormal(mvert, normal): + mvert.normal=mathutils.Vector(normal) + + @staticmethod + def setUv(mvert, uv): + pass -def boneIsConnected(b): - return b.connected -def constraintIsIKSolver(c): - return c.type=='IK' +class face: + @staticmethod + def getVertexCount(face): + return len(face.verts) + + @staticmethod + def getVertices(face): + return face.verts[:] + + @staticmethod + def getIndices(face): + return [face.verts[0], face.verts[1], face.verts[2]] + + @staticmethod + def setMaterial(face, material_index): + face.material_index=material_index + + @staticmethod + def getMaterialIndex(face): + return face.material_index + + @staticmethod + def setNormal(face, normal): + face.normal=normal + + @staticmethod + def getNormal(face): + return face.normal + + @staticmethod + def setSmooth(face, isSmooth): + face.smooth=True if isSmooth else False + + +class armature: + @staticmethod + def create(): + global SCENE + armature = bpy.data.armatures.new('Armature') + armature_object=bpy.data.objects.new('Armature', armature) + SCENE.objects.link(armature_object) + + armature_object.x_ray=True + armature.draw_names=True + armature.drawtype='OCTAHEDRAL' + armature.deform_envelope=False + armature.deform_vertexgroups=True + armature.x_axis_mirror=True + + return armature, armature_object + + @staticmethod + def makeEditable(armature_object): + global SCENE + # select only armature object and set edit mode + SCENE.objects.active=armature_object + bpy.ops.object.mode_set(mode='OBJECT', toggle=False) + bpy.ops.object.mode_set(mode='EDIT', toggle=False) + + @staticmethod + def createIkConstraint(armature_object, p_bone, effector_name, ik): + constraint = p_bone.constraints.new('IK') + constraint.chain_length=len(ik.children) + constraint.target=armature_object + constraint.subtarget=effector_name + constraint.use_tail=False + # not used. place folder when export. + constraint.weight=ik.weight + constraint.iterations=ik.iterations * 10 + return constraint + + @staticmethod + def createBone(armature, name): + return armature.edit_bones.new(name) + + @staticmethod + def update(armature): + pass -def ikChainLen(c): - return c.chain_length -def ikTarget(c): - return c.subtarget +class bone: + @staticmethod + def setConnected(bone): + bone.connected=True -def ikItration(c): - return c.iterations + @staticmethod + def isConnected(b): + return b.connected -def ikRotationWeight(c): - return c.weight + @staticmethod + def setLayerMask(bone, layers): + layer=[] + for i in range(32): + try: + layer.append(True if layers[i]!=0 else False) + except IndexError: + layer.append(False) + bone.layer=layer -def shapeKeyGet(b, index): - return b.data[index].co + @staticmethod + def getHeadLocal(b): + return b.head_local[0:3] -def shapeKeys(b): - for k in b.data: - yield k.co + @staticmethod + def getTailLocal(b): + return b.tail_local[0:3] -def VtoV(v): - return mathutils.Vector([v.x, v.y, v.z]) -def meshSetSmooth(mesh, smoothing): - mesh.autosmooth_angle=int(smoothing) - mesh.autosmooth=True +class constraint: + @staticmethod + def ikChainLen(c): + return c.chain_length -def meshRecalcNormals(mesh_object): - bpy.ops.object.select_all(action='DESELECT') - objectActivate(bpy.context.scene, mesh_object) - enterEditMode() - bpy.ops.mesh.normals_make_consistent() - exitEditMode() + @staticmethod + def ikTarget(c): + return c.subtarget -def meshFlipNormals(mesh): - mesh.flipNormals() + @staticmethod + def ikItration(c): + return c.iterations -def materialHasTexture(material): - return material.texture_slots[0] + @staticmethod + def ikRotationWeight(c): + return c.weight -def faceGetIndices(face): - return [face.verts[0], face.verts[1], face.verts[2]] + @staticmethod + def isIKSolver(c): + return c.type=='IK' -def internalToCp932(s): - return s.encode('cp932') diff --git a/swig/blender/mqo_export.py b/swig/blender/mqo_export.py index 5f753d5..f135187 100644 --- a/swig/blender/mqo_export.py +++ b/swig/blender/mqo_export.py @@ -20,12 +20,9 @@ Run this script from "File->Export" menu. 0.1 20080128: 0.2 20100518: refactoring. 0.3 20100606: integrate 2.4 and 2.5. +0.4 20100626: refactoring. """ - -############################################################################### -# import -############################################################################### import os import sys @@ -41,6 +38,10 @@ if isBlender24(): # wrapper import bl24 as bl + def materialToMqo(m): + return "\"%s\" shader(3) col(%f %f %f %f)" % ( + m.name, m.rgbCol[0], m.rgbCol[1], m.rgbCol[2], m.alpha) + else: # for 2.5 import bpy @@ -49,6 +50,12 @@ else: # wrapper import bl25 as bl + def materialToMqo(m): + return "\"%s\" shader(3) col(%f %f %f %f)" % ( + m.name, + m.diffuse_color[0], m.diffuse_color[1], m.diffuse_color[2], + m.alpha) + def apply_transform(vec, matrix): x, y, z = vec xloc, yloc, zloc = matrix[3][0], matrix[3][1], matrix[3][2] @@ -87,7 +94,6 @@ class MqoExporter(object): self.objects=[] self.materials=[] self.scale=scale - print('scaling', self.scale) def setup(self, scene): # 木構造を構築する @@ -128,7 +134,7 @@ class MqoExporter(object): self.materials.append(material) return index - def write(self, path, scene): + def write(self, path): io=bl.Writer(path, 'cp932') self.__write_header(io) self.__write_scene(io) @@ -136,7 +142,7 @@ class MqoExporter(object): self.__write_materials(io, os.path.dirname(path)) print("Writing ObjectChunk") for info in self.objects: - self.__write_object(io, info, scene) + self.__write_object(io, info) io.write("Eof\r\n") io.flush() io.close() @@ -155,20 +161,20 @@ class MqoExporter(object): # each material io.write("Material %d {\r\n" % (len(self.materials))) for m in self.materials: - tex, aplane=bl.getTexture(m, dirname) + tex, aplane=bl.material.getTexturePath(m, dirname) if len(tex): # textureがある場合は下地を白に io.write("\"%s\" shader(3) col(1 1 1 1)" % m.name) else: # 無い場合はそのまま - io.write(bl.materialToMqo(m)) + io.write(materialToMqo(m)) io.write(tex) io.write(aplane) io.write("\r\n") # end of chunk io.write("}\r\n") - def __write_object(self, io, info, scene): + def __write_object(self, io, info): print(info) obj=info.object @@ -186,19 +192,13 @@ class MqoExporter(object): # depth io.write("\tdepth %d\r\n" % info.depth) - # mirroring - isMirrorring=False - for mod in obj.modifiers: - if mod.name.upper()=="MIRROR": - isMirrorring=True - break - if isMirrorring: + if bl.modifier.hasType(obj, 'MIRROR'): io.write("\tmirror 1\r\n") io.write("\tmirror_axis 1\r\n") if obj.type.upper()=='MESH': # duplicate and applyMatrix - mesh, dumy=bl.objectDuplicate(scene, obj) + mesh, dumy=bl.object.duplicate(obj) # vertices io.write("\tvertex %d {\r\n" % len(mesh.verts)) @@ -211,63 +211,51 @@ class MqoExporter(object): # faces io.write("\tface %d {\r\n" % len(mesh.faces)) for i, face in enumerate(mesh.faces): - count=bl.faceVertexCount(face) + count=bl.face.getVertexCount(face) # V io.write("\t\t%d V(" % count) - face_list=[] - for j in bl.faceVertices(face): - face_list.insert(0, j) - # flip face - for j in face_list: + for j in reversed(bl.face.getVertices(face)): io.write("%d " % j) io.write(")") # mat if len(mesh.materials): io.write(" M(%d)" % - info.material_map[bl.faceMaterialIndex(face)]) + info.material_map[bl.face.getMaterialIndex(face)]) # UV - if bl.meshHasUV(mesh) and bl.faceHasUV(mesh, i, face): + if bl.mesh.hasUV(mesh) and bl.mesh.hasFaceUV(mesh, i, face): io.write(" UV(") - uv_list=[] - for uv in bl.faceGetUV(mesh, i, face, count): + for uv in reversed(bl.mesh.getFaceUV(mesh, i, face, count)): # reverse vertical value - uv_list.insert(0, uv) - # flip face - for uv in uv_list: io.write("%f %f " % (uv[0], 1.0-uv[1])) io.write(")") io.write("\r\n") io.write("\t}\r\n") # end of faces # 削除する - scene.objects.unlink(dumy) + bl.object.delete(dumy) io.write("}\r\n") # end of object def __execute(filename, scene, scale=10): + if not scene.objects.active: + bl.message('no active object !') + return + exporter=MqoExporter(scale) exporter.setup(scene) - exporter.write(filename, scene) + exporter.write(filename) if isBlender24(): # for 2.4 def execute_24(filename): - """ - export mqo. - """ - filename=filename.decode(bl.INTERNAL_ENCODING) - print("mqo exporter: %s" % filename) - - Blender.Window.WaitCursor(1) - t = Blender.sys.time() - - __execute(filename, Blender.Scene.GetCurrent()) - - print('finished in %.2f seconds' % (Blender.sys.time()-t) ) - Blender.Redraw() - Blender.Window.WaitCursor(0) + scene=Blender.Scene.GetCurrent() + bl.initialize('mqo_export', scene) + __execute( + filename.decode(bl.INTERNAL_ENCODING), + scene) + bl.finalize() # execute Blender.Window.FileSelector( @@ -277,8 +265,10 @@ if isBlender24(): else: # for 2.5 - def execute_25(*args): - __execute(*args) + def execute_25(path, scene, scale): + bl.initialize('mqo_export', scene) + __execute(path, scene, scale) + bl.finalize() # operator class EXPORT_OT_mqo(bpy.types.Operator): @@ -306,7 +296,7 @@ else: name="Scale", description="Scale the MQO by this value", min=0.0001, max=1000000.0, - soft_min=0.001, soft_max=100.0, default=100.0) + soft_min=0.001, soft_max=100.0, default=10.0) check_existing = BoolProperty( name="Check Existing", diff --git a/swig/blender/mqo_import.py b/swig/blender/mqo_import.py index b297a90..1124a41 100644 --- a/swig/blender/mqo_import.py +++ b/swig/blender/mqo_import.py @@ -22,12 +22,9 @@ This script imports a mqo into Blender for editing. 0.6 20100505: C extension. 0.7 20100606: integrate 2.4 and 2.5. 0.8 20100619: fix multibyte object name. +0.9 20100626: refactoring. ''' - -############################################################################### -# import -############################################################################### import os import sys @@ -45,6 +42,18 @@ if isBlender24(): # wrapper import bl24 as bl + + def createMqoMaterial(m): + material = Blender.Material.New( + m.getName().encode(bl.INTERNAL_ENCODING)) + material.mode |= Blender.Material.Modes.SHADELESS + material.rgbCol = [m.color.r, m.color.g, m.color.b] + material.alpha = m.color.a + material.amb = m.ambient + material.spec = m.specular + material.hard = int(255 * m.power) + return material + else: # for 2.5 import bpy @@ -53,6 +62,13 @@ else: # wrapper import bl25 as bl + def createMqoMaterial(m): + material = bpy.data.materials.new(m.getName()) + material.diffuse_color=[m.color.r, m.color.g, m.color.b] + material.alpha=m.color.a + material.diffuse_intensity=m.diffuse + return material + def has_mikoto(mqo): #for o in mqo.objects: @@ -65,7 +81,7 @@ def has_mikoto(mqo): return False -def __createMaterials(scene, mqo, directory): +def __createMaterials(mqo, directory): """ create blender materials and renturn material list. """ @@ -75,7 +91,7 @@ def __createMaterials(scene, mqo, directory): if len(mqo.materials)>0: for material_index, m in enumerate(mqo.materials): # material - material=bl.createMqoMaterial(m) + material=createMqoMaterial(m) materials.append(material) # texture texture_name=m.getTexture() @@ -93,20 +109,20 @@ def __createMaterials(scene, mqo, directory): # texture if os.path.exists(path): print("create texture:", path) - texture, image=bl.createTexture(path) + texture, image=bl.texture.create(path) textureMap[texture_name]=texture imageMap[material_index]=image else: print("%s not exits" % path) continue - bl.materialAddTexture(material, texture) + bl.material.addTexture(material, texture) else: # default material pass return materials, imageMap -def __createObjects(scene, mqo, root, materials, imageMap, scale): +def __createObjects(mqo, root, materials, imageMap, scale): """ create blender mesh objects. """ @@ -114,7 +130,7 @@ def __createObjects(scene, mqo, root, materials, imageMap, scale): stack=[root] objects=[] for o in mqo.objects: - mesh, mesh_object=bl.createMesh(scene, o.getName()) + mesh, mesh_object=bl.mesh.create(o.getName()) # add hierarchy stack_depth=len(stack)-1 @@ -122,15 +138,15 @@ def __createObjects(scene, mqo, root, materials, imageMap, scale): if o.depth