-
-
Notifications
You must be signed in to change notification settings - Fork 649
Expand file tree
/
Copy pathtiny_obj_loader.h
More file actions
4614 lines (3928 loc) · 137 KB
/
Copy pathtiny_obj_loader.h
File metadata and controls
4614 lines (3928 loc) · 137 KB
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-2018 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.
// * Support line primitive.
// * Support points primitive.
// * Experimental support of multi-threaded parser.
// 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 {
#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;
typedef struct {
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 (default = ?) TODO
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).
} texture_option_t;
typedef struct {
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
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
} material_t;
typedef struct {
std::string name;
std::vector<int> intValues;
std::vector<real_t> floatValues;
std::vector<std::string> stringValues;
} tag_t;
// Index struct to support different indices for vtx/normal/texcoord.
// -1 means not used.
typedef struct {
int vertex_index;
int normal_index;
int texcoord_index;
} index_t;
typedef struct {
std::vector<index_t> indices;
std::vector<unsigned char>
num_face_vertices; // The number of vertices per
// face. 3 = triangle, 4 = quad,
// ... Up to 255 vertices per face.
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
} mesh_t;
// typedef struct {
// std::vector<int> indices; // pairs of indices for lines
//} path_t;
typedef struct {
// 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.
} lines_t;
typedef struct {
std::vector<index_t> indices; // indices for points
} points_t;
typedef struct {
std::string name;
mesh_t mesh;
lines_t lines;
points_t points;
} shape_t;
// 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
attrib_t() {}
//
// For pybind11
//
const std::vector<real_t> &GetVertices() const { return vertices; }
const std::vector<real_t> &GetVertexWeights() const { return vertex_weights; }
};
typedef 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 (*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),
normal_cb(NULL),
texcoord_cb(NULL),
index_cb(NULL),
usemtl_cb(NULL),
mtllib_cb(NULL),
group_cb(NULL),
object_cb(NULL) {}
} callback_t;
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:
explicit MaterialFileReader(const std::string &mtl_basedir)
: m_mtlBaseDir(mtl_basedir) {}
virtual ~MaterialFileReader() {}
virtual bool operator()(const std::string &matId,
std::vector<material_t> *materials,
std::map<std::string, int> *matMap, std::string *warn,
std::string *err);
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() {}
virtual bool operator()(const std::string &matId,
std::vector<material_t> *materials,
std::map<std::string, int> *matMap, std::string *warn,
std::string *err);
private:
std::istream &m_inStream;
};
// v2 API
struct ObjReaderConfig {
bool triangulate; // triangulate polygon?
/// 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;
///
/// Use multithreaded parser(C++11 required).
/// Please keep in mind that multithreaded parser has limited support of parsing feature
/// compared to serialized(default) parser.
/// Also `TINYOBJLOADER_ENABLE_THREADED` must be defined.
///
bool threaded;
ObjReaderConfig() : triangulate(true), vertex_color(true), threaded(false) {}
};
///
/// Wavefront .obj reader class(v2 API)
///
class ObjReader {
public:
ObjReader() : valid_(false) {}
~ObjReader() {}
///
/// 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 <limits>
#include <utility>
#include <fstream>
#include <sstream>
#if defined(TINYOBJLOADER_ENABLE_THREADED)
// Assume C++11 or later
#include <thread>
#include <atomic>
#include <mutex>
// TODO(syoyo): Merge functions/structs with non-optimized version of code.
namespace tinyobj_opt {
// ----------------------------------------------------------------------------
// Small vector class useful for multi-threaded environment.
//
// stack_container.h
//
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This allocator can be used with STL containers to provide a stack buffer
// from which to allocate memory and overflows onto the heap. This stack buffer
// would be allocated on the stack and allows us to avoid heap operations in
// some situations.
//
// STL likes to make copies of allocators, so the allocator itself can't hold
// the data. Instead, we make the creator responsible for creating a
// StackAllocator::Source which contains the data. Copying the allocator
// merely copies the pointer to this shared source, so all allocators created
// based on our allocator will share the same stack buffer.
//
// This stack buffer implementation is very simple. The first allocation that
// fits in the stack buffer will use the stack buffer. Any subsequent
// allocations will not use the stack buffer, even if there is unused room.
// This makes it appropriate for array-like containers, but the caller should
// be sure to reserve() in the container up to the stack buffer size. Otherwise
// the container will allocate a small array which will "use up" the stack
// buffer.
template <typename T, size_t stack_capacity>
class StackAllocator : public std::allocator<T> {
public:
typedef typename std::allocator<T>::pointer pointer;
typedef typename std::allocator<T>::size_type size_type;
// Backing store for the allocator. The container owner is responsible for
// maintaining this for as long as any containers using this allocator are
// live.
struct Source {
Source() : used_stack_buffer_(false) {}
// Casts the buffer in its right type.
T *stack_buffer() { return reinterpret_cast<T *>(stack_buffer_); }
const T *stack_buffer() const {
return reinterpret_cast<const T *>(stack_buffer_);
}
//
// IMPORTANT: Take care to ensure that stack_buffer_ is aligned
// since it is used to mimic an array of T.
// Be careful while declaring any unaligned types (like bool)
// before stack_buffer_.
//
// The buffer itself. It is not of type T because we don't want the
// constructors and destructors to be automatically called. Define a POD
// buffer of the right size instead.
char stack_buffer_[sizeof(T[stack_capacity])];
// Set when the stack buffer is used for an allocation. We do not track
// how much of the buffer is used, only that somebody is using it.
bool used_stack_buffer_;
};
// Used by containers when they want to refer to an allocator of type U.
template <typename U>
struct rebind {
typedef StackAllocator<U, stack_capacity> other;
};
// For the straight up copy c-tor, we can share storage.
StackAllocator(const StackAllocator<T, stack_capacity> &rhs)
: source_(rhs.source_) {}
// ISO C++ requires the following constructor to be defined,
// and std::vector in VC++2008SP1 Release fails with an error
// in the class _Container_base_aux_alloc_real (from <xutility>)
// if the constructor does not exist.
// For this constructor, we cannot share storage; there's
// no guarantee that the Source buffer of Ts is large enough
// for Us.
// TODO(Google): If we were fancy pants, perhaps we could share storage
// iff sizeof(T) == sizeof(U).
template <typename U, size_t other_capacity>
StackAllocator(const StackAllocator<U, other_capacity> &other)
: source_(NULL) {
(void)other;
}
explicit StackAllocator(Source *source) : source_(source) {}
// Actually do the allocation. Use the stack buffer if nobody has used it yet
// and the size requested fits. Otherwise, fall through to the standard
// allocator.
pointer allocate(size_type n, void *hint = 0) {
if (source_ != NULL && !source_->used_stack_buffer_ &&
n <= stack_capacity) {
source_->used_stack_buffer_ = true;
return source_->stack_buffer();
} else {
return std::allocator<T>::allocate(n, hint);
}
}
// Free: when trying to free the stack buffer, just mark it as free. For
// non-stack-buffer pointers, just fall though to the standard allocator.
void deallocate(pointer p, size_type n) {
if (source_ != NULL && p == source_->stack_buffer())
source_->used_stack_buffer_ = false;
else
std::allocator<T>::deallocate(p, n);
}
private:
Source *source_;
};
// A wrapper around STL containers that maintains a stack-sized buffer that the
// initial capacity of the vector is based on. Growing the container beyond the
// stack capacity will transparently overflow onto the heap. The container must
// support reserve().
//
// WATCH OUT: the ContainerType MUST use the proper StackAllocator for this
// type. This object is really intended to be used only internally. You'll want
// to use the wrappers below for different types.
template <typename TContainerType, int stack_capacity>
class StackContainer {
public:
typedef TContainerType ContainerType;
typedef typename ContainerType::value_type ContainedType;
typedef StackAllocator<ContainedType, stack_capacity> Allocator;
// Allocator must be constructed before the container!
StackContainer() : allocator_(&stack_data_), container_(allocator_) {
// Make the container use the stack allocation by reserving our buffer size
// before doing anything else.
container_.reserve(stack_capacity);
}
// Getters for the actual container.
//
// Danger: any copies of this made using the copy constructor must have
// shorter lifetimes than the source. The copy will share the same allocator
// and therefore the same stack buffer as the original. Use std::copy to
// copy into a "real" container for longer-lived objects.
ContainerType &container() { return container_; }
const ContainerType &container() const { return container_; }
// Support operator-> to get to the container. This allows nicer syntax like:
// StackContainer<...> foo;
// std::sort(foo->begin(), foo->end());
ContainerType *operator->() { return &container_; }
const ContainerType *operator->() const { return &container_; }
#ifdef UNIT_TEST
// Retrieves the stack source so that that unit tests can verify that the
// buffer is being used properly.
const typename Allocator::Source &stack_data() const { return stack_data_; }
#endif
protected:
typename Allocator::Source stack_data_;
unsigned char pad_[7];
Allocator allocator_;
ContainerType container_;
// DISALLOW_EVIL_CONSTRUCTORS(StackContainer);
StackContainer(const StackContainer &);
void operator=(const StackContainer &);
};
// StackVector
//
// Example:
// StackVector<int, 16> foo;
// foo->push_back(22); // we have overloaded operator->
// foo[0] = 10; // as well as operator[]
template <typename T, size_t stack_capacity>
class StackVector
: public StackContainer<std::vector<T, StackAllocator<T, stack_capacity> >,
stack_capacity> {
public:
StackVector()
: StackContainer<std::vector<T, StackAllocator<T, stack_capacity> >,
stack_capacity>() {}
// We need to put this in STL containers sometimes, which requires a copy
// constructor. We can't call the regular copy constructor because that will
// take the stack buffer from the original. Here, we create an empty object
// and make a stack buffer of its own.
StackVector(const StackVector<T, stack_capacity> &other)
: StackContainer<std::vector<T, StackAllocator<T, stack_capacity> >,
stack_capacity>() {
this->container().assign(other->begin(), other->end());
}
StackVector<T, stack_capacity> &operator=(
const StackVector<T, stack_capacity> &other) {
this->container().assign(other->begin(), other->end());
return *this;
}
// Vectors are commonly indexed, which isn't very convenient even with
// operator-> (using "->at()" does exception stuff we don't want).
T &operator[](size_t i) { return this->container().operator[](i); }
const T &operator[](size_t i) const {
return this->container().operator[](i);
}
};
// ----------------------------------------------------------------------------
typedef struct {
std::string name;
float ambient[3];
float diffuse[3];
float specular[3];
float transmittance[3];
float emission[3];
float shininess;
float ior; // index of refraction
float 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
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, bump
std::string displacement_texname; // disp
std::string alpha_texname; // map_d
// PBR extension
// http://exocortex.com/blog/extending_wavefront_mtl_to_support_pbr
float roughness; // [0, 1] default 0
float metallic; // [0, 1] default 0
float sheen; // [0, 1] default 0
float clearcoat_thickness; // [0, 1] default 0
float clearcoat_roughness; // [0, 1] default 0
float anisotropy; // aniso. [0, 1] default 0
float anisotropy_rotation; // anisor. [0, 1] default 0
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.
std::map<std::string, std::string> unknown_parameter;
} material_t;
typedef struct {
std::string name; // group name or object name.
// Shape's corresponding faces are accessed by attrib.indices[face_offset,
// face_offset + length] NOTE: you'll need to sum up
// attrib.face_num_verts[face_offset, face_offset + length] to find actual
// number of faces.
unsigned int face_offset;
unsigned int length;
} shape_t;
struct index_t {
int vertex_index, texcoord_index, normal_index;
index_t() : vertex_index(-1), texcoord_index(-1), normal_index(-1) {}
explicit index_t(int idx)
: vertex_index(idx), texcoord_index(idx), normal_index(idx) {}
index_t(int vidx, int vtidx, int vnidx)
: vertex_index(vidx), texcoord_index(vtidx), normal_index(vnidx) {}
};
typedef struct {
std::vector<float> vertices;
std::vector<float> normals;
std::vector<float> texcoords;
std::vector<index_t> indices;
// # of vertices for each face.
// 3 for triangle, 4 for qual, ...
// If triangulation is enabled and the original face are quad,
// face_num_verts will be 6(3 + 3)
std::vector<int> face_num_verts;
// Per-face material IDs.
std::vector<int> material_ids;
} attrib_t;
typedef StackVector<char, 256> ShortString;
#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'))
static inline void skip_space(const char **token) {
while ((*token)[0] == ' ' || (*token)[0] == '\t') {
(*token)++;
}
}
static inline void skip_space_and_cr(const char **token) {
while ((*token)[0] == ' ' || (*token)[0] == '\t' || (*token)[0] == '\r') {
(*token)++;
}
}
static inline int until_space(const char *token) {
const char *p = token;
while (p[0] != '\0' && p[0] != ' ' && p[0] != '\t' && p[0] != '\r') {
p++;
}
return p - token;
}
static inline int length_until_newline(const char *token, int n) {
int len = 0;
// Assume token[n-1] = '\0'
for (len = 0; len < n - 1; len++) {
if (token[len] == '\n') {
break;
}
if ((token[len] == '\r') && ((len < (n - 2)) && (token[len + 1] != '\n'))) {
break;
}
}
return len;
}
// http://stackoverflow.com/questions/5710091/how-does-atoi-function-in-c-work
static inline int my_atoi(const char *c) {
int value = 0;
int sign = 1;
if (*c == '+' || *c == '-') {
if (*c == '-') sign = -1;
c++;
}
while (((*c) >= '0') && ((*c) <= '9')) { // isdigit(*c)
value *= 10;
value += (int)(*c - '0');
c++;
}
return value * sign;
}
// Make index zero-base, and also support relative index.
static inline int fixIndex(int idx, int n) {
if (idx > 0) return idx - 1;
if (idx == 0) return 0;
return n + idx; // negative value = relative
}
// Parse raw triples: i, i/j/k, i//k, i/j
static index_t parseRawTriple(const char **token) {
index_t vi(