1 //
2 // Copyright 2012-2015, Syoyo Fujita.
3 //
4 // Licensed under 2-clause BSD liecense.
5 //
6 
7 //
8 // version 0.9.14: Support specular highlight, bump, displacement and alpha map(#53)
9 // version 0.9.13: Report "Material file not found message" in `err`(#46)
10 // version 0.9.12: Fix groups being ignored if they have 'usemtl' just before 'g' (#44)
11 // version 0.9.11: Invert `Tr` parameter(#43)
12 // version 0.9.10: Fix seg fault on windows.
13 // version 0.9.9 : Replace atof() with custom parser.
14 // version 0.9.8 : Fix multi-materials(per-face material ID).
15 // version 0.9.7 : Support multi-materials(per-face material ID) per
16 // object/group.
17 // version 0.9.6 : Support Ni(index of refraction) mtl parameter.
18 //                 Parse transmittance material parameter correctly.
19 // version 0.9.5 : Parse multiple group name.
20 //                 Add support of specifying the base path to load material file.
21 // version 0.9.4 : Initial suupport of group tag(g)
22 // version 0.9.3 : Fix parsing triple 'x/y/z'
23 // version 0.9.2 : Add more .mtl load support
24 // version 0.9.1 : Add initial .mtl load support
25 // version 0.9.0 : Initial
26 //
27 
28 #include <cstdlib>
29 #include <cstring>
30 #include <cassert>
31 #include <cmath>
32 #include <cstddef>
33 #include <cctype>
34 
35 #include <string>
36 #include <vector>
37 #include <map>
38 #include <fstream>
39 #include <sstream>
40 
41 #include "tiny_obj_loader.h"
42 
43 namespace tinyobj {
44 
45 #define TINYOBJ_SSCANF_BUFFER_SIZE  (4096)
46 
47 struct vertex_index {
48   int v_idx, vt_idx, vn_idx;
vertex_indextinyobj::vertex_index49   vertex_index(){};
vertex_indextinyobj::vertex_index50   vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx){};
vertex_indextinyobj::vertex_index51   vertex_index(int vidx, int vtidx, int vnidx)
52       : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx){};
53 };
54 // for std::map
operator <(const vertex_index & a,const vertex_index & b)55 static inline bool operator<(const vertex_index &a, const vertex_index &b) {
56   if (a.v_idx != b.v_idx)
57     return (a.v_idx < b.v_idx);
58   if (a.vn_idx != b.vn_idx)
59     return (a.vn_idx < b.vn_idx);
60   if (a.vt_idx != b.vt_idx)
61     return (a.vt_idx < b.vt_idx);
62 
63   return false;
64 }
65 
66 struct obj_shape {
67   std::vector<float> v;
68   std::vector<float> vn;
69   std::vector<float> vt;
70 };
71 
isSpace(const char c)72 static inline bool isSpace(const char c) { return (c == ' ') || (c == '\t'); }
73 
isNewLine(const char c)74 static inline bool isNewLine(const char c) {
75   return (c == '\r') || (c == '\n') || (c == '\0');
76 }
77 
78 // Make index zero-base, and also support relative index.
fixIndex(int idx,int n)79 static inline int fixIndex(int idx, int n) {
80   if (idx > 0) return idx - 1;
81   if (idx == 0) return 0;
82   return n + idx; // negative value = relative
83 }
84 
parseString(const char * & token)85 static inline std::string parseString(const char *&token) {
86   std::string s;
87   token += strspn(token, " \t");
88   size_t e = strcspn(token, " \t\r");
89   s = std::string(token, &token[e]);
90   token += e;
91   return s;
92 }
93 
parseInt(const char * & token)94 static inline int parseInt(const char *&token) {
95   token += strspn(token, " \t");
96   int i = atoi(token);
97   token += strcspn(token, " \t\r");
98   return i;
99 }
100 
101 
102 // Tries to parse a floating point number located at s.
103 //
104 // s_end should be a location in the string where reading should absolutely
105 // stop. For example at the end of the string, to prevent buffer overflows.
106 //
107 // Parses the following EBNF grammar:
108 //   sign    = "+" | "-" ;
109 //   END     = ? anything not in digit ?
110 //   digit   = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
111 //   integer = [sign] , digit , {digit} ;
112 //   decimal = integer , ["." , integer] ;
113 //   float   = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ;
114 //
115 //  Valid strings are for example:
116 //   -0	 +3.1417e+2  -0.0E-3  1.0324  -1.41   11e2
117 //
118 // If the parsing is a success, result is set to the parsed value and true
119 // is returned.
120 //
121 // The function is greedy and will parse until any of the following happens:
122 //  - a non-conforming character is encountered.
123 //  - s_end is reached.
124 //
125 // The following situations triggers a failure:
126 //  - s >= s_end.
127 //  - parse failure.
128 //
tryParseDouble(const char * s,const char * s_end,double * result)129 static bool tryParseDouble(const char *s, const char *s_end, double *result)
130 {
131 	if (s >= s_end)
132 	{
133 		return false;
134 	}
135 
136 	double mantissa = 0.0;
137 	// This exponent is base 2 rather than 10.
138 	// However the exponent we parse is supposed to be one of ten,
139 	// thus we must take care to convert the exponent/and or the
140 	// mantissa to a * 2^E, where a is the mantissa and E is the
141 	// exponent.
142 	// To get the final double we will use ldexp, it requires the
143 	// exponent to be in base 2.
144 	int exponent = 0;
145 
146 	// NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED
147 	// TO JUMP OVER DEFINITIONS.
148 	char sign = '+';
149 	char exp_sign = '+';
150 	char const *curr = s;
151 
152 	// How many characters were read in a loop.
153 	int read = 0;
154 	// Tells whether a loop terminated due to reaching s_end.
155 	bool end_not_reached = false;
156 
157 	/*
158 		BEGIN PARSING.
159 	*/
160 
161 	// Find out what sign we've got.
162 	if (*curr == '+' || *curr == '-')
163 	{
164 		sign = *curr;
165 		curr++;
166 	}
167 	else if (isdigit(*curr)) { /* Pass through. */ }
168 	else
169 	{
170 		goto fail;
171 	}
172 
173 	// Read the integer part.
174 	while ((end_not_reached = (curr != s_end)) && isdigit(*curr))
175 	{
176 		mantissa *= 10;
177 		mantissa += static_cast<int>(*curr - 0x30);
178 		curr++;	read++;
179 	}
180 
181 	// We must make sure we actually got something.
182 	if (read == 0)
183 		goto fail;
184 	// We allow numbers of form "#", "###" etc.
185 	if (!end_not_reached)
186 		goto assemble;
187 
188 	// Read the decimal part.
189 	if (*curr == '.')
190 	{
191 		curr++;
192 		read = 1;
193 		while ((end_not_reached = (curr != s_end)) && isdigit(*curr))
194 		{
195 			// NOTE: Don't use powf here, it will absolutely murder precision.
196 			mantissa += static_cast<int>(*curr - 0x30) * pow(10.0, -read);
197 			read++; curr++;
198 		}
199 	}
200 	else if (*curr == 'e' || *curr == 'E') {}
201 	else
202 	{
203 		goto assemble;
204 	}
205 
206 	if (!end_not_reached)
207 		goto assemble;
208 
209 	// Read the exponent part.
210 	if (*curr == 'e' || *curr == 'E')
211 	{
212 		curr++;
213 		// Figure out if a sign is present and if it is.
214 		if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-'))
215 		{
216 			exp_sign = *curr;
217 			curr++;
218 		}
219 		else if (isdigit(*curr)) { /* Pass through. */ }
220 		else
221 		{
222 			// Empty E is not allowed.
223 			goto fail;
224 		}
225 
226 		read = 0;
227 		while ((end_not_reached = (curr != s_end)) && isdigit(*curr))
228 		{
229 			exponent *= 10;
230 			exponent += static_cast<int>(*curr - 0x30);
231 			curr++;	read++;
232 		}
233 		exponent *= (exp_sign == '+'? 1 : -1);
234 		if (read == 0)
235 			goto fail;
236 	}
237 
238 assemble:
239 	*result = (sign == '+'? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), exponent);
240 	return true;
241 fail:
242 	return false;
243 }
parseFloat(const char * & token)244 static inline float parseFloat(const char *&token) {
245   token += strspn(token, " \t");
246 #ifdef TINY_OBJ_LOADER_OLD_FLOAT_PARSER
247   float f = (float)atof(token);
248   token += strcspn(token, " \t\r");
249 #else
250   const char *end = token + strcspn(token, " \t\r");
251   double val = 0.0;
252   tryParseDouble(token, end, &val);
253   float f = static_cast<float>(val);
254   token = end;
255 #endif
256   return f;
257 }
258 
259 
parseFloat2(float & x,float & y,const char * & token)260 static inline void parseFloat2(float &x, float &y, const char *&token) {
261   x = parseFloat(token);
262   y = parseFloat(token);
263 }
264 
parseFloat3(float & x,float & y,float & z,const char * & token)265 static inline void parseFloat3(float &x, float &y, float &z,
266                                const char *&token) {
267   x = parseFloat(token);
268   y = parseFloat(token);
269   z = parseFloat(token);
270 }
271 
272 // Parse triples: i, i/j/k, i//k, i/j
parseTriple(const char * & token,int vsize,int vnsize,int vtsize)273 static vertex_index parseTriple(const char *&token, int vsize, int vnsize,
274                                 int vtsize) {
275   vertex_index vi(-1);
276 
277   vi.v_idx = fixIndex(atoi(token), vsize);
278   token += strcspn(token, "/ \t\r");
279   if (token[0] != '/') {
280     return vi;
281   }
282   token++;
283 
284   // i//k
285   if (token[0] == '/') {
286     token++;
287     vi.vn_idx = fixIndex(atoi(token), vnsize);
288     token += strcspn(token, "/ \t\r");
289     return vi;
290   }
291 
292   // i/j/k or i/j
293   vi.vt_idx = fixIndex(atoi(token), vtsize);
294   token += strcspn(token, "/ \t\r");
295   if (token[0] != '/') {
296     return vi;
297   }
298 
299   // i/j/k
300   token++; // skip '/'
301   vi.vn_idx = fixIndex(atoi(token), vnsize);
302   token += strcspn(token, "/ \t\r");
303   return vi;
304 }
305 
306 static unsigned int
updateVertex(std::map<vertex_index,unsigned int> & vertexCache,std::vector<float> & positions,std::vector<float> & normals,std::vector<float> & texcoords,const std::vector<float> & in_positions,const std::vector<float> & in_normals,const std::vector<float> & in_texcoords,const vertex_index & i)307 updateVertex(std::map<vertex_index, unsigned int> &vertexCache,
308              std::vector<float> &positions, std::vector<float> &normals,
309              std::vector<float> &texcoords,
310              const std::vector<float> &in_positions,
311              const std::vector<float> &in_normals,
312              const std::vector<float> &in_texcoords, const vertex_index &i) {
313   const std::map<vertex_index, unsigned int>::iterator it = vertexCache.find(i);
314 
315   if (it != vertexCache.end()) {
316     // found cache
317     return it->second;
318   }
319 
320   assert(in_positions.size() > (unsigned int)(3 * i.v_idx + 2));
321 
322   positions.push_back(in_positions[3 * i.v_idx + 0]);
323   positions.push_back(in_positions[3 * i.v_idx + 1]);
324   positions.push_back(in_positions[3 * i.v_idx + 2]);
325 
326   if (i.vn_idx >= 0) {
327     normals.push_back(in_normals[3 * i.vn_idx + 0]);
328     normals.push_back(in_normals[3 * i.vn_idx + 1]);
329     normals.push_back(in_normals[3 * i.vn_idx + 2]);
330   }
331 
332   if (i.vt_idx >= 0) {
333     texcoords.push_back(in_texcoords[2 * i.vt_idx + 0]);
334     texcoords.push_back(in_texcoords[2 * i.vt_idx + 1]);
335   }
336 
337   unsigned int idx = static_cast<unsigned int>(positions.size() / 3 - 1);
338   vertexCache[i] = idx;
339 
340   return idx;
341 }
342 
InitMaterial(material_t & material)343 void InitMaterial(material_t &material) {
344   material.name = "";
345   material.ambient_texname = "";
346   material.diffuse_texname = "";
347   material.specular_texname = "";
348   material.specular_highlight_texname = "";
349   material.bump_texname = "";
350   material.displacement_texname = "";
351   material.alpha_texname = "";
352   for (int i = 0; i < 3; i++) {
353     material.ambient[i] = 0.f;
354     material.diffuse[i] = 0.f;
355     material.specular[i] = 0.f;
356     material.transmittance[i] = 0.f;
357     material.emission[i] = 0.f;
358   }
359   material.illum = 0;
360   material.dissolve = 1.f;
361   material.shininess = 1.f;
362   material.ior = 1.f;
363   material.unknown_parameter.clear();
364 }
365 
exportFaceGroupToShape(shape_t & shape,std::map<vertex_index,unsigned int> vertexCache,const std::vector<float> & in_positions,const std::vector<float> & in_normals,const std::vector<float> & in_texcoords,const std::vector<std::vector<vertex_index>> & faceGroup,const int material_id,const std::string & name,bool clearCache)366 static bool exportFaceGroupToShape(
367     shape_t &shape, std::map<vertex_index, unsigned int> vertexCache,
368     const std::vector<float> &in_positions,
369     const std::vector<float> &in_normals,
370     const std::vector<float> &in_texcoords,
371     const std::vector<std::vector<vertex_index> > &faceGroup,
372     const int material_id, const std::string &name, bool clearCache) {
373   if (faceGroup.empty()) {
374     return false;
375   }
376 
377   // Flatten vertices and indices
378   for (size_t i = 0; i < faceGroup.size(); i++) {
379     const std::vector<vertex_index> &face = faceGroup[i];
380 
381     vertex_index i0 = face[0];
382     vertex_index i1(-1);
383     vertex_index i2 = face[1];
384 
385     size_t npolys = face.size();
386 
387     // Polygon -> triangle fan conversion
388     for (size_t k = 2; k < npolys; k++) {
389       i1 = i2;
390       i2 = face[k];
391 
392       unsigned int v0 = updateVertex(
393           vertexCache, shape.mesh.positions, shape.mesh.normals,
394           shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i0);
395       unsigned int v1 = updateVertex(
396           vertexCache, shape.mesh.positions, shape.mesh.normals,
397           shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i1);
398       unsigned int v2 = updateVertex(
399           vertexCache, shape.mesh.positions, shape.mesh.normals,
400           shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i2);
401 
402       shape.mesh.indices.push_back(v0);
403       shape.mesh.indices.push_back(v1);
404       shape.mesh.indices.push_back(v2);
405 
406       shape.mesh.material_ids.push_back(material_id);
407     }
408   }
409 
410   shape.name = name;
411 
412   if (clearCache)
413     vertexCache.clear();
414 
415   return true;
416 }
417 
LoadMtl(std::map<std::string,int> & material_map,std::vector<material_t> & materials,std::istream & inStream)418 std::string LoadMtl(std::map<std::string, int> &material_map,
419                     std::vector<material_t> &materials,
420                     std::istream &inStream) {
421   std::stringstream err;
422 
423   // Create a default material anyway.
424   material_t material;
425   InitMaterial(material);
426 
427   int maxchars = 8192;             // Alloc enough size.
428   std::vector<char> buf(maxchars); // Alloc enough size.
429   while (inStream.peek() != -1) {
430     inStream.getline(&buf[0], maxchars);
431 
432     std::string linebuf(&buf[0]);
433 
434     // Trim newline '\r\n' or '\n'
435     if (linebuf.size() > 0) {
436       if (linebuf[linebuf.size() - 1] == '\n')
437         linebuf.erase(linebuf.size() - 1);
438     }
439     if (linebuf.size() > 0) {
440       if (linebuf[linebuf.size() - 1] == '\r')
441         linebuf.erase(linebuf.size() - 1);
442     }
443 
444     // Skip if empty line.
445     if (linebuf.empty()) {
446       continue;
447     }
448 
449     // Skip leading space.
450     const char *token = linebuf.c_str();
451     token += strspn(token, " \t");
452 
453     assert(token);
454     if (token[0] == '\0')
455       continue; // empty line
456 
457     if (token[0] == '#')
458       continue; // comment line
459 
460     // new mtl
461     if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) {
462       // flush previous material.
463       if (!material.name.empty()) {
464         material_map.insert(
465             std::pair<std::string, int>(material.name, static_cast<int>(materials.size())));
466         materials.push_back(material);
467       }
468 
469       // initial temporary material
470       InitMaterial(material);
471 
472       // set new mtl name
473       char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE];
474       token += 7;
475 #ifdef _MSC_VER
476       sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf));
477 #else
478       sscanf(token, "%s", namebuf);
479 #endif
480       material.name = namebuf;
481       continue;
482     }
483 
484     // ambient
485     if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) {
486       token += 2;
487       float r, g, b;
488       parseFloat3(r, g, b, token);
489       material.ambient[0] = r;
490       material.ambient[1] = g;
491       material.ambient[2] = b;
492       continue;
493     }
494 
495     // diffuse
496     if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) {
497       token += 2;
498       float r, g, b;
499       parseFloat3(r, g, b, token);
500       material.diffuse[0] = r;
501       material.diffuse[1] = g;
502       material.diffuse[2] = b;
503       continue;
504     }
505 
506     // specular
507     if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) {
508       token += 2;
509       float r, g, b;
510       parseFloat3(r, g, b, token);
511       material.specular[0] = r;
512       material.specular[1] = g;
513       material.specular[2] = b;
514       continue;
515     }
516 
517     // transmittance
518     if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) {
519       token += 2;
520       float r, g, b;
521       parseFloat3(r, g, b, token);
522       material.transmittance[0] = r;
523       material.transmittance[1] = g;
524       material.transmittance[2] = b;
525       continue;
526     }
527 
528     // ior(index of refraction)
529     if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) {
530       token += 2;
531       material.ior = parseFloat(token);
532       continue;
533     }
534 
535     // emission
536     if (token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) {
537       token += 2;
538       float r, g, b;
539       parseFloat3(r, g, b, token);
540       material.emission[0] = r;
541       material.emission[1] = g;
542       material.emission[2] = b;
543       continue;
544     }
545 
546     // shininess
547     if (token[0] == 'N' && token[1] == 's' && isSpace(token[2])) {
548       token += 2;
549       material.shininess = parseFloat(token);
550       continue;
551     }
552 
553     // illum model
554     if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) {
555       token += 6;
556       material.illum = parseInt(token);
557       continue;
558     }
559 
560     // dissolve
561     if ((token[0] == 'd' && isSpace(token[1]))) {
562       token += 1;
563       material.dissolve = parseFloat(token);
564       continue;
565     }
566     if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) {
567       token += 2;
568       // Invert value of Tr(assume Tr is in range [0, 1])
569       material.dissolve = 1.0f - parseFloat(token);
570       continue;
571     }
572 
573     // ambient texture
574     if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) {
575       token += 7;
576       material.ambient_texname = token;
577       continue;
578     }
579 
580     // diffuse texture
581     if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) {
582       token += 7;
583       material.diffuse_texname = token;
584       continue;
585     }
586 
587     // specular texture
588     if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) {
589       token += 7;
590       material.specular_texname = token;
591       continue;
592     }
593 
594     // specular highlight texture
595     if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) {
596       token += 7;
597       material.specular_highlight_texname = token;
598       continue;
599     }
600 
601     // bump texture
602     if ((0 == strncmp(token, "map_bump", 8)) && isSpace(token[8])) {
603       token += 9;
604       material.bump_texname = token;
605       continue;
606     }
607 
608     // alpha texture
609     if ((0 == strncmp(token, "map_d", 5)) && isSpace(token[5])) {
610       token += 6;
611       material.alpha_texname = token;
612       continue;
613     }
614 
615     // bump texture
616     if ((0 == strncmp(token, "bump", 4)) && isSpace(token[4])) {
617       token += 5;
618       material.bump_texname = token;
619       continue;
620     }
621 
622     // displacement texture
623     if ((0 == strncmp(token, "disp", 4)) && isSpace(token[4])) {
624       token += 5;
625       material.displacement_texname = token;
626       continue;
627     }
628 
629     // unknown parameter
630     const char *_space = strchr(token, ' ');
631     if (!_space) {
632       _space = strchr(token, '\t');
633     }
634     if (_space) {
635       std::ptrdiff_t len = _space - token;
636       std::string key(token, len);
637       std::string value = _space + 1;
638       material.unknown_parameter.insert(
639           std::pair<std::string, std::string>(key, value));
640     }
641   }
642   // flush last material.
643   material_map.insert(
644       std::pair<std::string, int>(material.name, static_cast<int>(materials.size())));
645   materials.push_back(material);
646 
647   return err.str();
648 }
649 
operator ()(const std::string & matId,std::vector<material_t> & materials,std::map<std::string,int> & matMap)650 std::string MaterialFileReader::operator()(const std::string &matId,
651                                            std::vector<material_t> &materials,
652                                            std::map<std::string, int> &matMap) {
653   std::string filepath;
654 
655   if (!m_mtlBasePath.empty()) {
656     filepath = std::string(m_mtlBasePath) + matId;
657   } else {
658     filepath = matId;
659   }
660 
661   std::ifstream matIStream(filepath.c_str());
662   std::string err = LoadMtl(matMap, materials, matIStream);
663   if (!matIStream) {
664     std::stringstream ss;
665     ss << "WARN: Material file [ " << filepath << " ] not found. Created a default material.";
666     err += ss.str();
667   }
668   return err;
669 }
670 
LoadObj(std::vector<shape_t> & shapes,std::vector<material_t> & materials,const char * filename,const char * mtl_basepath)671 std::string LoadObj(std::vector<shape_t> &shapes,
672                     std::vector<material_t> &materials, // [output]
673                     const char *filename, const char *mtl_basepath) {
674 
675   shapes.clear();
676 
677   std::stringstream err;
678 
679   std::ifstream ifs(filename);
680   if (!ifs) {
681     err << "Cannot open file [" << filename << "]" << std::endl;
682     return err.str();
683   }
684 
685   std::string basePath;
686   if (mtl_basepath) {
687     basePath = mtl_basepath;
688   }
689   MaterialFileReader matFileReader(basePath);
690 
691   return LoadObj(shapes, materials, ifs, matFileReader);
692 }
693 
LoadObj(std::vector<shape_t> & shapes,std::vector<material_t> & materials,std::istream & inStream,MaterialReader & readMatFn)694 std::string LoadObj(std::vector<shape_t> &shapes,
695                     std::vector<material_t> &materials, // [output]
696                     std::istream &inStream, MaterialReader &readMatFn) {
697   std::stringstream err;
698 
699   std::vector<float> v;
700   std::vector<float> vn;
701   std::vector<float> vt;
702   std::vector<std::vector<vertex_index> > faceGroup;
703   std::string name;
704 
705   // material
706   std::map<std::string, int> material_map;
707   std::map<vertex_index, unsigned int> vertexCache;
708   int material = -1;
709 
710   shape_t shape;
711 
712   int maxchars = 8192;             // Alloc enough size.
713   std::vector<char> buf(maxchars); // Alloc enough size.
714   while (inStream.peek() != -1) {
715     inStream.getline(&buf[0], maxchars);
716 
717     std::string linebuf(&buf[0]);
718 
719     // Trim newline '\r\n' or '\n'
720     if (linebuf.size() > 0) {
721       if (linebuf[linebuf.size() - 1] == '\n')
722         linebuf.erase(linebuf.size() - 1);
723     }
724     if (linebuf.size() > 0) {
725       if (linebuf[linebuf.size() - 1] == '\r')
726         linebuf.erase(linebuf.size() - 1);
727     }
728 
729     // Skip if empty line.
730     if (linebuf.empty()) {
731       continue;
732     }
733 
734     // Skip leading space.
735     const char *token = linebuf.c_str();
736     token += strspn(token, " \t");
737 
738     assert(token);
739     if (token[0] == '\0')
740       continue; // empty line
741 
742     if (token[0] == '#')
743       continue; // comment line
744 
745     // vertex
746     if (token[0] == 'v' && isSpace((token[1]))) {
747       token += 2;
748       float x, y, z;
749       parseFloat3(x, y, z, token);
750       v.push_back(x);
751       v.push_back(y);
752       v.push_back(z);
753       continue;
754     }
755 
756     // normal
757     if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) {
758       token += 3;
759       float x, y, z;
760       parseFloat3(x, y, z, token);
761       vn.push_back(x);
762       vn.push_back(y);
763       vn.push_back(z);
764       continue;
765     }
766 
767     // texcoord
768     if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) {
769       token += 3;
770       float x, y;
771       parseFloat2(x, y, token);
772       vt.push_back(x);
773       vt.push_back(y);
774       continue;
775     }
776 
777     // face
778     if (token[0] == 'f' && isSpace((token[1]))) {
779       token += 2;
780       token += strspn(token, " \t");
781 
782       std::vector<vertex_index> face;
783       while (!isNewLine(token[0])) {
784         vertex_index vi =
785             parseTriple(token, static_cast<int>(v.size() / 3), static_cast<int>(vn.size() / 3), static_cast<int>(vt.size() / 2));
786         face.push_back(vi);
787         size_t n = strspn(token, " \t\r");
788         token += n;
789       }
790 
791       faceGroup.push_back(face);
792 
793       continue;
794     }
795 
796     // use mtl
797     if ((0 == strncmp(token, "usemtl", 6)) && isSpace((token[6]))) {
798 
799       char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE];
800       token += 7;
801 #ifdef _MSC_VER
802       sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf));
803 #else
804       sscanf(token, "%s", namebuf);
805 #endif
806 
807       // Create face group per material.
808       bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt,
809                                         faceGroup, material, name, true);
810       if (ret) {
811           shapes.push_back(shape);
812       }
813       shape = shape_t();
814       faceGroup.clear();
815 
816       if (material_map.find(namebuf) != material_map.end()) {
817         material = material_map[namebuf];
818       } else {
819         // { error!! material not found }
820         material = -1;
821       }
822 
823       continue;
824     }
825 
826     // load mtl
827     if ((0 == strncmp(token, "mtllib", 6)) && isSpace((token[6]))) {
828       char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE];
829       token += 7;
830 #ifdef _MSC_VER
831       sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf));
832 #else
833       sscanf(token, "%s", namebuf);
834 #endif
835 
836       std::string err_mtl = readMatFn(namebuf, materials, material_map);
837       if (!err_mtl.empty()) {
838         faceGroup.clear(); // for safety
839         return err_mtl;
840       }
841 
842       continue;
843     }
844 
845     // group name
846     if (token[0] == 'g' && isSpace((token[1]))) {
847 
848       // flush previous face group.
849       bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt,
850                                         faceGroup, material, name, true);
851       if (ret) {
852         shapes.push_back(shape);
853       }
854 
855       shape = shape_t();
856 
857       // material = -1;
858       faceGroup.clear();
859 
860       std::vector<std::string> names;
861       while (!isNewLine(token[0])) {
862         std::string str = parseString(token);
863         names.push_back(str);
864         token += strspn(token, " \t\r"); // skip tag
865       }
866 
867       assert(names.size() > 0);
868 
869       // names[0] must be 'g', so skip the 0th element.
870       if (names.size() > 1) {
871         name = names[1];
872       } else {
873         name = "";
874       }
875 
876       continue;
877     }
878 
879     // object name
880     if (token[0] == 'o' && isSpace((token[1]))) {
881 
882       // flush previous face group.
883       bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt,
884                                         faceGroup, material, name, true);
885       if (ret) {
886         shapes.push_back(shape);
887       }
888 
889       // material = -1;
890       faceGroup.clear();
891       shape = shape_t();
892 
893       // @todo { multiple object name? }
894       char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE];
895       token += 2;
896 #ifdef _MSC_VER
897       sscanf_s(token, "%s", namebuf, (unsigned)_countof(namebuf));
898 #else
899       sscanf(token, "%s", namebuf);
900 #endif
901       name = std::string(namebuf);
902 
903       continue;
904     }
905 
906     // Ignore unknown command.
907   }
908 
909   bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup,
910                                     material, name, true);
911   if (ret) {
912     shapes.push_back(shape);
913   }
914   faceGroup.clear(); // for safety
915 
916   return err.str();
917 }
918 }
919