[Bf-extensions-cvs] SVN commit: /data/svn/bf-extensions [2086] trunk/py/scripts/addons/ io_mesh_raw: code cleanup and minor re-arrangements to raw import/export.

Campbell Barton ideasman42 at gmail.com
Sun Jul 3 06:00:03 CEST 2011


Revision: 2086
          http://projects.blender.org/scm/viewvc.php?view=rev&root=bf-extensions&revision=2086
Author:   campbellbarton
Date:     2011-07-03 04:00:02 +0000 (Sun, 03 Jul 2011)
Log Message:
-----------
code cleanup and minor re-arrangements to raw import/export.

Modified Paths:
--------------
    trunk/py/scripts/addons/io_mesh_raw/__init__.py
    trunk/py/scripts/addons/io_mesh_raw/export_raw.py
    trunk/py/scripts/addons/io_mesh_raw/import_raw.py

Modified: trunk/py/scripts/addons/io_mesh_raw/__init__.py
===================================================================
--- trunk/py/scripts/addons/io_mesh_raw/__init__.py	2011-07-03 03:12:09 UTC (rev 2085)
+++ trunk/py/scripts/addons/io_mesh_raw/__init__.py	2011-07-03 04:00:02 UTC (rev 2086)
@@ -16,6 +16,9 @@
 #
 # ##### END GPL LICENSE BLOCK #####
 
