-
-
Notifications
You must be signed in to change notification settings - Fork 612
/
tiny_obj_loader.h
3499 lines (2962 loc) · 105 KB
/
tiny_obj_loader.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
The MIT License (MIT)
Copyright (c) 2012-Present, Syoyo Fujita and many contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//
// version 2.0.0 : Add new object oriented API. 1.x API is still provided.
// * Add python binding.
// * Support line primitive.
// * Support points primitive.
// * Support multiple search path for .mtl(v1 API).
// * Support vertex skinning weight `vw`(as an tinyobj
// extension). Note that this differs vertex weight([w]
// component in `v` line)
// * Support escaped whitespece in mtllib
// * Add robust triangulation using Mapbox
// earcut(TINYOBJLOADER_USE_MAPBOX_EARCUT).
// version 1.4.0 : Modifed ParseTextureNameAndOption API
// version 1.3.1 : Make ParseTextureNameAndOption API public
// version 1.3.0 : Separate warning and error message(breaking API of LoadObj)
// version 1.2.3 : Added color space extension('-colorspace') to tex opts.
// version 1.2.2 : Parse multiple group names.
// version 1.2.1 : Added initial support for line('l') primitive(PR #178)
// version 1.2.0 : Hardened implementation(#175)
// version 1.1.1 : Support smoothing groups(#162)
// version 1.1.0 : Support parsing vertex color(#144)
// version 1.0.8 : Fix parsing `g` tag just after `usemtl`(#138)
// version 1.0.7 : Support multiple tex options(#126)
// version 1.0.6 : Add TINYOBJLOADER_USE_DOUBLE option(#124)
// version 1.0.5 : Ignore `Tr` when `d` exists in MTL(#43)
// version 1.0.4 : Support multiple filenames for 'mtllib'(#112)
// version 1.0.3 : Support parsing texture options(#85)
// version 1.0.2 : Improve parsing speed by about a factor of 2 for large
// files(#105)
// version 1.0.1 : Fixes a shape is lost if obj ends with a 'usemtl'(#104)
// version 1.0.0 : Change data structure. Change license from BSD to MIT.
//
//
// Use this in *one* .cc
// #define TINYOBJLOADER_IMPLEMENTATION
// #include "tiny_obj_loader.h"
//
#ifndef TINY_OBJ_LOADER_H_
#define TINY_OBJ_LOADER_H_
#include <map>
#include <string>
#include <vector>
namespace tinyobj {
// TODO(syoyo): Better C++11 detection for older compiler
#if __cplusplus > 199711L
#define TINYOBJ_OVERRIDE override
#else
#define TINYOBJ_OVERRIDE
#endif
#ifdef __clang__
#pragma clang diagnostic push
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
#endif
#pragma clang diagnostic ignored "-Wpadded"
#endif
// https://en.wikipedia.org/wiki/Wavefront_.obj_file says ...
//
// -blendu on | off # set horizontal texture blending
// (default on)
// -blendv on | off # set vertical texture blending
// (default on)
// -boost real_value # boost mip-map sharpness
// -mm base_value gain_value # modify texture map values (default
// 0 1)
// # base_value = brightness,
// gain_value = contrast
// -o u [v [w]] # Origin offset (default
// 0 0 0)
// -s u [v [w]] # Scale (default
// 1 1 1)
// -t u [v [w]] # Turbulence (default
// 0 0 0)
// -texres resolution # texture resolution to create
// -clamp on | off # only render texels in the clamped
// 0-1 range (default off)
// # When unclamped, textures are
// repeated across a surface,
// # when clamped, only texels which
// fall within the 0-1
// # range are rendered.
// -bm mult_value # bump multiplier (for bump maps
// only)
//
// -imfchan r | g | b | m | l | z # specifies which channel of the file
// is used to
// # create a scalar or bump texture.
// r:red, g:green,
// # b:blue, m:matte, l:luminance,
// z:z-depth..
// # (the default for bump is 'l' and
// for decal is 'm')
// bump -imfchan r bumpmap.tga # says to use the red channel of
// bumpmap.tga as the bumpmap
//
// For reflection maps...
//
// -type sphere # specifies a sphere for a "refl"
// reflection map
// -type cube_top | cube_bottom | # when using a cube map, the texture
// file for each
// cube_front | cube_back | # side of the cube is specified
// separately
// cube_left | cube_right
//
// TinyObjLoader extension.
//
// -colorspace SPACE # Color space of the texture. e.g.
// 'sRGB` or 'linear'
//
#ifdef TINYOBJLOADER_USE_DOUBLE
//#pragma message "using double"
typedef double real_t;
#else
//#pragma message "using float"
typedef float real_t;
#endif
typedef enum {
TEXTURE_TYPE_NONE, // default
TEXTURE_TYPE_SPHERE,
TEXTURE_TYPE_CUBE_TOP,
TEXTURE_TYPE_CUBE_BOTTOM,
TEXTURE_TYPE_CUBE_FRONT,
TEXTURE_TYPE_CUBE_BACK,
TEXTURE_TYPE_CUBE_LEFT,
TEXTURE_TYPE_CUBE_RIGHT
} texture_type_t;
struct texture_option_t {
texture_type_t type; // -type (default TEXTURE_TYPE_NONE)
real_t sharpness; // -boost (default 1.0?)
real_t brightness; // base_value in -mm option (default 0)
real_t contrast; // gain_value in -mm option (default 1)
real_t origin_offset[3]; // -o u [v [w]] (default 0 0 0)
real_t scale[3]; // -s u [v [w]] (default 1 1 1)
real_t turbulence[3]; // -t u [v [w]] (default 0 0 0)
int texture_resolution; // -texres resolution (No default value in the spec.
// We'll use -1)
bool clamp; // -clamp (default false)
char imfchan; // -imfchan (the default for bump is 'l' and for decal is 'm')
bool blendu; // -blendu (default on)
bool blendv; // -blendv (default on)
real_t bump_multiplier; // -bm (for bump maps only, default 1.0)
// extension
std::string colorspace; // Explicitly specify color space of stored texel
// value. Usually `sRGB` or `linear` (default empty).
};
struct material_t {
std::string name;
real_t ambient[3];
real_t diffuse[3];
real_t specular[3];
real_t transmittance[3];
real_t emission[3];
real_t shininess;
real_t ior; // index of refraction
real_t dissolve; // 1 == opaque; 0 == fully transparent
// illumination model (see http://www.fileformat.info/format/material/)
int illum;
int dummy; // Suppress padding warning.
std::string ambient_texname; // map_Ka. For ambient or ambient occlusion.
std::string diffuse_texname; // map_Kd
std::string specular_texname; // map_Ks
std::string specular_highlight_texname; // map_Ns
std::string bump_texname; // map_bump, map_Bump, bump
std::string displacement_texname; // disp
std::string alpha_texname; // map_d
std::string reflection_texname; // refl
texture_option_t ambient_texopt;
texture_option_t diffuse_texopt;
texture_option_t specular_texopt;
texture_option_t specular_highlight_texopt;
texture_option_t bump_texopt;
texture_option_t displacement_texopt;
texture_option_t alpha_texopt;
texture_option_t reflection_texopt;
// PBR extension
// http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr
real_t roughness; // [0, 1] default 0
real_t metallic; // [0, 1] default 0
real_t sheen; // [0, 1] default 0
real_t clearcoat_thickness; // [0, 1] default 0
real_t clearcoat_roughness; // [0, 1] default 0
real_t anisotropy; // aniso. [0, 1] default 0
real_t anisotropy_rotation; // anisor. [0, 1] default 0
real_t pad0;
std::string roughness_texname; // map_Pr
std::string metallic_texname; // map_Pm
std::string sheen_texname; // map_Ps
std::string emissive_texname; // map_Ke
std::string normal_texname; // norm. For normal mapping.
texture_option_t roughness_texopt;
texture_option_t metallic_texopt;
texture_option_t sheen_texopt;
texture_option_t emissive_texopt;
texture_option_t normal_texopt;
int pad2;
std::map<std::string, std::string> unknown_parameter;
#ifdef TINY_OBJ_LOADER_PYTHON_BINDING
// For pybind11
std::array<double, 3> GetDiffuse() {
std::array<double, 3> values;
values[0] = double(diffuse[0]);
values[1] = double(diffuse[1]);
values[2] = double(diffuse[2]);
return values;
}
std::array<double, 3> GetSpecular() {
std::array<double, 3> values;
values[0] = double(specular[0]);
values[1] = double(specular[1]);
values[2] = double(specular[2]);
return values;
}
std::array<double, 3> GetTransmittance() {
std::array<double, 3> values;
values[0] = double(transmittance[0]);
values[1] = double(transmittance[1]);
values[2] = double(transmittance[2]);
return values;
}
std::array<double, 3> GetEmission() {
std::array<double, 3> values;
values[0] = double(emission[0]);
values[1] = double(emission[1]);
values[2] = double(emission[2]);
return values;
}
std::array<double, 3> GetAmbient() {
std::array<double, 3> values;
values[0] = double(ambient[0]);
values[1] = double(ambient[1]);
values[2] = double(ambient[2]);
return values;
}
void SetDiffuse(std::array<double, 3> &a) {
diffuse[0] = real_t(a[0]);
diffuse[1] = real_t(a[1]);
diffuse[2] = real_t(a[2]);
}
void SetAmbient(std::array<double, 3> &a) {
ambient[0] = real_t(a[0]);
ambient[1] = real_t(a[1]);
ambient[2] = real_t(a[2]);
}
void SetSpecular(std::array<double, 3> &a) {
specular[0] = real_t(a[0]);
specular[1] = real_t(a[1]);
specular[2] = real_t(a[2]);
}
void SetTransmittance(std::array<double, 3> &a) {
transmittance[0] = real_t(a[0]);
transmittance[1] = real_t(a[1]);
transmittance[2] = real_t(a[2]);
}
std::string GetCustomParameter(const std::string &key) {
std::map<std::string, std::string>::const_iterator it =
unknown_parameter.find(key);
if (it != unknown_parameter.end()) {
return it->second;
}
return std::string();
}
#endif
};
struct tag_t {
std::string name;
std::vector<int> intValues;
std::vector<real_t> floatValues;
std::vector<std::string> stringValues;
};
struct joint_and_weight_t {
int joint_id;
real_t weight;
};
struct skin_weight_t {
int vertex_id; // Corresponding vertex index in `attrib_t::vertices`.
// Compared to `index_t`, this index must be positive and
// start with 0(does not allow relative indexing)
std::vector<joint_and_weight_t> weightValues;
};
// Index struct to support different indices for vtx/normal/texcoord.
// -1 means not used.
struct index_t {
int vertex_index;
int normal_index;
int texcoord_index;
};
struct mesh_t {
std::vector<index_t> indices;
std::vector<unsigned int>
num_face_vertices; // The number of vertices per
// face. 3 = triangle, 4 = quad, ...
std::vector<int> material_ids; // per-face material ID
std::vector<unsigned int> smoothing_group_ids; // per-face smoothing group
// ID(0 = off. positive value
// = group id)
std::vector<tag_t> tags; // SubD tag
};
// struct path_t {
// std::vector<int> indices; // pairs of indices for lines
//};
struct lines_t {
// Linear flattened indices.
std::vector<index_t> indices; // indices for vertices(poly lines)
std::vector<int> num_line_vertices; // The number of vertices per line.
};
struct points_t {
std::vector<index_t> indices; // indices for points
};
struct shape_t {
std::string name;
mesh_t mesh;
lines_t lines;
points_t points;
};
// Vertex attributes
struct attrib_t {
std::vector<real_t> vertices; // 'v'(xyz)
// For backward compatibility, we store vertex weight in separate array.
std::vector<real_t> vertex_weights; // 'v'(w)
std::vector<real_t> normals; // 'vn'
std::vector<real_t> texcoords; // 'vt'(uv)
// For backward compatibility, we store texture coordinate 'w' in separate
// array.
std::vector<real_t> texcoord_ws; // 'vt'(w)
std::vector<real_t> colors; // extension: vertex colors
//
// TinyObj extension.
//
// NOTE(syoyo): array index is based on the appearance order.
// To get a corresponding skin weight for a specific vertex id `vid`,
// Need to reconstruct a look up table: `skin_weight_t::vertex_id` == `vid`
// (e.g. using std::map, std::unordered_map)
std::vector<skin_weight_t> skin_weights;
attrib_t() {}
//
// For pybind11
//
const std::vector<real_t> &GetVertices() const { return vertices; }
const std::vector<real_t> &GetVertexWeights() const { return vertex_weights; }
};
struct callback_t {
// W is optional and set to 1 if there is no `w` item in `v` line
void (*vertex_cb)(void *user_data, real_t x, real_t y, real_t z, real_t w);
void (*vertex_color_cb)(void *user_data, real_t x, real_t y, real_t z,
real_t r, real_t g, real_t b, bool has_color);
void (*normal_cb)(void *user_data, real_t x, real_t y, real_t z);
// y and z are optional and set to 0 if there is no `y` and/or `z` item(s) in
// `vt` line.
void (*texcoord_cb)(void *user_data, real_t x, real_t y, real_t z);
// called per 'f' line. num_indices is the number of face indices(e.g. 3 for
// triangle, 4 for quad)
// 0 will be passed for undefined index in index_t members.
void (*index_cb)(void *user_data, index_t *indices, int num_indices);
// `name` material name, `material_id` = the array index of material_t[]. -1
// if
// a material not found in .mtl
void (*usemtl_cb)(void *user_data, const char *name, int material_id);
// `materials` = parsed material data.
void (*mtllib_cb)(void *user_data, const material_t *materials,
int num_materials);
// There may be multiple group names
void (*group_cb)(void *user_data, const char **names, int num_names);
void (*object_cb)(void *user_data, const char *name);
callback_t()
: vertex_cb(NULL),
vertex_color_cb(NULL),
normal_cb(NULL),
texcoord_cb(NULL),
index_cb(NULL),
usemtl_cb(NULL),
mtllib_cb(NULL),
group_cb(NULL),
object_cb(NULL) {}
};
class MaterialReader {
public:
MaterialReader() {}
virtual ~MaterialReader();
virtual bool operator()(const std::string &matId,
std::vector<material_t> *materials,
std::map<std::string, int> *matMap, std::string *warn,
std::string *err) = 0;
};
///
/// Read .mtl from a file.
///
class MaterialFileReader : public MaterialReader {
public:
// Path could contain separator(';' in Windows, ':' in Posix)
explicit MaterialFileReader(const std::string &mtl_basedir)
: m_mtlBaseDir(mtl_basedir) {}
virtual ~MaterialFileReader() TINYOBJ_OVERRIDE {}
virtual bool operator()(const std::string &matId,
std::vector<material_t> *materials,
std::map<std::string, int> *matMap, std::string *warn,
std::string *err) TINYOBJ_OVERRIDE;
private:
std::string m_mtlBaseDir;
};
///
/// Read .mtl from a stream.
///
class MaterialStreamReader : public MaterialReader {
public:
explicit MaterialStreamReader(std::istream &inStream)
: m_inStream(inStream) {}
virtual ~MaterialStreamReader() TINYOBJ_OVERRIDE {}
virtual bool operator()(const std::string &matId,
std::vector<material_t> *materials,
std::map<std::string, int> *matMap, std::string *warn,
std::string *err) TINYOBJ_OVERRIDE;
private:
std::istream &m_inStream;
};
// v2 API
struct ObjReaderConfig {
bool triangulate; // triangulate polygon?
// Currently not used.
// "simple" or empty: Create triangle fan
// "earcut": Use the algorithm based on Ear clipping
std::string triangulation_method;
/// Parse vertex color.
/// If vertex color is not present, its filled with default value.
/// false = no vertex color
/// This will increase memory of parsed .obj
bool vertex_color;
///
/// Search path to .mtl file.
/// Default = "" = search from the same directory of .obj file.
/// Valid only when loading .obj from a file.
///
std::string mtl_search_path;
ObjReaderConfig()
: triangulate(true), triangulation_method("simple"), vertex_color(true) {}
};
///
/// Wavefront .obj reader class(v2 API)
///
class ObjReader {
public:
ObjReader() : valid_(false) {}
///
/// Load .obj and .mtl from a file.
///
/// @param[in] filename wavefront .obj filename
/// @param[in] config Reader configuration
///
bool ParseFromFile(const std::string &filename,
const ObjReaderConfig &config = ObjReaderConfig());
///
/// Parse .obj from a text string.
/// Need to supply .mtl text string by `mtl_text`.
/// This function ignores `mtllib` line in .obj text.
///
/// @param[in] obj_text wavefront .obj filename
/// @param[in] mtl_text wavefront .mtl filename
/// @param[in] config Reader configuration
///
bool ParseFromString(const std::string &obj_text, const std::string &mtl_text,
const ObjReaderConfig &config = ObjReaderConfig());
///
/// .obj was loaded or parsed correctly.
///
bool Valid() const { return valid_; }
const attrib_t &GetAttrib() const { return attrib_; }
const std::vector<shape_t> &GetShapes() const { return shapes_; }
const std::vector<material_t> &GetMaterials() const { return materials_; }
///
/// Warning message(may be filled after `Load` or `Parse`)
///
const std::string &Warning() const { return warning_; }
///
/// Error message(filled when `Load` or `Parse` failed)
///
const std::string &Error() const { return error_; }
private:
bool valid_;
attrib_t attrib_;
std::vector<shape_t> shapes_;
std::vector<material_t> materials_;
std::string warning_;
std::string error_;
};
/// ==>>========= Legacy v1 API =============================================
/// Loads .obj from a file.
/// 'attrib', 'shapes' and 'materials' will be filled with parsed shape data
/// 'shapes' will be filled with parsed shape data
/// Returns true when loading .obj become success.
/// Returns warning message into `warn`, and error message into `err`
/// 'mtl_basedir' is optional, and used for base directory for .mtl file.
/// In default(`NULL'), .mtl file is searched from an application's working
/// directory.
/// 'triangulate' is optional, and used whether triangulate polygon face in .obj
/// or not.
/// Option 'default_vcols_fallback' specifies whether vertex colors should
/// always be defined, even if no colors are given (fallback to white).
bool LoadObj(attrib_t *attrib, std::vector<shape_t> *shapes,
std::vector<material_t> *materials, std::string *warn,
std::string *err, const char *filename,
const char *mtl_basedir = NULL, bool triangulate = true,
bool default_vcols_fallback = true);
/// Loads .obj from a file with custom user callback.
/// .mtl is loaded as usual and parsed material_t data will be passed to
/// `callback.mtllib_cb`.
/// Returns true when loading .obj/.mtl become success.
/// Returns warning message into `warn`, and error message into `err`
/// See `examples/callback_api/` for how to use this function.
bool LoadObjWithCallback(std::istream &inStream, const callback_t &callback,
void *user_data = NULL,
MaterialReader *readMatFn = NULL,
std::string *warn = NULL, std::string *err = NULL);
/// Loads object from a std::istream, uses `readMatFn` to retrieve
/// std::istream for materials.
/// Returns true when loading .obj become success.
/// Returns warning and error message into `err`
bool LoadObj(attrib_t *attrib, std::vector<shape_t> *shapes,
std::vector<material_t> *materials, std::string *warn,
std::string *err, std::istream *inStream,
MaterialReader *readMatFn = NULL, bool triangulate = true,
bool default_vcols_fallback = true);
/// Loads materials into std::map
void LoadMtl(std::map<std::string, int> *material_map,
std::vector<material_t> *materials, std::istream *inStream,
std::string *warning, std::string *err);
///
/// Parse texture name and texture option for custom texture parameter through
/// material::unknown_parameter
///
/// @param[out] texname Parsed texture name
/// @param[out] texopt Parsed texopt
/// @param[in] linebuf Input string
///
bool ParseTextureNameAndOption(std::string *texname, texture_option_t *texopt,
const char *linebuf);
/// =<<========== Legacy v1 API =============================================
} // namespace tinyobj
#endif // TINY_OBJ_LOADER_H_
#ifdef TINYOBJLOADER_IMPLEMENTATION
#include <cassert>
#include <cctype>
#include <cmath>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <limits>
#include <set>
#include <sstream>
#include <utility>
#ifdef TINYOBJLOADER_USE_MAPBOX_EARCUT
#ifdef TINYOBJLOADER_DONOT_INCLUDE_MAPBOX_EARCUT
// Assume earcut.hpp is included outside of tiny_obj_loader.h
#else
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Weverything"
#endif
#include <array>
#include "mapbox/earcut.hpp"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
#endif // TINYOBJLOADER_USE_MAPBOX_EARCUT
namespace tinyobj {
MaterialReader::~MaterialReader() {}
struct vertex_index_t {
int v_idx, vt_idx, vn_idx;
vertex_index_t() : v_idx(-1), vt_idx(-1), vn_idx(-1) {}
explicit vertex_index_t(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {}
vertex_index_t(int vidx, int vtidx, int vnidx)
: v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {}
};
// Internal data structure for face representation
// index + smoothing group.
struct face_t {
unsigned int
smoothing_group_id; // smoothing group id. 0 = smoothing groupd is off.
int pad_;
std::vector<vertex_index_t> vertex_indices; // face vertex indices.
face_t() : smoothing_group_id(0), pad_(0) {}
};
// Internal data structure for line representation
struct __line_t {
// l v1/vt1 v2/vt2 ...
// In the specification, line primitrive does not have normal index, but
// TinyObjLoader allow it
std::vector<vertex_index_t> vertex_indices;
};
// Internal data structure for points representation
struct __points_t {
// p v1 v2 ...
// In the specification, point primitrive does not have normal index and
// texture coord index, but TinyObjLoader allow it.
std::vector<vertex_index_t> vertex_indices;
};
struct tag_sizes {
tag_sizes() : num_ints(0), num_reals(0), num_strings(0) {}
int num_ints;
int num_reals;
int num_strings;
};
struct obj_shape {
std::vector<real_t> v;
std::vector<real_t> vn;
std::vector<real_t> vt;
};
//
// Manages group of primitives(face, line, points, ...)
struct PrimGroup {
std::vector<face_t> faceGroup;
std::vector<__line_t> lineGroup;
std::vector<__points_t> pointsGroup;
void clear() {
faceGroup.clear();
lineGroup.clear();
pointsGroup.clear();
}
bool IsEmpty() const {
return faceGroup.empty() && lineGroup.empty() && pointsGroup.empty();
}
// TODO(syoyo): bspline, surface, ...
};
// See
// http://stackoverflow.com/questions/6089231/getting-std-ifstream-to-handle-lf-cr-and-crlf
static std::istream &safeGetline(std::istream &is, std::string &t) {
t.clear();
// The characters in the stream are read one-by-one using a std::streambuf.
// That is faster than reading them one-by-one using the std::istream.
// Code that uses streambuf this way must be guarded by a sentry object.
// The sentry object performs various tasks,
// such as thread synchronization and updating the stream state.
std::istream::sentry se(is, true);
std::streambuf *sb = is.rdbuf();
if (se) {
for (;;) {
int c = sb->sbumpc();
switch (c) {
case '\n':
return is;
case '\r':
if (sb->sgetc() == '\n') sb->sbumpc();
return is;
case EOF:
// Also handle the case when the last line has no line ending
if (t.empty()) is.setstate(std::ios::eofbit);
return is;
default:
t += static_cast<char>(c);
}
}
}
return is;
}
#define IS_SPACE(x) (((x) == ' ') || ((x) == '\t'))
#define IS_DIGIT(x) \
(static_cast<unsigned int>((x) - '0') < static_cast<unsigned int>(10))
#define IS_NEW_LINE(x) (((x) == '\r') || ((x) == '\n') || ((x) == '\0'))
template <typename T>
static inline std::string toString(const T &t) {
std::stringstream ss;
ss << t;
return ss.str();
}
struct warning_context {
std::string *warn;
size_t line_number;
};
// Make index zero-base, and also support relative index.
static inline bool fixIndex(int idx, int n, int *ret, bool allow_zero,
const warning_context &context) {
if (!ret) {
return false;
}
if (idx > 0) {
(*ret) = idx - 1;
return true;
}
if (idx == 0) {
// zero is not allowed according to the spec.
if (context.warn) {
(*context.warn) +=
"A zero value index found (will have a value of -1 for normal and "
"tex indices. Line " +
toString(context.line_number) + ").\n";
}
(*ret) = idx - 1;
return allow_zero;
}
if (idx < 0) {
(*ret) = n + idx; // negative value = relative
if ((*ret) < 0) {
return false; // invalid relative index
}
return true;
}
return false; // never reach here.
}
static inline std::string parseString(const char **token) {
std::string s;
(*token) += strspn((*token), " \t");
size_t e = strcspn((*token), " \t\r");
s = std::string((*token), &(*token)[e]);
(*token) += e;
return s;
}
static inline int parseInt(const char **token) {
(*token) += strspn((*token), " \t");
int i = atoi((*token));
(*token) += strcspn((*token), " \t\r");
return i;
}
// Tries to parse a floating point number located at s.
//
// s_end should be a location in the string where reading should absolutely
// stop. For example at the end of the string, to prevent buffer overflows.
//
// Parses the following EBNF grammar:
// sign = "+" | "-" ;
// END = ? anything not in digit ?
// digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
// integer = [sign] , digit , {digit} ;
// decimal = integer , ["." , integer] ;
// float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ;
//
// Valid strings are for example:
// -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2
//
// If the parsing is a success, result is set to the parsed value and true
// is returned.
//
// The function is greedy and will parse until any of the following happens:
// - a non-conforming character is encountered.
// - s_end is reached.
//
// The following situations triggers a failure:
// - s >= s_end.
// - parse failure.
//
static bool tryParseDouble(const char *s, const char *s_end, double *result) {
if (s >= s_end) {
return false;
}
double mantissa = 0.0;
// This exponent is base 2 rather than 10.
// However the exponent we parse is supposed to be one of ten,
// thus we must take care to convert the exponent/and or the
// mantissa to a * 2^E, where a is the mantissa and E is the
// exponent.
// To get the final double we will use ldexp, it requires the
// exponent to be in base 2.
int exponent = 0;
// NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED
// TO JUMP OVER DEFINITIONS.
char sign = '+';
char exp_sign = '+';
char const *curr = s;
// How many characters were read in a loop.
int read = 0;
// Tells whether a loop terminated due to reaching s_end.
bool end_not_reached = false;
bool leading_decimal_dots = false;
/*
BEGIN PARSING.
*/
// Find out what sign we've got.
if (*curr == '+' || *curr == '-') {
sign = *curr;
curr++;
if ((curr != s_end) && (*curr == '.')) {
// accept. Somethig like `.7e+2`, `-.5234`
leading_decimal_dots = true;
}
} else if (IS_DIGIT(*curr)) { /* Pass through. */
} else if (*curr == '.') {
// accept. Somethig like `.7e+2`, `-.5234`
leading_decimal_dots = true;
} else {
goto fail;
}
// Read the integer part.
end_not_reached = (curr != s_end);
if (!leading_decimal_dots) {
while (end_not_reached && IS_DIGIT(*curr)) {
mantissa *= 10;
mantissa += static_cast<int>(*curr - 0x30);
curr++;
read++;
end_not_reached = (curr != s_end);
}
// We must make sure we actually got something.
if (read == 0) goto fail;
}
// We allow numbers of form "#", "###" etc.
if (!end_not_reached) goto assemble;
// Read the decimal part.
if (*curr == '.') {
curr++;
read = 1;
end_not_reached = (curr != s_end);
while (end_not_reached && IS_DIGIT(*curr)) {
static const double pow_lut[] = {
1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 0.0000001,
};
const int lut_entries = sizeof pow_lut / sizeof pow_lut[0];
// NOTE: Don't use powf here, it will absolutely murder precision.
mantissa += static_cast<int>(*curr - 0x30) *
(read < lut_entries ? pow_lut[read] : std::pow(10.0, -read));
read++;
curr++;
end_not_reached = (curr != s_end);
}
} else if (*curr == 'e' || *curr == 'E') {
} else {
goto assemble;
}
if (!end_not_reached) goto assemble;
// Read the exponent part.
if (*curr == 'e' || *curr == 'E') {
curr++;
// Figure out if a sign is present and if it is.
end_not_reached = (curr != s_end);
if (end_not_reached && (*curr == '+' || *curr == '-')) {
exp_sign = *curr;
curr++;
} else if (IS_DIGIT(*curr)) { /* Pass through. */
} else {
// Empty E is not allowed.
goto fail;
}