forked from KhronosGroup/glTF-Sample-Models
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1054 lines (812 loc) · 27.2 KB
/
main.cpp
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
//#define assert(expr) if(!(expr)) __debugbreak();
#define BOOST_JSON_NO_LIB
#define BOOST_CONTAINER_NO_LIB
#include <boost/json.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <vector>
#include <string>
#include <stb_include.h>
#include <stb_image.h>
#define GLM_ENABLE_EXPERIMENTAL
#include <glad/gl.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/common.hpp>
#include <glm/vec2.hpp>
#include <glm/vec3.hpp>
#include <glm/vec4.hpp>
#include <glm/mat4x4.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <glm/gtx/string_cast.hpp>
namespace json{using namespace boost::json;}
using namespace std::filesystem;
uint32_t
g_width = 1460,
g_height = 780;
const uint32_t
ATTRIB_POS = 0,
ATTRIB_NORMAL = 1,
ATTRIB_TEX0 = 2;
static constexpr float g_cameraSpeed = .001f;
struct BufferView
{
GLuint buffer;
uint32_t
byteOffset = 0,
byteLength,
byteStride = 0;
GLenum target = 0;
};
struct Accessor
{
std::vector<BufferView>::const_iterator bufferView;
uint32_t byteOffset = 0;
GLenum componentType;
bool normalized;
uint32_t count;
std::string type;
//todo min max and sparse
};
struct Node;
struct Animation
{
struct Sampler {
std::vector<Accessor>::const_iterator
input, output;
std::string interpolation;
};
struct Channel {
std::vector<Animation::Sampler>::const_iterator sampler;
std::vector<Node>::const_iterator node;
std::string path;
};
std::vector<Animation::Channel> channels;
std::vector<Animation::Sampler> samplers;
std::string name;
};
struct Image {
uint32_t x, y;
stbi_uc* image;
uint32_t channels;
};
struct Texture {
GLuint sampler;
GLuint tex;
};
struct TextureInfo
{
std::vector<Texture>::const_iterator tex;
uint32_t unit = 0;
};
struct Material
{
bool unlit = false;
glm::vec4 baseColorFactor = { 1.f, 1.f, 1.f, 1.f };
glm::vec3
attenuationColor = { 1,1,1 },
normalScale = { 1.0f, 1.0f, 1.0f },
clearcoatNormalScale = { 1, 1, 1 },
sheenColorFactor = { 0,0,0 },
specularColorFactor = { 1,1,1 }
;
float
attenuationDistance = INFINITY,
clearcoatFactor = 0.0,
clearcoatRoughnessFactor = 0.0,
emissiveStrength = 1.0,
ior = 1.5,
iridescenceFactor = 0.0,
iridescenceIor = 1.3,
iridescenceThicknessMinimum = 100.0,
iridescenceThicknessMaximum = 400.0,
metallicFactor = 1.f,
roughnessFactor = 1.f,
sheenRoughnessFactor = 0.0,
specularFactor = 0.0,
thicknessFactor = 0,
transmissionFactor = 0.0
;
struct TextureInfo
baseColorTexture,
clearcoatTexture,
clearcoatRoughnessTexture,
emissiveTexture,
iridescenceTexture,
iridescenceThicknessTexture,
metallicRoughnessTexture,
normalTexture,
occlusionTexture,
sheenColorTexture,
specularColorTexture,
specularTexture,
thicknessTexture,
transmissionTexture
;
};
struct Mesh
{
struct Primitive
{
uint32_t count = 0; // vertex count
std::vector<Accessor>::const_iterator indices;
std::vector<Material>::const_iterator material;
GLenum mode = GL_TRIANGLES;
};
std::vector<Primitive> primitives;
std::vector<GLuint> vaos;
};
struct Node
{
//todo camera
std::vector<std::vector<Node>::const_iterator> children;
//todo skin
glm::mat4 matrix = glm::mat4(1.f);
std::vector<Mesh>::const_iterator mesh;
glm::quat rotation;
glm::vec3 scale;
glm::vec3 translation;
std::vector<float> weights;
static constexpr glm::quat DEFAULT_ROTATION = { 1.f, 0, 0, 0 };
static constexpr glm::vec3 DEFAULT_SCALE = { 1.f, 1.f, 1.f };
static constexpr glm::vec3 DEFAULT_TRANSLATION = { 0,0,0 };
};
struct Scene
{
std::vector<std::vector<Node>::const_iterator> nodes;
};
;
static float getFloat(json::value v)
{
return (float)(v.is_double() ? v.as_double() : v.as_int64());
}
static GLuint makeShader(GLenum type, const char* path)
{
char error[256];
char* source = stb_include_file((char*)path, NULL, NULL, error);
if (source == NULL)
{
glDebugMessageInsert(GL_DEBUG_SOURCE_THIRD_PARTY, GL_DEBUG_TYPE_ERROR, 1, GL_DEBUG_SEVERITY_HIGH, -(signed)strlen(error), error);
return 0;
}
int32_t length = strlen(source);
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &source, &length);
glCompileShader(shader);
GLint isCompiled = false;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
if (!isCompiled)
{
GLint len = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
assert(len != 0);
char* msg = (char*)malloc(len * sizeof * msg);
glGetShaderInfoLog(shader, len, NULL, (GLchar*)msg);
std::cout << msg << '\n';
free(msg);
glDeleteShader(shader);
shader = 0;
}
if (!isCompiled)
{
glDeleteShader(shader);
shader = 0;
}
free(source);
return shader;
}
constexpr static uint32_t getAccessorTypeComponentCount(std::string type)
{
if (type == "SCALAR") return 1;
if (type == "VEC2") return 2;
if (type == "VEC3") return 3;
if (type == "VEC4") return 4;
if (type == "MAT2") return 4;
if (type == "MAT3") return 9;
if (type == "MAT4") return 16;
else return 0;
}
constexpr static uint32_t getComponentTypeByteSize(GLenum type)
{
switch (type)
{
case GL_BYTE: case GL_UNSIGNED_BYTE: return sizeof(char);
case GL_SHORT: case GL_UNSIGNED_SHORT: return sizeof(short);
case GL_INT: case GL_UNSIGNED_INT: return sizeof(int);
case GL_FLOAT: return sizeof(float);
default: return 0;
}
}
path filepath = "2.0/Sponza/glTF/Sponza.gltf";
int main()
{
glfwInit();
glfwWindowHint(GLFW_VISIBLE, false);
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow* window = glfwCreateWindow(g_width, g_height, "glTF Manifest", NULL, NULL);
glfwMakeContextCurrent(window);
gladLoaderLoadGL();
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback([](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam)
{
std::cout << message << "\n";
}, NULL);
GLuint program = glCreateProgram();
{
GLuint
vShader = makeShader(GL_VERTEX_SHADER, "shader.vert"),
fShader = makeShader(GL_FRAGMENT_SHADER, "shader.frag");
assert(vShader != 0);
assert(fShader != 0);
glAttachShader(program, vShader);
glAttachShader(program, fShader);
glLinkProgram(program);
GLint isLinked = false;
glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
if (!isLinked)
{
GLint len = 0;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &len);
assert(len != 0);
char* msg = (char*)malloc(len * sizeof * msg);
glGetProgramInfoLog(program, len, NULL, (GLchar*)msg);
std::cout << msg << '\n';
free(msg);
glDeleteProgram(program);
program = 0;
return 0;
}
glDetachShader(program, vShader);
glDetachShader(program, fShader);
glDeleteShader(vShader);
glDeleteShader(fShader);
}
glUseProgram(program);
GLuint matrixUBO;
glCreateBuffers(1, &matrixUBO);
glNamedBufferData(matrixUBO, 4 * sizeof(glm::mat4), NULL, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 0, matrixUBO);
GLuint camLightUBO;
glCreateBuffers(1, &camLightUBO);
glNamedBufferData(camLightUBO, 3 * sizeof(glm::vec4), NULL, GL_DYNAMIC_DRAW);
glBindBufferBase(GL_UNIFORM_BUFFER, 1, camLightUBO);
//
// Reading
//
json::error_code err;
auto gltf = json::parse([]()->std::string
{
std::ifstream in(filepath);
if (in.fail())
throw std::exception("Failed to read gltf file");
return (std::stringstream() << in.rdbuf()).str();
}
(), err).as_object();
if (err)
{
std::cout << err.message() << std::endl;
return -1;
}
//
// Parsing
//
auto accessors = std::vector<Accessor> (gltf.if_contains("accessors") ? gltf["accessors"] .as_array().size() : 0);
auto animations = std::vector<Animation> (gltf.if_contains("animations") ? gltf["animations"] .as_array().size() : 0);
auto buffers = std::vector<GLuint> (gltf.if_contains("buffers") ? gltf["buffers"] .as_array().size() : 0);
auto bufferViews= std::vector<BufferView>(gltf.if_contains("bufferViews")? gltf["bufferViews"] .as_array().size() : 0);
auto images = std::vector <Image> (gltf.if_contains("images") ? gltf["images"] .as_array().size() : 0);
auto materials = std::vector<Material> (gltf.if_contains("materials") ? gltf["materials"] .as_array().size() : 0);
auto meshes = std::vector<Mesh> (gltf.if_contains("meshes") ? gltf["meshes"] .as_array().size() : 0);
auto nodes = std::vector<Node> (gltf.if_contains("nodes") ? gltf["nodes"] .as_array().size() : 0);
auto samplers = std::vector<GLuint> (gltf.if_contains("samplers") ? gltf["samplers"] .as_array().size() : 0);
auto scenes = std::vector<Scene> (gltf.if_contains("scenes") ? gltf["scenes"] .as_array().size() : 0);
auto textures = std::vector<Texture> (gltf.if_contains("textures") ? gltf["textures"] .as_array().size() : 0);
glCreateBuffers((GLsizei)buffers.size(), buffers.data());
for (uint32_t i = 0; i < buffers.size(); i++)
{
auto jo = gltf["buffers"].as_array()[i].as_object();
auto uri = (std::string)jo["uri"].as_string();
auto byteLenth = jo["byteLength"].as_int64();
glObjectLabel(GL_BUFFER, buffers[i], -1, jo["name"].is_null() ? uri.c_str() : jo["name"].as_string().c_str());
glNamedBufferData(buffers[i], byteLenth, NULL, GL_STATIC_DRAW);
auto input = std::ifstream((filepath.parent_path() / uri).string(), std::ios::binary);
char* block = (char*)glMapNamedBuffer(buffers[i], GL_WRITE_ONLY);
{
input.read(block, byteLenth);
}
glUnmapNamedBuffer(buffers[i]);
input.close();
}
glCreateSamplers((GLsizei)samplers.size(), samplers.data());
for (uint32_t i = 0; i < samplers.size(); i++)
{
auto jo = gltf["samplers"].as_array()[i].as_object();
if (!jo["name"].is_null())
glObjectLabel(GL_SAMPLER, samplers[i], -1, jo["name"].as_string().c_str());
if (!jo["magFilter"].is_null())
glSamplerParameteri(samplers[i], GL_TEXTURE_MAG_FILTER, jo["magFilter"].as_int64());
if (!jo["minFilter"].is_null())
glSamplerParameteri(samplers[i], GL_TEXTURE_MIN_FILTER, jo["minFilter"].as_int64());
glSamplerParameteri(samplers[i], GL_TEXTURE_WRAP_S, jo["wrapS"].is_null() ? GL_REPEAT : jo["wrapS"].as_int64());
glSamplerParameteri(samplers[i], GL_TEXTURE_WRAP_T, jo["wrapT"].is_null() ? GL_REPEAT : jo["wrapT"].as_int64());
}
//default sampler:
{
GLuint sampler;
glCreateSamplers(1, &sampler);
glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_REPEAT);
glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
samplers.push_back(sampler);
}
auto parseTextureInfo = [&textures](json::object& o) -> TextureInfo
{
auto t = TextureInfo{
.tex = textures.begin() + o.at("index").as_int64(),
};
if (o.if_contains("texCoord"))
t.unit = o.at("texCoord").as_int64();
return t;
};
for (uint32_t i = 0; i < bufferViews.size(); i++)
{
auto jo = gltf["bufferViews"].as_array()[i].as_object();
bufferViews[i].buffer = buffers[jo["buffer"].as_int64()];
if (!jo["byteOffset"].is_null())
bufferViews[i].byteOffset = jo["byteOffset"].as_int64();
bufferViews[i].byteLength = jo["byteLength"].as_int64();
if (!jo["byteStride"].is_null())
bufferViews[i].byteStride = jo["byteStride"].as_int64();
if (!jo["target"].is_null())
{
auto val = jo["target"].as_int64();
assert(val == GL_ARRAY_BUFFER || val == GL_ELEMENT_ARRAY_BUFFER);
bufferViews[i].target = val;
}
}
for (uint32_t i = 0; i < accessors.size(); i++)
{
auto jo = gltf["accessors"].as_array()[i].as_object();
auto& a = accessors[i];
//todo sparse
a.bufferView = bufferViews.begin() + jo["bufferView"].as_int64();
if (!jo["byteOffset"].is_null())
a.byteOffset = jo["byteOffset"].as_int64();
a.componentType = jo["componentType"].as_int64();
if (!jo["normalized"].is_null())
a.normalized = jo["normalized"].as_bool();
a.count = jo["count"].as_int64();
a.type = (std::string)jo["type"].as_string();
//todo min max
}
for (uint32_t i = 0; i < images.size(); i++)
{
auto jo = gltf["images"].as_array()[i].as_object();
auto uri = (std::string) jo["uri"].as_string();
auto p = (filepath.parent_path() / uri).string();
boost::algorithm::replace_all(p, "%20", " ");
FILE* file = NULL;
fopen_s(&file, p.c_str(), "rb");
assert(file != NULL);
int x, y, channels;
auto img = stbi_load_from_file(file, &x, &y, &channels, STBI_rgb_alpha);
fclose(file);
images[i].channels = channels;
images[i].x = x;
images[i].y = y;
images[i].image = img;
}
for (uint32_t i = 0; i < textures.size(); i++)
{
auto jo = gltf["textures"].as_array()[i].as_object();
auto sampler = jo.if_contains("sampler") ? samplers[jo["sampler"].as_int64()] : samplers[samplers.size()-1];
auto image = images[jo["source"].as_int64() ];
GLuint tex;
glCreateTextures(GL_TEXTURE_2D, 1, &tex);
glTextureStorage2D(tex, 1, GL_RGBA8, image.x, image.y);
glBindTexture(GL_TEXTURE_2D, textures[i].tex);
glTextureSubImage2D(tex, 0, 0, 0, image.x, image.y, GL_RGBA, GL_UNSIGNED_BYTE, image.image);
textures[i] = Texture{.sampler = sampler, .tex = tex };
}
for (uint32_t i = 0; i < materials.size(); i++)
{
auto jo = gltf["materials"].as_array()[i].as_object();
auto& mat = materials[i];
if (!jo["pbrMetallicRoughness"].is_null())
{
auto pbr = jo["pbrMetallicRoughness"].as_object();
if (pbr.if_contains("baseColorFactor"))
{
auto arr = pbr["baseColorFactor"].as_array();
for (uint32_t j = 0; j < glm::vec4::length(); j++)
mat.baseColorFactor[j] = getFloat(arr[j]);
}
if (!pbr["metallicFactor"].is_null())
mat.metallicFactor = getFloat(pbr["metallicFactor"]);
if (!pbr["roughnessFactor"].is_null())
mat.roughnessFactor = getFloat(pbr["roughnessFactor"]);
auto bct = pbr["baseColorTexture"];
auto mrt = pbr["metallicRoughnessTexture"];
if (!bct.is_null())
mat.baseColorTexture = parseTextureInfo(bct.as_object());
if (!mrt.is_null())
mat.metallicRoughnessTexture = parseTextureInfo(mrt.as_object());
}
if (jo.if_contains("normalTexture"))
{
auto nt = jo["normalTexture"].as_object();
mat.normalTexture = parseTextureInfo(nt);
if (nt.if_contains("scale"))
{
for (uint32_t j = 0; j < glm::vec3::length(); j++)
mat.normalScale[j] = getFloat(nt["scale"].as_array()[j]);
}
}
}
for (uint32_t i = 0; i < meshes.size(); i++)
{
auto jom = gltf["meshes"].as_array()[i].as_object();
meshes[i].primitives.resize(jom["primitives"].as_array().size());
meshes[i].vaos.resize(meshes[i].primitives.size());
glCreateVertexArrays(meshes[i].vaos.size(), meshes[i].vaos.data());
for (uint32_t j = 0; j < meshes[i].vaos.size(); j++)
{
auto& prim = meshes[i].primitives[j];
auto& vao = meshes[i].vaos[j];
auto jop = jom["primitives"].as_array()[j].as_object();
///
/// Name: | Accessor Type | Component Type
///-------------+---------------+---------------
/// POSITION | VEC3 | float
/// NORMAL | VEC3 | float
/// TANGENT | VEC3 | float
/// TEXCOORD_n | VEC2 | float / (un)signed normalized (byte / short)
/// COLOR_n | VEC3 / VEC4 | float / (un)signed normalized (byte / short)
/// indices | SCALAR | unsigned (byte / short / int)
///
auto attribs = jop["attributes"].as_object();
auto linkAttribute = [attribs, vao, accessors](Accessor const& a, uint32_t location)
{
auto stride = a.bufferView->byteStride != 0 ? a.bufferView->byteStride : getAccessorTypeComponentCount(a.type) * getComponentTypeByteSize(a.componentType);
glVertexArrayVertexBuffer (vao, location, a.bufferView->buffer, a.bufferView->byteOffset + a.byteOffset, stride);
glEnableVertexArrayAttrib (vao, location);
glVertexArrayAttribBinding(vao, location, location); //I feel like this is wrong but I don't know why
glVertexArrayAttribFormat (vao, location, getAccessorTypeComponentCount(a.type), a.componentType, a.normalized, 0);
};
uint32_t count = 0;
if (!attribs["POSITION"].is_null())
{
auto a = accessors.begin() + attribs["POSITION"].as_int64();
assert(a->type == "VEC3");
assert(a->componentType == GL_FLOAT);
linkAttribute(*a, ATTRIB_POS);
count = std::max(count, a->count);
}
if (!attribs["NORMAL"].is_null())
{
auto a = accessors.begin() + attribs["NORMAL"].as_int64();
assert(a->type == "VEC3");
assert(a->componentType == GL_FLOAT);
linkAttribute(*a, ATTRIB_NORMAL);
count = std::max(count, a->count);
}
if (attribs.if_contains("TEXCOORD_0"))
{
auto a = accessors.begin() + attribs["TEXCOORD_0"].as_int64();
linkAttribute(*a, ATTRIB_TEX0);
}
if (!jop["indices"].is_null())
{
auto a = accessors.begin() + jop["indices"].as_int64();
prim.indices = a;
glVertexArrayElementBuffer(vao, a->bufferView->buffer);
}
if (!jop["material"].is_null())
{
prim.material = materials.begin() + jop["material"].as_int64();
}
prim.count = count;
prim.mode = jop["mode"].is_null() ? GL_TRIANGLES : jop["mode"].as_int64();
}
}
for (uint32_t i = 0; i < nodes.size(); i++)
{
auto jo = gltf["nodes"].as_array()[i].as_object();
auto& n = nodes[i];
if(!jo["children"].is_null())
n.children.resize(jo["children"].as_array().size());
for (uint32_t i = 0; i < n.children.size(); i++)
n.children[i] = nodes.begin() + jo["children"].as_array()[i].as_int64();
if (!jo["matrix"].is_null())
{
auto matrix = jo["matrix"].as_array();
assert(matrix.size() == 16);
for (uint32_t i = 0; i < matrix.size(); i++)
{
*(glm::value_ptr(n.matrix) + i) = getFloat(matrix[i]);
}
}
else n.matrix = glm::mat4(1.f);
if (!jo["mesh"].is_null())
n.mesh = meshes.begin() + jo["mesh"].as_int64();
if (jo["rotation"].is_null())
n.rotation = Node::DEFAULT_ROTATION;
else
{
auto vec = jo["rotation"].as_array();
n.rotation[0] = getFloat(vec[3]);
n.rotation[1] = getFloat(vec[0]);
n.rotation[2] = getFloat(vec[1]);
n.rotation[3] = getFloat(vec[2]);
}
if (jo["scale"].is_null())
n.scale = Node::DEFAULT_SCALE;
else
{
auto vec = jo["scale"].as_array();
n.scale[0] = getFloat(vec[0]);
n.scale[1] = getFloat(vec[1]);
n.scale[2] = getFloat(vec[2]);
}
if (jo["translation"].is_null())
n.translation = Node::DEFAULT_TRANSLATION;
else
{
auto vec = jo["translation"].as_array();
n.translation[0] = getFloat(vec[0]);
n.translation[1] = getFloat(vec[1]);
n.translation[2] = getFloat(vec[2]);
}
if (jo.if_contains("matrix"))
{
n.matrix = glm::translate(n.translation) * glm::toMat4(n.rotation) * glm::scale(n.scale);
}
if (!jo["weights"].is_null())
n.weights = std::vector<float>(jo["weights"].as_array().size());
for (uint32_t i = 0; i < n.weights.size(); i++)
n.weights[i] = getFloat(jo["weights"].as_array()[i]);
}
for (uint32_t i = 0; i < scenes.size(); i++)
{
auto jo = gltf["scenes"].as_array()[i].as_object();
auto& scene = scenes[i];
if (!jo["nodes"].is_null())
{
auto ns = jo["nodes"].as_array();
scene.nodes.resize(ns.size());
for (uint32_t j = 0; j < ns.size(); j++)
{
scene.nodes[j] = nodes.begin() + ns[j].as_int64();
}
}
}
for (uint32_t i = 0; i < animations.size(); i++)
{
auto jo = gltf["animations"].as_array()[i].as_object();
auto& a = animations[i];
if (jo.if_contains("name"))
a.name = (std::string)jo["name"].as_string();
auto joss = jo["samplers"].as_array();
a.samplers.resize(joss.size());
for (uint32_t j = 0; j < a.samplers.size(); j++)
{
auto& s = a.samplers[j];
auto jos = joss[j].as_object();
s.input = accessors.begin() + jos["input"].as_int64();
s.output = accessors.begin() + jos["output"].as_int64();
s.interpolation = (std::string)jos["interpolation"].as_string();
}
auto jocs = jo["channels"].as_array();
a.channels.resize(jocs.size());
for (uint32_t j = 0; j < a.channels.size(); j++)
{
auto joc = jocs[j].as_object();
auto c = a.channels[j];
c.sampler = a.samplers.begin() + joc["sampler"].as_int64();
if (joc.if_contains("target"))
{
auto jot = joc["target"].as_object();
c.node = nodes.begin() + jot["node"].as_int64();
c.path = (std::string)jot["path"].as_string();
}
}
}
auto scene = scenes.begin() + (gltf.if_contains("scene") ? gltf["scene"].as_int64() : 0);
//
// Remove intermediates
//
for (const auto& img : images)
stbi_image_free(img.image);
//
// Rendering
//
glm::vec3 lightPos = { 0, 10, 0 };
glm::vec4 lightColor = { 1, 1, 1, 1 };
glm::vec3
pos = { 0, 0, -10 },
dir = { 0, 0, 1 },
up = { 0, 1, 0 };
bool firstClick = true;
float speed = .1f;
float sensitivity = 100.f;
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glNamedBufferSubData(camLightUBO, 1 * sizeof(glm::vec4), sizeof(glm::vec3), glm::value_ptr(lightPos));
glNamedBufferSubData(camLightUBO, 2 * sizeof(glm::vec4), sizeof(glm::vec4), glm::value_ptr(lightColor));
glfwShowWindow(window);
while (!glfwWindowShouldClose(window))
{
glfwPollEvents();
glfwGetFramebufferSize(window, (int*)& g_width, (int*)&g_height);
#pragma region Input handling
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
pos += speed * dir;
}
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
pos += speed * -glm::normalize(glm::cross(dir, up));
}
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
pos += speed * -dir;
}
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
pos += speed * glm::normalize(glm::cross(dir, up));
}
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
{
pos += speed * up;
}
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
{
pos += speed * -up;
}
if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
{
speed = 0.4f;
}
else if (glfwGetKey(window, GLFW_KEY_LEFT_SHIFT) == GLFW_RELEASE)
{
speed = 0.01f;
}
// Handles mouse inputs
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
// Hides mouse cursor
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
// Prevents camera from jumping on the first click
if (firstClick)
{
glfwSetCursorPos(window, (g_width / 2), (g_height / 2));
firstClick = false;
}
// Stores the coordinates of the cursor
double mouseX;
double mouseY;
// Fetches the coordinates of the cursor
glfwGetCursorPos(window, &mouseX, &mouseY);
// Normalizes and shifts the coordinates of the cursor such that they begin in the middle of the screen
// and then "transforms" them into degrees
float rotX = sensitivity * (float)(mouseY - (g_height / 2)) / g_height;
float rotY = sensitivity * (float)(mouseX - (g_width / 2)) / g_width;
// Calculates upcoming vertical change in the Orientation
glm::vec3 newOrientation = glm::rotate(dir, glm::radians(-rotX), glm::normalize(glm::cross(dir, up)));
// Decides whether or not the next vertical Orientation is legal or not
if (abs(glm::angle(newOrientation, up) - glm::radians(90.0f)) <= glm::radians(85.0f))
{
dir = newOrientation;
}
// Rotates the Orientation left and right
dir = glm::rotate(dir, glm::radians(-rotY), up);
// Sets mouse cursor to the middle of the screen so that it doesn't end up roaming around
glfwSetCursorPos(window, (g_width / 2), (g_height / 2));
}
else if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE)
{
// Unhides cursor since camera is not looking around anymore
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// Makes sure the next time the camera looks around it doesn't jump
firstClick = true;
}
#pragma endregion
glm::mat4
projection = glm::perspective(glm::radians(45.f), (float)g_width / g_height, .1f, 100.f),
view = glm::lookAt(pos, (pos + dir), up);
glNamedBufferSubData(matrixUBO, 0 * sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(projection));
glNamedBufferSubData(matrixUBO, 1 * sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(view));
glNamedBufferSubData(camLightUBO, 0, sizeof(glm::vec3), glm::value_ptr(pos));
glClearColor(0, 0, 0, 1);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glViewport(0, 0, g_width, g_height);
std::function<void(std::vector<Node>::const_iterator, glm::mat4)> drawNodes;
drawNodes = [matrixUBO, &drawNodes, program](std::vector<Node>::const_iterator node, glm::mat4 mtx)
{
glm::mat4
matrix = mtx * node->matrix, //todo
normal = glm::inverse(glm::transpose(matrix));
if (node->mesh._Ptr != NULL)
{
glNamedBufferSubData(matrixUBO, 2 * sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(matrix)); //let the node's matrix eb the mesh's matrix
glNamedBufferSubData(matrixUBO, 3 * sizeof(glm::mat4), sizeof(glm::mat4), glm::value_ptr(normal));
auto& mesh = *node->mesh;
for (uint32_t i = 0; i < mesh.primitives.size(); i++)
{
auto prim = mesh.primitives[i];
auto mat = prim.material;
auto vao = mesh.vaos[i];
if (mat._Ptr)
{
glProgramUniform4fv(program, 0, 1, glm::value_ptr(mat->baseColorFactor));
glProgramUniform1i (program, 1, mat->baseColorTexture.tex._Ptr != NULL);
if (mat->baseColorTexture.tex._Ptr)
{
glActiveTexture(GL_TEXTURE0 + 0);
glBindSampler(0, mat->baseColorTexture.tex->sampler);
glBindTexture(GL_TEXTURE_2D, mat->baseColorTexture.tex->tex);
}
glProgramUniform2fv(program, 2, 1, glm::value_ptr(glm::vec2(mat->metallicFactor, mat->roughnessFactor)));
glProgramUniform1i (program, 3, mat->metallicRoughnessTexture.tex._Ptr != NULL);
if (mat->metallicRoughnessTexture.tex._Ptr)
{
glActiveTexture(GL_TEXTURE0 + 1);
glBindSampler(1, mat->metallicRoughnessTexture.tex->sampler);
glBindTexture(GL_TEXTURE_2D, mat->metallicRoughnessTexture.tex->tex);
}
glProgramUniform3fv(program, 4, 1, glm::value_ptr(mat->normalScale));
glProgramUniform1i (program, 5, mat->normalTexture.tex._Ptr != NULL);
if (mat->normalTexture.tex._Ptr)
{
glActiveTexture(GL_TEXTURE0 + 2);
glBindSampler(2, mat->normalTexture.tex->sampler);
glBindTexture(GL_TEXTURE_2D, mat->normalTexture.tex->tex);
}
}
else // To not screw up the rendering when no material at all is present