forked from KhronosGroup/Vulkan-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgltf_loader.cpp
More file actions
1699 lines (1366 loc) · 52.7 KB
/
gltf_loader.cpp
File metadata and controls
1699 lines (1366 loc) · 52.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2018-2026, Arm Limited and Contributors
* Copyright (c) 2019-2026, Sascha Willems
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 the "License";
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define TINYGLTF_IMPLEMENTATION
#include "gltf_loader.h"
#include <future>
#include <limits>
#include <queue>
#include "common/error.h"
#include "common/glm_common.h"
#include <glm/gtc/type_ptr.hpp>
#include <core/util/profiling.hpp>
#include "api_vulkan_sample.h"
#include "common/utils.h"
#include "common/vk_common.h"
#include "core/device.h"
#include "core/image.h"
#include "core/util/logging.hpp"
#include "filesystem/legacy.h"
#include "scene_graph/components/camera.h"
#include "scene_graph/components/image.h"
#include "scene_graph/components/image/astc.h"
#include "scene_graph/components/light.h"
#include "scene_graph/components/mesh.h"
#include "scene_graph/components/pbr_material.h"
#include "scene_graph/components/perspective_camera.h"
#include "scene_graph/components/sampler.h"
#include "scene_graph/components/sub_mesh.h"
#include "scene_graph/components/texture.h"
#include "scene_graph/components/transform.h"
#include "scene_graph/node.h"
#include "scene_graph/scene.h"
#include "scene_graph/scripts/animation.h"
namespace vkb
{
namespace
{
inline VkFilter find_min_filter(int min_filter)
{
switch (min_filter)
{
case TINYGLTF_TEXTURE_FILTER_NEAREST:
case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST:
case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR:
return VK_FILTER_NEAREST;
case TINYGLTF_TEXTURE_FILTER_LINEAR:
case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST:
case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR:
return VK_FILTER_LINEAR;
default:
return VK_FILTER_LINEAR;
}
};
inline VkSamplerMipmapMode find_mipmap_mode(int min_filter)
{
switch (min_filter)
{
case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_NEAREST:
case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_NEAREST:
return VK_SAMPLER_MIPMAP_MODE_NEAREST;
case TINYGLTF_TEXTURE_FILTER_NEAREST_MIPMAP_LINEAR:
case TINYGLTF_TEXTURE_FILTER_LINEAR_MIPMAP_LINEAR:
return VK_SAMPLER_MIPMAP_MODE_LINEAR;
default:
return VK_SAMPLER_MIPMAP_MODE_LINEAR;
}
};
inline VkFilter find_mag_filter(int mag_filter)
{
switch (mag_filter)
{
case TINYGLTF_TEXTURE_FILTER_NEAREST:
return VK_FILTER_NEAREST;
case TINYGLTF_TEXTURE_FILTER_LINEAR:
return VK_FILTER_LINEAR;
default:
return VK_FILTER_LINEAR;
}
};
inline VkSamplerAddressMode find_wrap_mode(int wrap)
{
switch (wrap)
{
case TINYGLTF_TEXTURE_WRAP_REPEAT:
return VK_SAMPLER_ADDRESS_MODE_REPEAT;
case TINYGLTF_TEXTURE_WRAP_CLAMP_TO_EDGE:
return VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
case TINYGLTF_TEXTURE_WRAP_MIRRORED_REPEAT:
return VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT;
default:
return VK_SAMPLER_ADDRESS_MODE_REPEAT;
}
};
inline std::vector<uint8_t> get_attribute_data(const tinygltf::Model *model, uint32_t accessorId)
{
assert(accessorId < model->accessors.size());
auto &accessor = model->accessors[accessorId];
assert(accessor.bufferView < model->bufferViews.size());
auto &bufferView = model->bufferViews[accessor.bufferView];
assert(bufferView.buffer < model->buffers.size());
auto &buffer = model->buffers[bufferView.buffer];
size_t stride = accessor.ByteStride(bufferView);
size_t startByte = accessor.byteOffset + bufferView.byteOffset;
size_t endByte = startByte + accessor.count * stride;
return {buffer.data.begin() + startByte, buffer.data.begin() + endByte};
};
inline size_t get_attribute_size(const tinygltf::Model *model, uint32_t accessorId)
{
assert(accessorId < model->accessors.size());
return model->accessors[accessorId].count;
};
inline size_t get_attribute_stride(const tinygltf::Model *model, uint32_t accessorId)
{
assert(accessorId < model->accessors.size());
auto &accessor = model->accessors[accessorId];
assert(accessor.bufferView < model->bufferViews.size());
auto &bufferView = model->bufferViews[accessor.bufferView];
return accessor.ByteStride(bufferView);
};
inline VkFormat get_attribute_format(const tinygltf::Model *model, uint32_t accessorId)
{
assert(accessorId < model->accessors.size());
auto &accessor = model->accessors[accessorId];
VkFormat format;
switch (accessor.componentType)
{
case TINYGLTF_COMPONENT_TYPE_BYTE:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R8_SINT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R8G8_SINT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R8G8B8_SINT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R8G8B8A8_SINT}};
format = mapped_format.at(accessor.type);
break;
}
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_BYTE:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R8_UINT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R8G8_UINT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R8G8B8_UINT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R8G8B8A8_UINT}};
static const std::map<int, VkFormat> mapped_format_normalize = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R8_UNORM},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R8G8_UNORM},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R8G8B8_UNORM},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R8G8B8A8_UNORM}};
if (accessor.normalized)
{
format = mapped_format_normalize.at(accessor.type);
}
else
{
format = mapped_format.at(accessor.type);
}
break;
}
case TINYGLTF_COMPONENT_TYPE_SHORT:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R8_SINT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R8G8_SINT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R8G8B8_SINT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R8G8B8A8_SINT}};
format = mapped_format.at(accessor.type);
break;
}
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R16_UINT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R16G16_UINT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R16G16B16_UINT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R16G16B16A16_UINT}};
static const std::map<int, VkFormat> mapped_format_normalize = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R16_UNORM},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R16G16_UNORM},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R16G16B16_UNORM},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R16G16B16A16_UNORM}};
if (accessor.normalized)
{
format = mapped_format_normalize.at(accessor.type);
}
else
{
format = mapped_format.at(accessor.type);
}
break;
}
case TINYGLTF_COMPONENT_TYPE_INT:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R32_SINT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R32G32_SINT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R32G32B32_SINT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R32G32B32A32_SINT}};
format = mapped_format.at(accessor.type);
break;
}
case TINYGLTF_COMPONENT_TYPE_UNSIGNED_INT:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R32_UINT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R32G32_UINT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R32G32B32_UINT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R32G32B32A32_UINT}};
format = mapped_format.at(accessor.type);
break;
}
case TINYGLTF_COMPONENT_TYPE_FLOAT:
{
static const std::map<int, VkFormat> mapped_format = {{TINYGLTF_TYPE_SCALAR, VK_FORMAT_R32_SFLOAT},
{TINYGLTF_TYPE_VEC2, VK_FORMAT_R32G32_SFLOAT},
{TINYGLTF_TYPE_VEC3, VK_FORMAT_R32G32B32_SFLOAT},
{TINYGLTF_TYPE_VEC4, VK_FORMAT_R32G32B32A32_SFLOAT}};
format = mapped_format.at(accessor.type);
break;
}
default:
{
format = VK_FORMAT_UNDEFINED;
break;
}
}
return format;
};
inline std::vector<uint8_t> convert_underlying_data_stride(const std::vector<uint8_t> &src_data, uint32_t src_stride, uint32_t dst_stride)
{
auto elem_count = to_u32(src_data.size()) / src_stride;
std::vector<uint8_t> result(elem_count * dst_stride);
for (uint32_t idxSrc = 0, idxDst = 0;
idxSrc < src_data.size() && idxDst < result.size();
idxSrc += src_stride, idxDst += dst_stride)
{
std::copy(src_data.begin() + idxSrc, src_data.begin() + idxSrc + src_stride, result.begin() + idxDst);
}
return result;
}
inline void upload_image_to_gpu(vkb::core::CommandBufferC &command_buffer, vkb::core::BufferC &staging_buffer, sg::Image &image)
{
// Clean up the image data, as they are copied in the staging buffer
image.clear_data();
{
ImageMemoryBarrier memory_barrier{};
memory_barrier.old_layout = VK_IMAGE_LAYOUT_UNDEFINED;
memory_barrier.new_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
memory_barrier.src_access_mask = 0;
memory_barrier.dst_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT;
memory_barrier.src_stage_mask = VK_PIPELINE_STAGE_HOST_BIT;
memory_barrier.dst_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
command_buffer.image_memory_barrier(image.get_vk_image_view(), memory_barrier);
}
// Create a buffer image copy for every mip level
auto &mipmaps = image.get_mipmaps();
std::vector<VkBufferImageCopy> buffer_copy_regions(mipmaps.size());
for (size_t i = 0; i < mipmaps.size(); ++i)
{
auto &mipmap = mipmaps[i];
auto ©_region = buffer_copy_regions[i];
copy_region.bufferOffset = mipmap.offset;
copy_region.imageSubresource = image.get_vk_image_view().get_subresource_layers();
// Update miplevel
copy_region.imageSubresource.mipLevel = mipmap.level;
copy_region.imageExtent = mipmap.extent;
}
command_buffer.copy_buffer_to_image(staging_buffer, image.get_vk_image(), buffer_copy_regions);
{
ImageMemoryBarrier memory_barrier{};
memory_barrier.old_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
memory_barrier.new_layout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
memory_barrier.src_access_mask = VK_ACCESS_TRANSFER_WRITE_BIT;
memory_barrier.dst_access_mask = VK_ACCESS_SHADER_READ_BIT;
memory_barrier.src_stage_mask = VK_PIPELINE_STAGE_TRANSFER_BIT;
memory_barrier.dst_stage_mask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
command_buffer.image_memory_barrier(image.get_vk_image_view(), memory_barrier);
}
}
inline void prepare_meshlets(std::vector<Meshlet> &meshlets, std::unique_ptr<vkb::sg::SubMesh> &submesh, std::vector<unsigned char> &index_data)
{
Meshlet meshlet;
meshlet.vertex_count = 0;
meshlet.index_count = 0;
std::set<uint32_t> vertices; // set for unique vertices
uint32_t triangle_check = 0; // each meshlet needs to contain full primitives
for (uint32_t i = 0; i < submesh->vertex_indices; i++)
{
// index_data is unsigned char type, casting to uint32_t* will give proper value
meshlet.indices[meshlet.index_count] = *(reinterpret_cast<uint32_t *>(index_data.data()) + i);
if (vertices.insert(meshlet.indices[meshlet.index_count]).second)
{
++meshlet.vertex_count;
}
meshlet.index_count++;
triangle_check = triangle_check < 3 ? ++triangle_check : 1;
// 96 because for each traingle we draw a line in a mesh shader sample, 32 triangles/lines per meshlet = 64 vertices on output
if (meshlet.vertex_count == 64 || meshlet.index_count == 96 || i == submesh->vertex_indices - 1)
{
if (i == submesh->vertex_indices - 1)
{
assert(triangle_check == 3);
}
uint32_t counter = 0;
for (auto v : vertices)
{
meshlet.vertices[counter++] = v;
}
if (triangle_check != 3)
{
meshlet.index_count -= triangle_check;
i -= triangle_check;
triangle_check = 0;
}
meshlets.push_back(meshlet);
meshlet.vertex_count = 0;
meshlet.index_count = 0;
vertices.clear();
}
}
}
static inline bool texture_needs_srgb_colorspace(const std::string &name)
{
// The gltf spec states that the base and emissive textures MUST be encoded with the sRGB
// transfer function. All other texture types are linear.
if (name == "baseColorTexture" || name == "emissiveTexture")
{
return true;
}
// metallicRoughnessTexture, normalTexture & occlusionTexture must be linear
assert(name == "metallicRoughnessTexture" || name == "normalTexture" || name == "occlusionTexture");
return false;
}
} // namespace
std::unordered_map<std::string, bool> GLTFLoader::supported_extensions = {
{KHR_LIGHTS_PUNCTUAL_EXTENSION, false}};
GLTFLoader::GLTFLoader(vkb::core::DeviceC &device) :
device{device}
{
}
std::unique_ptr<vkb::scene_graph::SceneC> GLTFLoader::read_scene_from_file(const std::string &file_name, int scene_index, VkBufferUsageFlags additional_buffer_usage_flags)
{
PROFILE_SCOPE("Load GLTF Scene");
std::string err;
std::string warn;
tinygltf::TinyGLTF gltf_loader;
std::string gltf_file = vkb::fs::path::get(vkb::fs::path::Type::Assets) + file_name;
bool importResult = gltf_loader.LoadASCIIFromFile(&model, &err, &warn, gltf_file.c_str());
if (!importResult)
{
LOGE("Failed to load gltf file {}.", gltf_file.c_str());
return nullptr;
}
if (!err.empty())
{
LOGE("Error loading gltf model: {}.", err.c_str());
return nullptr;
}
if (!warn.empty())
{
LOGI("{}", warn.c_str());
}
size_t pos = file_name.find_last_of('/');
model_path = file_name.substr(0, pos);
if (pos == std::string::npos)
{
model_path.clear();
}
return std::make_unique<vkb::scene_graph::SceneC>(load_scene(scene_index, additional_buffer_usage_flags));
}
std::unique_ptr<sg::SubMesh> GLTFLoader::read_model_from_file(const std::string &file_name, uint32_t index, bool storage_buffer, VkBufferUsageFlags additional_buffer_usage_flags)
{
PROFILE_SCOPE("Load GLTF Model");
std::string err;
std::string warn;
tinygltf::TinyGLTF gltf_loader;
std::string gltf_file = vkb::fs::path::get(vkb::fs::path::Type::Assets) + file_name;
bool importResult = gltf_loader.LoadASCIIFromFile(&model, &err, &warn, gltf_file.c_str());
if (!importResult)
{
LOGE("Failed to load gltf file {}.", gltf_file.c_str());
return nullptr;
}
if (!err.empty())
{
LOGE("Error loading gltf model: {}.", err.c_str());
return nullptr;
}
if (!warn.empty())
{
LOGI("{}", warn.c_str());
}
size_t pos = file_name.find_last_of('/');
model_path = file_name.substr(0, pos);
if (pos == std::string::npos)
{
model_path.clear();
}
return std::move(load_model(index, storage_buffer, additional_buffer_usage_flags));
}
vkb::scene_graph::SceneC GLTFLoader::load_scene(int scene_index, VkBufferUsageFlags additional_buffer_usage_flags)
{
PROFILE_SCOPE("Process Scene");
auto scene = vkb::scene_graph::SceneC();
scene.set_name("gltf_scene");
// Check extensions
for (auto &used_extension : model.extensionsUsed)
{
auto it = supported_extensions.find(used_extension);
// Check if extension isn't supported by the GLTFLoader
if (it == supported_extensions.end())
{
// If extension is required then we shouldn't allow the scene to be loaded
if (std::ranges::find(model.extensionsRequired, used_extension) != model.extensionsRequired.end())
{
throw std::runtime_error("Cannot load glTF file. Contains a required unsupported extension: " + used_extension);
}
else
{
// Otherwise, if extension isn't required (but is in the file) then print a warning to the user
LOGW("glTF file contains an unsupported extension, unexpected results may occur: {}", used_extension);
}
}
else
{
// Extension is supported, so enable it
LOGI("glTF file contains extension: {}", used_extension);
it->second = true;
}
}
// Load lights
std::vector<std::unique_ptr<sg::Light>> light_components = parse_khr_lights_punctual();
scene.set_components(std::move(light_components));
// Load samplers
std::vector<std::unique_ptr<vkb::scene_graph::components::SamplerC>>
sampler_components(model.samplers.size());
for (size_t sampler_index = 0; sampler_index < model.samplers.size(); sampler_index++)
{
auto sampler = parse_sampler(model.samplers[sampler_index]);
sampler_components[sampler_index] = std::move(sampler);
}
scene.set_components(std::move(sampler_components));
Timer timer;
timer.start();
// Load images
auto image_count = to_u32(model.images.size());
std::vector<std::future<std::unique_ptr<sg::Image>>> image_component_futures;
for (size_t image_index = 0; image_index < image_count; image_index++)
{
image_component_futures.push_back(std::async(
[this, image_index]() {
auto image = parse_image(model.images[image_index]);
LOGI("Loaded gltf image #{} ({})", image_index, model.images[image_index].uri.c_str());
return image;
}));
}
std::vector<std::unique_ptr<sg::Image>> image_components;
// Upload images to GPU. We do this in batches of 64MB of data to avoid needing
// double the amount of memory (all the images and all the corresponding buffers).
// This helps keep memory footprint lower which is helpful on smaller devices.
size_t image_index = 0;
while (image_index < image_count)
{
std::vector<vkb::core::BufferC> transient_buffers;
auto command_buffer = device.get_command_pool().request_command_buffer();
command_buffer->begin(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, 0);
size_t batch_size = 0;
// Deal with 64MB of image data at a time to keep memory footprint low
while (image_index < image_count && batch_size < 64 * 1024 * 1024)
{
// Wait for this image to complete loading, then stage for upload
image_components.push_back(image_component_futures[image_index].get());
auto &image = image_components[image_index];
core::Buffer stage_buffer = vkb::core::BufferC::create_staging_buffer(device, image->get_data());
batch_size += image->get_data().size();
upload_image_to_gpu(*command_buffer, stage_buffer, *image);
transient_buffers.push_back(std::move(stage_buffer));
image_index++;
}
command_buffer->end();
auto &queue = device.get_queue_by_flags(VK_QUEUE_GRAPHICS_BIT, 0);
queue.submit(*command_buffer, device.get_fence_pool().request_fence());
device.get_fence_pool().wait();
device.get_fence_pool().reset();
device.get_command_pool().reset_pool();
device.wait_idle();
// Remove the staging buffers for the batch we just processed
transient_buffers.clear();
}
scene.set_components(std::move(image_components));
auto elapsed_time = timer.stop();
auto thread_count = std::thread::hardware_concurrency();
thread_count = thread_count == 0 ? 1 : thread_count;
LOGI("Time spent loading images: {} seconds across {} threads.", vkb::to_string(elapsed_time), thread_count);
// Load textures
auto images = scene.get_components<sg::Image>();
auto samplers = scene.get_components<vkb::scene_graph::components::SamplerC>();
auto default_sampler_linear = create_default_sampler(TINYGLTF_TEXTURE_FILTER_LINEAR);
auto default_sampler_nearest = create_default_sampler(TINYGLTF_TEXTURE_FILTER_NEAREST);
bool used_nearest_sampler = false;
for (auto &gltf_texture : model.textures)
{
auto texture = parse_texture(gltf_texture);
assert(gltf_texture.source < images.size());
texture->set_image(*images[gltf_texture.source]);
if (gltf_texture.sampler >= 0 && gltf_texture.sampler < static_cast<int>(samplers.size()))
{
texture->set_sampler(*samplers[gltf_texture.sampler]);
}
else
{
if (gltf_texture.name.empty())
{
gltf_texture.name = images[gltf_texture.source]->get_name();
}
// Get the properties for the image format. We'll need to check whether a linear sampler is valid.
const VkFormatProperties fmtProps = device.get_gpu().get_format_properties(images[gltf_texture.source]->get_format());
if (fmtProps.optimalTilingFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)
{
texture->set_sampler(*default_sampler_linear);
}
else
{
texture->set_sampler(*default_sampler_nearest);
used_nearest_sampler = true;
}
}
scene.add_component(std::move(texture));
}
scene.add_component(std::move(default_sampler_linear));
if (used_nearest_sampler)
{
scene.add_component(std::move(default_sampler_nearest));
}
// Load materials
bool has_textures = scene.has_component<sg::Texture>();
std::vector<vkb::sg::Texture *> textures;
if (has_textures)
{
textures = scene.get_components<sg::Texture>();
}
for (auto &gltf_material : model.materials)
{
auto material = parse_material(gltf_material);
for (auto &gltf_value : gltf_material.values)
{
if (gltf_value.first.find("Texture") != std::string::npos)
{
std::string tex_name = to_snake_case(gltf_value.first);
assert(gltf_value.second.TextureIndex() < textures.size());
vkb::sg::Texture *tex = textures[gltf_value.second.TextureIndex()];
if (texture_needs_srgb_colorspace(gltf_value.first))
{
tex->get_image()->coerce_format_to_srgb();
}
material->textures[tex_name] = tex;
}
}
for (auto &gltf_value : gltf_material.additionalValues)
{
if (gltf_value.first.find("Texture") != std::string::npos)
{
std::string tex_name = to_snake_case(gltf_value.first);
assert(gltf_value.second.TextureIndex() < textures.size());
vkb::sg::Texture *tex = textures[gltf_value.second.TextureIndex()];
if (texture_needs_srgb_colorspace(gltf_value.first))
{
tex->get_image()->coerce_format_to_srgb();
}
material->textures[tex_name] = tex;
}
}
scene.add_component(std::move(material));
}
auto default_material = create_default_material();
// Load meshes
auto materials = scene.get_components<sg::PBRMaterial>();
for (auto &gltf_mesh : model.meshes)
{
PROFILE_SCOPE("Processing Mesh");
auto mesh = parse_mesh(gltf_mesh);
for (size_t i_primitive = 0; i_primitive < gltf_mesh.primitives.size(); i_primitive++)
{
const auto &gltf_primitive = gltf_mesh.primitives[i_primitive];
auto submesh_name = fmt::format("'{}' mesh, primitive #{}", gltf_mesh.name, i_primitive);
auto submesh = std::make_unique<sg::SubMesh>(std::move(submesh_name));
for (auto &attribute : gltf_primitive.attributes)
{
std::string attrib_name = attribute.first;
std::transform(attrib_name.begin(), attrib_name.end(), attrib_name.begin(), ::tolower);
auto vertex_data = get_attribute_data(&model, attribute.second);
if (attrib_name == "position")
{
assert(attribute.second < model.accessors.size());
submesh->vertices_count = to_u32(model.accessors[attribute.second].count);
}
vkb::core::BufferC buffer{device,
vertex_data.size(),
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | additional_buffer_usage_flags,
VMA_MEMORY_USAGE_CPU_TO_GPU};
buffer.update(vertex_data);
buffer.set_debug_name(fmt::format("'{}' mesh, primitive #{}: '{}' vertex buffer",
gltf_mesh.name, i_primitive, attrib_name));
submesh->vertex_buffers.insert(std::make_pair(attrib_name, std::move(buffer)));
sg::VertexAttribute attrib;
attrib.format = get_attribute_format(&model, attribute.second);
attrib.stride = to_u32(get_attribute_stride(&model, attribute.second));
submesh->set_attribute(attrib_name, attrib);
}
if (gltf_primitive.indices >= 0)
{
submesh->vertex_indices = to_u32(get_attribute_size(&model, gltf_primitive.indices));
auto format = get_attribute_format(&model, gltf_primitive.indices);
auto index_data = get_attribute_data(&model, gltf_primitive.indices);
switch (format)
{
case VK_FORMAT_R8_UINT:
// Converts uint8 data into uint16 data, still represented by a uint8 vector
index_data = convert_underlying_data_stride(index_data, 1, 2);
submesh->index_type = VK_INDEX_TYPE_UINT16;
break;
case VK_FORMAT_R16_UINT:
submesh->index_type = VK_INDEX_TYPE_UINT16;
break;
case VK_FORMAT_R32_UINT:
submesh->index_type = VK_INDEX_TYPE_UINT32;
break;
default:
LOGE("gltf primitive has invalid format type");
break;
}
submesh->index_buffer = std::make_unique<vkb::core::BufferC>(device,
index_data.size(),
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | additional_buffer_usage_flags,
VMA_MEMORY_USAGE_GPU_TO_CPU);
submesh->index_buffer->set_debug_name(fmt::format("'{}' mesh, primitive #{}: index buffer",
gltf_mesh.name, i_primitive));
submesh->index_buffer->update(index_data);
}
else
{
submesh->vertices_count = to_u32(get_attribute_size(&model, gltf_primitive.attributes.at("POSITION")));
}
if (gltf_primitive.material < 0)
{
submesh->set_material(*default_material);
}
else
{
assert(gltf_primitive.material < materials.size());
submesh->set_material(*materials[gltf_primitive.material]);
}
mesh->add_submesh(*submesh);
scene.add_component(std::move(submesh));
}
scene.add_component(std::move(mesh));
}
device.get_fence_pool().wait();
device.get_fence_pool().reset();
device.get_command_pool().reset_pool();
scene.add_component(std::move(default_material));
// Load cameras
for (auto &gltf_camera : model.cameras)
{
auto camera = parse_camera(gltf_camera);
scene.add_component(std::move(camera));
}
// Load nodes
auto meshes = scene.get_components<sg::Mesh>();
std::vector<std::unique_ptr<vkb::scene_graph::NodeC>> nodes;
for (size_t node_index = 0; node_index < model.nodes.size(); ++node_index)
{
auto gltf_node = model.nodes[node_index];
auto node = parse_node(gltf_node, node_index);
if (gltf_node.mesh >= 0)
{
assert(gltf_node.mesh < meshes.size());
auto mesh = meshes[gltf_node.mesh];
node->set_component(*mesh);
mesh->add_node(*node);
}
if (gltf_node.camera >= 0)
{
auto cameras = scene.get_components<sg::Camera>();
assert(gltf_node.camera < cameras.size());
auto camera = cameras[gltf_node.camera];
node->set_component(*camera);
camera->set_node(*node);
}
if (auto extension = get_extension(gltf_node.extensions, KHR_LIGHTS_PUNCTUAL_EXTENSION))
{
auto lights = scene.get_components<sg::Light>();
int light_index = extension->Get("light").Get<int>();
assert(light_index < lights.size());
auto light = lights[light_index];
node->set_component(*light);
light->set_node(*node);
}
nodes.push_back(std::move(node));
}
std::vector<std::unique_ptr<sg::Animation>> animations;
// Load animations
for (size_t animation_index = 0; animation_index < model.animations.size(); ++animation_index)
{
auto &gltf_animation = model.animations[animation_index];
std::vector<sg::AnimationSampler> samplers;
for (size_t sampler_index = 0; sampler_index < gltf_animation.samplers.size(); ++sampler_index)
{
auto gltf_sampler = gltf_animation.samplers[sampler_index];
sg::AnimationSampler sampler;
if (gltf_sampler.interpolation == "LINEAR")
{
sampler.type = sg::AnimationType::Linear;
}
else if (gltf_sampler.interpolation == "STEP")
{
sampler.type = sg::AnimationType::Step;
}
else if (gltf_sampler.interpolation == "CUBICSPLINE")
{
sampler.type = sg::AnimationType::CubicSpline;
}
else
{
LOGW("Gltf animation sampler #{} has unknown interpolation value", sampler_index);
}
auto input_accessor = model.accessors[gltf_sampler.input];
auto input_accessor_data = get_attribute_data(&model, gltf_sampler.input);
const float *data = reinterpret_cast<const float *>(input_accessor_data.data());
for (size_t i = 0; i < input_accessor.count; ++i)
{
sampler.inputs.push_back(data[i]);
}
auto output_accessor = model.accessors[gltf_sampler.output];
auto output_accessor_data = get_attribute_data(&model, gltf_sampler.output);
switch (output_accessor.type)
{
case TINYGLTF_TYPE_VEC3:
{
const glm::vec3 *data = reinterpret_cast<const glm::vec3 *>(output_accessor_data.data());
for (size_t i = 0; i < output_accessor.count; ++i)
{
sampler.outputs.push_back(glm::vec4(data[i], 0.0f));
}
break;
}
case TINYGLTF_TYPE_VEC4:
{
const glm::vec4 *data = reinterpret_cast<const glm::vec4 *>(output_accessor_data.data());
for (size_t i = 0; i < output_accessor.count; ++i)
{
sampler.outputs.push_back(glm::vec4(data[i]));
}
break;
}
default:
{
LOGW("Gltf animation sampler #{} has unknown output data type", sampler_index);
continue;
}
}
samplers.push_back(sampler);
}
auto animation = std::make_unique<sg::Animation>(gltf_animation.name);
for (size_t channel_index = 0; channel_index < gltf_animation.channels.size(); ++channel_index)
{
auto &gltf_channel = gltf_animation.channels[channel_index];
sg::AnimationTarget target;
if (gltf_channel.target_path == "translation")
{
target = sg::AnimationTarget::Translation;
}
else if (gltf_channel.target_path == "rotation")
{
target = sg::AnimationTarget::Rotation;
}
else if (gltf_channel.target_path == "scale")
{
target = sg::AnimationTarget::Scale;
}
else if (gltf_channel.target_path == "weights")
{
LOGW("Gltf animation channel #{} has unsupported target path: {}", channel_index, gltf_channel.target_path);
continue;
}
else
{
LOGW("Gltf animation channel #{} has unknown target path", channel_index);
continue;
}
float start_time{std::numeric_limits<float>::max()};
float end_time{std::numeric_limits<float>::min()};
for (auto input : samplers[gltf_channel.sampler].inputs)
{
if (input < start_time)
{
start_time = input;