-
Notifications
You must be signed in to change notification settings - Fork 34
/
fastgltf.cpp
5666 lines (4939 loc) · 207 KB
/
fastgltf.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) 2022 - 2024 spnda
* This file is part of fastgltf <https://github.com/spnda/fastgltf>.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#if !defined(__cplusplus) || (!defined(_MSVC_LANG) && __cplusplus < 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG < 201703L)
#error "fastgltf requires C++17"
#endif
#include <fstream>
#include <functional>
#include <mutex>
#include <utility>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 5030) // attribute 'x' is not recognized
#pragma warning(disable : 4514) // unreferenced inline function has been removed
#pragma warning(disable : 4710) // function not inlined
#endif
#include <simdjson.h>
#ifdef SIMDJSON_TARGET_VERSION
// Make sure that SIMDJSON_TARGET_VERSION is equal to SIMDJSON_VERSION.
static_assert(std::string_view { SIMDJSON_TARGET_VERSION } == SIMDJSON_VERSION, "Outdated version of simdjson. Reconfigure project to update.");
#endif
#include <fastgltf/core.hpp>
#include <fastgltf/base64.hpp>
#if defined(FASTGLTF_IS_X86)
#include <nmmintrin.h> // SSE4.2 for the CRC-32C instructions
#elif defined(FASTGLTF_ENABLE_ARMV8_CRC)
// MSVC does not provide the arm crc32 intrinsics.
#include <arm_acle.h>
#endif
namespace fg = fastgltf;
namespace fs = std::filesystem;
namespace fastgltf {
constexpr std::uint32_t binaryGltfHeaderMagic = 0x46546C67; // ASCII for "glTF".
constexpr std::uint32_t binaryGltfJsonChunkMagic = 0x4E4F534A;
constexpr std::uint32_t binaryGltfDataChunkMagic = 0x004E4942;
struct BinaryGltfHeader {
std::uint32_t magic;
std::uint32_t version;
std::uint32_t length;
};
static_assert(sizeof(BinaryGltfHeader) == 12, "Binary gltf header must be 12 bytes");
static_assert(std::is_trivially_copyable_v<BinaryGltfHeader>);
constexpr void readUint32LE(std::uint32_t& x, std::byte* bytes) noexcept {
x = std::uint32_t(bytes[0])
| (std::uint32_t(bytes[1]) << 8)
| (std::uint32_t(bytes[2]) << 16)
| (std::uint32_t(bytes[3]) << 24);
}
constexpr void writeUint32LE(std::uint32_t x, std::byte* buffer) noexcept {
buffer[0] = static_cast<std::byte>(x);
buffer[1] = static_cast<std::byte>(x >> 8);
buffer[2] = static_cast<std::byte>(x >> 16);
buffer[3] = static_cast<std::byte>(x >> 24);
}
/** GLBs are always little-endian, meaning we need to read the values accordingly */
[[nodiscard, gnu::always_inline]] inline auto readBinaryHeader(GltfDataGetter& getter) noexcept {
std::array<std::byte, sizeof(BinaryGltfHeader)> bytes {};
getter.read(bytes.data(), bytes.size());
BinaryGltfHeader header = {};
readUint32LE(header.magic, &bytes[offsetof(BinaryGltfHeader, magic)]);
readUint32LE(header.version, &bytes[offsetof(BinaryGltfHeader, version)]);
readUint32LE(header.length, &bytes[offsetof(BinaryGltfHeader, length)]);
return header;
}
[[gnu::always_inline]] inline auto writeBinaryHeader(const BinaryGltfHeader& header) noexcept {
std::array<std::byte, sizeof(BinaryGltfHeader)> bytes {};
writeUint32LE(header.magic, &bytes[offsetof(BinaryGltfHeader, magic)]);
writeUint32LE(header.version, &bytes[offsetof(BinaryGltfHeader, version)]);
writeUint32LE(header.length, &bytes[offsetof(BinaryGltfHeader, length)]);
return bytes;
}
struct BinaryGltfChunk {
std::uint32_t chunkLength;
std::uint32_t chunkType;
};
static_assert(std::is_trivially_copyable_v<BinaryGltfChunk>);
[[nodiscard, gnu::always_inline]] inline auto readBinaryChunk(GltfDataGetter& getter) noexcept {
std::array<std::byte, sizeof(BinaryGltfChunk)> bytes {};
getter.read(bytes.data(), bytes.size());
BinaryGltfChunk chunk = {};
readUint32LE(chunk.chunkLength, &bytes[offsetof(BinaryGltfChunk, chunkLength)]);
readUint32LE(chunk.chunkType, &bytes[offsetof(BinaryGltfChunk, chunkType)]);
return chunk;
}
[[gnu::always_inline]] inline auto writeBinaryChunk(const BinaryGltfChunk& chunk) noexcept {
std::array<std::byte, sizeof(BinaryGltfChunk)> bytes {};
writeUint32LE(chunk.chunkLength, &bytes[offsetof(BinaryGltfChunk, chunkLength)]);
writeUint32LE(chunk.chunkType, &bytes[offsetof(BinaryGltfChunk, chunkType)]);
return bytes;
}
using CRCStringFunction = std::uint32_t(*)(std::string_view str);
#if defined(FASTGLTF_IS_X86)
[[gnu::hot, gnu::const, gnu::target("sse4.2")]] std::uint32_t sse_crc32c(std::string_view str) noexcept {
return sse_crc32c(reinterpret_cast<const std::uint8_t*>(str.data()), str.size());
}
[[gnu::hot, gnu::const, gnu::target("sse4.2")]] std::uint32_t sse_crc32c(const std::uint8_t* d, std::size_t len) noexcept {
std::uint32_t crc = 0;
// Ddecode as much as possible using 4 byte steps.
// We specifically don't use the 8 byte instruction here because it uses a 64-bit output integer.
auto length = static_cast<std::int64_t>(len);
while ((length -= sizeof(std::uint32_t)) >= 0) {
std::uint32_t v;
std::memcpy(&v, d, sizeof v);
crc = _mm_crc32_u32(crc, v);
d += sizeof v;
}
if (length & sizeof(std::uint16_t)) {
std::uint16_t v;
std::memcpy(&v, d, sizeof v);
crc = _mm_crc32_u16(crc, v);
d += sizeof v;
}
if (length & sizeof(std::uint8_t)) {
crc = _mm_crc32_u8(crc, *d);
}
return crc;
}
#elif defined(FASTGLTF_ENABLE_ARMV8_CRC)
[[gnu::hot, gnu::const, gnu::target("+crc")]] std::uint32_t armv8_crc32c(std::string_view str) noexcept {
return armv8_crc32c(reinterpret_cast<const std::uint8_t*>(str.data()), str.size());
}
[[gnu::hot, gnu::const, gnu::target("+crc")]] std::uint32_t armv8_crc32c(const std::uint8_t* d, std::size_t len) noexcept {
std::uint32_t crc = 0;
// Decrementing the length variable and incrementing the pointer directly has better codegen with Clang
// than using a std::size_t i = 0.
auto length = static_cast<std::int64_t>(len);
while ((length -= sizeof(std::uint64_t)) >= 0) {
std::uint64_t value;
std::memcpy(&value, d, sizeof value);
crc = __crc32cd(crc, value);
d += sizeof value;
}
if (length & sizeof(std::uint32_t)) {
std::uint32_t value;
std::memcpy(&value, d, sizeof value);
crc = __crc32cw(crc, value);
d += sizeof value;
}
if (length & sizeof(std::uint16_t)) {
std::uint16_t value;
std::memcpy(&value, d, sizeof value);
crc = __crc32ch(crc, value);
d += sizeof value;
}
if (length & sizeof(std::uint8_t)) {
crc = __crc32cb(crc, *d);
}
return crc;
}
#endif
/**
* Points to the most 'optimal' CRC32-C encoding function. After initialiseCrc has been called,
* this might also point to sse_crc32c or armv8_crc32c. We only use this for runtime evaluation of hashes, and is
* intended to work for any length of data.
*/
static CRCStringFunction crcStringFunction = crc32c;
std::once_flag crcInitialisation;
/**
* Checks if SSE4.2 is available to try and use the hardware accelerated version.
*/
void initialiseCrc() {
#if defined(FASTGLTF_IS_X86)
const auto& impls = simdjson::get_available_implementations();
if (const auto* sse4 = impls["westmere"]; sse4 != nullptr && sse4->supported_by_runtime_system()) {
crcStringFunction = sse_crc32c;
}
#elif defined(FASTGLTF_ENABLE_ARMV8_CRC)
const auto& impls = simdjson::get_available_implementations();
if (const auto* neon = impls["arm64"]; neon != nullptr && neon->supported_by_runtime_system()) {
crcStringFunction = armv8_crc32c;
}
#endif
}
[[nodiscard, gnu::always_inline]] inline bool getImageIndexForExtension(const simdjson::dom::element& element, Optional<std::size_t>& imageIndexOut) {
using namespace simdjson;
dom::object source;
if (element.get(source) != simdjson::SUCCESS) FASTGLTF_UNLIKELY {
return false;
}
std::uint64_t imageIndex;
if (source["source"].get_uint64().get(imageIndex) != simdjson::SUCCESS) FASTGLTF_UNLIKELY {
return false;
}
imageIndexOut = static_cast<std::size_t>(imageIndex);
return true;
}
[[nodiscard, gnu::always_inline]] inline bool parseTextureExtensions(Texture& texture, simdjson::dom::object& extensions, Extensions extensionFlags) {
for (auto extension : extensions) {
auto hashedKey = crcStringFunction(extension.key);
switch (hashedKey) {
case force_consteval<crc32c(extensions::KHR_texture_basisu)>: {
if (!hasBit(extensionFlags, Extensions::KHR_texture_basisu))
break;
if (!getImageIndexForExtension(extension.value, texture.basisuImageIndex))
return false;
break;
}
case force_consteval<crc32c(extensions::MSFT_texture_dds)>: {
if (!hasBit(extensionFlags, Extensions::MSFT_texture_dds))
break;
if (!getImageIndexForExtension(extension.value, texture.ddsImageIndex))
return false;
break;
}
case force_consteval<crc32c(extensions::EXT_texture_webp)>: {
if (!hasBit(extensionFlags, Extensions::EXT_texture_webp))
break;
if (!getImageIndexForExtension(extension.value, texture.webpImageIndex))
return false;
break;
}
default:
break;
}
}
return true;
}
[[nodiscard, gnu::always_inline]] inline Error getJsonArray(const simdjson::dom::object& parent, std::string_view arrayName, simdjson::dom::array* array) noexcept {
using namespace simdjson;
const auto error = parent[arrayName].get_array().get(*array);
if (error == NO_SUCH_FIELD) {
return Error::MissingField;
}
if (error == SUCCESS) FASTGLTF_LIKELY {
return Error::None;
}
return Error::InvalidJson;
}
enum class TextureInfoType : std::uint_fast8_t {
Standard = 0,
NormalTexture = 1,
OcclusionTexture = 2,
};
fg::Error parseTextureInfo(simdjson::dom::object& object, std::string_view key, TextureInfo* info, Extensions extensions, TextureInfoType type = TextureInfoType::Standard) noexcept {
using namespace simdjson;
dom::object child;
if (auto childErr = object[key].get_object().get(child); childErr == NO_SUCH_FIELD) {
return Error::MissingField;
} else if (childErr != SUCCESS) FASTGLTF_UNLIKELY {
return Error::InvalidGltf;
}
std::uint64_t index;
if (child["index"].get_uint64().get(index) == SUCCESS) FASTGLTF_LIKELY {
info->textureIndex = static_cast<std::size_t>(index);
} else {
return Error::InvalidGltf;
}
if (auto error = child["texCoord"].get_uint64().get(index); error == SUCCESS) FASTGLTF_LIKELY {
info->texCoordIndex = static_cast<std::size_t>(index);
} else if (error != NO_SUCH_FIELD) FASTGLTF_UNLIKELY {
return Error::InvalidJson;
}
if (type == TextureInfoType::NormalTexture) {
double scale;
if (auto error = child["scale"].get_double().get(scale); error == SUCCESS) FASTGLTF_LIKELY {
reinterpret_cast<NormalTextureInfo*>(info)->scale = static_cast<num>(scale);
} else if (error != NO_SUCH_FIELD) FASTGLTF_UNLIKELY {
return Error::InvalidGltf;
}
} else if (type == TextureInfoType::OcclusionTexture) {
double strength;
if (auto error = child["strength"].get_double().get(strength); error == SUCCESS) FASTGLTF_LIKELY {
reinterpret_cast<OcclusionTextureInfo*>(info)->strength = static_cast<num>(strength);
} else if (error != NO_SUCH_FIELD) FASTGLTF_UNLIKELY {
return Error::InvalidGltf;
}
}
dom::object extensionsObject;
if (child["extensions"].get_object().get(extensionsObject) == SUCCESS) FASTGLTF_LIKELY {
dom::object textureTransform;
if (hasBit(extensions, Extensions::KHR_texture_transform) && extensionsObject[extensions::KHR_texture_transform].get_object().get(textureTransform) == SUCCESS) FASTGLTF_LIKELY {
auto transform = std::make_unique<TextureTransform>();
transform->rotation = 0.0F;
if (textureTransform["texCoord"].get_uint64().get(index) == SUCCESS) FASTGLTF_LIKELY {
transform->texCoordIndex = index;
}
double rotation = 0.0F;
if (textureTransform["rotation"].get_double().get(rotation) == SUCCESS) FASTGLTF_LIKELY {
transform->rotation = static_cast<num>(rotation);
}
dom::array array;
if (textureTransform["offset"].get_array().get(array) == SUCCESS) FASTGLTF_LIKELY {
for (auto i = 0U; i < 2; ++i) {
double val;
if (array.at(i).get_double().get(val) != SUCCESS) FASTGLTF_UNLIKELY {
return Error::InvalidGltf;
}
transform->uvOffset[i] = static_cast<num>(val);
}
}
if (textureTransform["scale"].get_array().get(array) == SUCCESS) FASTGLTF_LIKELY {
for (auto i = 0U; i < 2; ++i) {
double val;
if (array.at(i).get_double().get(val) != SUCCESS) FASTGLTF_UNLIKELY {
return Error::InvalidGltf;
}
transform->uvScale[i] = static_cast<num>(val);
}
}
info->transform = std::move(transform);
}
}
return Error::None;
}
void writeTextureInfo(std::string& json, const TextureInfo* info, TextureInfoType type = TextureInfoType::Standard) {
json += '{';
json += "\"index\":" + std::to_string(info->textureIndex);
if (info->texCoordIndex != 0) {
json += ",\"texCoord\":" + std::to_string(info->texCoordIndex);
}
if (type == TextureInfoType::NormalTexture) {
json += ",\"scale\":" + std::to_string(reinterpret_cast<const NormalTextureInfo*>(info)->scale);
} else if (type == TextureInfoType::OcclusionTexture) {
json += ",\"strength\":" + std::to_string(reinterpret_cast<const OcclusionTextureInfo*>(info)->strength);
}
if (info->transform != nullptr) {
json += R"(,"extensions":{"KHR_texture_transform":{)";
const auto& transform = *info->transform;
if (transform.uvOffset[0] != 0.0 || transform.uvOffset[1] != 0.0) {
json += "\"offset\":[" + std::to_string(transform.uvOffset[0]) + ',' + std::to_string(transform.uvOffset[1]) + ']';
}
if (transform.rotation != 0.0) {
if (json.back() != '{') json += ',';
json += "\"rotation\":" + std::to_string(transform.rotation);
}
if (transform.uvScale[0] != 1.0 || transform.uvScale[1] != 1.0) {
if (json.back() != '{') json += ',';
json += "\"scale\":[" + std::to_string(transform.uvScale[0]) + ',' + std::to_string(transform.uvScale[1]) + ']';
}
if (transform.texCoordIndex.has_value()) {
if (json.back() != '{') json += ',';
json += "\"texCoord\":" + std::to_string(transform.texCoordIndex.value());
}
json += "}}";
}
json += '}';
}
} // namespace fastgltf
#pragma region URI
fg::URIView::URIView() noexcept = default;
fg::URIView::URIView(std::string_view uri) noexcept : view(uri) {
parse();
}
fg::URIView::URIView(const URIView& other) noexcept {
*this = other;
}
fg::URIView& fg::URIView::operator=(const URIView& other) {
view = other.view;
_scheme = other._scheme;
_path = other._path;
_userinfo = other._userinfo;
_host = other._host;
_port = other._port;
_query = other._query;
_fragment = other._fragment;
return *this;
}
fg::URIView& fg::URIView::operator=(std::string_view other) {
view = other;
parse();
return *this;
}
void fg::URIView::parse() {
if (view.empty()) {
_valid = false;
return;
}
std::size_t idx = 0;
auto firstColon = view.find(':');
if (firstColon != std::string::npos) {
// URI has a scheme.
if (firstColon == 0) {
// Empty scheme is invalid
_valid = false;
return;
}
_scheme = view.substr(0, firstColon);
idx = firstColon + 1;
}
if (startsWith(view.substr(idx), "//")) {
// URI has an authority part.
idx += 2;
auto nextSlash = view.find('/', idx);
auto userInfo = view.find('@', idx);
if (userInfo != std::string::npos && userInfo < nextSlash) {
_userinfo = view.substr(idx, userInfo - idx);
idx += _userinfo.size() + 1;
}
auto hostEnd = nextSlash - 1;
std::size_t portColon;
if (view[idx] == '[') {
hostEnd = view.find(']', idx);
if (hostEnd == std::string::npos) {
_valid = false;
return;
}
// IPv6 addresses are made up of colons, so we need to search after its address.
// This will just be hostEnd + 1 or std::string::npos.
portColon = view.find(':', hostEnd);
} else {
portColon = view.find(':', idx);
}
if (portColon != std::string::npos) {
_host = view.substr(idx, portColon - idx);
++portColon; // We don't want to include the colon in the port string.
_port = view.substr(portColon, nextSlash - portColon);
} else {
++idx;
_host = view.substr(idx, hostEnd - idx);
}
idx = nextSlash; // Path includes this slash
}
if (_scheme == "data") {
// The data scheme is just followed by a mime and then bytes.
// Also, let's avoid all the find and substr on very large data strings
// which can be multiple MB.
_path = view.substr(idx);
} else {
// Parse the path.
auto questionIdx = view.find('?', idx);
auto hashIdx = view.find('#', idx);
if (questionIdx != std::string::npos) {
_path = view.substr(idx, questionIdx - idx);
if (hashIdx == std::string::npos) {
_query = view.substr(++questionIdx);
} else {
++questionIdx;
_query = view.substr(questionIdx, hashIdx - questionIdx);
_fragment = view.substr(++hashIdx);
}
} else if (hashIdx != std::string::npos) {
_path = view.substr(idx, hashIdx - idx);
_fragment = view.substr(++hashIdx);
} else {
_path = view.substr(idx);
}
}
}
const char* fg::URIView::data() const noexcept {
return view.data();
}
std::string_view fg::URIView::string() const noexcept { return view; }
std::string_view fg::URIView::scheme() const noexcept { return _scheme; }
std::string_view fg::URIView::userinfo() const noexcept { return _userinfo; }
std::string_view fg::URIView::host() const noexcept { return _host; }
std::string_view fg::URIView::port() const noexcept { return _port; }
std::string_view fg::URIView::path() const noexcept { return _path; }
std::string_view fg::URIView::query() const noexcept { return _query; }
std::string_view fg::URIView::fragment() const noexcept { return _fragment; }
fs::path fg::URIView::fspath() const {
if (!isLocalPath())
return {};
return { path() };
}
bool fg::URIView::valid() const noexcept {
return _valid;
}
bool fg::URIView::isLocalPath() const noexcept {
return scheme().empty() || (scheme() == "file" && host().empty());
}
bool fg::URIView::isDataUri() const noexcept {
return scheme() == "data";
}
fg::URI::URI() noexcept = default;
fg::URI::URI(std::string uri) noexcept : uri(std::move(uri)) {
decodePercents(this->uri);
view = this->uri; // Also parses.
}
fg::URI::URI(std::string_view uri) noexcept : uri(uri) {
decodePercents(this->uri);
view = this->uri; // Also parses.
}
fg::URI::URI(const URIView& view) noexcept : uri(view.view) {
auto oldSize = uri.size();
decodePercents(uri);
if (uri.size() == oldSize) {
readjustViews(view);
} else {
// Reparses the URI string
this->view = this->uri;
}
}
// Some C++ stdlib implementations copy in some cases when moving strings, which invalidates the
// views stored in the URI struct. This function adjusts the views from the old string to the new
// string for safe copying.
fg::URI::URI(const URI& other) {
*this = other;
}
fg::URI::URI(URI&& other) noexcept {
*this = other;
}
fg::URI& fg::URI::operator=(const URI& other) {
uri = other.uri;
// We'll assume that with copying the string will always have to reallocate.
readjustViews(other.view);
return *this;
}
fg::URI& fg::URI::operator=(const URIView& other) {
uri = other.view;
auto oldSize = uri.size();
decodePercents(uri);
if (uri.size() == oldSize) {
readjustViews(other);
} else {
// We removed some encoded chars, which have now invalidated all the string views.
// Therefore, the URI needs to be parsed again.
view = this->uri;
}
return *this;
}
fg::URI& fg::URI::operator=(URI&& other) noexcept {
auto* oldData = other.uri.data();
uri = std::move(other.uri);
// Invalidate the previous URI's view.
view._valid = other.view._valid;
other.view._valid = false;
if (uri.data() != oldData) {
// Allocation changed, we need to readjust views
readjustViews(other.view);
} else {
// No reallocation happened, we can safely copy the view.
view = other.view;
}
return *this;
}
fg::URI::operator fg::URIView() const noexcept {
return view;
}
void fg::URI::readjustViews(const URIView& other) {
if (!other._scheme.empty()) { view._scheme = std::string_view(uri.data() + (other._scheme.data() - other.view.data()), other._scheme.size()); }
if (!other._path.empty()) { view._path = std::string_view(uri.data() + (other._path.data() - other.view.data()), other._path.size()); }
if (!other._userinfo.empty()) { view._userinfo = std::string_view(uri.data() + (other._userinfo.data() - other.view.data()), other._userinfo.size()); }
if (!other._host.empty()) { view._host = std::string_view(uri.data() + (other._host.data() - other.view.data()), other._host.size()); }
if (!other._port.empty()) { view._port = std::string_view(uri.data() + (other._port.data() - other.view.data()), other._port.size()); }
if (!other._query.empty()) { view._query = std::string_view(uri.data() + (other._query.data() - other.view.data()), other._query.size()); }
if (!other._fragment.empty()) { view._fragment = std::string_view(uri.data() + (other._fragment.data() - other.view.data()), other._fragment.size()); }
view.view = uri;
}
void fg::URI::decodePercents(std::string& x) noexcept {
for (std::size_t i = 0; i < x.size(); ++i) {
if (x[i] != '%')
continue;
// Read the next two chars and store them
std::array<char, 3> chars = {x[i + 1], x[i + 2]};
x[i] = static_cast<char>(std::strtoul(chars.data(), nullptr, 16));
x.erase(i + 1, 2);
}
}
std::string_view fg::URI::string() const noexcept { return uri; }
const char* fg::URI::c_str() const noexcept { return uri.c_str(); }
std::string_view fg::URI::scheme() const noexcept { return view.scheme(); }
std::string_view fg::URI::userinfo() const noexcept { return view.userinfo(); }
std::string_view fg::URI::host() const noexcept { return view.host(); }
std::string_view fg::URI::port() const noexcept { return view.port(); }
std::string_view fg::URI::path() const noexcept { return view.path(); }
std::string_view fg::URI::query() const noexcept { return view.query(); }
std::string_view fg::URI::fragment() const noexcept { return view.fragment(); }
fs::path fg::URI::fspath() const {
return view.fspath();
}
bool fg::URI::valid() const noexcept {
return view.valid();
}
bool fg::URI::isLocalPath() const noexcept {
return view.isLocalPath();
}
bool fg::URI::isDataUri() const noexcept {
return view.isDataUri();
}
#pragma endregion
#pragma region glTF parsing
fg::Expected<fg::DataSource> fg::Parser::decodeDataUri(URIView& uri) const noexcept {
auto path = uri.path();
auto mimeEnd = path.find(';');
auto mime = path.substr(0, mimeEnd);
auto encodingEnd = path.find(',');
auto encoding = path.substr(mimeEnd + 1, encodingEnd - mimeEnd - 1);
if (encoding != "base64") {
return Error::InvalidURI;
}
auto encodedData = path.substr(encodingEnd + 1);
if (config.mapCallback != nullptr) {
// If a map callback is specified, we use a pointer to memory specified by it.
auto padding = base64::getPadding(encodedData);
auto size = base64::getOutputSize(encodedData.size(), padding);
auto info = config.mapCallback(size, config.userPointer);
if (info.mappedMemory != nullptr) {
if (config.decodeCallback != nullptr) {
config.decodeCallback(encodedData, reinterpret_cast<std::uint8_t*>(info.mappedMemory), padding, size, config.userPointer);
} else {
base64::decode_inplace(encodedData, reinterpret_cast<std::uint8_t*>(info.mappedMemory), padding);
}
if (config.unmapCallback != nullptr) {
config.unmapCallback(&info, config.userPointer);
}
sources::CustomBuffer source = {};
source.id = info.customId;
source.mimeType = getMimeTypeFromString(mime);
return { source };
}
}
// Decode the base64 data into a traditional vector
auto padding = base64::getPadding(encodedData);
fg::StaticVector<std::byte> uriData(base64::getOutputSize(encodedData.size(), padding));
if (config.decodeCallback != nullptr) {
config.decodeCallback(encodedData, reinterpret_cast<std::uint8_t*>(uriData.data()), padding, uriData.size(), config.userPointer);
} else {
base64::decode_inplace(encodedData, reinterpret_cast<std::uint8_t*>(uriData.data()), padding);
}
sources::Array source {
std::move(uriData),
getMimeTypeFromString(mime),
};
return { std::move(source) };
}
void fg::Parser::fillCategories(Category& inputCategories) noexcept {
if (inputCategories == Category::All)
return;
// The Category enum used to already OR values together so that e.g. Scenes would also implicitly
// have the Nodes bit set. This, however, caused some issues within the parse function as it tries
// to bail out when all requested categories have been parsed, as now something that hasn't been
// parsed could still be set. So, this has to exist...
if (hasBit(inputCategories, Category::Scenes))
inputCategories |= Category::Nodes;
if (hasBit(inputCategories, Category::Nodes))
inputCategories |= Category::Cameras | Category::Meshes | Category::Skins;
if (hasBit(inputCategories, Category::Skins))
// Skins needs nodes, nodes needs skins. To counter this circular dep we just redefine what we just wrote above.
inputCategories |= Category::Accessors | (Category::Nodes | Category::Cameras | Category::Meshes | Category::Skins);
if (hasBit(inputCategories, Category::Meshes))
inputCategories |= Category::Accessors | Category::Materials;
if (hasBit(inputCategories, Category::Materials))
inputCategories |= Category::Textures;
if (hasBit(inputCategories, Category::Animations))
inputCategories |= Category::Accessors;
if (hasBit(inputCategories, Category::Textures))
inputCategories |= Category::Images | Category::Samplers;
if (hasBit(inputCategories, Category::Images) || hasBit(inputCategories, Category::Accessors))
inputCategories |= Category::BufferViews;
if (hasBit(inputCategories, Category::BufferViews))
inputCategories |= Category::Buffers;
}
fg::MimeType fg::Parser::getMimeTypeFromString(std::string_view mime) {
const auto hash = crcStringFunction(mime);
switch (hash) {
case force_consteval<crc32c(mimeTypeJpeg)>: {
return MimeType::JPEG;
}
case force_consteval<crc32c(mimeTypePng)>: {
return MimeType::PNG;
}
case force_consteval<crc32c(mimeTypeKtx)>: {
return MimeType::KTX2;
}
case force_consteval<crc32c(mimeTypeDds)>: {
return MimeType::DDS;
}
case force_consteval<crc32c(mimeTypeGltfBuffer)>: {
return MimeType::GltfBuffer;
}
case force_consteval<crc32c(mimeTypeOctetStream)>: {
return MimeType::OctetStream;
}
default: {
return MimeType::None;
}
}
}
template <typename T> fg::Error fg::Parser::parseAttributes(simdjson::dom::object& object, T& attributes) {
using namespace simdjson;
// We iterate through the JSON object and write each key/pair value into the
// attribute map. The keys are only validated in the validate() method.
attributes = FASTGLTF_CONSTRUCT_PMR_RESOURCE(std::remove_reference_t<decltype(attributes)>, resourceAllocator.get(), 0);
attributes.reserve(object.size());
for (const auto& field : object) {
const auto key = field.key;
std::uint64_t accessorIndex;
if (field.value.get_uint64().get(accessorIndex) != SUCCESS) FASTGLTF_UNLIKELY {
return Error::InvalidGltf;
}
attributes.emplace_back(Attribute {
FASTGLTF_CONSTRUCT_PMR_RESOURCE(FASTGLTF_STD_PMR_NS::string, resourceAllocator.get(), key),
static_cast<std::size_t>(accessorIndex),
});
}
return Error::None;
}
// TODO: Is there some nicer way of declaring a templated version parseAttributes?
// Currently, this exists because resourceAllocator is a optional field of Parser, which we can't unconditionally
// pass as a parameter to a function, so parseAttributes needs to be a member function of Parser.
template fg::Error fg::Parser::parseAttributes(simdjson::dom::object&, FASTGLTF_STD_PMR_NS::vector<Attribute>&);
template fg::Error fg::Parser::parseAttributes(simdjson::dom::object&, decltype(fastgltf::Primitive::attributes)&);
namespace fastgltf {
template<typename T>
void writeIndices(PrimitiveType type, span<T> indices, std::size_t primitiveCount) {
// Generate the correct indices for every primitive topology
switch (type) {
case PrimitiveType::Points: {
for (std::size_t i = 0; i < primitiveCount; ++i)
indices[i] = static_cast<T>(i);
break;
}
case PrimitiveType::Lines:
case PrimitiveType::LineLoop:
case PrimitiveType::LineStrip: {
for (std::size_t i = 0; i < primitiveCount; ++i) {
indices[i * 2 + 0] = static_cast<T>(i * 2 + 0);
indices[i * 2 + 1] = static_cast<T>(i * 2 + 1);
}
break;
}
case PrimitiveType::Triangles:
case PrimitiveType::TriangleStrip:
case PrimitiveType::TriangleFan: {
for (std::size_t i = 0; i < primitiveCount; ++i) {
indices[i * 3 + 0] = static_cast<T>(i * 3 + 0);
indices[i * 3 + 1] = static_cast<T>(i * 3 + 1);
indices[i * 3 + 2] = static_cast<T>(i * 3 + 2);
}
break;
}
default: FASTGLTF_UNREACHABLE
}
}
std::pair<StaticVector<std::byte>, ComponentType> writeIndices(PrimitiveType type, std::size_t indexCount, std::size_t primitiveCount) {
if (indexCount < 255) {
StaticVector<std::byte> generatedIndices(indexCount * sizeof(std::uint8_t));
span<std::uint8_t> indices(reinterpret_cast<std::uint8_t*>(generatedIndices.data()), generatedIndices.size() / sizeof(std::uint8_t));
writeIndices(type, indices, primitiveCount);
return std::make_pair(generatedIndices, ComponentType::UnsignedByte);
} else if (indexCount < 65535) {
StaticVector<std::byte> generatedIndices(indexCount * sizeof(std::uint16_t));
span<std::uint16_t> indices(reinterpret_cast<std::uint16_t*>(generatedIndices.data()), generatedIndices.size() / sizeof(std::uint16_t));
writeIndices(type, indices, primitiveCount);
return std::make_pair(generatedIndices, ComponentType::UnsignedShort);
} else {
StaticVector<std::byte> generatedIndices(indexCount * sizeof(std::uint32_t));
span<std::uint32_t> indices(reinterpret_cast<std::uint32_t*>(generatedIndices.data()), generatedIndices.size() / sizeof(std::uint32_t));
writeIndices(type, indices, primitiveCount);
return std::make_pair(generatedIndices, ComponentType::UnsignedInt);
}
}
}
fg::Error fg::Parser::generateMeshIndices(fastgltf::Asset& asset) const {
for (auto& mesh : asset.meshes) {
for (auto& primitive : mesh.primitives) {
if (primitive.indicesAccessor.has_value())
continue;
auto* positionAttribute = primitive.findAttribute("POSITION");
if (positionAttribute == primitive.attributes.end()) {
return Error::InvalidGltf;
}
auto positionCount = asset.accessors[positionAttribute->accessorIndex].count;
auto primitiveCount = [&]() -> std::size_t {
switch (primitive.type) {
case PrimitiveType::Points: return positionCount;
case PrimitiveType::Lines: return positionCount / 2;
case PrimitiveType::LineLoop:
case PrimitiveType::LineStrip: return max<std::size_t>(0, positionCount - 1);
case PrimitiveType::Triangles: return positionCount / 3;
case PrimitiveType::TriangleStrip: return max<std::size_t>(0U, positionCount - 2);
case PrimitiveType::TriangleFan: return max<std::size_t>(0U, positionCount - 2);
default: FASTGLTF_UNREACHABLE
}
}();
auto indexCount = [&]() -> std::size_t {
switch (primitive.type) {
case PrimitiveType::Points: return primitiveCount;
case PrimitiveType::Lines:
case PrimitiveType::LineLoop:
case PrimitiveType::LineStrip: return primitiveCount * 2;
case PrimitiveType::Triangles:
case PrimitiveType::TriangleStrip:
case PrimitiveType::TriangleFan: return primitiveCount * 3;
default: FASTGLTF_UNREACHABLE
}
}();
auto [generatedIndices, componentType] = writeIndices(primitive.type, indexCount, primitiveCount);
auto bufferIdx = asset.buffers.size();
auto& buffer = asset.buffers.emplace_back();
buffer.byteLength = generatedIndices.size_bytes();
sources::Array indicesArray {
std::move(generatedIndices),
MimeType::GltfBuffer,
};
buffer.data = std::move(indicesArray);
auto bufferViewIdx = asset.bufferViews.size();
auto& bufferView = asset.bufferViews.emplace_back();
bufferView.byteLength = buffer.byteLength;
bufferView.bufferIndex = bufferIdx;
bufferView.byteOffset = 0;
primitive.indicesAccessor = asset.accessors.size();
auto& accessor = asset.accessors.emplace_back();
accessor.byteOffset = 0;
accessor.count = positionCount;
accessor.type = AccessorType::Scalar;
accessor.componentType = componentType;
accessor.normalized = false;
accessor.bufferViewIndex = bufferViewIdx;
}
}
return Error::None;
}
fg::Error fg::validate(const fastgltf::Asset& asset) {
auto isExtensionUsed = [&used = asset.extensionsUsed](std::string_view extension) {
for (const auto& extensionUsed : used) {
if (extension == extensionUsed) {
return true;
}
}
return false;
};
// From the spec: extensionsRequired is a subset of extensionsUsed. All values in extensionsRequired MUST also exist in extensionsUsed.
if (asset.extensionsRequired.size() > asset.extensionsUsed.size()) {
return Error::InvalidGltf;
}
for (const auto& required : asset.extensionsRequired) {
bool found = false;
for (const auto& used : asset.extensionsUsed) {
if (required == used)
found = true;
}
if (!found)
return Error::InvalidGltf;
}
for (const auto& accessor : asset.accessors) {
if (accessor.type == AccessorType::Invalid)
return Error::InvalidGltf;
if (accessor.componentType == ComponentType::Invalid)
return Error::InvalidGltf;
if (accessor.count < 1)
return Error::InvalidGltf;
if (accessor.bufferViewIndex.has_value() &&
accessor.bufferViewIndex.value() >= asset.bufferViews.size())
return Error::InvalidGltf;
if (accessor.byteOffset != 0) {
// The offset of an accessor into a bufferView (i.e., accessor.byteOffset)
// and the offset of an accessor into a buffer (i.e., accessor.byteOffset + bufferView.byteOffset)
// MUST be a multiple of the size of the accessor’s component type.
auto componentByteSize = getComponentByteSize(accessor.componentType);
if (accessor.byteOffset % componentByteSize != 0)
return Error::InvalidGltf;
if (accessor.bufferViewIndex.has_value()) {
const auto& bufferView = asset.bufferViews[accessor.bufferViewIndex.value()];
if ((accessor.byteOffset + bufferView.byteOffset) % componentByteSize != 0)
return Error::InvalidGltf;
// When byteStride is defined, it MUST be a multiple of the size of the accessor’s component type.
if (bufferView.byteStride.has_value() && bufferView.byteStride.value() % componentByteSize != 0)
return Error::InvalidGltf;
}
}