OSDN Git Service

refactoring import_scene_mqo.py
authorousttrue <ousttrue@gmail.com>
Sat, 8 May 2010 15:48:37 +0000 (00:48 +0900)
committerousttrue <ousttrue@gmail.com>
Sat, 8 May 2010 15:48:37 +0000 (00:48 +0900)
blender25/import_scene_mqo.py

index 445d862..4ec63bc 100644 (file)
@@ -9,227 +9,191 @@ mqo Importer
 This script imports a mqo into Blender for editing.
 '''
 
+import bpy
+from bpy.props import *
+import Mathutils
+import sys
+import os
 from meshio import mqo
-try:
-    import bpy
-    import Mathutils
-except:
-    pass
 
 
 SCALING=0.01
 
 
-if 'bpy' in globals(): 
-    ####################
-    # blender2.5
-    ####################
-    import sys
-    import os
-    from bpy.props import *
-
-    fs_encoding=sys.getfilesystemencoding()
-
-    def create_materials(mqo, scene, directory):
-        materials = []
-        textureMap={}
-        imageMap={}
-        if len(mqo.materials)>0:
-            for m in mqo.materials:
-                material = bpy.data.materials.new(m.getName())
-                materials.append(material)
-                # mqo material
-                material.diffuse_color=[m.color.r, m.color.g, m.color.b]
-                material.alpha=m.color.a
-                material.diffuse_intensity=m.diffuse
-                texture_name=m.getTexture()
-                if texture_name!='':
-                    if texture_name in textureMap:
-                        texture=textureMap[texture_name]
-                    else:
-                        texture=bpy.data.textures.new(texture_name)
-                        textureMap[m.texture]=texture
-                        texture.type='IMAGE'
-                        texture=texture.recast_type()
-                        texturePath="%s/%s" % (directory, texture_name)
-                        image=bpy.data.add_image(texturePath)
-                        imageMap[m.texture]=image
-                        texture.image=image
-                        texture.mipmap = True
-                        texture.interpolation = True
-                        texture.use_alpha = True
-                    material.add_texture(texture, "UV", ("COLOR", "ALPHA"))
-                    # temporary
-                    material.emit=1.0
-        else:
-            material = bpy.data.materials.new('Default')
+def create_materials(mqo, scene, directory):
+    materials = []
+    textureMap={}
+    imageMap={}
+    if len(mqo.materials)>0:
+        for m in mqo.materials:
+            material = bpy.data.materials.new(m.getName())
             materials.append(material)
-        return materials, imageMap
-
-    def create_objects(mqo, scene, parent, materials, imageMap):
-        for o in mqo.objects:
-
-            # create mesh
-            mesh=bpy.data.meshes.new("Mesh")
-            meshObject= bpy.data.objects.new(o.name, mesh)
-            scene.objects.link(meshObject)
-            meshObject.parent=parent
-
-            mesh.add_geometry(len(o.vertices), 0, len(o.faces))
-
-            # add vertex
-            unpackedVertices=[]
-            for v in o.vertices:
-                # convert right-handed y-up to right-handed z-up
-                unpackedVertices.extend(
-                        (SCALING*v.x, SCALING*-v.z, SCALING*v.y))
-            mesh.verts.foreach_set("co", unpackedVertices)
-
-            # add face
-            unpackedFaces = []
-            usedMaterial=set()
-            for f in o.faces:
-                face = []
-                for i in range(f.index_count):
-                    face.append(f.getIndex(i))
-
-                if len(face) != 3 and len(face) != 4:
-                    raise RuntimeError(
-                            "{0} vertices in face.".format(len(face)))
-
-                # rotate indices if the 4th is 0
-                if len(face) == 4 and face[3] == 0:
-                    face = [face[3], face[0], face[1], face[2]]
-
-                if len(face) == 3:
-                    face.append(0)
-
-                unpackedFaces.extend(face)
-                usedMaterial.add(f.material_index)
-            mesh.faces.foreach_set("verts_raw", unpackedFaces)
-
-            # add material
-            meshMaterialMap={}
-            materialIndex=0
-            for i in usedMaterial:
-                mesh.add_material(materials[i])
-                meshMaterialMap[i]=materialIndex
-                materialIndex+=1
-
-            # each face
-            mesh.add_uv_texture()
-            for mqo_face, blender_face, uv_face in zip(
-                    o.faces, mesh.faces, mesh.uv_textures[0].data):
-                blender_face.material_index=meshMaterialMap[mqo_face.material_index]
-                if mqo_face.index_count>=3:
-                    uv_face.uv1=[mqo_face.getUV(0).x, 1.0-mqo_face.getUV(0).y]
-                    uv_face.uv2=[mqo_face.getUV(1).x, 1.0-mqo_face.getUV(1).y]
-                    uv_face.uv3=[mqo_face.getUV(2).x, 1.0-mqo_face.getUV(2).y]
-                    if mqo_face.index_count==4:
-                        uv_face.uv4=[
-                                mqo_face.getUV(3).x, 1.0-mqo_face.getUV(3).y]
-                if materials[mqo_face.material_index] in imageMap:
-                    uv_face.image=imageMap[mqo_face.tex]
-                    uv_face.tex=True
-
-            mesh.update()
-
-    def load(filename, context):
-        io=mqo.IO()
-        if not io.read(filename):
-            return
-
-        scene=context.scene
-
-        # create material
-        materials, imageMap=create_materials(
-                io, scene, os.path.dirname(filename))
-
-        # create group
-        empty=bpy.data.objects.new(os.path.basename(filename), None)
-        scene.objects.link(empty)
+            # mqo material
+            material.diffuse_color=[m.color.r, m.color.g, m.color.b]
+            material.alpha=m.color.a
+            material.diffuse_intensity=m.diffuse
+            texture_name=m.getTexture()
+            if texture_name!='':
+                if texture_name in textureMap:
+                    texture=textureMap[texture_name]
+                else:
+                    texture=bpy.data.textures.new(texture_name)
+                    textureMap[m.texture]=texture
+                    texture.type='IMAGE'
+                    texture=texture.recast_type()
+                    texturePath="%s/%s" % (directory, texture_name)
+                    image=bpy.data.add_image(texturePath)
+                    imageMap[m.texture]=image
+                    texture.image=image
+                    texture.mipmap = True
+                    texture.interpolation = True
+                    texture.use_alpha = True
+                material.add_texture(texture, "UV", ("COLOR", "ALPHA"))
+                # temporary
+                material.emit=1.0
+    else:
+        material = bpy.data.materials.new('Default')
+        materials.append(material)
+    return materials, imageMap
+
+def create_objects(mqo, scene, parent, materials, imageMap):
+    for o in mqo.objects:
 
         # create mesh
-        create_objects(io, scene, empty, materials, imageMap)
-     
-
-    class IMPORT_OT_mqo(bpy.types.Operator):
-        '''Import from Metasequoia file format (.mqo)'''
-        bl_idname = "import_scene.mqo"
-        bl_label = 'Import MQO'
-
-        # List of operator properties, the attributes will be assigned
-        # to the class instance from the operator settings before calling.
-
-        path = StringProperty(
-                name="File Path", 
-                description="File path used for importing the MQO file", 
-                maxlen= 1024, default= "")
-        filename = StringProperty(
-                name="File Name", 
-                description="Name of the file.")
-        directory = StringProperty(
-                name="Directory", 
-                description="Directory of the file.")
-
-        def execute(self, context):
-            load(self.properties.path, context)
-            return {'FINISHED'}
-
-        def invoke(self, context, event):
-            wm = context.manager
-            wm.add_fileselect(self)
-            return {'RUNNING_MODAL'}
-
-
-    menu_func = lambda self, context: self.layout.operator(
-            IMPORT_OT_mqo.bl_idname, text="Metasequoia (.mqo)")
-
-
-    def register():
-        bpy.types.register(IMPORT_OT_mqo)
-        bpy.types.INFO_MT_file_import.append(menu_func)
-
-    def unregister():
-        bpy.types.unregister(IMPORT_OT_mqo)
-        bpy.types.INFO_MT_file_import.remove(menu_func)
-
-
-    if __name__=="__main__":
-        register()
-
-else:
-    ####################
-    # for test
-    ####################
-    def load(path):
-        io=open(sys.argv[1], encoding='cp932')
-        if not io:
-            return None
-
-        mqo=MQO()
-        if not mqo.parse(io):
-            return None
-
-        return mqo
-
-
-    if __name__=="__main__":
-        import sys
-        if len(sys.argv)<2:
-            print("usage: %s {mqo file}" % sys.argv[0])
-            sys.exit()
-
-        import time        
-        t=time.time()
-        mqo=load(sys.argv[1])
-        if not mqo:
-            sys.exit()
-        print("%.2f seconds" % (time.time()-t))
-
-        print(mqo)
-        for m in mqo.materials:
-            print(m)
-        for o in mqo.objects:
-            print(o)
+        mesh=bpy.data.meshes.new("Mesh")
+        meshObject= bpy.data.objects.new(o.name, mesh)
+        scene.objects.link(meshObject)
+        meshObject.parent=parent
+
+        mesh.add_geometry(len(o.vertices), 0, len(o.faces))
+
+        # add vertex
+        unpackedVertices=[]
+        for v in o.vertices:
+            # convert right-handed y-up to right-handed z-up
+            unpackedVertices.extend(
+                    (SCALING*v.x, SCALING*-v.z, SCALING*v.y))
+        mesh.verts.foreach_set("co", unpackedVertices)
+
+        # add face
+        unpackedFaces = []
+        usedMaterial=set()
+        for f in o.faces:
+            face = []
+            for i in range(f.index_count):
+                face.append(f.getIndex(i))
+
+            if len(face) != 3 and len(face) != 4:
+                raise RuntimeError(
+                        "{0} vertices in face.".format(len(face)))
+
+            # rotate indices if the 4th is 0
+            if len(face) == 4 and face[3] == 0:
+                face = [face[3], face[0], face[1], face[2]]
+
+            if len(face) == 3:
+                face.append(0)
+
+            unpackedFaces.extend(face)
+            usedMaterial.add(f.material_index)
+        mesh.faces.foreach_set("verts_raw", unpackedFaces)
+
+        # add material
+        meshMaterialMap={}
+        materialIndex=0
+        for i in usedMaterial:
+            mesh.add_material(materials[i])
+            meshMaterialMap[i]=materialIndex
+            materialIndex+=1
+
+        # each face
+        mesh.add_uv_texture()
+        for mqo_face, blender_face, uv_face in zip(
+                o.faces, mesh.faces, mesh.uv_textures[0].data):
+            blender_face.material_index=meshMaterialMap[mqo_face.material_index]
+            if mqo_face.index_count>=3:
+                uv_face.uv1=[mqo_face.getUV(0).x, 1.0-mqo_face.getUV(0).y]
+                uv_face.uv2=[mqo_face.getUV(1).x, 1.0-mqo_face.getUV(1).y]
+                uv_face.uv3=[mqo_face.getUV(2).x, 1.0-mqo_face.getUV(2).y]
+                if mqo_face.index_count==4:
+                    uv_face.uv4=[
+                            mqo_face.getUV(3).x, 1.0-mqo_face.getUV(3).y]
+            if materials[mqo_face.material_index] in imageMap:
+                uv_face.image=imageMap[mqo_face.tex]
+                uv_face.tex=True
+
+        mesh.update()
+
+def load(filename, context):
+    """
+    load mqo file to context.
+    """
+    io=mqo.IO()
+    if not io.read(filename):
+        return
+
+    scene=context.scene
+
+    # create material
+    materials, imageMap=create_materials(
+            io, scene, os.path.dirname(filename))
+
+    # create group
+    empty=bpy.data.objects.new(os.path.basename(filename), None)
+    scene.objects.link(empty)
+
+    # create mesh
+    create_objects(io, scene, empty, materials, imageMap)
+
+###############################################################################
+# import operator
+###############################################################################
+class IMPORT_OT_mqo(bpy.types.Operator):
+    '''Import from Metasequoia file format (.mqo)'''
+    bl_idname = "import_scene.mqo"
+    bl_label = 'Import MQO'
+
+    # List of operator properties, the attributes will be assigned
+    # to the class instance from the operator settings before calling.
+
+    path = StringProperty(
+            name="File Path", 
+            description="File path used for importing the MQO file", 
+            maxlen= 1024, default= "")
+    filename = StringProperty(
+            name="File Name", 
+            description="Name of the file.")
+    directory = StringProperty(
+            name="Directory", 
+            description="Directory of the file.")
+
+    def execute(self, context):
+        load(self.properties.path, context)
+        return {'FINISHED'}
+
+    def invoke(self, context, event):
+        wm = context.manager
+        wm.add_fileselect(self)
+        return {'RUNNING_MODAL'}
+
+
+###############################################################################
+# register menu
+###############################################################################
+menu_func = lambda self, context: self.layout.operator(
+        IMPORT_OT_mqo.bl_idname, text="Metasequoia (.mqo)")
+
+
+def register():
+    bpy.types.register(IMPORT_OT_mqo)
+    bpy.types.INFO_MT_file_import.append(menu_func)
+
+def unregister():
+    bpy.types.unregister(IMPORT_OT_mqo)
+    bpy.types.INFO_MT_file_import.remove(menu_func)
+
+
+if __name__=="__main__":
+    register()