-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathModelLoader.hpp
executable file
·1805 lines (1491 loc) · 68.2 KB
/
ModelLoader.hpp
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
/** @file ModelLoader.hpp
* @brief Loads OBJ+MTL, OFF, PLY, STL object files into a VAO
* @author Dr. Jeffrey Paone
*
* @copyright MIT License Copyright (c) 2017 Dr. Jeffrey Paone
*
* This class will load and render object files. Currently supports:
* .obj + .mtl
* .off
* .ply
* .stl
*
* @warning NOTE: This header file will only work with OpenGL 3.0+
* @warning NOTE: This header file depends upon GLAD (or GLEW), glm, stb_image
*/
#ifndef CSCI441_MODEL_LOADER_HPP
#define CSCI441_MODEL_LOADER_HPP
#include "modelMaterial.hpp"
#ifdef CSCI441_USE_GLEW
#include <GL/glew.h>
#else
#include <glad/gl.h>
#endif
#include <glm/glm.hpp>
#include <stb_image.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <sstream>
#include <map>
#include <string>
#include <utility>
#include <vector>
////////////////////////////////////////////////////////////////////////////////////
namespace CSCI441 {
/**
* @class ModelLoader
* @brief Loads object models from file and renders using VBOs/VAOs
*/
class [[maybe_unused]] ModelLoader final {
public:
/**
* @brief Creates an empty model
*/
ModelLoader();
/**
* @brief Loads a model from the given file
* @param filename file to load model from
*/
[[maybe_unused]] explicit ModelLoader( const char* filename );
/**
* @brief Frees memory associated with model on both CPU and GPU
*/
~ModelLoader();
/**
* @brief do not allow models to be copied
*/
ModelLoader(const ModelLoader&) = delete;
/**
* @brief do not allow models to be copied
*/
ModelLoader& operator=(const ModelLoader&) = delete;
/**
* @brief Loads a model from the given file
* @param filename file to load model from
* @param INFO flag to control if informational messages should be displayed
* @param ERRORS flag to control if error messages should be displayed
* @return true if load succeeded, false otherwise
*/
bool loadModelFile( std::string filename, bool INFO = true, bool ERRORS = true );
/**
* @brief Enables VBO attribute array locations
* @param positionLocation attribute location of vertex position
* @param normalLocation attribute location of vertex normal
* @param texCoordLocation attribute location of vertex texture coordinate
*/
[[maybe_unused]] void setAttributeLocations(GLint positionLocation, GLint normalLocation = -1, GLint texCoordLocation = -1) const;
/**
* @brief Renders a model
* @param shaderProgramHandle shader program handle that
* @param matDiffLocation uniform location of material diffuse component
* @param matSpecLocation uniform location of material specular component
* @param matShinLocation uniform location of material shininess component
* @param matAmbLocation uniform location of material ambient component
* @param diffuseTexture texture number to bind diffuse texture map to
* @return true if draw succeeded, false otherwise
*/
[[maybe_unused]] bool draw( GLuint shaderProgramHandle,
GLint matDiffLocation = -1, GLint matSpecLocation = -1, GLint matShinLocation = -1, GLint matAmbLocation = -1,
GLenum diffuseTexture = GL_TEXTURE0 ) const;
/**
* @brief Return the number of vertices the model is made up of. This value corresponds to the size of the Vertices, TexCoords, and Normals arrays.
* @return the number of vertices within the model
*/
[[maybe_unused]] [[nodiscard]] GLuint getNumberOfVertices() const;
/**
* @brief Return the vertex array that makes up the model mesh.
* @return pointer to vertex array
* @note For use with VBOs
*/
[[maybe_unused]] [[nodiscard]] GLfloat* getVertices() const;
/**
* @brief Return the normal array that corresponds to the model mesh.
* @return pointer to the normal array
* @note For use with VBOs
*/
[[maybe_unused]] [[nodiscard]] GLfloat* getNormals() const;
/**
* @brief Return the texture coordinates array that corresponds to the model mesh.
* @return pointer to texture coordinate array
* @note For use with VBOs
*/
[[maybe_unused]] [[nodiscard]] GLfloat* getTexCoords() const;
/**
* @brief Return the number of indices to draw the model. This value corresponds to the size of the Indices array.
* @return the number of indices when drawing the model
*/
[[maybe_unused]] [[nodiscard]] GLuint getNumberOfIndices() const;
/**
* @brief Return the index array that dictates the order to draw the model mesh.
* @return pointer to the index array
* @note For use with IBOs
*/
[[maybe_unused]] [[nodiscard]] GLuint* getIndices() const;
/**
* @brief Enable auto-generation of vertex normals
* @warning Must be called prior to loading in a model from file
* @note If an object model does not contain vertex normal data, then normals will be computed based on the cross product of vertex winding order.
* @note No normals are generated by default
* @note To disable, call disableAutoGenerateNormals
*/
[[maybe_unused]] static void enableAutoGenerateNormals();
/**
* @brief Disable auto-generation of vertex normals
* @warning Must be called prior to loading in a model from file
* @note No normals are generated by default
* @note To enable, call enableAutoGenerateNormals
*/
[[maybe_unused]] static void disableAutoGenerateNormals();
private:
void _init();
bool _loadMTLFile( const char *mtlFilename, bool INFO, bool ERRORS );
bool _loadOBJFile( bool INFO, bool ERRORS );
bool _loadOFFFile( bool INFO, bool ERRORS );
bool _loadPLYFile( bool INFO, bool ERRORS );
bool _loadSTLFile( bool INFO, bool ERRORS );
static std::vector<std::string> _tokenizeString( std::string input, const std::string& delimiters );
void _allocateAttributeArrays(GLuint numVertices, GLuint numIndices);
void _bufferData();
std::string _filename;
CSCI441_INTERNAL::MODEL_TYPE _modelType;
GLuint _vaod;
GLuint _vbods[2];
glm::vec3* _vertices;
glm::vec3* _normals;
glm::vec2* _texCoords;
GLuint* _indices;
GLuint _uniqueIndex;
GLuint _numIndices;
std::map< std::string, CSCI441_INTERNAL::ModelMaterial* > _materials;
std::map< std::string, std::vector< std::pair< GLuint, GLuint > > > _materialIndexStartStop;
bool _hasVertexTexCoords;
bool _hasVertexNormals;
static bool sAUTO_GEN_NORMALS;
};
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
namespace CSCI441_INTERNAL {
unsigned char* createTransparentTexture( const unsigned char *imageData, const unsigned char *imageMask, int texWidth, int texHeight, int texChannels, int maskChannels );
[[maybe_unused]] void flipImageY( int texWidth, int texHeight, int textureChannels, unsigned char *textureData );
}
inline bool CSCI441::ModelLoader::sAUTO_GEN_NORMALS = false;
inline CSCI441::ModelLoader::ModelLoader() {
_init();
}
[[maybe_unused]]
inline CSCI441::ModelLoader::ModelLoader( const char* filename ) {
_init();
loadModelFile( filename );
}
inline CSCI441::ModelLoader::~ModelLoader() {
delete[] _vertices;
delete[] _normals;
delete[] _texCoords;
delete[] _indices;
glDeleteBuffers( 2, _vbods );
glDeleteVertexArrays( 1, &_vaod );
}
inline void CSCI441::ModelLoader::_init() {
_hasVertexTexCoords = false;
_hasVertexNormals = false;
_vertices = nullptr;
_texCoords = nullptr;
_normals = nullptr;
_indices = nullptr;
_uniqueIndex = 0;
_numIndices = 0;
glGenVertexArrays( 1, &_vaod );
glGenBuffers( 2, _vbods );
}
inline bool CSCI441::ModelLoader::loadModelFile( std::string filename, bool INFO, bool ERRORS ) {
bool result = true;
_filename = std::move(filename);
if( _filename.find(".obj") != std::string::npos ) {
result = _loadOBJFile( INFO, ERRORS );
_modelType = CSCI441_INTERNAL::MODEL_TYPE::OBJ;
}
else if( _filename.find(".off") != std::string::npos ) {
result = _loadOFFFile( INFO, ERRORS );
_modelType = CSCI441_INTERNAL::MODEL_TYPE::OFF;
}
else if( _filename.find(".ply") != std::string::npos ) {
result = _loadPLYFile( INFO, ERRORS );
_modelType = CSCI441_INTERNAL::MODEL_TYPE::PLY;
}
else if( _filename.find(".stl") != std::string::npos ) {
result = _loadSTLFile( INFO, ERRORS );
_modelType = CSCI441_INTERNAL::MODEL_TYPE::STL;
}
else {
result = false;
if (ERRORS) fprintf( stderr, "[ERROR]: Unsupported file format for file: %s\n", _filename.c_str() );
}
return result;
}
[[maybe_unused]]
inline void CSCI441::ModelLoader::setAttributeLocations(GLint positionLocation, GLint normalLocation, GLint texCoordLocation) const {
glBindVertexArray( _vaod );
glBindBuffer( GL_ARRAY_BUFFER, _vbods[0] );
glEnableVertexAttribArray( positionLocation );
glVertexAttribPointer( positionLocation, 3, GL_FLOAT, GL_FALSE, 0, (void*)nullptr );
glEnableVertexAttribArray( normalLocation );
glVertexAttribPointer( normalLocation, 3, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec3) * _uniqueIndex) );
glEnableVertexAttribArray( texCoordLocation );
glVertexAttribPointer( texCoordLocation, 2, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec3) * _uniqueIndex * 2) );
}
[[maybe_unused]]
inline bool CSCI441::ModelLoader::draw( GLuint shaderProgramHandle,
GLint matDiffLocation, GLint matSpecLocation, GLint matShinLocation, GLint matAmbLocation,
GLenum diffuseTexture ) const {
glBindVertexArray( _vaod );
bool result = true;
if( _modelType == CSCI441_INTERNAL::MODEL_TYPE::OBJ ) {
for(const auto & materialIter : _materialIndexStartStop) {
auto materialName = materialIter.first;
auto indexStartStop = materialIter.second;
CSCI441_INTERNAL::ModelMaterial* material = nullptr;
if( _materials.find( materialName ) != _materials.end() )
material = _materials.find( materialName )->second;
for(auto & idxIter : indexStartStop) {
auto start = idxIter.first;
auto end = idxIter.second;
GLsizei length = (GLsizei)(end - start) + 1;
// printf( "rendering material %s (%u, %u) = %u\n", materialName.c_str(), start, end, length );
if( material != nullptr ) {
glProgramUniform4fv( shaderProgramHandle, matAmbLocation, 1, &material->ambient[0] );
glProgramUniform4fv( shaderProgramHandle, matDiffLocation, 1, &material->diffuse[0] );
glProgramUniform4fv( shaderProgramHandle, matSpecLocation, 1, &material->specular[0] );
glProgramUniform1f( shaderProgramHandle, matShinLocation, material->shininess );
if( material->map_Kd != -1 ) {
glActiveTexture( diffuseTexture );
glBindTexture( GL_TEXTURE_2D, material->map_Kd );
}
}
glDrawElements( GL_TRIANGLES, length, GL_UNSIGNED_INT, (void*)(sizeof(GLuint)*start) );
}
}
} else {
glDrawElements( GL_TRIANGLES, static_cast<GLint>(_numIndices), GL_UNSIGNED_INT, (void*)nullptr );
}
return result;
}
[[maybe_unused]] inline GLuint CSCI441::ModelLoader::getNumberOfVertices() const { return _uniqueIndex; }
[[maybe_unused]] inline GLfloat* CSCI441::ModelLoader::getVertices() const { return (_vertices != nullptr ? (GLfloat*)&_vertices[0] : nullptr); }
[[maybe_unused]] inline GLfloat* CSCI441::ModelLoader::getNormals() const { return (_normals != nullptr ? (GLfloat*)&_normals[0] : nullptr); }
[[maybe_unused]] inline GLfloat* CSCI441::ModelLoader::getTexCoords() const { return (_texCoords != nullptr ? (GLfloat*)&_texCoords[0] : nullptr); }
[[maybe_unused]] inline GLuint CSCI441::ModelLoader::getNumberOfIndices() const { return _numIndices; }
[[maybe_unused]] inline GLuint* CSCI441::ModelLoader::getIndices() const { return _indices; }
// Read in a WaveFront *.obj File
inline bool CSCI441::ModelLoader::_loadOBJFile( bool INFO, bool ERRORS ) {
bool result = true;
if ( INFO ) fprintf( stdout, "[.obj]: -=-=-=-=-=-=-=- BEGIN %s Info -=-=-=-=-=-=-=- \n", _filename.c_str() );
time_t start, end;
time(&start);
std::ifstream in( _filename );
if( !in.is_open() ) {
if (ERRORS) fprintf( stderr, "[.obj]: [ERROR]: Could not open \"%s\"\n", _filename.c_str() );
if ( INFO ) fprintf( stdout, "[.obj]: -=-=-=-=-=-=-=- END %s Info -=-=-=-=-=-=-=- \n", _filename.c_str() );
return false;
}
GLuint numObjects = 0, numGroups = 0;
GLuint numVertices = 0, numTexCoords = 0, numNormals = 0;
GLuint numFaces = 0, numTriangles = 0;
glm::vec3 minDimension = {999999.f, 999999.f, 999999.f};
glm::vec3 maxDimension = { -999999.f, -999999.f, -999999.f };
std::string line;
std::map<std::string, GLuint> uniqueCounts;
_uniqueIndex = 0;
int progressCounter = 0;
while( getline( in, line ) ) {
if( line.length() > 1 && line.at(0) == '\t' )
line = line.substr( 1 );
line.erase( line.find_last_not_of( " \n\r\t" ) + 1 );
std::vector< std::string > tokens = _tokenizeString( line, " \t" );
if( tokens.empty() ) continue;
//the line should have a single character that lets us know if it's a...
if( tokens[0] == "#" || tokens[0].find_first_of('#') == 0 ) {
// comment ignore
} else if( tokens[0] == "o" ) { // object name ignore
numObjects++;
} else if( tokens[0] == "g" ) { // polygon group name ignore
numGroups++;
} else if( tokens[0] == "mtllib" ) { // material library
_loadMTLFile( tokens[1].c_str(), INFO, ERRORS );
} else if( tokens[0] == "v" ) { //vertex
numVertices++;
glm::vec3 pos = { strtof( tokens[1].c_str(), nullptr ),
strtof( tokens[2].c_str(), nullptr ),
strtof( tokens[3].c_str(), nullptr ) };
if( pos.x < minDimension.x ) minDimension.x = pos.x;
if( pos.x > maxDimension.x ) maxDimension.x = pos.x;
if( pos.y < minDimension.y ) minDimension.y = pos.y;
if( pos.y > maxDimension.y ) maxDimension.y = pos.y;
if( pos.z < minDimension.z ) minDimension.z = pos.z;
if( pos.z > maxDimension.z ) maxDimension.z = pos.z;
} else if( tokens[0] == "vn" ) { //vertex normal
numNormals++;
} else if( tokens[0] == "vt" ) { //vertex tex coord
numTexCoords++;
} else if( tokens[0] == "f" ) { //face!
//now, faces can be either quads or triangles (or maybe more?)
//split the string on spaces to get the number of vertices+attributes.
std::vector<std::string> faceTokens = _tokenizeString(line, " ");
for (GLuint i = 1; i < faceTokens.size(); i++) {
//need to use both the tokens and number of slashes to determine what info is there.
std::vector<std::string> groupTokens = _tokenizeString(faceTokens[i], "/");
int numSlashes = 0;
for (char j: faceTokens[i]) {
if (j == '/') numSlashes++;
}
std::stringstream currentFaceTokenStream;
auto signedVertexIndex = (GLint) strtol(groupTokens[0].c_str(), nullptr, 10);
GLuint vertexIndex = signedVertexIndex;
if (signedVertexIndex < 0) vertexIndex = numVertices + signedVertexIndex + 1;
currentFaceTokenStream << vertexIndex;
//based on combination of number of tokens and slashes, we can determine what we have.
if (groupTokens.size() == 2 && numSlashes == 1) {
_hasVertexTexCoords = true;
auto signedTexCoordIndex = (GLint) strtol(groupTokens[1].c_str(), nullptr, 10);
GLuint texCoordIndex = signedTexCoordIndex;
if (signedTexCoordIndex < 0) texCoordIndex = numTexCoords + signedTexCoordIndex + 1;
currentFaceTokenStream << "/" << texCoordIndex;
} else if (groupTokens.size() == 2 && numSlashes == 2) {
_hasVertexNormals = true;
auto signedNormalIndex = (GLint) strtol(groupTokens[1].c_str(), nullptr, 10);
GLuint normalIndex = signedNormalIndex;
if (signedNormalIndex < 0) normalIndex = numNormals + signedNormalIndex + 1;
currentFaceTokenStream << "//" << normalIndex;
} else if (groupTokens.size() == 3) {
_hasVertexTexCoords = true;
_hasVertexNormals = true;
auto signedTexCoordIndex = (GLint) strtol(groupTokens[1].c_str(), nullptr, 10);
GLuint texCoordIndex = signedTexCoordIndex;
if (signedTexCoordIndex < 0) texCoordIndex = numTexCoords + signedTexCoordIndex + 1;
auto signedNormalIndex = (GLint) strtol(groupTokens[2].c_str(), nullptr, 10);
GLuint normalIndex = signedNormalIndex;
if (signedNormalIndex < 0) normalIndex = numNormals + signedNormalIndex + 1;
currentFaceTokenStream << "/" << texCoordIndex << "/" << normalIndex;
} else if (groupTokens.size() != 1) {
if (ERRORS) fprintf(stderr, "[.obj]: [ERROR]: Malformed OBJ file, %s.\n", _filename.c_str());
return false;
}
std::string processedFaceToken = currentFaceTokenStream.str();
if (uniqueCounts.find(processedFaceToken) == uniqueCounts.end()) {
uniqueCounts.insert(std::pair<std::string, long int>(processedFaceToken, _uniqueIndex));
_uniqueIndex++;
}
}
numTriangles += (faceTokens.size() - 1 - 3 + 1);
numFaces++;
} else if( tokens[0] == "usemtl" ) { // use material library
} else {
if (INFO) printf( "[.obj]: ignoring line: %s\n", line.c_str() );
}
if (INFO) {
progressCounter++;
if( progressCounter % 5000 == 0 ) {
printf("\33[2K\r");
switch( progressCounter ) {
case 5000: printf("[.obj]: scanning %s...\\", _filename.c_str()); break;
case 10000: printf("[.obj]: scanning %s...|", _filename.c_str()); break;
case 15000: printf("[.obj]: scanning %s.../", _filename.c_str()); break;
case 20000: printf("[.obj]: scanning %s...-", _filename.c_str()); break;
default: break;
}
fflush(stdout);
}
if( progressCounter == 20000 )
progressCounter = 0;
}
}
in.close();
if (INFO) {
printf( "\33[2K\r" );
printf( "[.obj]: scanning %s...done!\n", _filename.c_str() );
printf( "[.obj]: ------------\n" );
printf( "[.obj]: Model Stats:\n" );
printf( "[.obj]: Vertices: \t%u\tNormals: \t%u\tTex Coords:\t%u\n", numVertices, numNormals, numTexCoords );
printf( "[.obj]: Unique Verts:\t%u\n", _uniqueIndex );
printf( "[.obj]: Faces: \t%u\tTriangles:\t%u\n", numFaces, numTriangles );
printf( "[.obj]: Objects: \t%u\tGroups: \t%u\n", numObjects, numGroups );
glm::vec3 sizeDimensions = maxDimension - minDimension;
printf( "[.obj]: Dimensions:\t(%f, %f, %f)\n", sizeDimensions.x, sizeDimensions.y, sizeDimensions.z );
}
if( _hasVertexNormals || !sAUTO_GEN_NORMALS ) {
if (INFO && !_hasVertexNormals)
printf( "[.obj]: [WARN]: No vertex normals exist on model. To autogenerate vertex\n\tnormals, call CSCI441::ModelLoader::enableAutoGenerateNormals()\n\tprior to loading the model file.\n" );
_allocateAttributeArrays(_uniqueIndex, numTriangles*3);
} else {
if (INFO) printf( "[.obj]: No vertex normals exist on model, vertex normals will be autogenerated\n" );
_allocateAttributeArrays(numTriangles * 3, numTriangles*3);
}
auto objVertices = new glm::vec3[numVertices];
auto objNormals = new glm::vec3[numNormals];
auto objTexCoords = new glm::vec2[numTexCoords];
std::vector<glm::vec3> verticesTemps;
std::vector<glm::vec2> texCoordsTemp;
printf( "[.obj]: ------------\n" );
uniqueCounts.clear();
_uniqueIndex = 0;
_numIndices = 0;
in.open( _filename );
GLuint verticesSeen = 0, texCoordsSeen = 0, normalsSeen = 0, indicesSeen = 0;
GLuint uniqueNumVertices = 0;
std::string currentMaterial = "default";
_materialIndexStartStop.insert( std::pair< std::string, std::vector< std::pair< GLuint, GLuint > > >( currentMaterial, std::vector< std::pair< GLuint, GLuint > >(1) ) );
_materialIndexStartStop.find( currentMaterial )->second.back().first = indicesSeen;
while( getline( in, line ) ) {
if( line.length() > 1 && line.at(0) == '\t' )
line = line.substr( 1 );
line.erase( line.find_last_not_of( " \n\r\t" ) + 1 );
auto tokens = _tokenizeString( line, " \t" );
if( tokens.empty() ) continue;
//the line should have a single character that lets us know if it's a...
if( tokens[0] == "#" || tokens[0].find_first_of('#') == 0 // comment ignore
|| tokens[0] == "o" // object name ignore
|| tokens[0] == "g" // polygon group name ignore
|| tokens[0] == "mtllib" // material library
|| tokens[0] == "s" // smooth shading
) {
} else if( tokens[0] == "usemtl" ) { // use material library
if( currentMaterial == "default" && indicesSeen == 0 ) {
_materialIndexStartStop.clear();
} else {
_materialIndexStartStop.find( currentMaterial )->second.back().second = indicesSeen - 1;
}
currentMaterial = tokens[1];
if( _materialIndexStartStop.find( currentMaterial ) == _materialIndexStartStop.end() ) {
_materialIndexStartStop.insert( std::pair< std::string, std::vector< std::pair< GLuint, GLuint > > >( currentMaterial, std::vector< std::pair< GLuint, GLuint > >(1) ) );
_materialIndexStartStop.find( currentMaterial )->second.back().first = indicesSeen;
} else {
_materialIndexStartStop.find( currentMaterial )->second.emplace_back( indicesSeen, -1 );
}
} else if( tokens[0] == "v" ) { //vertex
objVertices[verticesSeen++] = glm::vec3(strtof(tokens[1].c_str(), nullptr ),
strtof( tokens[2].c_str(), nullptr ),
strtof( tokens[3].c_str(), nullptr ) );
} else if( tokens[0] == "vn" ) { //vertex normal
objNormals[normalsSeen++] = glm::vec3(strtof(tokens[1].c_str(), nullptr ),
strtof( tokens[2].c_str(), nullptr ),
strtof( tokens[3].c_str(), nullptr ));
} else if( tokens[0] == "vt" ) { //vertex tex coord
objTexCoords[texCoordsSeen++] = glm::vec2(strtof(tokens[1].c_str(), nullptr ),
strtof( tokens[2].c_str(), nullptr ));
} else if( tokens[0] == "f" ) { //face!
std::vector<std::string> processedFaceTokens;
bool faceHasVertexNormals = false;
bool faceHasTextureCoordinates = false;
for(GLuint i = 1; i < tokens.size(); i++) {
//need to use both the tokens and number of slashes to determine what info is there.
auto vertexAttributeTokens = _tokenizeString(tokens[i], "/");
int numAttributeSlashes = 0;
for(char j : tokens[i]) {
if(j == '/') numAttributeSlashes++;
}
GLuint vertexIndex = 0, texCoordIndex = 0, normalIndex = 0;
std::stringstream currentFaceTokenStream;
auto signedVertexIndex = (GLint)strtol(vertexAttributeTokens[0].c_str(), nullptr, 10);
vertexIndex = signedVertexIndex;
if(signedVertexIndex < 0) vertexIndex = verticesSeen + signedVertexIndex + 1;
currentFaceTokenStream << vertexIndex;
//based on combination of number of tokens and slashes, we can determine what we have.
if(vertexAttributeTokens.size() == 2 && numAttributeSlashes == 1) {
// v/t
_hasVertexTexCoords = true;
faceHasTextureCoordinates = true;
auto signedTexCoordIndex = (GLint)strtol(vertexAttributeTokens[1].c_str(), nullptr, 10);
texCoordIndex = signedTexCoordIndex;
if(signedTexCoordIndex < 0) texCoordIndex = texCoordsSeen + signedTexCoordIndex + 1;
currentFaceTokenStream << "/" << texCoordIndex;
} else if(vertexAttributeTokens.size() == 2 && numAttributeSlashes == 2) {
// v//n
_hasVertexNormals = true;
faceHasVertexNormals = true;
auto signedNormalIndex = (GLint)strtol(vertexAttributeTokens[1].c_str(), nullptr, 10);
normalIndex = signedNormalIndex;
if(signedNormalIndex < 0) normalIndex = normalsSeen + signedNormalIndex + 1;
currentFaceTokenStream << "//" << normalIndex;
} else if(vertexAttributeTokens.size() == 3) {
// v/t/n
_hasVertexTexCoords = true;
faceHasTextureCoordinates = true;
_hasVertexNormals = true;
faceHasVertexNormals = true;
auto signedTexCoordIndex = (GLint)strtol(vertexAttributeTokens[1].c_str(), nullptr, 10);
texCoordIndex = signedTexCoordIndex;
if(signedTexCoordIndex < 0) texCoordIndex = texCoordsSeen + signedTexCoordIndex + 1;
auto signedNormalIndex = (GLint)strtol(vertexAttributeTokens[2].c_str(), nullptr, 10);
normalIndex = signedNormalIndex;
if(signedNormalIndex < 0) normalIndex = normalsSeen + signedNormalIndex + 1;
currentFaceTokenStream << "/" << texCoordIndex << "/" << normalIndex;
} else if(vertexAttributeTokens.size() != 1) {
if (ERRORS) fprintf(stderr, "[.obj]: [ERROR]: Malformed OBJ file, %s.\n", _filename.c_str());
return false;
}
auto processedFaceToken = currentFaceTokenStream.str();
processedFaceTokens.push_back(processedFaceToken);
// check if we've seen this attribute combination before
if( uniqueCounts.find( processedFaceToken ) == uniqueCounts.end() ) {
// if not, add it to the list
uniqueCounts.insert( std::pair<std::string,GLuint>(processedFaceToken, uniqueNumVertices) );
if( _hasVertexNormals || !sAUTO_GEN_NORMALS ) {
_vertices[ _uniqueIndex ] = objVertices[ vertexIndex - 1 ];
if(faceHasTextureCoordinates && texCoordIndex != 0) { _texCoords[ _uniqueIndex ] = objTexCoords[ texCoordIndex - 1 ]; }
if(faceHasVertexNormals && normalIndex != 0) _normals[ _uniqueIndex ] = objNormals[ normalIndex - 1 ];
_uniqueIndex++;
} else {
verticesTemps.push_back( objVertices[ vertexIndex - 1 ] );
if(faceHasTextureCoordinates && texCoordIndex != 0) { texCoordsTemp.push_back( objTexCoords[ texCoordIndex - 1 ] ); }
if( (vertexAttributeTokens.size() == 2 && numAttributeSlashes == 2)
|| (vertexAttributeTokens.size() == 3) ) {
// should not occur if no normals
if (ERRORS) fprintf( stderr, "[.obj]: [ERROR]: no vertex normals were specified, should not be trying to access values\n" );
}
}
uniqueNumVertices++;
}
}
for(GLuint i = 1; i < processedFaceTokens.size()-1; i++) {
if( _hasVertexNormals || !sAUTO_GEN_NORMALS ) {
_indices[ indicesSeen++ ] = uniqueCounts.find( processedFaceTokens[0] )->second;
_indices[ indicesSeen++ ] = uniqueCounts.find( processedFaceTokens[i] )->second;
_indices[ indicesSeen++ ] = uniqueCounts.find( processedFaceTokens[i+1] )->second;
_numIndices += 3;
} else {
GLuint aI = uniqueCounts.find( processedFaceTokens[0] )->second;
GLuint bI = uniqueCounts.find( processedFaceTokens[i] )->second;
GLuint cI = uniqueCounts.find( processedFaceTokens[i+1] )->second;
glm::vec3 a = verticesTemps[aI];
glm::vec3 b = verticesTemps[bI];
glm::vec3 c = verticesTemps[cI];
glm::vec3 ab = b - a; glm::vec3 ac = c - a;
glm::vec3 ba = a - b; glm::vec3 bc = c - b;
glm::vec3 ca = a - c; glm::vec3 cb = b - c;
glm::vec3 aN = glm::normalize( glm::cross( ab, ac ) );
glm::vec3 bN = glm::normalize( glm::cross( bc, ba ) );
glm::vec3 cN = glm::normalize( glm::cross( ca, cb ) );
_vertices[ _uniqueIndex ] = a;
_normals[ _uniqueIndex ] = aN;
if( faceHasTextureCoordinates && _hasVertexTexCoords ) { _texCoords[ _uniqueIndex ] = texCoordsTemp[ aI ]; }
_indices[ _numIndices++ ] = _uniqueIndex++;
indicesSeen++;
_vertices[ _uniqueIndex ] = b;
_normals[ _uniqueIndex ] = bN;
if( faceHasTextureCoordinates && _hasVertexTexCoords ) { _texCoords[ _uniqueIndex ] = texCoordsTemp[ bI ]; }
_indices[ _numIndices++ ] = _uniqueIndex++;
indicesSeen++;
_vertices[ _uniqueIndex ] = c;
_normals[ _uniqueIndex ] = cN;
if( faceHasTextureCoordinates && _hasVertexTexCoords ) { _texCoords[ _uniqueIndex ] = texCoordsTemp[ cI ]; }
_indices[ _numIndices++ ] = _uniqueIndex++;
indicesSeen++;
}
}
}
if (INFO) {
progressCounter++;
if( progressCounter % 5000 == 0 ) {
printf("\33[2K\r");
switch( progressCounter ) {
case 5000: printf("[.obj]: parsing %s...\\", _filename.c_str()); break;
case 10000: printf("[.obj]: parsing %s...|", _filename.c_str()); break;
case 15000: printf("[.obj]: parsing %s.../", _filename.c_str()); break;
case 20000: printf("[.obj]: parsing %s...-", _filename.c_str()); break;
default: break;
}
fflush(stdout);
}
if( progressCounter == 20000 )
progressCounter = 0;
}
}
in.close();
if (INFO) {
printf( "\33[2K\r" );
printf( "[.obj]: parsing %s...done!\n", _filename.c_str() );
}
_materialIndexStartStop.find( currentMaterial )->second.back().second = indicesSeen - 1;
_bufferData();
time(&end);
double seconds = difftime( end, start );
if (INFO) {
printf( "[.obj]: Completed in %.3fs\n", seconds );
printf( "[.obj]: -=-=-=-=-=-=-=- END %s Info -=-=-=-=-=-=-=- \n\n", _filename.c_str() );
}
return result;
}
inline bool CSCI441::ModelLoader::_loadMTLFile( const char* mtlFilename, bool INFO, bool ERRORS ) {
bool result = true;
if (INFO) printf( "[.mtl]: -*-*-*-*-*-*-*- BEGIN %s Info -*-*-*-*-*-*-*-\n", mtlFilename );
std::string line;
std::string path;
if( _filename.find('/') != std::string::npos ) {
path = _filename.substr( 0, _filename.find_last_of('/')+1 );
} else {
path = "./";
}
std::ifstream in;
in.open( mtlFilename );
if( !in.is_open() ) {
std::string folderMtlFile = path + mtlFilename;
in.open( folderMtlFile.c_str() );
if( !in.is_open() ) {
if (ERRORS) fprintf( stderr, "[.mtl]: [ERROR]: could not open material file: %s\n", mtlFilename );
if ( INFO ) printf( "[.mtl]: -*-*-*-*-*-*-*- END %s Info -*-*-*-*-*-*-*-\n", mtlFilename );
return false;
}
}
CSCI441_INTERNAL::ModelMaterial* currentMaterial = nullptr;
std::string materialName;
unsigned char *textureData = nullptr;
unsigned char *maskData = nullptr;
unsigned char *fullData;
int texWidth, texHeight, textureChannels = 1, maskChannels = 1;
GLuint textureHandle = 0;
std::map< std::string, GLuint > imageHandles;
int numMaterials = 0;
while( getline( in, line ) ) {
if( line.length() > 1 && line.at(0) == '\t' )
line = line.substr( 1 );
line.erase( line.find_last_not_of( " \n\r\t" ) + 1 );
std::vector< std::string > tokens = _tokenizeString( line, " /" );
if( tokens.empty() ) continue;
//the line should have a single character that lets us know if it's a...
if( tokens[0] == "#" ) { // comment
// ignore
} else if( tokens[0] == "newmtl" ) { //new material
if (INFO) printf( "[.mtl]: Parsing material %s properties\n", tokens[1].c_str() );
currentMaterial = new CSCI441_INTERNAL::ModelMaterial();
materialName = tokens[1];
_materials.insert( std::pair<std::string, CSCI441_INTERNAL::ModelMaterial*>( materialName, currentMaterial ) );
textureHandle = 0;
textureData = nullptr;
maskData = nullptr;
textureChannels = 1;
maskChannels = 1;
numMaterials++;
} else if( tokens[0] == "Ka" ) { // ambient component
currentMaterial->ambient[0] = strtof( tokens[1].c_str(), nullptr );
currentMaterial->ambient[1] = strtof( tokens[2].c_str(), nullptr );
currentMaterial->ambient[2] = strtof( tokens[3].c_str(), nullptr );
} else if( tokens[0] == "Kd" ) { // diffuse component
currentMaterial->diffuse[0] = strtof( tokens[1].c_str(), nullptr );
currentMaterial->diffuse[1] = strtof( tokens[2].c_str(), nullptr );
currentMaterial->diffuse[2] = strtof( tokens[3].c_str(), nullptr );
} else if( tokens[0] == "Ks" ) { // specular component
currentMaterial->specular[0] = strtof( tokens[1].c_str(), nullptr );
currentMaterial->specular[1] = strtof( tokens[2].c_str(), nullptr );
currentMaterial->specular[2] = strtof( tokens[3].c_str(), nullptr );
} else if( tokens[0] == "Ke" ) { // emissive component
currentMaterial->emissive[0] = strtof( tokens[1].c_str(), nullptr );
currentMaterial->emissive[1] = strtof( tokens[2].c_str(), nullptr );
currentMaterial->emissive[2] = strtof( tokens[3].c_str(), nullptr );
} else if( tokens[0] == "Ns" ) { // shininess component
currentMaterial->shininess = strtof( tokens[1].c_str(), nullptr );
} else if( tokens[0] == "Tr"
|| tokens[0] == "d" ) { // transparency component - Tr or d can be used depending on the format
currentMaterial->ambient[3] = strtof( tokens[1].c_str(), nullptr );
currentMaterial->diffuse[3] = strtof( tokens[1].c_str(), nullptr );
currentMaterial->specular[3] = strtof( tokens[1].c_str(), nullptr );
} else if( tokens[0] == "illum" ) { // illumination type component
// TODO illumination type?
} else if( tokens[0] == "map_Kd" ) { // diffuse color texture map
if( imageHandles.find( tokens[1] ) != imageHandles.end() ) {
// _textureHandles->insert( pair< string, GLuint >( materialName, imageHandles.find( tokens[1] )->second ) );
currentMaterial->map_Kd = imageHandles.find( tokens[1] )->second;
} else {
stbi_set_flip_vertically_on_load(true);
textureData = stbi_load( tokens[1].c_str(), &texWidth, &texHeight, &textureChannels, 0 );
if( !textureData ) {
std::string folderName = path + tokens[1];
textureData = stbi_load( folderName.c_str(), &texWidth, &texHeight, &textureChannels, 0 );
}
if( !textureData ) {
if (ERRORS) fprintf( stderr, "[.mtl]: [ERROR]: File Not Found: %s\n", tokens[1].c_str() );
} else {
if (INFO) printf( "[.mtl]: TextureMap:\t%s\tSize: %dx%d\tColors: %d\n", tokens[1].c_str(), texWidth, texHeight, textureChannels );
if( maskData == nullptr ) {
if( textureHandle == 0 ) {
glGenTextures( 1, &textureHandle );
imageHandles.insert( std::pair<std::string, GLuint>( tokens[1], textureHandle ) );
}
glBindTexture( GL_TEXTURE_2D, textureHandle );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
GLint colorSpace = GL_RGB;
if( textureChannels == 4 )
colorSpace = GL_RGBA;
glTexImage2D( GL_TEXTURE_2D, 0, colorSpace, texWidth, texHeight, 0, colorSpace, GL_UNSIGNED_BYTE, textureData );
currentMaterial->map_Kd = textureHandle;
} else {
fullData = CSCI441_INTERNAL::createTransparentTexture( textureData, maskData, texWidth, texHeight, textureChannels, maskChannels );
if( textureHandle == 0 ) {
glGenTextures( 1, &textureHandle );
imageHandles.insert( std::pair<std::string, GLuint>( tokens[1], textureHandle ) );
}
glBindTexture( GL_TEXTURE_2D, textureHandle );
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, fullData );
delete[] fullData;
currentMaterial->map_Kd = textureHandle;
}
}
}
} else if( tokens[0] == "map_d" ) { // alpha texture map
if( imageHandles.find( tokens[1] ) != imageHandles.end() ) {
// _textureHandles->insert( pair< string, GLuint >( materialName, imageHandles.find( tokens[1] )->second ) );
currentMaterial->map_d = imageHandles.find( tokens[1] )->second;
} else {
stbi_set_flip_vertically_on_load(true);
maskData = stbi_load( tokens[1].c_str(), &texWidth, &texHeight, &textureChannels, 0 );
if( !textureData ) {
std::string folderName = path + tokens[1];
maskData = stbi_load( folderName.c_str(), &texWidth, &texHeight, &textureChannels, 0 );
}
if( !maskData ) {
if (ERRORS) fprintf( stderr, "[.mtl]: [ERROR]: File Not Found: %s\n", tokens[1].c_str() );
} else {
if (INFO) printf( "[.mtl]: AlphaMap: \t%s\tSize: %dx%d\tColors: %d\n", tokens[1].c_str(), texWidth, texHeight, maskChannels );
if( textureData != nullptr ) {
fullData = CSCI441_INTERNAL::createTransparentTexture( textureData, maskData, texWidth, texHeight, textureChannels, maskChannels );
if( textureHandle == 0 ) {
glGenTextures( 1, &textureHandle );
imageHandles.insert( std::pair<std::string, GLuint>( tokens[1], textureHandle ) );
}
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, fullData );
delete[] fullData;
currentMaterial->map_Kd = textureHandle;
}
}
}
} else if( tokens[0] == "map_Ka" ) { // ambient color texture map
// TODO ambient color map?
} else if( tokens[0] == "map_Ks" ) { // specular color texture map
// TODO specular color map?
} else if( tokens[0] == "map_Ns" ) { // specular highlight map (shininess map)
// TODO specular highlight map?
} else if( tokens[0] == "Ni" ) { // optical density / index of refraction
// TODO index of refraction?
} else if( tokens[0] == "Tf" ) { // transmission filter
// TODO transmission filter?
} else if( tokens[0] == "bump"
|| tokens[0] == "map_bump" ) { // bump map
// TODO bump map?
} else {
if (INFO) printf( "[.mtl]: ignoring line: %s\n", line.c_str() );
}
}
in.close();
if ( INFO ) {
printf( "[.mtl]: Materials:\t%d\n", numMaterials );
printf( "[.mtl]: -*-*-*-*-*-*-*- END %s Info -*-*-*-*-*-*-*-\n", mtlFilename );
}
return result;
}
inline bool CSCI441::ModelLoader::_loadOFFFile( bool INFO, bool ERRORS ) {
bool result = true;
if (INFO ) printf( "[.off]: -=-=-=-=-=-=-=- BEGIN %s Info -=-=-=-=-=-=-=-\n", _filename.c_str() );
time_t start, end;
time(&start);
std::ifstream in( _filename );
if( !in.is_open() ) {
if (ERRORS) fprintf( stderr, "[.off]: [ERROR]: Could not open \"%s\"\n", _filename.c_str() );
if ( INFO ) printf( "[.off]: -=-=-=-=-=-=-=- END %s Info -=-=-=-=-=-=-=-\n\n", _filename.c_str() );
return false;
}
GLuint numVertices = 0, numFaces = 0, numTriangles = 0;
GLfloat minX = 999999.0f, maxX = -999999.0f, minY = 999999.0f, maxY = -999999.0f, minZ = 999999.0f, maxZ = -999999.0f;
std::string line;
enum OFF_FILE_STATE { HEADER, VERTICES, FACES, DONE };
OFF_FILE_STATE fileState = HEADER;
GLuint vSeen = 0, fSeen = 0;
while( getline( in, line ) ) {
if( line.length() > 1 && line.at(0) == '\t' )
line = line.substr( 1 );
line.erase( line.find_last_not_of( " \n\r\t" ) + 1 );
std::vector< std::string > tokens = _tokenizeString( line, " \t" );
if( tokens.empty() ) continue;
//the line should have a single character that lets us know if it's a...
if( tokens[0] == "#" || tokens[0].find_first_of('#') == 0 ) { // comment ignore
} else if( fileState == HEADER ) {
if( tokens[0] == "OFF" ) { // denotes OFF File type
} else {
if( tokens.size() != 3 ) {
if (ERRORS) fprintf( stderr, "[.off]: [ERROR]: Malformed OFF file. # vertices, faces, edges not properly specified\n" );