Debian Codegraph @

vcg/wrap/io_trimesh/import_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: import_obj.h,v $
28 Revision 1.20 2008/02/27 23:48:06 cignoni
29 removed duplicated material class
30
31 Revision 1.19 2008/01/17 18:02:02 cignoni
32 added missing cast for normal assignments
33
34 Revision 1.18 2007/12/13 17:57:33 cignoni
35 removed harmless gcc warnings
36
37 Revision 1.17 2007/10/17 09:49:50 cignoni
38 correct management of point only files
39
40 Revision 1.16 2007/07/20 14:49:46 cignoni
41 Added in load mask the face color bit when there is a generic material used
42
43 Revision 1.15 2007/07/05 14:47:04 cignoni
44 Added face coloring when there is a texture (and therefore a material)
45
46 Revision 1.14 2007/04/18 13:33:11 cignoni
47 resolved issue related to the parsing of CR LF under *nixes
48
49 Revision 1.13 2007/04/18 07:01:26 cignoni
50 Added managment of map_Ka textures (and not only map_Kd)
51
52 Revision 1.12 2006/12/21 00:36:17 cignoni
53 Removed a bug in the managment of non triangular faces
54
55 Revision 1.11 2006/12/12 02:47:12 cignoni
56 Removed use of tellg that is broken in current version of mingw
57
58 Revision 1.10 2006/11/21 10:56:41 cignoni
59 ReWrote loadMask. Now shorter and faster.
60
61 Revision 1.9 2006/10/09 19:58:08 cignoni
62 Added casts to remove warnings
63
64 Revision 1.8 2006/07/09 05:41:17 cignoni
65 Major rewrite. Now shorter and more robust.
66
67 Revision 1.7 2006/06/21 04:26:26 cignoni
68 added initial test on end of file in the tokenize
69
70 Revision 1.6 2006/05/21 07:01:04 cignoni
71 Added mask clamping to the effective capabilities of the mesh
72
73 Revision 1.5 2006/04/11 09:48:00 zifnab1974
74 changes needed for compilation on linux 64b with gcc 3.4.5
75
76 Revision 1.4 2006/03/29 09:27:07 cignoni
77 Added managemnt of non critical errors
78
79 Revision 1.3 2006/03/29 08:51:16 corsini
80 reset to zero warnings
81
82 Revision 1.2 2006/03/27 07:18:22 cignoni
83 added missing std::
84
85 Revision 1.1 2006/03/07 13:19:29 cignoni
86 First Release with OBJ import support
87
88 Initial Working version coded by Buzzelli.
89 ****************************************************************************/
90
91 #ifndef __VCGLIB_IMPORT_OBJ
92 #define __VCGLIB_IMPORT_OBJ
93
94 #include <wrap/callback.h>
95 #include <vcg/complex/trimesh/allocate.h>
96 #include <wrap/io_trimesh/io_mask.h>
97 #include <wrap/io_trimesh/io_material.h>
98
99 #include <fstream>
100 #include <string>
101 #include <vector>
102
103
104 namespace vcg {
105 namespace tri {
106 namespace io {
107
108 /**
109 This class encapsulate a filter for importing obj (Alias Wavefront) meshes.
110 Warning: this code assume little endian (PC) architecture!!!
111 */
112 template <class OpenMeshType>
113 class ImporterOBJ
114 {
115 public:
116
117 typedef typename OpenMeshType::VertexPointer VertexPointer;
118 typedef typename OpenMeshType::ScalarType ScalarType;
119 typedef typename OpenMeshType::VertexType VertexType;
120 typedef typename OpenMeshType::FaceType FaceType;
121 typedef typename OpenMeshType::VertexIterator VertexIterator;
122 typedef typename OpenMeshType::FaceIterator FaceIterator;
123 typedef typename OpenMeshType::CoordType CoordType;
124
125 class Info
126 {
127 public:
128
129 Info()
130 {
131 mask = 0;
132 cb = 0;
133 numTexCoords=0;
134 }
135
136 /// It returns a bit mask describing the field preesnt in the ply file
137 int mask;
138
139 /// a Simple callback that can be used for long obj parsing.
140 // it returns the current position, and formats a string with a description of what th efunction is doing (loading vertexes, faces...)
141 CallBackPos *cb;
142
143 /// number of vertices
144 int numVertices;
145 /// number of faces (the number of triangles could be
146 /// larger in presence of polygonal faces
147 int numFaces;
148 /// number of texture coords indexes
149 int numTexCoords;
150
151 }; // end class
152
153
154 //struct OBJFacet
155 //{
156 // CoordType n;
157 // CoordType t;
158 // CoordType v[3];
159 //
160 // short attr; // material index
161 //};
162 struct ObjIndexedFace
163 {
164 int v[3];
165 int n[3];
166 int t[3];
167 int tInd;
168 Color4b c;
169 };
170
171 struct ObjTexCoord
172 {
173 float u;
174 float v;
175 };
176
177 enum OBJError {
178 // Successfull opening
179 E_NOERROR = 0x000, // 0 (position of correspondig string in the array)
180
181 // Non Critical Errors (only odd numbers)
182 E_NON_CRITICAL_ERROR = 0x001,
183 E_MATERIAL_FILE_NOT_FOUND = 0x003, // 1
184 E_MATERIAL_NOT_FOUND = 0x005, // 2
185 E_TEXTURE_NOT_FOUND = 0x007, // 3
186 E_VERTICES_WITH_SAME_IDX_IN_FACE = 0x009, // 4
187
188 // Critical Opening Errors (only even numbers)
189 E_CANTOPEN = 0x00A, // 5
190 E_UNESPECTEDEOF = 0x00C, // 6
191 E_ABORTED = 0x00E, // 7
192 E_NO_VERTEX = 0x010, // 8
193 E_NO_FACE = 0x012, // 9
194 E_BAD_VERTEX_STATEMENT = 0x014, // 10
195 E_BAD_VERT_TEX_STATEMENT = 0x016, // 11
196 E_BAD_VERT_NORMAL_STATEMENT = 0x018, // 12
197 E_LESS_THAN_3VERTINFACE = 0x01A, // 13
198 E_BAD_VERT_INDEX = 0x01C, // 14
199 E_BAD_VERT_TEX_INDEX = 0x01E, // 15
200 E_BAD_VERT_NORMAL_INDEX = 0x020 // 16
201 };
202
203 // to check if a given error is critical or not.
204 static bool ErrorCritical(int err)
205 {
206 if(err<0x00A && err>=0) return false;
207 return true;
208 }
209
210 static const char* ErrorMsg(int error)
211 {
212 static const char* obj_error_msg[] =
213 {
214 "No errors", // 0
215
216 "Material library file not found, a default white material is used", // 1
217 "Some materials definitions were not found, a default white material is used where no material was available", // 2
218 "Texture file not found", // 3
219 "Identical index vertices found in the same face", // 4
220
221 "Can't open file", // 5
222 "Premature End of file", // 6
223 "File opening aborted", // 7
224 "No vertex field found", // 8
225 "No face field found", // 9
226 "Vertex statement with less than 3 coords", // 10
227 "Texture coords statement with less than 2 coords", // 11
228 "Vertex normal statement with less than 3 coords", // 12
229 "Face with less than 3 vertices", // 13
230 "Bad vertex index in face", // 14
231 "Bad texture coords index in face", // 15
232 "Bad vertex normal index in face" // 16
233 };
234
235 // due to approximation, following line works well for either even (critical err codes)
236 // or odd (non critical ones) numbers
237 error = (int) error/2;
238
239 if(error>15 || error<0) return "Unknown error";
240 else return obj_error_msg[error];
241 };
242
243 // Helper functions that checks the range of indexes
244 // putting them in the correct range if less than zero (as in the obj style)
245
246 static bool GoodObjIndex(int &index, const int maxVal)
247 {
248 if (index > maxVal) return false;
249 if (index < 0)
250 {
251 index += maxVal+1;
252 if (index<0 || index > maxVal) return false;
253 }
254 return true;
255 }
256
257 static int Open(OpenMeshType &mesh, const char *filename, int &loadmask, CallBackPos *cb=0)
258 {
259 Info oi;
260 oi.mask=-1;
261 oi.cb=cb;
262 int ret=Open(mesh,filename,oi);
263 loadmask=oi.mask;
264 return ret;
265 }
266
267 /*!
268 * Opens an object file (in ascii format) and populates the mesh passed as first
269 * accordingly to read data
270 * \param m The mesh model to be populated with data stored into the file
271 * \param filename The name of the file to be opened
272 * \param oi A structure containing infos about the object to be opened
273 */
274 static int Open( OpenMeshType &m, const char * filename, Info &oi)
275 {
276 int result = E_NOERROR;
277
278 m.Clear();
279 CallBackPos *cb = oi.cb;
280
281 // if LoadMask has not been called yet, we call it here
282 if (oi.mask == -1)
283 LoadMask(filename, oi);
284
285 Mask::ClampMask<OpenMeshType>(m,oi.mask);
286
287 if (oi.numVertices == 0)
288 return E_NO_VERTEX;
289
290 // Commented out this test. You should be allowed to load point clouds.
291 //if (oi.numFaces == 0)
292 // return E_NO_FACE;
293
294 std::ifstream stream(filename);
295 if (stream.fail())
296 return E_CANTOPEN;
297
298 std::vector<Material> materials; // materials vector
299 std::vector<ObjTexCoord> texCoords; // texture coordinates
300 std::vector<CoordType> normals; // vertex normals
301 std::vector<ObjIndexedFace> indexedFaces;
302 std::vector< std::string > tokens;
303 std::string header;
304
305 short currentMaterialIdx = 0; // index of current material into materials vector
306 Color4b currentColor=Color4b::LightGray; // we declare this outside code block since other
307 // triangles of this face will share the same color
308
309 Material defaultMaterial; // default material: white
310 materials.push_back(defaultMaterial);
311
312 int numVertices = 0; // stores the number of vertices been read till now
313 int numTriangles = 0; // stores the number of faces been read till now
314 int numTexCoords = 0; // stores the number of texture coordinates been read till now
315 int numVNormals = 0; // stores the number of vertex normals been read till now
316
317 int numVerticesPlusFaces = oi.numVertices + oi.numFaces;
318 int extraTriangles=0;
319 // vertices and faces allocatetion
320 VertexIterator vi = Allocator<OpenMeshType>::AddVertices(m,oi.numVertices);
321 //FaceIterator fi = Allocator<OpenMeshType>::AddFaces(m,oi.numFaces);
322
323 ObjIndexedFace ff;
324
325 while (!stream.eof())
326 {
327 tokens.clear();
328 TokenizeNextLine(stream, tokens);
329
330 unsigned int numTokens = static_cast<unsigned int>(tokens.size());
331 if (numTokens > 0)
332 {
333 header.clear();
334 header = tokens[0];
335
336 if (header.compare("v")==0) // vertex
337 {
338 if (numTokens < 4) return E_BAD_VERTEX_STATEMENT;
339
340 (*vi).P()[0] = (ScalarType) atof(tokens[1].c_str());
341 (*vi).P()[1] = (ScalarType) atof(tokens[2].c_str());
342 (*vi).P()[2] = (ScalarType) atof(tokens[3].c_str());
343 ++numVertices;
344
345 // assigning vertex color
346 // ----------------------
347 if( oi.mask & vcg::tri::io::Mask::IOM_VERTCOLOR)
348 (*vi).C() = currentColor;
349
350 ++vi; // move to next vertex iterator
351
352 // callback invocation, abort loading process if the call returns false
353 if ((cb !=NULL) && (((numTriangles + numVertices)%100)==0) && !(*cb)((100*(numTriangles + numVertices))/numVerticesPlusFaces, "Vertex Loading"))
354 return E_ABORTED;
355 }
356 else if (header.compare("vt")==0) // vertex texture coords
357 {
358 if (numTokens < 3) return E_BAD_VERT_TEX_STATEMENT;
359
360 ObjTexCoord t;
361 t.u = static_cast<float>(atof(tokens[1].c_str()));
362 t.v = static_cast<float>(atof(tokens[2].c_str()));
363 texCoords.push_back(t);
364
365 numTexCoords++;
366 }
367 else if (header.compare("vn")==0) // vertex normal
368 {
369 if (numTokens != 4) return E_BAD_VERT_NORMAL_STATEMENT;
370
371 CoordType n;
372 n[0] = (ScalarType) atof(tokens[1].c_str());
373 n[1] = (ScalarType) atof(tokens[2].c_str());
374 n[2] = (ScalarType) atof(tokens[3].c_str());
375 normals.push_back(n);
376
377 numVNormals++;
378 }
379 else if (header.compare("f")==0) // face
380 {
381 if (numTokens < 4) return E_LESS_THAN_3VERTINFACE;
382
383 std::string vertex;
384 std::string texcoord;
385 std::string normal;
386 for(int i=0;i<3;++i) // remember index starts from 1 instead of 0
387 SplitToken(tokens[i+1], ff.v[i], ff.n[i], ff.t[i], oi.mask);
388
389 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGTEXCOORD )
390 {
391 // verifying validity of texture coords indices
392 for(int i=0;i<3;i++)
393 if(!GoodObjIndex(ff.t[i],oi.numTexCoords))
394 return E_BAD_VERT_TEX_INDEX;
395
396 ff.tInd=materials[currentMaterialIdx].index;
397 }
398
399 // verifying validity of vertex indices
400 if ((ff.v[0] == ff.v[1]) || (ff.v[0] == ff.v[2]) || (ff.v[1] == ff.v[2]))
401 result = E_VERTICES_WITH_SAME_IDX_IN_FACE;
402
403 for(int i=0;i<3;i++)
404 if(!GoodObjIndex(ff.v[i],numVertices))
405 return E_BAD_VERT_INDEX;
406
407 // assigning face normal
408 // ---------------------
409 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGNORMAL )
410 {
411 // verifying validity of vertex normal indices
412 // -------------------------------------------
413 for(int i=0;i<3;i++)
414 if(!GoodObjIndex(ff.n[i],numVNormals)) return E_BAD_VERT_NORMAL_INDEX;
415 }
416
417 // assigning face color
418 // --------------------
419 if( oi.mask & vcg::tri::io::Mask::IOM_FACECOLOR)
420 ff.c = currentColor;
421
422 ++numTriangles;
423 indexedFaces.push_back(ff);
424 /*
425 // A face polygon composed of more than three vertices is triangulated
426 // according to the following schema:
427 // v5
428 // / \
429 // / \
430 // / \
431 // v1------v4
432 // |\ /
433 // | \ /
434 // | \ /
435 // v2---v3
436 //
437 // As shown above, the 5 vertices polygon (v1,v2,v3,v4,v5)
438 // has been split into the triangles (v1,v2,v3), (v1,v3,v4) e (v1,v4,v5).
439 // This way vertex v1 becomes the common vertex of all newly generated
440 // triangles, and this may lead to the creation of very thin triangles.
441 */
442
443 int vertexesPerFace = static_cast<int>(tokens.size()-1);
444 int iVertex = 3;
445 while (iVertex < vertexesPerFace) // add other triangles
446 {
447 ObjIndexedFace ffNew=ff;
448 int v4_index;
449 int vt4_index;
450 int vn4_index;
451
452 SplitToken(tokens[++iVertex], v4_index, vn4_index, vt4_index, oi.mask);
453
454 // assigning wedge texture coordinates
455 // -----------------------------------
456 if( oi.mask & vcg::tri::io::Mask::IOM_WEDGTEXCOORD )
457 {
458 // verifying validity of texture coords index
459 // ------------------------------------------
460 if(!GoodObjIndex(v4_index, numVertices))
461 return E_BAD_VERT_INDEX;
462 if(!GoodObjIndex(vt4_index,oi.numTexCoords))
463 return E_BAD_VERT_TEX_INDEX;
464
465 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGNORMAL )
466 if(!GoodObjIndex(vn4_index,numVNormals))
467 return E_BAD_VERT_NORMAL_INDEX;
468
469 ffNew.t[1]=ff.t[2];
470 ffNew.t[2]=vt4_index;
471 }
472
473 if ((ff.v[0] == v4_index) || (ff.v[2] == v4_index)) result = E_VERTICES_WITH_SAME_IDX_IN_FACE;
474 ffNew.v[1]=ff.v[2];
475 ffNew.v[2]=v4_index;
476
477 // assigning face normal
478 // ---------------------
479 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGNORMAL )
480 {
481 ffNew.n[1]=ff.n[2];
482 ffNew.n[2]=vn4_index;
483 }
484
485 ++numTriangles;
486 ++extraTriangles;
487 indexedFaces.push_back(ffNew);
488 ff.v[2] = v4_index;
489 }
490
491 // callback invocation, abort loading process if the call returns false
492 if ((cb !=NULL)&& (((numTriangles + numVertices)%100)==0) )
493 {
494 if (!(*cb)( (100*(numTriangles +numVertices))/ numVerticesPlusFaces, "Face Loading"))
495 return E_ABORTED;
496 }
497 }
498 else if (header.compare("mtllib")==0) // material library
499 {
500 // obtain the name of the file containing materials library
501 std::string materialFileName = tokens[1];
502 if (!LoadMaterials( materialFileName.c_str(), materials, m.textures))
503 result = E_MATERIAL_FILE_NOT_FOUND;
504 }
505 else if (header.compare("usemtl")==0) // material usage
506 {
507 std::string materialName = tokens[1];
508 bool found = false;
509 unsigned i = 0;
510 while (!found && (i < materials.size()))
511 {
512 std::string currentMaterialName = materials[i].materialName;
513 if (currentMaterialName == materialName)
514 {
515 currentMaterialIdx = i;
516 Material &material = materials[currentMaterialIdx];
517 Point3f diffuseColor = material.Kd;
518 unsigned char r = (unsigned char) (diffuseColor[0] * 255.0);
519 unsigned char g = (unsigned char) (diffuseColor[1] * 255.0);
520 unsigned char b = (unsigned char) (diffuseColor[2] * 255.0);
521 unsigned char alpha = (unsigned char) (material.Tr * 255.0);
522 currentColor= Color4b(r, g, b, alpha);
523 found = true;
524 }
525 ++i;
526 }
527
528 if (!found)
529 {
530 currentMaterialIdx = 0;
531 result = E_MATERIAL_NOT_FOUND;
532 }
533 }
534 // we simply ignore other situations
535 } // end for each line...
536 } // end while stream not eof
537 assert((numTriangles +numVertices) == numVerticesPlusFaces+extraTriangles);
538
539 FaceIterator fi = Allocator<OpenMeshType>::AddFaces(m,numTriangles);
540 //-------------------------------------------------------------------------------
541 // Now the final pass to convert indexes into pointers for face to vert/norm/tex references
542 for(int i=0;i<numTriangles;++i)
543 {
544 assert(m.face.size()==size_t(m.fn));
545 for(int j=0;j<3;++j)
546 {
547 m.face[i].V(j)=&(m.vert[indexedFaces[i].v[j]]);
548 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGTEXCOORD ) {
549 ObjTexCoord t = texCoords[indexedFaces[i].t[j]];
550 m.face[i].WT(j).u() = t.u;
551 m.face[i].WT(j).v() = t.v;
552 m.face[i].WT(j).n() = indexedFaces[i].tInd;
553 }
554 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGNORMAL )
555 m.face[i].WN(j).Import(normals[indexedFaces[i].n[j]]);
556 }
557 if ( oi.mask & vcg::tri::io::Mask::IOM_FACECOLOR )
558 m.face[i].C()=indexedFaces[i].c;
559 if ( oi.mask & vcg::tri::io::Mask::IOM_WEDGNORMAL )
560 // face normal is computed as an average of wedge normals
561 m.face[i].N().Import(m.face[i].WN(0)+m.face[i].WN(1)+m.face[i].WN(2));
562 else // computing face normal from position of face vertices
563 face::ComputeNormalizedNormal(m.face[i]);
564 }
565
566 return result;
567 } // end of Open
568
569
570 /*!
571 * Read the next valid line and parses it into "tokens", allowing
572 * the tokens to be read one at a time.
573 * \param stream The object providing the input stream
574 * \param tokens The "tokens" in the next line
575 */
576 inline static const void TokenizeNextLine(std::ifstream &stream, std::vector< std::string > &tokens)
577 {
578 if(stream.eof()) return;
579 std::string line;
580 do
581 std::getline(stream, line);
582 while ((line[0] == '#' || line.length()==0) && !stream.eof()); // skip comments and empty lines
583
584 if ((line[0] == '#') || (line.length() == 0)) // can be true only on last line of file
585 return;
586
587 size_t from = 0;
588 size_t to = 0;
589 size_t length = line.size();
590 tokens.clear();
591 do
592 {
593 while (from!=length && (line[from]==' ' || line[from]=='\t' || line[from]=='\r') )
594 from++;
595 if(from!=length)
596 {
597 to = from+1;
598 while (to!=length && line[to]!=' ' && line[to]!='\r')
599 to++;
600 tokens.push_back(line.substr(from, to-from).c_str());
601 from = to;
602 }
603 }
604 while (from<length);
605 } // end TokenizeNextLine
606
607 inline static const void SplitToken(std::string token, int &vId, int &nId, int &tId, int mask)
608 {
609 std::string vertex;
610 std::string texcoord;
611 std::string normal;
612 if( ( mask & Mask::IOM_WEDGTEXCOORD ) && (mask & Mask::IOM_WEDGNORMAL) ) SplitVVTVNToken(token, vertex, texcoord, normal);
613 if(!( mask & Mask::IOM_WEDGTEXCOORD ) && (mask & Mask::IOM_WEDGNORMAL) ) SplitVVNToken(token, vertex, normal);
614 if( ( mask & Mask::IOM_WEDGTEXCOORD ) &&!(mask & Mask::IOM_WEDGNORMAL) ) SplitVVTToken(token, vertex, texcoord);
615 if(!( mask & Mask::IOM_WEDGTEXCOORD ) &&!(mask & Mask::IOM_WEDGNORMAL) ) SplitVToken(token, vertex);
616
617 vId = atoi(vertex.c_str())-1;
618 if(mask & Mask::IOM_WEDGTEXCOORD) tId = atoi(texcoord.c_str())-1;
619 if(mask & Mask::IOM_WEDGNORMAL) nId= atoi(normal.c_str())-1;
620 }
621
622 inline static const void SplitVToken(std::string token, std::string &vertex)
623 {
624 vertex=token;
625 }
626
627 inline static const void SplitVVTToken(std::string token, std::string &vertex, std::string &texcoord)
628 {
629 vertex.clear();
630 texcoord.clear();
631
632 size_t from = 0;
633 size_t to = 0;
634 size_t length = token.size();
635
636 if(from!=length)
637 {
638 char c = token[from];
639 vertex.push_back(c);
640
641 to = from+1;
642 while (to!=length && ((c = token[to]) !='/'))
643 {
644 vertex.push_back(c);
645 ++to;
646 }
647 ++to;
648 while (to!=length && ((c = token[to]) !=' '))
649 {
650 texcoord.push_back(c);
651 ++to;
652 }
653 }
654 } // end of SplitVVTToken
655
656 inline static const void SplitVVNToken(std::string token, std::string &vertex, std::string &normal)
657 {
658 vertex.clear();
659 normal.clear();
660
661 size_t from = 0;
662 size_t to = 0;
663 size_t length = token.size();
664
665 if(from!=length)
666 {
667 char c = token[from];
668 vertex.push_back(c);
669
670 to = from+1;
671 while (to!=length && ((c = token[to]) !='/'))
672 {
673 vertex.push_back(c);
674 ++to;
675 }
676 ++to;
677 ++to; // should be the second '/'
678 while (to!=length && ((c = token[to]) !=' '))
679 {
680 normal.push_back(c);
681 ++to;
682 }
683 }
684 } // end of SplitVVNToken
685
686 inline static const void SplitVVTVNToken(std::string token, std::string &vertex, std::string &texcoord, std::string &normal)
687 {
688 vertex.clear();
689 texcoord.clear();
690 normal.clear();
691
692 size_t from = 0;
693 size_t to = 0;
694 size_t length = token.size();
695
696 if(from!=length)
697 {
698 char c = token[from];
699 vertex.push_back(c);
700
701 to = from+1;
702 while (to!=length && ((c = token[to]) !='/'))
703 {
704 vertex.push_back(c);
705 ++to;
706 }
707 ++to;
708 while (to!=length && ((c = token[to]) !='/'))
709 {
710 texcoord.push_back(c);
711 ++to;
712 }
713 ++to;
714 while (to!=length && ((c = token[to]) !=' '))
715 {
716 normal.push_back(c);
717 ++to;
718 }
719 }
720 } // end of SplitVVTVNToken
721
722 /*!
723 * Retrieves infos about kind of data stored into the file and fills a mask appropriately
724 * \param filename The name of the file to open
725 * \param mask A mask which will be filled according to type of data found in the object
726 * \param oi A structure which will be filled with infos about the object to be opened
727 */
728
729 static bool LoadMask(const char * filename, Info &oi)
730 {
731 std::ifstream stream(filename);
732 if (stream.fail()) return false;
733
734 // obtain length of file:
735 stream.seekg (0, std::ios::end);
736 int length = stream.tellg();
737 stream.seekg (0, std::ios::beg);
738
739 if (length == 0) return false;
740
741 bool bHasPerFaceColor = false;
742
743 oi.numVertices=0;
744 oi.numFaces=0;
745 oi.numTexCoords=0;
746 int lineCount=0;
747 int totRead=0;
748 std::string line;
749 while (!stream.eof())
750 {
751 lineCount++;
752 std::getline(stream, line);
753 totRead+=line.size();
754 if(oi.cb && (lineCount%1000)==0)
755 (*oi.cb)( (int)(100.0*(float(totRead))/float(length)), "Loading mask...");
756 if(line.size()>2)
757 {
758 if(line[0]=='v')
759 {
760 if(line[1]==' ') oi.numVertices++;
761 if(line[1]=='t') oi.numTexCoords++;
762 }
763 else
764 if(line[0]=='f') oi.numFaces++;
765 else
766 if(line[0]=='u' && line[1]=='s') bHasPerFaceColor = true; // there is a usematerial so add per face color
767 }
768 }
769 oi.mask = 0;
770 if (oi.numTexCoords)
771 {
772 oi.mask |= vcg::tri::io::Mask::IOM_WEDGTEXCOORD;
773 // Usually if you have tex coords you also have materials
774 oi.mask |= vcg::tri::io::Mask::IOM_FACECOLOR;
775 }
776 if(bHasPerFaceColor) oi.mask |= vcg::tri::io::Mask::IOM_FACECOLOR;
777
778
779 return true;
780 }
781
782 static bool LoadMask(const char * filename, int &mask)
783 {
784 Info oi;
785 bool ret=LoadMask(filename, oi);
786 mask= oi.mask;
787 return ret;
788 }
789
790 static bool LoadMaterials(const char * filename, std::vector<Material> &materials, std::vector<std::string> &textures)
791 {
792 // assumes we are in the right directory
793
794 std::ifstream stream(filename);
795 if (stream.fail())
796 return false;
797
798 std::vector< std::string > tokens;
799 std::string header;
800
801 materials.clear();
802 Material currentMaterial;
803
804 bool first = true;
805 while (!stream.eof())
806 {
807 tokens.clear();
808 TokenizeNextLine(stream, tokens);
809
810 if (tokens.size() > 0)
811 {
812 header.clear();
813 header = tokens[0];
814
815 if (header.compare("newmtl")==0)
816 {
817 if (!first)
818 {
819 materials.push_back(currentMaterial);
820 currentMaterial = Material();
821 }
822 else
823 first = false;
824 //strcpy(currentMaterial.name, tokens[1].c_str());
825 currentMaterial.materialName=tokens[1];
826 }
827 else if (header.compare("Ka")==0)
828 {
829 float r = (float) atof(tokens[1].c_str());
830 float g = (float) atof(tokens[2].c_str());
831 float b = (float) atof(tokens[3].c_str());
832
833 currentMaterial.Ka = Point3f(r, g, b);
834 }
835 else if (header.compare("Kd")==0)
836 {
837 float r = (float) atof(tokens[1].c_str());
838 float g = (float) atof(tokens[2].c_str());
839 float b = (float) atof(tokens[3].c_str());
840
841 currentMaterial.Kd = Point3f(r, g, b);
842 }
843 else if (header.compare("Ks")==0)
844 {
845 float r = (float) atof(tokens[1].c_str());
846 float g = (float) atof(tokens[2].c_str());
847 float b = (float) atof(tokens[3].c_str());
848
849 currentMaterial.Ks = Point3f(r, g, b);
850 }
851 else if ( (header.compare("d")==0) ||
852 (header.compare("Tr")==0) ) // alpha
853 {
854 currentMaterial.Tr = (float) atof(tokens[1].c_str());
855 }
856 else if (header.compare("Ns")==0) // shininess
857 {
858 currentMaterial.Ns = atoi(tokens[1].c_str());
859 }
860 else if (header.compare("illum")==0) // specular illumination on/off
861 {
862 int illumination = atoi(tokens[1].c_str());
863 //currentMaterial.bSpecular = (illumination == 2);
864 currentMaterial.illum = illumination;
865 }
866 else if( (header.compare("map_Kd")==0) || (header.compare("map_Ka")==0) ) // texture name
867 {
868 std::string textureName = tokens[1];
869 //strcpy(currentMaterial.textureFileName, textureName.c_str());
870 currentMaterial.map_Kd=textureName;
871
872 // adding texture name into textures vector (if not already present)
873 // avoid adding the same name twice
874 bool found = false;
875 unsigned int size = static_cast<unsigned int>(textures.size());
876 unsigned j = 0;
877 while (!found && (j < size))
878 {
879 if (textureName.compare(textures[j])==0)
880 {
881 currentMaterial.index = (int)j;
882 found = true;
883 }
884 ++j;
885 }
886 if (!found)
887 {
888 textures.push_back(textureName);
889 currentMaterial.index = (int)size;
890 }
891 }
892 // we simply ignore other situations
893 }
894 }
895 materials.push_back(currentMaterial); // add last read material
896
897 stream.close();
898
899 return true;
900 }
901
902 }; // end class
903 } // end Namespace tri
904 } // end Namespace io
905 } // end Namespace vcg
906
907 #endif // ndef __VCGLIB_IMPORT_OBJ