3 __author__ = "Bruce Merry"
6 This script exports Stanford PLY files from Blender. It supports normals,
7 colours, and texture coordinates per face or per vertex.
8 Only one mesh can be exported at a time.
11 # Copyright (C) 2004, 2005: Bruce Merry, bmerry@cs.uct.ac.za
13 # This program is free software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; either version 2
16 # of the License, or (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software Foundation,
25 # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 # Vector rounding se we can use as keys
28 # Updated on Aug 11, 2008 by Campbell Barton
29 # - added 'comment' prefix to comments - Needed to comply with the PLY spec.
31 # Updated on Jan 1, 2007 by Gabe Ghearing
32 # - fixed normals so they are correctly smooth/flat
33 # - fixed crash when the model doesn't have uv coords or vertex colors
34 # - fixed crash when the model has vertex colors but doesn't have uv coords
35 # - changed float32 to float and uint8 to uchar for compatibility
36 # Errata/Notes as of Jan 1, 2007
37 # - script exports texture coords if they exist even if TexFace isn't selected (not a big deal to me)
38 # - ST(R) should probably be renamed UV(T) like in most PLY files (importer needs to be updated to take either)
40 # Updated on Jan 3, 2007 by Gabe Ghearing
41 # - fixed "sticky" vertex UV exporting
42 # - added pupmenu to enable/disable exporting normals, uv coords, and colors
43 # Errata/Notes as of Jan 3, 2007
44 # - ST(R) coords should probably be renamed UV(T) like in most PLY files (importer needs to be updated to take either)
45 # - edges should be exported since PLY files support them
46 # - code is getting spaghettish, it should be refactored...
50 def rvec3d(v): return round(v[0], 6), round(v[1], 6), round(v[2], 6)
51 def rvec2d(v): return round(v[0], 6), round(v[1], 6)
53 def write(filename, ob, EXPORT_APPLY_MODIFIERS= True, EXPORT_NORMALS= True, EXPORT_UV= True, EXPORT_COLORS= True):
55 if not filename.lower().endswith('.ply'):
59 raise Exception("Error, Select 1 active object")
62 file = open(filename, 'wb')
65 #EXPORT_EDGES = Draw.Create(0)
67 is_editmode = Blender.Window.EditMode()
69 Blender.Window.EditMode(0, '', 0)
74 #mesh = BPyMesh.getMeshFromObject(ob, None, EXPORT_APPLY_MODIFIERS, False, scn) # XXX
78 raise ("Error, could not get mesh data from active object")
81 # mesh.transform(ob.matrixWorld) # XXX
83 faceUV = len(mesh.uv_layers) > 0
84 vertexUV = len(mesh.sticky) > 0
85 vertexColors = len(mesh.vcol_layers) > 0
87 if (not faceUV) and (not vertexUV): EXPORT_UV = False
88 if not vertexColors: EXPORT_COLORS = False
90 if not EXPORT_UV: faceUV = vertexUV = False
91 if not EXPORT_COLORS: vertexColors = False
94 active_uv_layer = None
95 for lay in mesh.uv_layers:
97 active_uv_layer= lay.data
99 if not active_uv_layer:
104 active_col_layer = None
105 for lay in mesh.vcol_layers:
107 active_col_layer= lay.data
108 if not active_col_layer:
109 EXPORT_COLORS = False
113 color = uvcoord = uvcoord_key = normal = normal_key = None
115 mesh_verts = mesh.verts # save a lookup
116 ply_verts = [] # list of dictionaries
117 # vdict = {} # (index, normal, uv) -> new index
118 vdict = [{} for i in xrange(len(mesh_verts))]
119 ply_faces = [[] for f in xrange(len(mesh.faces))]
121 for i, f in enumerate(mesh.faces):
125 # XXX need face normals
129 normal_key = rvec3d(normal)
132 uv = active_uv_layer[i]
133 uv = uv.uv1, uv.uv2, uv.uv3, uv.uv4 # XXX - crufty :/
135 col = active_col_layer[i]
136 col = col.color1, col.color2, col.color3, col.color4
138 f_verts= list(f.verts)
139 if not f_verts[3]: f_verts.pop() # XXX face length should be 3/4, not always 4
142 for j, vidx in enumerate(f_verts):
147 normal_key = rvec3d(normal)
149 normal_key = None # XXX
152 uvcoord= uv[j][0], 1.0-uv[j][1]
153 uvcoord_key = rvec2d(uvcoord)
155 uvcoord= v.uvco[0], 1.0-v.uvco[1]
156 uvcoord_key = rvec2d(uvcoord)
160 color= int(color[0]*255.0), int(color[1]*255.0), int(color[2]*255.0)
163 key = normal_key, uvcoord_key, color
165 vdict_local = vdict[vidx]
166 pf_vidx = vdict_local.get(key) # Will be None initially
168 if pf_vidx == None: # same as vdict_local.has_key(key)
169 pf_vidx = vdict_local[key] = vert_count;
170 ply_verts.append((vidx, normal, uvcoord, color))
176 file.write('format ascii 1.0\n')
177 version = "2.5" # Blender.Get('version')
178 file.write('comment Created by Blender3D %s - www.blender.org, source file: %s\n' % (version, bpy.data.filename.split('/')[-1].split('\\')[-1] ))
180 file.write('element vertex %d\n' % len(ply_verts))
182 file.write('property float x\n')
183 file.write('property float y\n')
184 file.write('property float z\n')
189 file.write('property float nx\n')
190 file.write('property float ny\n')
191 file.write('property float nz\n')
194 file.write('property float s\n')
195 file.write('property float t\n')
197 file.write('property uchar red\n')
198 file.write('property uchar green\n')
199 file.write('property uchar blue\n')
201 file.write('element face %d\n' % len(mesh.faces))
202 file.write('property list uchar uint vertex_indices\n')
203 file.write('end_header\n')
205 for i, v in enumerate(ply_verts):
206 file.write('%.6f %.6f %.6f ' % tuple(mesh_verts[v[0]].co)) # co
209 file.write('%.6f %.6f %.6f ' % v[1]) # no
211 if EXPORT_UV: file.write('%.6f %.6f ' % v[2]) # uv
212 if EXPORT_COLORS: file.write('%u %u %u' % v[3]) # col
216 if len(pf)==3: file.write('3 %d %d %d\n' % tuple(pf))
217 else: file.write('4 %d %d %d %d\n' % tuple(pf))
220 print("writing", filename, "done")
225 Blender.Window.EditMode(1, '', 0)
230 Blender.Window.FileSelector(file_callback, 'PLY Export', Blender.sys.makename(ext='.ply'))
232 if __name__=='__main__':
236 class EXPORT_OT_ply(bpy.types.Operator):
238 Operator documentatuon text, will be used for the operator tooltip and python docs.
240 __label__ = "Export PLY"
242 # List of operator properties, the attributes will be assigned
243 # to the class instance from the operator settings before calling.
246 bpy.props.StringProperty(attr="filename", name="File Name", description="File name used for exporting the PLY file", maxlen= 1024, default= "")
249 def poll(self, context):
251 return context.active_object != None
253 def execute(self, context):
254 # print("Selected: " + context.active_object.name)
256 if not self.filename:
257 raise Exception("filename not set")
259 write(self.filename, context.active_object)
263 def invoke(self, context, event):
264 print("Invoke", context, event)
266 self.execute(context)
270 bpy.ops.add(EXPORT_OT_ply)
272 if __name__ == "__main__":
273 bpy.ops.EXPORT_OT_ply(filename="/tmp/test.ply")