forked from facebook/igl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tiny_MeshLarge.cpp
2720 lines (2386 loc) · 92.1 KB
/
Tiny_MeshLarge.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* A brief tutorial how to run this beast:
*
* 1) Run the script "deploy_deps.py" from the IGL root folder.
* 2) Run the script "deploy_content.py" from the IGL root folder.
* 3) Run this app.
*
*/
#if !defined(_USE_MATH_DEFINES)
#define _USE_MATH_DEFINES
#endif // _USE_MATH_DEFINES
#include <cassert>
#include <cmath>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <stdio.h>
#include <thread>
#include <igl/FPSCounter.h>
#include <igl/IGL.h>
#include <igl/vulkan/util/TextureFormat.h>
#include <glm/ext.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/random.hpp>
#include <ktx.h>
#include <Compress.h>
#include <meshoptimizer.h>
#include <shared/Camera.h>
#include <shared/UtilsCubemap.h>
#include <stb/stb_image.h>
#include <stb/stb_image_resize.h>
#include <taskflow/taskflow.hpp>
#include <tiny_obj_loader.h>
#define USE_TEXTURE_LOADER 0
#define USE_OPENGL_BACKEND 0
#if IGL_BACKEND_OPENGL && !IGL_BACKEND_VULKAN
// no IGL/Vulkan was compiled in, switch to IGL/OpenGL
#undef USE_OPENGL_BACKEND
#define USE_OPENGL_BACKEND 1
#endif
#if USE_OPENGL_BACKEND
// for KTX textures
#define VK_FORMAT_R32G32B32A32_SFLOAT 109
#define VK_FORMAT_BC7_UNORM_BLOCK 145
#endif // USE_OPENGL_BACKEND
#if defined(__cpp_lib_format)
#include <format>
#define IGL_FORMAT std::format
#else
#include <fmt/core.h>
#define IGL_FORMAT fmt::format
#endif // __cpp_lib_format
#include <igl/IGL.h>
// clang-format off
#if USE_OPENGL_BACKEND
#include <igl/RenderCommandEncoder.h>
#include <igl/opengl/RenderCommandEncoder.h>
#include <igl/opengl/RenderPipelineState.h>
#if IGL_PLATFORM_WIN
#include <igl/opengl/wgl/Context.h>
#include <igl/opengl/wgl/Device.h>
#include <igl/opengl/wgl/HWDevice.h>
#include <igl/opengl/wgl/PlatformDevice.h>
#elif IGL_PLATFORM_LINUX
#include <igl/opengl/glx/Context.h>
#include <igl/opengl/glx/Device.h>
#include <igl/opengl/glx/HWDevice.h>
#include <igl/opengl/glx/PlatformDevice.h>
#endif
#else
#include <igl/vulkan/Common.h>
#include <igl/vulkan/Device.h>
#include <igl/vulkan/HWDevice.h>
#include <igl/vulkan/PlatformDevice.h>
#include <igl/vulkan/Texture.h>
#include <igl/vulkan/VulkanContext.h>
#endif
// clang-format on
#ifdef _WIN32
#define GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WGL
#elif __APPLE__
#define GLFW_EXPOSE_NATIVE_COCOA
#elif defined(__linux__)
#define GLFW_EXPOSE_NATIVE_X11
#define GLFW_EXPOSE_NATIVE_GLX
#else
#error Unsupported OS
#endif
#include <GLFW/glfw3.h>
#include <GLFW/glfw3native.h>
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
// @fb-only
#if IGL_WITH_IGLU
#include <IGLU/imgui/Session.h>
#endif // IGL_WITH_IGLU
#if USE_TEXTURE_LOADER
#include <IGLU/texture_loader/ktx1/TextureLoaderFactory.h>
#include <IGLU/texture_loader/ktx2/TextureLoaderFactory.h>
static_assert(IGL_WITH_IGLU != 0,
"USE_TEXTURE_LOADER can be enabled only together with IGL_WITH_IGLU");
#endif // USE_TEXTURE_LOADER
namespace {
constexpr uint32_t kMeshCacheVersion = 0xC0DE0009;
constexpr int kNumSamplesMSAA = 8;
#if USE_OPENGL_BACKEND
constexpr bool kEnableCompression = false;
#else
constexpr bool kEnableCompression = true;
constexpr bool kPreferIntegratedGPU = false;
#if defined(NDEBUG)
constexpr bool kEnableValidationLayers = false;
#else
constexpr bool kEnableValidationLayers = true;
#endif // NDEBUG
#endif // USE_OPENGL_BACKEND
std::string contentRootFolder;
#if IGL_WITH_IGLU
std::unique_ptr<iglu::imgui::Session> imguiSession_;
igl::shell::InputDispatcher inputDispatcher_;
#endif // IGL_WITH_IGLU
#if USE_TEXTURE_LOADER
void loadKtxTexture(const igl::IDevice& device,
igl::ICommandQueue& commandQueue,
const std::string filename,
std::shared_ptr<igl::ITexture>& texture,
bool generateMipmaps) {
igl::Result result;
if (!filename.empty() && filename.back() != '2' && std::filesystem::exists(filename + "2")) {
loadKtxTexture(device, commandQueue, filename + "2", texture, generateMipmaps);
return;
}
const auto size = std::filesystem::file_size(filename);
FILE* file = std::fopen(filename.c_str(), "rb");
if (!IGL_VERIFY(file)) {
return;
}
std::unique_ptr<uint8_t[]> data = std::make_unique<uint8_t[]>(size);
std::fread(data.get(), 1, size, file);
std::fclose(file);
iglu::textureloader::ktx1::TextureLoaderFactory factory1;
iglu::textureloader::ktx2::TextureLoaderFactory factory2;
iglu::textureloader::ITextureLoaderFactory* factory =
filename.back() == '2' ? static_cast<iglu::textureloader::ITextureLoaderFactory*>(&factory2)
: &factory1;
auto loader = factory->tryCreate(data.get(), size, &result);
if (!IGL_VERIFY(loader && result.isOk())) {
return;
}
if (!texture) {
IGL_ASSERT(loader->isSupported(device));
texture = loader->create(device, &result);
if (!IGL_VERIFY(texture && result.isOk())) {
return;
}
}
IGL_ASSERT(loader->isSupported(device, texture->getUsage()));
loader->upload(*texture, &result);
if (IGL_VERIFY(result.isOk())) {
if (generateMipmaps) {
texture->generateMipmap(commandQueue);
}
}
}
#endif // USE_TEXTURE_LOADER
const char* kCodeComputeTest = R"(
layout(local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
#ifdef VULKAN
// kBinding_StorageImages in VulkanContext.cpp
layout (set = 3, binding = 6, rgba8) uniform readonly image2D kTextures2Din[];
layout (set = 3, binding = 6, rgba8) uniform writeonly image2D kTextures2Dout[];
layout(push_constant) uniform PushConstants {
uint textureId;
} pc;
#else
layout (binding = 3, rgba8) uniform readonly image2D kTextures2Din;
layout (binding = 3, rgba8) uniform writeonly image2D kTextures2Dout;
#endif
vec4 imageLoad2D(ivec2 uv) {
#ifdef VULKAN
return imageLoad(kTextures2Din[pc.textureId], uv);
#else
return imageLoad(kTextures2Din, uv);
#endif
}
void imageStore2D(ivec2 uv, vec4 data) {
#ifdef VULKAN
imageStore(kTextures2Dout[pc.textureId], uv, data);
#else
imageStore(kTextures2Dout, uv, data);
#endif
}
void main() {
vec4 pixel = imageLoad2D(ivec2(gl_GlobalInvocationID.xy));
float luminance = dot(pixel, vec4(0.299, 0.587, 0.114, 0.0)); // https://www.w3.org/TR/AERT/#color-contrast
imageStore2D(ivec2(gl_GlobalInvocationID.xy), vec4(vec3(luminance), 1.0));
}
)";
const char* kCodeFullscreenVS = R"(
layout (location=0) out vec2 uv;
void main() {
// generate a triangle covering the entire screen
uv = vec2((gl_VertexIndex << 1) & 2, gl_VertexIndex & 2);
#ifdef VULKAN
gl_Position = vec4(uv * vec2(2, -2) + vec2(-1, 1), 0.0, 1.0);
#else
gl_Position = vec4(uv * vec2(2, 2) + vec2(-1, -1), 0.0, 1.0);
#endif
}
)";
const char* kCodeFullscreenFS = R"(
layout (location=0) in vec2 uv;
layout (location=0) out vec4 out_FragColor;
#ifdef VULKAN
layout(set = 0, binding = 0) uniform sampler2D texFullScreen;
#else
uniform sampler2D texFullScreen;
#endif
void main() {
out_FragColor = texture(texFullScreen, uv);
}
)";
const char* kCodeVS = R"(
layout (location=0) in vec3 pos;
layout (location=1) in vec3 normal;
layout (location=2) in vec2 uv;
#ifdef VULKAN
layout (location=3) in uint mtlIndex;
#else
layout (location=3) in float mtlIndex;
#endif
struct UniformsPerFrame {
mat4 proj;
mat4 view;
mat4 light;
int bDrawNormals;
int bDebugLines;
vec2 padding;
};
struct UniformsPerObject {
mat4 model;
};
struct Material {
vec4 ambient;
vec4 diffuse;
int texAmbient;
int texDiffuse;
int texAlpha;
int padding;
};
#ifdef VULKAN
layout(set = 1, binding = 0, std140) uniform PerFrame {
UniformsPerFrame perFrame;
};
layout(set = 1, binding = 1, std140) uniform PerObject {
UniformsPerObject perObject;
};
layout(set = 2, binding = 2, std430) readonly buffer Materials {
Material mtl[];
} mat;
#else
uniform PerFrame {
UniformsPerFrame perFrame;
};
uniform PerObject {
UniformsPerObject perObject;
};
uniform MeshMaterials {
Material materials[132];
};
#endif
// output
struct PerVertex {
vec3 normal;
vec2 uv;
vec4 shadowCoords;
};
layout (location=0) out PerVertex vtx;
layout (location=5) flat out Material mtl;
//
void main() {
mat4 proj = perFrame.proj;
mat4 view = perFrame.view;
mat4 model = perObject.model;
mat4 light = perFrame.light;
#ifdef VULKAN
mtl = mat.mtl[uint(mtlIndex)];
#else
mtl = materials[int(mtlIndex)];
#endif
gl_Position = proj * view * model * vec4(pos, 1.0);
// Compute the normal in world-space
mat3 norm_matrix = transpose(inverse(mat3(model)));
vtx.normal = normalize(norm_matrix * normal);
vtx.uv = uv;
vtx.shadowCoords = light * model * vec4(pos, 1.0);
}
)";
const char* kCodeVS_Wireframe = R"(
layout (location=0) in vec3 pos;
struct UniformsPerFrame {
mat4 proj;
mat4 view;
};
struct UniformsPerObject {
mat4 model;
};
#ifdef VULKAN
layout(set = 1, binding = 0, std140)
#endif
uniform PerFrame {
UniformsPerFrame perFrame;
};
#ifdef VULKAN
layout(set = 1, binding = 1, std140)
#endif
uniform PerObject{
UniformsPerObject perObject;
};
void main() {
mat4 proj = perFrame.proj;
mat4 view = perFrame.view;
mat4 model = perObject.model;
gl_Position = proj * view * model * vec4(pos, 1.0);
}
)";
const char* kCodeFS_Wireframe = R"(
layout (location=0) out vec4 out_FragColor;
void main() {
out_FragColor = vec4(1.0);
};
)";
const char* kCodeFS = R"(
struct UniformsPerFrame {
mat4 proj;
mat4 view;
mat4 light;
int bDrawNormals;
int bDebugLines;
vec2 padding;
};
#ifdef VULKAN
layout(set = 1, binding = 0, std140)
#endif
uniform PerFrame {
UniformsPerFrame perFrame;
};
struct Material {
vec4 ambient;
vec4 diffuse;
int texAmbient;
int texDiffuse;
int texAlpha;
int padding;
};
struct PerVertex {
vec3 normal;
vec2 uv;
vec4 shadowCoords;
};
layout (location=0) in PerVertex vtx;
layout (location=5) flat in Material mtl;
layout (location=0) out vec4 out_FragColor;
#ifdef VULKAN
layout(set = 0, binding = 0) uniform sampler2DShadow texShadow;
layout(set = 0, binding = 4) uniform samplerCube texSkyboxIrradiance;
vec4 textureBindless2D(uint textureid, vec2 uv) {
return texture(sampler2D(kTextures2D[textureid], kSamplers[1]), uv);
}
#else
layout(binding = 0) uniform sampler2D texShadow;
layout(binding = 1) uniform sampler2D texAmbient;
layout(binding = 2) uniform sampler2D texDiffuse;
layout(binding = 3) uniform sampler2D texAlpha;
layout(binding = 4) uniform samplerCube texSkyboxIrradiance;
#endif // VULKAN
float PCF3(vec3 uvw) {
float size = 1.0 / float( textureSize(texShadow, 0).x );
float shadow = 0.0;
for (int v=-1; v<=+1; v++)
for (int u=-1; u<=+1; u++)
#ifdef VULKAN
shadow += texture(texShadow, uvw + size * vec3(u, v, 0));
#else
shadow += (uvw.z <= texture(texShadow, uvw.xy + size * vec2(u, v) ).r) ? 1.0 : 0.0;
#endif
return shadow / 9;
}
float shadow(vec4 s) {
s = s / s.w;
if (s.z > -1.0 && s.z < 1.0) {
float depthBias = -0.00005;
#ifdef VULKAN
s.y = 1.0 - s.y;
#endif
float shadowSample = PCF3(vec3(s.x, s.y, s.z + depthBias));
return mix(0.3, 1.0, shadowSample);
}
return 1.0;
}
void main() {
#ifdef VULKAN
vec4 alpha = textureBindless2D(mtl.texAlpha, vtx.uv);
if (mtl.texAlpha > 0 && alpha.r < 0.5)
discard;
vec4 Ka = mtl.ambient * textureBindless2D(mtl.texAmbient, vtx.uv);
vec4 Kd = mtl.diffuse * textureBindless2D(mtl.texDiffuse, vtx.uv);
#else
vec4 alpha = texture(texAlpha, vtx.uv);
// check it is not a dummy 1x1 texture
if (textureSize(texAlpha, 0).x > 1 && alpha.r < 0.5)
discard;
vec4 Ka = mtl.ambient * texture(texAmbient, vtx.uv);
vec4 Kd = mtl.diffuse * texture(texDiffuse, vtx.uv);
#endif
bool drawNormals = perFrame.bDrawNormals > 0;
if (Kd.a < 0.5)
discard;
vec3 n = normalize(vtx.normal);
float NdotL1 = clamp(dot(n, normalize(vec3(-1, 1,+1))), 0.0, 1.0);
float NdotL2 = clamp(dot(n, normalize(vec3(-1, 1,-1))), 0.0, 1.0);
float NdotL = 0.5 * (NdotL1+NdotL2);
// IBL diffuse
const vec4 f0 = vec4(0.04);
vec4 diffuse = texture(texSkyboxIrradiance, n) * Kd * (vec4(1.0) - f0);
out_FragColor = drawNormals ?
vec4(0.5 * (n+vec3(1.0)), 1.0) :
Ka + diffuse * shadow(vtx.shadowCoords);
};
)";
const char* kShadowVS = R"(
layout (location=0) in vec3 pos;
struct UniformsPerFrame {
mat4 proj;
mat4 view;
mat4 light;
int bDrawNormals;
int bDebugLines;
vec2 padding;
};
struct UniformsPerObject {
mat4 model;
};
#ifdef VULKAN
layout(set = 1, binding = 0, std140) uniform PerFrame {
UniformsPerFrame perFrame;
};
layout(set = 1, binding = 1, std140) uniform PerObject {
UniformsPerObject perObject;
};
#else
uniform ShadowFrameUniforms {
UniformsPerFrame perFrame;
};
uniform ShadowObjectUniforms {
UniformsPerObject perObject;
};
#endif
void main() {
mat4 proj = perFrame.proj;
mat4 view = perFrame.view;
mat4 model = perObject.model;
gl_Position = proj * view * model * vec4(pos, 1.0);
}
)";
const char* kShadowFS = R"(
void main() {
};
)";
const char* kSkyboxVS = R"(
layout (location=0) out vec3 textureCoords;
const vec3 positions[8] = vec3[8](
vec3(-1.0,-1.0, 1.0), vec3( 1.0,-1.0, 1.0), vec3( 1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0),
vec3(-1.0,-1.0,-1.0), vec3( 1.0,-1.0,-1.0), vec3( 1.0, 1.0,-1.0), vec3(-1.0, 1.0,-1.0)
);
const int indices[36] = int[36](
0, 1, 2, 2, 3, 0, 1, 5, 6, 6, 2, 1, 7, 6, 5, 5, 4, 7, 4, 0, 3, 3, 7, 4, 4, 5, 1, 1, 0, 4, 3, 2, 6, 6, 7, 3
);
struct UniformsPerFrame {
mat4 proj;
mat4 view;
mat4 light;
int bDrawNormals;
int bDebugLines;
vec2 padding;
};
#ifdef VULKAN
layout(set = 1, binding = 0, std140) uniform PerFrame {
UniformsPerFrame perFrame;
};
#else
uniform SkyboxFrameUniforms {
UniformsPerFrame perFrame;
};
#endif
void main() {
mat4 proj = perFrame.proj;
mat4 view = perFrame.view;
// discard translation
view = mat4(view[0], view[1], view[2], vec4(0, 0, 0, 1));
mat4 transform = proj * view;
vec3 pos = positions[indices[gl_VertexIndex]];
gl_Position = (transform * vec4(pos, 1.0)).xyww;
// skybox
textureCoords = pos;
#ifdef VULKAN
// Draws the skybox edges. One color per edge
const bool drawDebugLines = perFrame.bDebugLines > 0;
if (drawDebugLines) {
const int[12][2] edgeIndices = {
{0,1}, {1,2}, {2,3}, {3,0}, {4,5}, {5,6}, {6,7}, {7,4}, {0,4}, {1,5}, {2,6}, {3,7}
};
const vec4 edgeColors[12] = vec4[12](
vec4( 1, 0, 0, 1), vec4( 1, 1, 0, 1), vec4( 0, 1, 0, 1), vec4( 0, 1, 1, 1),
vec4( 1, 0, 1, 1), vec4( 0, 0, 1, 1), vec4( 1, 1, 1, 1), vec4( 0, 0, 0, 1),
vec4(0.5, 0.7, 0.8, 1), vec4(0.4, 0.4, 0.4, 1), vec4( 1, 0.3, 0.6, 1), vec4( 1, 0.8, 0, 1)
);
uint index = gl_VertexIndex / 3;
drawLine(positions[edgeIndices[index][0]],
positions[edgeIndices[index][1]],
edgeColors[index],
edgeColors[index],
transform);
}
#endif
}
)";
const char* kSkyboxFS = R"(
layout (location=0) in vec3 textureCoords;
layout (location=0) out vec4 out_FragColor;
#ifdef VULKAN
layout(set = 0, binding = 1) uniform samplerCube texSkybox;
#else
uniform samplerCube texSkybox;
#endif
void main() {
out_FragColor = texture(texSkybox, textureCoords);
}
)";
// @fb-only
// @fb-only
// @fb-only
using namespace igl;
using glm::mat4;
using glm::vec2;
using glm::vec3;
using glm::vec4;
GLFWwindow* window_ = nullptr;
int width_ = 0;
int height_ = 0;
igl::FPSCounter fps_;
constexpr uint32_t kNumBufferedFrames = 3;
std::unique_ptr<IDevice> device_;
std::shared_ptr<ICommandQueue> commandQueue_;
RenderPassDesc renderPassOffscreen_;
RenderPassDesc renderPassMain_;
RenderPassDesc renderPassShadow_;
std::shared_ptr<IFramebuffer> fbMain_; // swapchain
std::shared_ptr<IFramebuffer> fbOffscreen_;
std::shared_ptr<IFramebuffer> fbShadowMap_;
std::shared_ptr<IComputePipelineState> computePipelineState_Grayscale_;
std::shared_ptr<IRenderPipelineState> renderPipelineState_Mesh_;
std::shared_ptr<IRenderPipelineState> renderPipelineState_MeshWireframe_;
std::shared_ptr<IRenderPipelineState> renderPipelineState_Shadow_;
std::shared_ptr<IRenderPipelineState> renderPipelineState_Skybox_;
std::shared_ptr<IRenderPipelineState> renderPipelineState_Fullscreen_;
std::shared_ptr<IBuffer> vb0_, ib0_; // buffers for vertices and indices
std::shared_ptr<IBuffer> sbMaterials_; // storage buffer for materials
std::vector<std::shared_ptr<IBuffer>> ubPerFrame_, ubPerFrameShadow_, ubPerObject_;
std::shared_ptr<IVertexInputState> vertexInput0_;
std::shared_ptr<IVertexInputState> vertexInputShadows_;
std::shared_ptr<IDepthStencilState> depthStencilState_;
std::shared_ptr<IDepthStencilState> depthStencilStateLEqual_;
std::shared_ptr<ISamplerState> sampler_;
std::shared_ptr<ISamplerState> samplerShadow_;
std::shared_ptr<ITexture> textureDummyWhite_;
#if USE_OPENGL_BACKEND
std::shared_ptr<ITexture> textureDummyBlack_;
#endif // USE_OPENGL_BACKEND
std::shared_ptr<ITexture> skyboxTextureReference_;
std::shared_ptr<ITexture> skyboxTextureIrradiance_;
// scene navigation
CameraPositioner_FirstPerson positioner_(vec3(-100, 40, -47), vec3(0, 35, 0), vec3(0, 1, 0));
Camera camera_(positioner_);
glm::vec2 mousePos_ = glm::vec2(0.0f);
bool mousePressed_ = false;
bool enableComputePass_ = false;
bool enableWireframe_ = false;
bool isShadowMapDirty_ = true;
struct VertexData {
vec3 position;
uint32_t normal; // Int_2_10_10_10_REV
uint32_t uv; // hvec2
uint32_t mtlIndex;
};
std::vector<VertexData> vertexData_;
std::vector<uint32_t> indexData_;
std::vector<uint32_t> shapeVertexCnt_;
struct UniformsPerFrame {
mat4 proj;
mat4 view;
mat4 light;
int bDrawNormals = 0;
int bDebugLines = 0;
vec2 padding;
} perFrame_;
struct UniformsPerObject {
mat4 model;
};
#define MAX_MATERIAL_NAME 128
struct CachedMaterial {
char name[MAX_MATERIAL_NAME] = {};
vec3 ambient = vec3(0.0f);
vec3 diffuse = vec3(0.0f);
char ambient_texname[MAX_MATERIAL_NAME] = {};
char diffuse_texname[MAX_MATERIAL_NAME] = {};
char alpha_texname[MAX_MATERIAL_NAME] = {};
};
// this goes into our GLSL shaders
struct GPUMaterial {
vec4 ambient = vec4(0.0f);
vec4 diffuse = vec4(0.0f);
uint32_t texAmbient = 0;
uint32_t texDiffuse = 0;
uint32_t texAlpha = 0;
uint32_t padding[1];
};
static_assert(sizeof(GPUMaterial) % 16 == 0);
std::vector<CachedMaterial> cachedMaterials_;
std::vector<GPUMaterial> materials_;
struct MaterialTextures {
std::shared_ptr<ITexture> ambient;
std::shared_ptr<ITexture> diffuse;
std::shared_ptr<ITexture> alpha;
};
std::vector<MaterialTextures> textures_; // same indexing as in materials_
struct LoadedImage {
int w = 0;
int h = 0;
uint8_t* pixels = nullptr;
int channels = 0;
std::string debugName;
std::string compressedFileName;
};
struct LoadedMaterial {
size_t idx = 0;
LoadedImage ambient;
LoadedImage diffuse;
LoadedImage alpha;
};
// file name -> LoadedImage
std::mutex imagesCacheMutex_;
std::unordered_map<std::string, LoadedImage> imagesCache_; // accessible only from the loader thread
// pool (multiple threads)
std::unordered_map<std::string, std::shared_ptr<ITexture>> texturesCache_; // accessible only from
// the main thread
std::vector<LoadedMaterial> loadedMaterials_;
std::mutex loadedMaterialsMutex_;
std::atomic<bool> loaderShouldExit_ = false;
std::atomic<uint32_t> remainingMaterialsToLoad_ = 0;
std::unique_ptr<tf::Executor> loaderPool_ =
std::make_unique<tf::Executor>(std::max(2u, std::thread::hardware_concurrency() / 2));
std::string convertFileName(std::string fileName) {
// generate compressed filename
const std::string compressedPathPrefix = contentRootFolder;
if (fileName.find(compressedPathPrefix) == 0) {
// remove leading path
fileName = fileName.substr(compressedPathPrefix.length());
}
std::replace(fileName.begin(), fileName.end(), ':', '_');
std::replace(fileName.begin(), fileName.end(), '.', '_');
std::replace(fileName.begin(), fileName.end(), '/', '_');
std::replace(fileName.begin(), fileName.end(), '\\', '_');
// return absolute compressed filename
return compressedPathPrefix + fileName + ".ktx2";
}
[[maybe_unused]] void stringReplaceAll(std::string& s,
const std::string& searchString,
const std::string& replaceString) {
size_t pos = 0;
while ((pos = s.find(searchString, pos)) != std::string::npos) {
s.replace(pos, searchString.length(), replaceString);
}
}
bool initWindow(GLFWwindow** outWindow) {
if (!glfwInit())
return false;
#if USE_OPENGL_BACKEND
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_VISIBLE, true);
glfwWindowHint(GLFW_DOUBLEBUFFER, true);
glfwWindowHint(GLFW_SRGB_CAPABLE, true);
glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
const char* title = "OpenGL Mesh";
#else
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
const char* title = "Vulkan Mesh";
#endif
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
// render full screen without overlapping taskbar
GLFWmonitor* monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(monitor);
int posX = 0;
int posY = 0;
int width = mode->width;
int height = mode->height;
glfwGetMonitorWorkarea(monitor, &posX, &posY, &width, &height);
GLFWwindow* window = glfwCreateWindow(width, height, title, nullptr, nullptr);
if (!window) {
glfwTerminate();
return false;
}
glfwSetWindowPos(window, posX, posY);
glfwSetErrorCallback([](int error, const char* description) {
printf("GLFW Error (%i): %s\n", error, description);
});
glfwSetCursorPosCallback(window, [](auto* window, double x, double y) {
int width, height;
glfwGetFramebufferSize(window, &width, &height);
mousePos_ = vec2(x / width, 1.0f - y / height);
#if IGL_WITH_IGLU
inputDispatcher_.queueEvent(igl::shell::MouseMotionEvent(x, y, 0, 0));
#endif // IGL_WITH_IGLU
});
glfwSetMouseButtonCallback(window, [](auto* window, int button, int action, int mods) {
#if IGL_WITH_IGLU
if (!ImGui::GetIO().WantCaptureMouse) {
#endif // IGL_WITH_IGLU
if (button == GLFW_MOUSE_BUTTON_LEFT) {
mousePressed_ = (action == GLFW_PRESS);
}
#if IGL_WITH_IGLU
} else {
// release the mouse
mousePressed_ = false;
}
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
using igl::shell::MouseButton;
const MouseButton iglButton =
(button == GLFW_MOUSE_BUTTON_LEFT)
? MouseButton::Left
: (button == GLFW_MOUSE_BUTTON_RIGHT ? MouseButton::Right : MouseButton::Middle);
inputDispatcher_.queueEvent(
igl::shell::MouseButtonEvent(iglButton, action == GLFW_PRESS, (float)xpos, (float)ypos));
#endif // IGL_WITH_IGLU
});
glfwSetKeyCallback(window, [](GLFWwindow* window, int key, int, int action, int mods) {
const bool pressed = action != GLFW_RELEASE;
if (key == GLFW_KEY_ESCAPE && pressed) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
if (key == GLFW_KEY_N && pressed) {
perFrame_.bDrawNormals = (perFrame_.bDrawNormals + 1) % 2;
}
if (key == GLFW_KEY_C && pressed) {
enableComputePass_ = !enableComputePass_;
}
if (key == GLFW_KEY_T && pressed) {
enableWireframe_ = !enableWireframe_;
}
if (key == GLFW_KEY_ESCAPE && pressed)
glfwSetWindowShouldClose(window, GLFW_TRUE);
if (key == GLFW_KEY_W) {
positioner_.movement_.forward_ = pressed;
}
if (key == GLFW_KEY_S) {
positioner_.movement_.backward_ = pressed;
}
if (key == GLFW_KEY_A) {
positioner_.movement_.left_ = pressed;
}
if (key == GLFW_KEY_D) {
positioner_.movement_.right_ = pressed;
}
if (key == GLFW_KEY_1) {
positioner_.movement_.up_ = pressed;
}
if (key == GLFW_KEY_2) {
positioner_.movement_.down_ = pressed;
}
if (mods & GLFW_MOD_SHIFT) {
positioner_.movement_.fastSpeed_ = pressed;
}
if (key == GLFW_KEY_LEFT_SHIFT || key == GLFW_KEY_RIGHT_SHIFT) {
positioner_.movement_.fastSpeed_ = pressed;
}
if (key == GLFW_KEY_SPACE) {
positioner_.setUpVector(vec3(0.0f, 1.0f, 0.0f));
}
if (key == GLFW_KEY_L && pressed) {
perFrame_.bDebugLines = (perFrame_.bDebugLines + 1) % 2;
}
});
glfwGetWindowSize(window, &width_, &height_);
if (outWindow) {
*outWindow = window;
}
return true;
}
void initIGL() {
// create a device
{
{
Result result;
#if USE_OPENGL_BACKEND
#if IGL_PLATFORM_WIN
auto ctx = std::make_unique<igl::opengl::wgl::Context>(GetDC(glfwGetWin32Window(window_)),
glfwGetWGLContext(window_));
device_ = std::make_unique<igl::opengl::wgl::Device>(std::move(ctx));
#elif IGL_PLATFORM_LINUX
auto ctx = std::make_unique<igl::opengl::glx::Context>(
nullptr,
glfwGetX11Display(),
(igl::opengl::glx::GLXDrawable)glfwGetX11Window(window_),
(igl::opengl::glx::GLXContext)glfwGetGLXContext(window_));
device_ = std::make_unique<igl::opengl::glx::Device>(std::move(ctx));
#endif
#else
const igl::vulkan::VulkanContextConfig cfg = {
.terminateOnValidationError = true,
.enhancedShaderDebugging = false,
.enableValidation = kEnableValidationLayers,
.enableDescriptorIndexing = true,
.swapChainColorSpace = igl::ColorSpace::SRGB_LINEAR,
};
#ifdef _WIN32
auto ctx = vulkan::HWDevice::createContext(cfg, (void*)glfwGetWin32Window(window_));
#elif __APPLE__
auto ctx = vulkan::HWDevice::createContext(cfg, (void*)glfwGetCocoaWindow(window_));
#elif defined(__linux__)
auto ctx = vulkan::HWDevice::createContext(
cfg, (void*)glfwGetX11Window(window_), 0, nullptr, (void*)glfwGetX11Display());
#else
#error Unsupported OS
#endif
const HWDeviceType hardwareType = kPreferIntegratedGPU ? HWDeviceType::IntegratedGpu
: HWDeviceType::DiscreteGpu;
std::vector<HWDeviceDesc> devices =
vulkan::HWDevice::queryDevices(*ctx.get(), HWDeviceQueryDesc(hardwareType), nullptr);
if (devices.empty()) {
const HWDeviceType fallbackHardwareType =
!kPreferIntegratedGPU ? HWDeviceType::IntegratedGpu : HWDeviceType::DiscreteGpu;
devices = vulkan::HWDevice::queryDevices(
*ctx.get(), HWDeviceQueryDesc(fallbackHardwareType), nullptr);
}
IGL_ASSERT_MSG(!devices.empty(), "GPU is not found");
device_ =
vulkan::HWDevice::create(std::move(ctx), devices[0], (uint32_t)width_, (uint32_t)height_);
#endif
IGL_ASSERT(device_);
}
}