+# <pep8 compliant>
+
+
 bl_info = {
     "name": "Raw mesh format (.raw)",
     "author": "Anthony D,Agostino (Scorpius), Aurel Wildfellner",
@@ -33,23 +36,69 @@
 
 if "bpy" in locals():
     import imp
-    imp.reload(import_raw)
-    imp.reload(export_raw)
+    if "import_raw" in locals():
+        imp.reload(import_raw)
+    if "export_raw" in locals():
+        imp.reload(export_raw)
 else:
-    from . import import_raw
-    from . import export_raw
+    import bpy
 
+from bpy.props import StringProperty, BoolProperty
 
-import bpy
 
+class RawImporter(bpy.types.Operator):
+    '''Load Raw triangle mesh data'''
+    bl_idname = "import_mesh.raw"
+    bl_label = "Import RAW"
+
+    filepath = StringProperty(name="File Path", description="Filepath used for importing the RAW file", maxlen=1024, default="", subtype='FILE_PATH')
+    filter_glob = StringProperty(default="*.raw", options={'HIDDEN'})
+
+    def execute(self, context):
+        from . import import_raw
+        import_raw.read(self.filepath)
+        return {'FINISHED'}
+
+    def invoke(self, context, event):
+        wm = context.window_manager
+        wm.fileselect_add(self)
+        return {'RUNNING_MODAL'}
+
+
+class RawExporter(bpy.types.Operator):
+    '''Save Raw triangle mesh data'''
+    bl_idname = "export_mesh.raw"
+    bl_label = "Export RAW"
+
+    filepath = StringProperty(name="File Path", description="Filepath used for exporting the RAW file", maxlen=1024, default= "", subtype='FILE_PATH')
+    check_existing = BoolProperty(name="Check Existing", description="Check and warn on overwriting existing files", default=True, options={'HIDDEN'})
+
+    apply_modifiers = BoolProperty(name="Apply Modifiers", description="Use transformed mesh data from each object", default=True)
+    triangulate = BoolProperty(name="Triangulate", description="Triangulate quads.", default=True)
+
+    def execute(self, context):
+        from . import export_raw
+        export_raw.write(self.filepath,
+                         self.apply_modifiers,
+                         self.triangulate,
+                         )
+
+        return {'FINISHED'}
+
+    def invoke(self, context, event):
+        if not self.filepath:
+            self.filepath = bpy.path.ensure_ext(bpy.data.filepath, ".raw")
+        wm = context.window_manager
+        wm.fileselect_add(self)
+        return {'RUNNING_MODAL'}
+
+
 def menu_import(self, context):
-    self.layout.operator(import_raw.RawImporter.bl_idname, text="Raw Faces (.raw)").filepath = "*.raw"
+    self.layout.operator(RawImporter.bl_idname, text="Raw Faces (.raw)")
 
 
 def menu_export(self, context):
-    import os
-    default_path = os.path.splitext(bpy.data.filepath)[0] + ".raw"
-    self.layout.operator(export_raw.RawExporter.bl_idname, text="Raw Faces (.raw)").filepath = default_path
+    self.layout.operator(RawExporter.bl_idname, text="Raw Faces (.raw)")
 
 
 def register():

Modified: trunk/py/scripts/addons/io_mesh_raw/export_raw.py
===================================================================
--- trunk/py/scripts/addons/io_mesh_raw/export_raw.py	2011-07-03 03:12:09 UTC (rev 2085)
+++ trunk/py/scripts/addons/io_mesh_raw/export_raw.py	2011-07-03 04:00:02 UTC (rev 2086)
@@ -16,6 +16,8 @@
 #
 # ##### END GPL LICENSE BLOCK #####
 
+# <pep8 compliant>
+
 __author__ = ["Aurel Wildfellner"]
 __version__ = '0.2'
 __bpydoc__ = """\
@@ -38,9 +40,9 @@
 
 def faceToTriangles(face):
     triangles = []
-    if (len(face) == 4): #quad
-        triangles.append( [ face[0], face[1], face[2] ] )
-        triangles.append( [ face[2], face[3], face[0] ] )
+    if (len(face) == 4):
+        triangles.append([face[0], face[1], face[2]])
+        triangles.append([face[2], face[3], face[0]])
     else:
         triangles.append(face)
 
@@ -50,28 +52,35 @@
 def faceValues(face, mesh, matrix):
     fv = []
     for verti in face.vertices:
-        fv.append(mesh.vertices[verti].co * matrix)
+        fv.append((mesh.vertices[verti].co * matrix)[:])
     return fv
 
 
 def faceToLine(face):
-    line = ""
-    for v in face:
-        line += str(v[0]) + " " + str(v[1]) + " " + str(v[2]) + " "
-    return line[:-1] + "\n"
+    return " ".join([("%.6f %.6f %.6f" % v) for v in face] + ["\n"])
 
 
-def export_raw(filepath, applyMods, triangulate):
+def write(filepath,
+          applyMods=True,
+          triangulate=True,
+          ):
+
+    scene = bpy.context.scene
+
     faces = []
     for obj in bpy.context.selected_objects:
-        if obj.type == 'MESH':
-            matrix = obj.matrix_world
+        if applyMods or obj.type != 'MESH':
+            try:
+                me = obj.to_mesh(scene, True, "PREVIEW")
+            except:
+                me = None
+            is_tmp_mesh = True
+        else:
+            me = obj.data
+            is_tmp_mesh = False
 
-            if (applyMods):
-                me = obj.to_mesh(bpy.context.scene, True, "PREVIEW")
-            else:
-                me = obj.data
-
+        if me is not None:
+            matrix = obj.matrix_world.copy()
             for face in me.faces:
                 fv = faceValues(face, me, matrix)
                 if triangulate:
@@ -79,34 +88,11 @@
                 else:
                     faces.append(fv)
 
+            if is_tmp_mesh:
+                bpy.data.meshes.remove(me)
+
     # write the faces to a file
     file = open(filepath, "w")
     for face in faces:
         file.write(faceToLine(face))
     file.close()
-
-
-from bpy.props import *
-
-
-class RawExporter(bpy.types.Operator):
-    '''Save Raw triangle mesh data'''
-    bl_idname = "export_mesh.raw"
-    bl_label = "Export RAW"
-
-    filepath = StringProperty(name="File Path", description="Filepath used for exporting the RAW file", maxlen= 1024, default= "", subtype='FILE_PATH')
-    check_existing = BoolProperty(name="Check Existing", description="Check and warn on overwriting existing files", default=True, options={'HIDDEN'})
-
-    apply_modifiers = BoolProperty(name="Apply Modifiers", description="Use transformed mesh data from each object", default=True)
-    triangulate = BoolProperty(name="Triangulate", description="Triangulate quads.", default=True)
-
-    def execute(self, context):
-        export_raw(self.filepath, self.apply_modifiers, self.triangulate)
-        return {'FINISHED'}
-
-    def invoke(self, context, event):
-        wm = context.window_manager
-        wm.fileselect_add(self)
-        return {'RUNNING_MODAL'}
-
-# package manages registering

Modified: trunk/py/scripts/addons/io_mesh_raw/import_raw.py
===================================================================
--- trunk/py/scripts/addons/io_mesh_raw/import_raw.py	2011-07-03 03:12:09 UTC (rev 2085)
+++ trunk/py/scripts/addons/io_mesh_raw/import_raw.py	2011-07-03 04:00:02 UTC (rev 2086)
@@ -16,6 +16,8 @@
 #
 # ##### END GPL LICENSE BLOCK #####
 
+# <pep8 compliant>
+
 __author__ = ["Anthony D'Agostino (Scorpius)", "Aurel Wildfellner"]
 __version__ = '0.2'
 __bpydoc__ = """\
@@ -39,11 +41,10 @@
 """
 
 
-
 import bpy
 
 # move those to a utility modul
-from bpy_extras.io_utils import unpack_face_list, unpack_list # TODO, make generic
+from bpy_extras.io_utils import unpack_face_list, unpack_list
 
 
 def readMesh(filename, objName):
@@ -51,18 +52,14 @@
 
     def line_to_face(line):
         # Each triplet is an xyz float
-        line_split = []
+        line_split = line.split()
         try:
-            line_split = list(map(float, line.split()))
+            line_split_float = map(float, line_split)
         except:
             return None
 
-        if len(line_split) == 9: # Tri
-            f1, f2, f3, f4, f5, f6, f7, f8, f9 = line_split
-            return [(f1, f2, f3), (f4, f5, f6), (f7, f8, f9)]
-        elif len(line_split) == 12: # Quad
-            f1, f2, f3, f4, f5, f6, f7, f8, f9, A, B, C = line_split
-            return [(f1, f2, f3), (f4, f5, f6), (f7, f8, f9), (A, B, C)]
+        if len(line_split) in {9, 12}:
+            return zip(*[iter(line_split_float)] * 3)  # group in 3's
         else:
             return None
 
@@ -80,7 +77,7 @@
     coords = {}
     index_tot = 0
     faces_indices = []
-    
+
     for f in faces:
         fi = []
         for i, v in enumerate(f):
@@ -118,28 +115,8 @@
         scn.objects.active = nobj
 
 
-from bpy.props import *
-
-class RawImporter(bpy.types.Operator):
-    '''Load Raw triangle mesh data'''
-    bl_idname = "import_mesh.raw"
-    bl_label = "Import RAW"
-
-    filepath = StringProperty(name="File Path", description="Filepath used for importing the RAW file", maxlen=1024, default="", subtype='FILE_PATH')
-
-    def execute(self, context):
-
-        #convert the filename to an object name
-        objName = bpy.path.display_name(self.filepath.split("\\")[-1].split("/")[-1])
-
-        mesh = readMesh(self.filepath, objName)
-        addMeshObj(mesh, objName)
-
-        return {'FINISHED'}
-
-    def invoke(self, context, event):
-        wm = context.window_manager
-        wm.fileselect_add(self)
-        return {'RUNNING_MODAL'}
-
-# package manages registering
+def read(filepath):
+    #convert the filename to an object name
+    objName = bpy.path.display_name_from_filepath(filepath)
+    mesh = readMesh(filepath, objName)
+    addMeshObj(mesh, objName)



More information about the Bf-extensions-cvs mailing list