PLY: Export alpha channel for vertex colors
[blender-addons.git] / io_mesh_ply / export_ply.py
blob942fbce12596d0ed66997241dd6b0920efb37ee0
1 # ##### BEGIN GPL LICENSE BLOCK #####
3 # This program is free software; you can redistribute it and/or
4 # modify it under the terms of the GNU General Public License
5 # as published by the Free Software Foundation; either version 2
6 # of the License, or (at your option) any later version.
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software Foundation,
15 # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 # ##### END GPL LICENSE BLOCK #####
19 # <pep8-80 compliant>
21 """
22 This script exports Stanford PLY files from Blender. It supports normals,
23 colors, and texture coordinates per face or per vertex.
24 Only one mesh can be exported at a time.
25 """
27 import bpy
28 import os
31 def save_mesh(filepath,
32 mesh,
33 use_normals=True,
34 use_uv_coords=True,
35 use_colors=True,
38 def rvec3d(v):
39 return round(v[0], 6), round(v[1], 6), round(v[2], 6)
41 def rvec2d(v):
42 return round(v[0], 6), round(v[1], 6)
44 file = open(filepath, "w", encoding="utf8", newline="\n")
45 fw = file.write
47 # Be sure tessellated loop trianlges are available!
48 if not mesh.loop_triangles and mesh.polygons:
49 mesh.calc_loop_triangles()
51 has_uv = bool(mesh.uv_layers)
52 has_vcol = bool(mesh.vertex_colors)
54 if not has_uv:
55 use_uv_coords = False
56 if not has_vcol:
57 use_colors = False
59 if not use_uv_coords:
60 has_uv = False
61 if not use_colors:
62 has_vcol = False
64 if has_uv:
65 active_uv_layer = mesh.uv_layers.active
66 if not active_uv_layer:
67 use_uv_coords = False
68 has_uv = False
69 else:
70 active_uv_layer = active_uv_layer.data
72 if has_vcol:
73 active_col_layer = mesh.vertex_colors.active
74 if not active_col_layer:
75 use_colors = False
76 has_vcol = False
77 else:
78 active_col_layer = active_col_layer.data
80 # in case
81 color = uvcoord = uvcoord_key = normal = normal_key = None
83 mesh_verts = mesh.vertices # save a lookup
84 ply_verts = [] # list of dictionaries
85 # vdict = {} # (index, normal, uv) -> new index
86 vdict = [{} for i in range(len(mesh_verts))]
87 ply_faces = [[] for f in range(len(mesh.loop_triangles))]
88 vert_count = 0
89 for i, f in enumerate(mesh.loop_triangles):
91 smooth = not use_normals or f.use_smooth
92 if not smooth:
93 normal = f.normal[:]
94 normal_key = rvec3d(normal)
96 if has_uv:
97 uv = [active_uv_layer[l].uv[:] for l in f.loops]
98 if has_vcol:
99 col = [active_col_layer[l].color[:] for l in f.loops]
101 pf = ply_faces[i]
102 for j, vidx in enumerate(f.vertices):
103 v = mesh_verts[vidx]
105 if smooth:
106 normal = v.normal[:]
107 normal_key = rvec3d(normal)
109 if has_uv:
110 uvcoord = uv[j][0], uv[j][1]
111 uvcoord_key = rvec2d(uvcoord)
113 if has_vcol:
114 color = col[j]
115 color = (int(color[0] * 255.0),
116 int(color[1] * 255.0),
117 int(color[2] * 255.0),
118 int(color[3] * 255.0),
120 key = normal_key, uvcoord_key, color
122 vdict_local = vdict[vidx]
123 pf_vidx = vdict_local.get(key) # Will be None initially
125 if pf_vidx is None: # same as vdict_local.has_key(key)
126 pf_vidx = vdict_local[key] = vert_count
127 ply_verts.append((vidx, normal, uvcoord, color))
128 vert_count += 1
130 pf.append(pf_vidx)
132 fw("ply\n")
133 fw("format ascii 1.0\n")
134 fw("comment Created by Blender %s - "
135 "www.blender.org, source file: %r\n" %
136 (bpy.app.version_string, os.path.basename(bpy.data.filepath)))
138 fw("element vertex %d\n" % len(ply_verts))
140 fw("property float x\n"
141 "property float y\n"
142 "property float z\n")
144 if use_normals:
145 fw("property float nx\n"
146 "property float ny\n"
147 "property float nz\n")
148 if use_uv_coords:
149 fw("property float s\n"
150 "property float t\n")
151 if use_colors:
152 fw("property uchar red\n"
153 "property uchar green\n"
154 "property uchar blue\n"
155 "property uchar alpha\n")
157 fw("element face %d\n" % len(mesh.loop_triangles))
158 fw("property list uchar uint vertex_indices\n")
159 fw("end_header\n")
161 for i, v in enumerate(ply_verts):
162 fw("%.6f %.6f %.6f" % mesh_verts[v[0]].co[:]) # co
163 if use_normals:
164 fw(" %.6f %.6f %.6f" % v[1]) # no
165 if use_uv_coords:
166 fw(" %.6f %.6f" % v[2]) # uv
167 if use_colors:
168 fw(" %u %u %u %u" % v[3]) # col
169 fw("\n")
171 for pf in ply_faces:
172 if len(pf) == 3:
173 fw("3 %d %d %d\n" % tuple(pf))
174 else:
175 fw("4 %d %d %d %d\n" % tuple(pf))
177 file.close()
178 print("writing %r done" % filepath)
180 return {'FINISHED'}
183 def save(operator,
184 context,
185 filepath="",
186 use_mesh_modifiers=True,
187 use_normals=True,
188 use_uv_coords=True,
189 use_colors=True,
190 global_matrix=None
193 obj = context.active_object
195 if global_matrix is None:
196 from mathutils import Matrix
197 global_matrix = Matrix()
199 if bpy.ops.object.mode_set.poll():
200 bpy.ops.object.mode_set(mode='OBJECT')
202 if use_mesh_modifiers and obj.modifiers:
203 mesh = obj.to_mesh(context.depsgraph, True)
205 else:
206 mesh = obj.data.copy()
208 if not mesh:
209 raise Exception("Error, could not get mesh data from active object")
211 mesh.transform(global_matrix @ obj.matrix_world)
212 if use_normals:
213 mesh.calc_normals()
215 ret = save_mesh(filepath, mesh,
216 use_normals=use_normals,
217 use_uv_coords=use_uv_coords,
218 use_colors=use_colors,
221 bpy.data.meshes.remove(mesh)
223 return ret