Debian Codegraph @

vcg/wrap/io_trimesh/export_obj.h

raw symbols SCIP
1 /****************************************************************************
2 * VCGLib o o *
3 * Visual and Computer Graphics Library o o *
4 * _ O _ *
5 * Copyright(C) 2004 \/)\/ *
6 * Visual Computing Lab /\/| *
7 * ISTI - Italian National Research Council | *
8 * \ *
9 * All rights reserved. *
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU General Public License as published by *
13 * the Free Software Foundation; either version 2 of the License, or *
14 * (at your option) any later version. *
15 * *
16 * This program is distributed in the hope that it will be useful, *
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
19 * GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
20 * for more details. *
21 * *
22 ****************************************************************************/
23
24 /****************************************************************************
25 History
26
27 $Log: export_obj.h,v $
28 Revision 1.11 2008/02/27 00:34:43 cignoni
29 corrected various bugs in the export of texture coords
30
31 Revision 1.10 2007/10/17 09:49:50 cignoni
32 correct management of point only files
33
34 Revision 1.9 2007/03/12 16:40:16 tarini
35 Texture coord name change! "TCoord" and "Texture" are BAD. "TexCoord" is GOOD.
36
37 Revision 1.8 2007/03/08 11:27:52 ganovelli
38 added include to tcoord2
39
40 Revision 1.7 2007/02/16 21:12:13 m_di_benedetto
41 Commented out strange abort in WriteMaterials()
42
43 Revision 1.6 2006/12/07 00:37:58 cignoni
44 Corrected bug in the management of deleted vertices
45
46 Revision 1.5 2006/10/09 19:58:08 cignoni
47 Added casts to remove warnings
48
49 Revision 1.4 2006/09/18 12:14:38 cignoni
50 Removed bug in the creation of the material filename
51
52 Revision 1.3 2006/03/07 13:19:29 cignoni
53 First Release with OBJ import support
54
55 Revision 1.2 2006/02/28 14:38:09 corsini
56 remove qt include
57
58 Revision 1.1 2006/02/16 19:28:36 fmazzant
59 transfer of Export_3ds.h, Export_obj.h, Io_3ds_obj_material.h from Meshlab to vcg
60
61 Revision 1.7 2006/02/06 11:04:40 fmazzant
62 added file material.h. it include struct Material, CreateNewMaterial(...) and MaterialsCompare(...)
63
64 Revision 1.6 2006/02/04 10:18:46 fmazzant
65 clean code
66
67 Revision 1.5 2006/02/03 10:04:41 fmazzant
68 no significant updated
69
70 Revision 1.4 2006/01/30 14:02:05 fmazzant
71 bug-fix
72
73 Revision 1.3 2006/01/29 23:52:43 fmazzant
74 correct a small bug
75
76 Revision 1.2 2006/01/29 18:33:42 fmazzant
77 added some comment to the code
78
79 Revision 1.1 2006/01/29 16:33:03 fmazzant
80 moved export_obj and export_3ds from test/io into meshio/
81
82 Revision 1.34 2006/01/22 23:59:01 fmazzant
83 changed default value of diffuse. 1.0 -> 0.8
84
85 Revision 1.33 2006/01/19 09:36:29 fmazzant
86 cleaned up history log
87
88 Revision 1.32 2006/01/18 00:45:56 fmazzant
89 added control on face's diffuse
90
91 Revision 1.31 2006/01/17 13:48:54 fmazzant
92 added capability mask on export file format
93
94 Revision 1.30 2006/01/15 00:45:40 fmazzant
95 extend mask exporter for all type file format +
96
97 Revision 1.29 2006/01/14 00:03:26 fmazzant
98 added more controls
99
100 ****************************************************************************/
101
102 #ifndef __VCGLIB_EXPORT_OBJ
103 #define __VCGLIB_EXPORT_OBJ
104
105 #include <wrap/callback.h>
106 #include <vcg/complex/trimesh/allocate.h>
107 #include <vcg/space/texcoord2.h>
108 #include <wrap/io_trimesh/io_mask.h>
109 #include "io_material.h"
110 #include <iostream>
111 #include <fstream>
112 #include <map>
113
114 namespace vcg {
115 namespace tri {
116 namespace io {
117
118 template <class SaveMeshType>
119 class ExporterOBJ
120 {
121 public:
122 typedef typename SaveMeshType::FaceIterator FaceIterator;
123 typedef typename SaveMeshType::VertexIterator VertexIterator;
124 typedef typename SaveMeshType::VertexType VertexType;
125
126 /*
127 enum of all the types of error
128 */
129 enum SaveError
130 {
131 E_NOERROR, // 0
132 E_CANTOPENFILE, // 1
133 E_CANTCLOSEFILE, // 2
134 E_UNESPECTEDEOF, // 3
135 E_ABORTED, // 4
136 E_NOTDEFINITION, // 5
137 E_NOTVEXTEXVALID, // 6
138 E_NOTFACESVALID // 7
139 };
140
141 /*
142 this function takes an index and the relative error message gets back
143 */
144 static const char* ErrorMsg(int error)
145 {
146 static const char* obj_error_msg[] =
147 {
148 "No errors", // 0
149 "Can't open file", // 1
150 "can't close file", // 2
151 "Premature End of file", // 3
152 "File saving aborted", // 4
153 "Function not defined", // 5
154 "Vertices not valid", // 6
155 "Faces not valid" // 7
156 };
157
158 if(error>7 || error<0) return "Unknown error";
159 else return obj_error_msg[error];
160 };
161
162 /*
163 returns mask of capability one define with what are the saveable information of the format.
164 */
165 static int GetExportMaskCapability()
166 {
167 int capability = 0;
168
169 //vert
170 capability |= vcg::tri::io::Mask::IOM_VERTNORMAL;
171
172 //face
173 capability |= vcg::tri::io::Mask::IOM_FACECOLOR;
174
175 //wedg
176 capability |= vcg::tri::io::Mask::IOM_WEDGTEXCOORD;
177 capability |= vcg::tri::io::Mask::IOM_WEDGNORMAL;
178
179 return capability;
180 }
181
182 /*
183 function which saves in OBJ file format
184 */
185 static int Save(SaveMeshType &m, const char * filename, int mask, CallBackPos *cb=0)
186 {
187 if(m.vn == 0) return E_NOTVEXTEXVALID;
188 // Commented out this control. You should be allowed to save a point cloud.
189 // if(m.fn == 0) return E_NOTFACESVALID;
190
191 int current = 0;
192 int totalPrimitives = m.vn+m.fn;
193
194 std::vector<Material> materialVec;
195
196 std::string fn(filename);
197 int LastSlash=fn.size()-1;
198 while(LastSlash>=0 && fn[LastSlash]!='/')
199 --LastSlash;
200
201 FILE *fp;
202 fp = fopen(filename,"w");
203 if(fp == NULL) return E_CANTOPENFILE;
204
205 fprintf(fp,"####\n#\n# OBJ File Generated by Meshlab\n#\n####\n");
206 fprintf(fp,"# Object %s\n#\n# Vertices: %d\n# Faces: %d\n#\n####\n",fn.substr(LastSlash+1).c_str(),m.vn,m.fn);
207
208 //library materialVec
209 if( (mask & vcg::tri::io::Mask::IOM_FACECOLOR) || (mask & Mask::IOM_WEDGTEXCOORD) )
210 fprintf(fp,"mtllib ./%s.mtl\n\n",fn.substr(LastSlash+1).c_str());
211
212 //vertexs + normal
213 VertexIterator vi;
214 std::map<Point3f,int> NormalVertex;
215 std::vector<int> VertexId(m.vert.size());
216 int numvert = 0;
217 int curNormalIndex = 1;
218 for(vi=m.vert.begin(); vi!=m.vert.end(); ++vi) if( !(*vi).IsD() )
219 {
220 VertexId[vi-m.vert.begin()]=numvert;
221 //saves normal per vertex
222 if((mask & Mask::IOM_VERTNORMAL) || (mask & vcg::tri::io::Mask::IOM_WEDGTEXCOORD) )
223 {
224 if(AddNewNormalVertex(NormalVertex,(*vi).N(),curNormalIndex))
225 {
226 fprintf(fp,"vn %f %f %f\n",(*vi).N()[0],(*vi).N()[1],(*vi).N()[2]);
227 curNormalIndex++;
228 }
229 }
230
231 //saves vertex
232 fprintf(fp,"v %f %f %f\n",(*vi).P()[0],(*vi).P()[1],(*vi).P()[2]);
233
234 if (cb !=NULL) {
235 if(!(*cb)((100*++current)/totalPrimitives, "writing vertices "))
236 { fclose(fp); return E_ABORTED;} }
237 numvert++;
238 }
239 assert(numvert == m.vn);
240
241 fprintf(fp,"# %d vertices, %d vertices normals\n\n",m.vn,NormalVertex.size());
242
243 //faces + texture coords
244 FaceIterator fi;
245 std::map<vcg::TexCoord2<float>,int> CoordIndexTexture;
246 unsigned int material_num = 0;
247 int mem_index = 0; //var temporany
248 int curTexCoordIndex = 1;
249 for(fi=m.face.begin(); fi!=m.face.end(); ++fi) if( !(*fi).IsD() )
250 {
251 if((mask & Mask::IOM_FACECOLOR) || (mask & Mask::IOM_WEDGTEXCOORD) )
252 {
253 int index = Materials<SaveMeshType>::CreateNewMaterial(m,materialVec,material_num,fi);
254
255 if(index == materialVec.size())//inserts a new element material
256 {
257 material_num++;
258 fprintf(fp,"\nusemtl material_%d\n",materialVec[index-1].index);
259 mem_index = index-1;
260 }
261 else
262 {
263 if(index != mem_index)//inserts old name elemente material
264 {
265 fprintf(fp,"\nusemtl material_%d\n",materialVec[index].index);
266 mem_index=index;
267 }
268 }
269 }
270
271 //saves texture coord
272 for(unsigned int k=0;k<3;k++)
273 {
274 if(HasPerWedgeTexCoord(m) && (mask & Mask::IOM_WEDGTEXCOORD))
275 {
276 if(AddNewTextureCoord(CoordIndexTexture,(*fi).WT(k),curTexCoordIndex))
277 {
278 fprintf(fp,"vt %f %f\n",(*fi).WT(k).u(),(*fi).WT(k).v());
279 curTexCoordIndex++; //ncreases the value number to be associated to the Texture
280 }
281 }
282 }
283
284 fprintf(fp,"f ");
285 for(unsigned int k=0;k<3;k++)
286 {
287 if(k!=0) fprintf(fp," ");
288 int vInd = -1;
289 // +1 because Obj file format begins from index = 1 but not from index = 0.
290 vInd = VertexId[GetIndexVertex(m, (*fi).V(k))] + 1;//index of vertex per face
291
292 int vt = -1;
293 if(mask & Mask::IOM_WEDGTEXCOORD)
294 vt = GetIndexVertexTexture(CoordIndexTexture,(*fi).WT(k));//index of vertex texture per face
295
296 int vn = -1;
297 if((mask & Mask::IOM_VERTNORMAL) || (mask & Mask::IOM_WEDGNORMAL) )
298 vn = GetIndexVertexNormal(m, NormalVertex, (*fi).V(k)->cN());//index of vertex normal per face.
299
300 //writes elements on file obj
301 WriteFacesElement(fp,vInd,vt,vn);
302 }
303 fprintf(fp,"\n");
304 if (cb !=NULL) {
305 if(!(*cb)((100*++current)/totalPrimitives, "writing vertices "))
306 { fclose(fp); return E_ABORTED;}
307 }
308
309 }//for
310 fprintf(fp,"# %d faces, %d coords texture\n\n",m.face.size(),CoordIndexTexture.size());
311
312 fprintf(fp,"# End of File");
313 fclose(fp);
314
315 int r = 0;
316 if((mask & Mask::IOM_WEDGTEXCOORD) || (mask & Mask::IOM_FACECOLOR) )
317 r = WriteMaterials(materialVec, filename,cb);//write material
318
319 if(r!= E_NOERROR)
320 return r;
321 return E_NOERROR;
322 }
323
324 /*
325 returns index of the vertex
326 */
327 inline static int GetIndexVertex(SaveMeshType &m, VertexType *p)
328 {
329 return p-&*(m.vert.begin());
330 }
331
332 /*
333 returns index of the texture coord
334 */
335 inline static int GetIndexVertexTexture(std::map<TexCoord2<float>,int> &mapTexToInt, const vcg::TexCoord2<float> &wt)
336 {
337 std::map<vcg::TexCoord2<float>,int>::iterator iter= mapTexToInt.find(wt);
338 if(iter != mapTexToInt.end()) return (*iter).second;
339 else return -1;
340 // Old wrong version.
341 // int index = mapTexToInt[wt];
342 // if(index!=0){return index;}
343 }
344
345 /*
346 returns index of the vertex normal
347 */
348 inline static int GetIndexVertexNormal(SaveMeshType &m, std::map<Point3f,int> &mapNormToInt, const Point3f &norm )
349 {
350 std::map<Point3f,int>::iterator iter= mapNormToInt.find(norm);
351 if(iter != mapNormToInt.end()) return (*iter).second;
352 else return -1;
353 // Old wrong version.
354 // int index = mapNormToInt[m.vert[iv].N()];
355 // if(index!=0){return index;}
356 }
357
358 /*
359 write elements on file
360
361 f v/tc/vn v/tc/vn v/tc/vn ...
362 f v/tc v/tc v/tc ...
363 f v//vn v//vn v//vn ...
364 f v v v ...
365
366 */
367 inline static void WriteFacesElement(FILE *fp,int v,int vt, int vn)
368 {
369 fprintf(fp,"%d",v);
370 if(vt!=-1)
371 {
372 fprintf(fp,"/%d",vt);
373 if(vn!=-1)
374 fprintf(fp,"/%d",vn);
375 }
376 else if(vn!=-1)
377 fprintf(fp,"//%d",vn);
378 }
379
380 /*
381 adds a new index to the coordinate of Texture if it is the first time
382 which is otherwise met not execute anything
383 */
384 inline static bool AddNewTextureCoord(std::map<vcg::TexCoord2<float>,int> &m, const vcg::TexCoord2<float> &wt,int value)
385 {
386 int index = m[wt];
387 if(index==0){m[wt]=value;return true;}
388 return false;
389 }
390
391 /*
392 adds a new index to the normal per vertex if it is the first time
393 which is otherwise met does not execute anything
394 */
395 inline static bool AddNewNormalVertex(std::map<Point3f,int> &m, Point3f &n ,int value)
396 {
397 int index = m[n];
398 if(index==0){m[n]=value;return true;}
399 return false;
400 }
401
402 /*
403 writes material into file
404 */
405 inline static int WriteMaterials(std::vector<Material> &materialVec, const char * filename, CallBackPos *cb=0)
406 {
407 std::string fileName = std::string(filename);
408 fileName+=".mtl";
409
410 if(materialVec.size() > 0)
411 {
412 FILE *fp;
413 fp = fopen(fileName.c_str(),"w");
414 if(fp==NULL)return E_ABORTED;
415
416 fprintf(fp,"#\n# Wavefront material file\n# Converted by Meshlab Group\n#\n\n");
417
418 int current = 0;
419
420 for(unsigned int i=0;i<materialVec.size();i++)
421 {
422 if (cb !=NULL)
423 (*cb)((100 * ++current)/materialVec.size(), "saving material file ");
424 else
425 { /* fclose(fp); return E_ABORTED; */ }
426
427 fprintf(fp,"newmtl material_%d\n",materialVec[i].index);
428 fprintf(fp,"Ka %f %f %f\n",materialVec[i].Ka[0],materialVec[i].Ka[1],materialVec[i].Ka[2]);
429 fprintf(fp,"Kd %f %f %f\n",materialVec[i].Kd[0],materialVec[i].Kd[1],materialVec[i].Kd[2]);
430 fprintf(fp,"Ks %f %f %f\n",materialVec[i].Ks[0],materialVec[i].Ks[1],materialVec[i].Ks[2]);
431 fprintf(fp,"Tr %f\n",materialVec[i].Tr);
432 fprintf(fp,"illum %d\n",materialVec[i].illum);
433 fprintf(fp,"Ns %f\n",materialVec[i].Ns);
434
435 if(materialVec[i].map_Kd.size()>0)
436 fprintf(fp,"map_Kd %s\n",materialVec[i].map_Kd.c_str());
437 fprintf(fp,"\n");
438 }
439 fclose(fp);
440 }
441 return E_NOERROR;
442 }
443
444 }; // end class
445 } // end Namespace tri
446 } // end Namespace io
447 } // end Namespace vcg
448
449 #endif