Skip to content
Snippets Groups Projects
export_ply.py 6.44 KiB
Newer Older
  • Learn to ignore specific revisions
  • # ##### BEGIN GPL LICENSE BLOCK #####
    #
    #  This program is free software; you can redistribute it and/or
    #  modify it under the terms of the GNU General Public License
    #  as published by the Free Software Foundation; either version 2
    #  of the License, or (at your option) any later version.
    #
    #  This program is distributed in the hope that it will be useful,
    #  but WITHOUT ANY WARRANTY; without even the implied warranty of
    #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    #  GNU General Public License for more details.
    #
    #  You should have received a copy of the GNU General Public License
    #  along with this program; if not, write to the Free Software Foundation,
    #  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
    #
    # ##### END GPL LICENSE BLOCK #####
    
    
    # <pep8-80 compliant>
    
    
    """
    This script exports Stanford PLY files from Blender. It supports normals,
    
    colors, and texture coordinates per face or per vertex.
    
    Only one mesh can be exported at a time.
    """
    
    import bpy
    import os
    
    
    
    Campbell Barton's avatar
    Campbell Barton committed
    def save_mesh(
            filepath,
            mesh,
            use_normals=True,
            use_uv_coords=True,
            use_colors=True,
    ):
    
    
        def rvec3d(v):
            return round(v[0], 6), round(v[1], 6), round(v[2], 6)
    
        def rvec2d(v):
            return round(v[0], 6), round(v[1], 6)
    
    
        file = open(filepath, "w", encoding="utf8", newline="\n")
    
        fw = file.write
    
        has_uv = bool(mesh.uv_layers)
        has_vcol = bool(mesh.vertex_colors)
    
        if not has_uv:
    
        if not has_vcol:
    
            use_colors = False
    
        if not use_uv_coords:
    
            has_uv = False
    
            has_vcol = False
    
        if has_uv:
    
            active_uv_layer = mesh.uv_layers.active
    
            if not active_uv_layer:
                use_uv_coords = False
    
                has_uv = False
    
            else:
                active_uv_layer = active_uv_layer.data
    
    
        if has_vcol:
    
            active_col_layer = mesh.vertex_colors.active
    
            if not active_col_layer:
                use_colors = False
    
                has_vcol = False
    
            else:
                active_col_layer = active_col_layer.data
    
    
        # in case
    
        color = uvcoord = uvcoord_key = normal = normal_key = None
    
        mesh_verts = mesh.vertices  # save a lookup
        ply_verts = []  # list of dictionaries
        # vdict = {} # (index, normal, uv) -> new index
        vdict = [{} for i in range(len(mesh_verts))]
    
        ply_faces = [[] for f in range(len(mesh.polygons))]
    
        for i, f in enumerate(mesh.polygons):
    
                normal = f.normal[:]
    
            if has_uv:
    
                uv = [
                    active_uv_layer[l].uv[:]
                    for l in range(f.loop_start, f.loop_start + f.loop_total)
                ]
    
            if has_vcol:
    
                col = [
                    active_col_layer[l].color[:]
                    for l in range(f.loop_start, f.loop_start + f.loop_total)
                ]
    
            for j, vidx in enumerate(f.vertices):
    
                    normal = v.normal[:]
    
                if has_uv:
    
                    uvcoord = uv[j][0], uv[j][1]
    
                if has_vcol:
    
    Campbell Barton's avatar
    Campbell Barton committed
                    color = (
                        int(color[0] * 255.0),
                        int(color[1] * 255.0),
                        int(color[2] * 255.0),
                        int(color[3] * 255.0),
                    )
    
                key = normal_key, uvcoord_key, color
    
                vdict_local = vdict[vidx]
                pf_vidx = vdict_local.get(key)  # Will be None initially
    
                if pf_vidx is None:  # same as vdict_local.has_key(key)
                    pf_vidx = vdict_local[key] = vert_count
                    ply_verts.append((vidx, normal, uvcoord, color))
                    vert_count += 1
    
                pf.append(pf_vidx)
    
    
        fw("ply\n")
        fw("format ascii 1.0\n")
        fw("comment Created by Blender %s - "
           "www.blender.org, source file: %r\n" %
           (bpy.app.version_string, os.path.basename(bpy.data.filepath)))
    
        fw("element vertex %d\n" % len(ply_verts))
    
        fw("property float x\n"
           "property float y\n"
           "property float z\n")
    
            fw("property float nx\n"
               "property float ny\n"
               "property float nz\n")
    
            fw("property float s\n"
               "property float t\n")
    
            fw("property uchar red\n"
               "property uchar green\n"
    
               "property uchar blue\n"
               "property uchar alpha\n")
    
        fw("element face %d\n" % len(mesh.polygons))
    
        fw("property list uchar uint vertex_indices\n")
        fw("end_header\n")
    
            fw("%.6f %.6f %.6f" % mesh_verts[v[0]].co[:])  # co
    
                fw(" %.6f %.6f %.6f" % v[1])  # no
    
                fw(" %.6f %.6f" % v[2])  # uv
    
                fw(" %u %u %u %u" % v[3])  # col
    
            fw("\n")
    
            # fw(f"{len(pf)} {' '.join(str(x) for x in pf)}\n")
            fw("%d" % len(pf))
            for v in pf:
                fw(" %d" % v)
            fw("\n")
    
    
        file.close()
        print("writing %r done" % filepath)
    
    
    Campbell Barton's avatar
    Campbell Barton committed
    def save(
            operator,
            context,
            filepath="",
            use_mesh_modifiers=True,
            use_normals=True,
            use_uv_coords=True,
            use_colors=True,
            global_matrix=None
    ):
    
        obj = context.active_object
    
    
        if global_matrix is None:
            from mathutils import Matrix
            global_matrix = Matrix()
    
        if bpy.ops.object.mode_set.poll():
            bpy.ops.object.mode_set(mode='OBJECT')
    
        mesh_owner_object = None
    
        if use_mesh_modifiers and obj.modifiers:
    
            depsgraph = context.evaluated_depsgraph_get()
    
            mesh_owner_object = obj.evaluated_get(depsgraph)
            mesh = mesh_owner_object.to_mesh()
    
            mesh_owner_object = obj
            mesh = mesh_owner_object.to_mesh()
    
        if not mesh:
            raise Exception("Error, could not get mesh data from active object")
    
        mesh.transform(global_matrix @ obj.matrix_world)
    
        if use_normals:
            mesh.calc_normals()
    
    
        ret = save_mesh(filepath, mesh,
                        use_normals=use_normals,
                        use_uv_coords=use_uv_coords,
                        use_colors=use_colors,
                        )
    
    
        mesh_owner_object.to_mesh_clear()