forked from KhronosGroup/Vulkan-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer_resources.cpp
More file actions
2329 lines (2022 loc) · 100 KB
/
renderer_resources.cpp
File metadata and controls
2329 lines (2022 loc) · 100 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
#include "renderer.h"
#include "model_loader.h"
#include "mesh_component.h"
#include "transform_component.h"
#include <fstream>
#include <stdexcept>
#include <array>
#include <iostream>
#include <filesystem>
#include <cstring>
#include <functional>
// stb_image dependency removed; all GLTF textures are uploaded via memory path from ModelLoader.
// KTX2 support
#include <ktx.h>
#include <ranges>
// This file contains resource-related methods from the Renderer class
// Define shared default PBR texture identifiers (static constants)
const std::string Renderer::SHARED_DEFAULT_ALBEDO_ID = "__shared_default_albedo__";
const std::string Renderer::SHARED_DEFAULT_NORMAL_ID = "__shared_default_normal__";
const std::string Renderer::SHARED_DEFAULT_METALLIC_ROUGHNESS_ID = "__shared_default_metallic_roughness__";
const std::string Renderer::SHARED_DEFAULT_OCCLUSION_ID = "__shared_default_occlusion__";
const std::string Renderer::SHARED_DEFAULT_EMISSIVE_ID = "__shared_default_emissive__";
const std::string Renderer::SHARED_BRIGHT_RED_ID = "__shared_bright_red__";
// Create depth resources
bool Renderer::createDepthResources() {
try {
// Find depth format
vk::Format depthFormat = findDepthFormat();
// Create depth image using memory pool
auto [depthImg, depthImgAllocation] = createImagePooled(
swapChainExtent.width,
swapChainExtent.height,
depthFormat,
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eDepthStencilAttachment,
vk::MemoryPropertyFlagBits::eDeviceLocal
);
depthImage = std::move(depthImg);
depthImageAllocation = std::move(depthImgAllocation);
// Create depth image view
depthImageView = createImageView(depthImage, depthFormat, vk::ImageAspectFlagBits::eDepth);
// Transition depth image layout
transitionImageLayout(
*depthImage,
depthFormat,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eDepthStencilAttachmentOptimal
);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create depth resources: " << e.what() << std::endl;
return false;
}
}
// Helper: coerce an sRGB/UNORM variant of a given VkFormat while preserving block type where possible
static vk::Format CoerceFormatSRGB(vk::Format fmt, bool wantSRGB) {
switch (fmt) {
case vk::Format::eR8G8B8A8Unorm: return wantSRGB ? vk::Format::eR8G8B8A8Srgb : vk::Format::eR8G8B8A8Unorm;
case vk::Format::eR8G8B8A8Srgb: return wantSRGB ? vk::Format::eR8G8B8A8Srgb : vk::Format::eR8G8B8A8Unorm;
case vk::Format::eBc1RgbUnormBlock: return wantSRGB ? vk::Format::eBc1RgbSrgbBlock : vk::Format::eBc1RgbUnormBlock;
case vk::Format::eBc1RgbSrgbBlock: return wantSRGB ? vk::Format::eBc1RgbSrgbBlock : vk::Format::eBc1RgbUnormBlock;
case vk::Format::eBc1RgbaUnormBlock: return wantSRGB ? vk::Format::eBc1RgbaSrgbBlock : vk::Format::eBc1RgbaUnormBlock;
case vk::Format::eBc1RgbaSrgbBlock: return wantSRGB ? vk::Format::eBc1RgbaSrgbBlock : vk::Format::eBc1RgbaUnormBlock;
case vk::Format::eBc2UnormBlock: return wantSRGB ? vk::Format::eBc2SrgbBlock : vk::Format::eBc2UnormBlock;
case vk::Format::eBc2SrgbBlock: return wantSRGB ? vk::Format::eBc2SrgbBlock : vk::Format::eBc2UnormBlock;
case vk::Format::eBc3UnormBlock: return wantSRGB ? vk::Format::eBc3SrgbBlock : vk::Format::eBc3UnormBlock;
case vk::Format::eBc3SrgbBlock: return wantSRGB ? vk::Format::eBc3SrgbBlock : vk::Format::eBc3UnormBlock;
case vk::Format::eBc7UnormBlock: return wantSRGB ? vk::Format::eBc7SrgbBlock : vk::Format::eBc7UnormBlock;
case vk::Format::eBc7SrgbBlock: return wantSRGB ? vk::Format::eBc7SrgbBlock : vk::Format::eBc7UnormBlock;
default: return fmt;
}
}
// Create texture image
bool Renderer::createTextureImage(const std::string& texturePath_, TextureResources& resources) {
try {
ensureThreadLocalVulkanInit();
const std::string textureId = ResolveTextureId(texturePath_);
// Check if texture already exists
{
std::shared_lock<std::shared_mutex> texLock(textureResourcesMutex);
auto it = textureResources.find(textureId);
if (it != textureResources.end()) {
// Texture already loaded and cached; leave cache intact and return success
return true;
}
}
// Resolve on-disk path (may differ from logical ID)
std::string resolvedPath = textureId;
// Ensure command pool is initialized before any GPU work
if (!*commandPool) {
std::cerr << "createTextureImage: commandPool not initialized yet for '" << textureId << "'" << std::endl;
return false;
}
// Per-texture de-duplication (serialize loads of the same texture ID only)
{
std::unique_lock<std::mutex> lk(textureLoadStateMutex);
while (texturesLoading.contains(textureId)) {
textureLoadStateCv.wait(lk);
}
}
// Double-check cache after the wait
{
std::shared_lock<std::shared_mutex> texLock(textureResourcesMutex);
auto it2 = textureResources.find(textureId);
if (it2 != textureResources.end()) {
return true;
}
}
// Mark as loading and ensure we notify on all exit paths
{
std::lock_guard<std::mutex> lk(textureLoadStateMutex);
texturesLoading.insert(textureId);
}
auto _loadingGuard = std::unique_ptr<void, std::function<void(void*)>>(reinterpret_cast<void *>(1), [this, textureId](void*){
std::lock_guard<std::mutex> lk(textureLoadStateMutex);
texturesLoading.erase(textureId);
textureLoadStateCv.notify_all();
});
// Check if this is a KTX2 file
bool isKtx2 = resolvedPath.find(".ktx2") != std::string::npos;
// If it's a KTX2 texture but the path doesn't exist, try common fallback filename variants
if (isKtx2) {
std::filesystem::path origPath(resolvedPath);
if (!std::filesystem::exists(origPath)) {
std::string fname = origPath.filename().string();
std::string dir = origPath.parent_path().string();
auto tryCandidate = [&](const std::string& candidateName) -> bool {
std::filesystem::path cand = std::filesystem::path(dir) / candidateName;
if (std::filesystem::exists(cand)) {
std::cout << "Resolved missing texture '" << resolvedPath << "' to existing file '" << cand.string() << "'" << std::endl;
resolvedPath = cand.string();
return true;
}
return false;
};
// Known suffix variants near the end of filename before extension
// Examples: *_c.ktx2, *_d.ktx2, *_cm.ktx2, *_diffuse.ktx2, *_basecolor.ktx2, *_albedo.ktx2
std::vector<std::string> suffixes = {"_c", "_d", "_cm", "_diffuse", "_basecolor", "_albedo"};
// If filename matches one known suffix, try others
for (const auto& s : suffixes) {
std::string key = s + ".ktx2";
if (fname.size() > key.size() && fname.rfind(key) == fname.size() - key.size()) {
std::string prefix = fname.substr(0, fname.size() - key.size());
for (const auto& alt : suffixes) {
if (alt == s) continue;
std::string candName = prefix + alt + ".ktx2";
if (tryCandidate(candName)) { isKtx2 = true; break; }
}
break; // Only replace last suffix occurrence
}
}
}
}
int texWidth, texHeight, texChannels;
unsigned char* pixels = nullptr;
ktxTexture2* ktxTex = nullptr;
vk::DeviceSize imageSize;
// Track KTX2 transcoding state across the function scope (BasisU only)
bool wasTranscoded = false;
// Track KTX2 header-provided VkFormat (0 == VK_FORMAT_UNDEFINED)
uint32_t headerVkFormatRaw = 0;
uint32_t mipLevels = 1;
std::vector<vk::BufferImageCopy> copyRegions;
if (isKtx2) {
// Load KTX2 file
KTX_error_code result = ktxTexture2_CreateFromNamedFile(resolvedPath.c_str(),
KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT,
&ktxTex);
if (result != KTX_SUCCESS) {
// Retry with sibling suffix variants if file exists but cannot be parsed/opened
std::filesystem::path origPath(resolvedPath);
std::string fname = origPath.filename().string();
std::string dir = origPath.parent_path().string();
auto tryLoad = [&](const std::string& candidateName) -> bool {
std::filesystem::path cand = std::filesystem::path(dir) / candidateName;
if (std::filesystem::exists(cand)) {
std::string candStr = cand.string();
std::cout << "Retrying KTX2 load with sibling candidate '" << candStr << "' for original '" << resolvedPath << "'" << std::endl;
result = ktxTexture2_CreateFromNamedFile(candStr.c_str(), KTX_TEXTURE_CREATE_LOAD_IMAGE_DATA_BIT, &ktxTex);
if (result == KTX_SUCCESS) {
resolvedPath = candStr; // Use the successfully opened candidate
return true;
}
}
return false;
};
// Known suffix variants near the end of filename before extension
std::vector<std::string> suffixes = {"_c", "_d", "_cm", "_diffuse", "_basecolor", "_albedo"};
for (const auto& s : suffixes) {
std::string key = s + ".ktx2";
if (fname.size() > key.size() && fname.rfind(key) == fname.size() - key.size()) {
std::string prefix = fname.substr(0, fname.size() - key.size());
bool loaded = false;
for (const auto& alt : suffixes) {
if (alt == s) continue;
std::string candName = prefix + alt + ".ktx2";
if (tryLoad(candName)) { loaded = true; break; }
}
if (loaded) break;
}
}
}
// Bail out if we still failed to load
if (result != KTX_SUCCESS || ktxTex == nullptr) {
std::cerr << "Failed to load KTX2 texture: " << resolvedPath << " (error: " << result << ")" << std::endl;
return false;
}
// Read header-provided vkFormat (if already GPU-compressed/transcoded offline)
headerVkFormatRaw = static_cast<uint32_t>(ktxTex->vkFormat);
// Check if the texture needs BasisU transcoding; if so, transcode to RGBA32
wasTranscoded = ktxTexture2_NeedsTranscoding(ktxTex);
if (wasTranscoded) {
result = ktxTexture2_TranscodeBasis(ktxTex, KTX_TTF_RGBA32, 0);
if (result != KTX_SUCCESS) {
std::cerr << "Failed to transcode KTX2 BasisU texture to RGBA32: " << resolvedPath << " (error: " << result << ")" << std::endl;
ktxTexture_Destroy((ktxTexture*)ktxTex);
return false;
}
}
texWidth = ktxTex->baseWidth;
texHeight = ktxTex->baseHeight;
texChannels = 4; // logical channels; compressed size handled below
// Disable mipmapping for now - memory pool only supports single mip level
// TODO: Implement proper mipmap support in memory pool
mipLevels = 1;
// Calculate size for base level only (use libktx for correct size incl. compression)
imageSize = ktxTexture_GetImageSize((ktxTexture*)ktxTex, 0);
// Create single copy region for base level only
copyRegions.push_back({
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1
},
.imageOffset = {0, 0, 0},
.imageExtent = {static_cast<uint32_t>(texWidth), static_cast<uint32_t>(texHeight), 1}
});
} else {
// Non-KTX texture loading via file path is disabled to simplify pipeline.
std::cerr << "Unsupported non-KTX2 texture path: " << textureId << std::endl;
return false;
}
// Create staging buffer
auto [stagingBuffer, stagingBufferMemory] = createBuffer(
imageSize,
vk::BufferUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// Copy pixel data to staging buffer
void* data = stagingBufferMemory.mapMemory(0, imageSize);
if (isKtx2) {
// Copy KTX2 texture data for base level only (level 0), regardless of transcode target
ktx_size_t offset = 0;
ktxTexture_GetImageOffset((ktxTexture*)ktxTex, 0, 0, 0, &offset);
const void* levelData = ktxTexture_GetData(reinterpret_cast<ktxTexture *>(ktxTex)) + offset;
size_t levelSize = ktxTexture_GetImageSize((ktxTexture*)ktxTex, 0);
memcpy(data, levelData, levelSize);
} else {
// Copy regular image data
memcpy(data, pixels, static_cast<size_t>(imageSize));
}
stagingBufferMemory.unmapMemory();
// Determine appropriate texture format
vk::Format textureFormat;
const bool wantSRGB = (Renderer::determineTextureFormat(textureId) == vk::Format::eR8G8B8A8Srgb);
bool alphaMaskedHint = false;
if (isKtx2) {
// If the KTX2 provided a valid VkFormat and we did NOT transcode, respect its block type
// but coerce the sRGB/UNORM variant based on texture usage (baseColor vs data maps)
if (!wasTranscoded) {
VkFormat headerFmt = static_cast<VkFormat>(headerVkFormatRaw);
if (headerFmt != VK_FORMAT_UNDEFINED) {
textureFormat = CoerceFormatSRGB(static_cast<vk::Format>(headerFmt), wantSRGB);
} else {
textureFormat = wantSRGB ? vk::Format::eR8G8B8A8Srgb : vk::Format::eR8G8B8A8Unorm;
}
// Can't easily scan alpha in compressed formats here; leave hint at default false
} else {
// Transcoded to RGBA32; choose SRGB/UNORM by heuristic
textureFormat = wantSRGB ? vk::Format::eR8G8B8A8Srgb : vk::Format::eR8G8B8A8Unorm;
// We have CPU-visible RGBA data in 'levelData' above; scan alpha for masking hint
if (ktxTex) {
ktx_size_t offsetScan = 0;
ktxTexture_GetImageOffset((ktxTexture*)ktxTex, 0, 0, 0, &offsetScan);
const uint8_t* rgba = ktxTexture_GetData(reinterpret_cast<ktxTexture *>(ktxTex)) + offsetScan;
size_t pixelCount = static_cast<size_t>(texWidth) * static_cast<size_t>(texHeight);
for (size_t i = 0; i < pixelCount; ++i) {
if (rgba[i * 4 + 3] < 250) { alphaMaskedHint = true; break; }
}
}
}
} else {
textureFormat = wantSRGB ? vk::Format::eR8G8B8A8Srgb : vk::Format::eR8G8B8A8Unorm;
}
// Now that we're done reading libktx data, destroy the KTX texture to avoid leaks
if (isKtx2 && ktxTex) {
ktxTexture_Destroy((ktxTexture*)ktxTex);
ktxTex = nullptr;
}
// Create texture image using memory pool
auto [textureImg, textureImgAllocation] = createImagePooled(
texWidth,
texHeight,
textureFormat,
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
vk::MemoryPropertyFlagBits::eDeviceLocal
);
resources.textureImage = std::move(textureImg);
resources.textureImageAllocation = std::move(textureImgAllocation);
// GPU upload for this texture
uploadImageFromStaging(*stagingBuffer, *resources.textureImage, textureFormat, copyRegions, mipLevels);
// Store the format and mipLevels for createTextureImageView
resources.format = textureFormat;
resources.mipLevels = mipLevels;
resources.alphaMaskedHint = alphaMaskedHint;
// Create texture image view
if (!createTextureImageView(resources)) {
return false;
}
// Create texture sampler
if (!createTextureSampler(resources)) {
return false;
}
// Add to texture resources map (guarded)
{
std::unique_lock<std::shared_mutex> texLock(textureResourcesMutex);
textureResources[textureId] = std::move(resources);
}
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create texture image: " << e.what() << std::endl;
return false;
}
}
// Create texture image view
bool Renderer::createTextureImageView(TextureResources& resources) {
try {
resources.textureImageView = createImageView(
resources.textureImage,
resources.format, // Use the stored format instead of hardcoded sRGB
vk::ImageAspectFlagBits::eColor,
resources.mipLevels // Use the stored mipLevels
);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create texture image view: " << e.what() << std::endl;
return false;
}
}
// Create shared default PBR textures (to avoid creating hundreds of identical textures)
bool Renderer::createSharedDefaultPBRTextures() {
try {
unsigned char translucentPixel[4] = {128, 128, 128, 125}; // 50% alpha
if (!LoadTextureFromMemory(SHARED_DEFAULT_ALBEDO_ID, translucentPixel, 1, 1, 4)) {
std::cerr << "Failed to create shared default albedo texture" << std::endl;
return false;
}
// Create shared default normal texture (flat normal)
unsigned char normalPixel[4] = {128, 128, 255, 255}; // (0.5, 0.5, 1.0, 1.0) in 0-255 range
if (!LoadTextureFromMemory(SHARED_DEFAULT_NORMAL_ID, normalPixel, 1, 1, 4)) {
std::cerr << "Failed to create shared default normal texture" << std::endl;
return false;
}
// Create shared default metallic-roughness texture (non-metallic, fully rough)
unsigned char metallicRoughnessPixel[4] = {0, 255, 0, 255}; // (unused, roughness=1.0, metallic=0.0, alpha=1.0)
if (!LoadTextureFromMemory(SHARED_DEFAULT_METALLIC_ROUGHNESS_ID, metallicRoughnessPixel, 1, 1, 4)) {
std::cerr << "Failed to create shared default metallic-roughness texture" << std::endl;
return false;
}
// Create shared default occlusion texture (white - no occlusion)
unsigned char occlusionPixel[4] = {255, 255, 255, 255};
if (!LoadTextureFromMemory(SHARED_DEFAULT_OCCLUSION_ID, occlusionPixel, 1, 1, 4)) {
std::cerr << "Failed to create shared default occlusion texture" << std::endl;
return false;
}
// Create shared default emissive texture (black - no emission)
unsigned char emissivePixel[4] = {0, 0, 0, 255};
if (!LoadTextureFromMemory(SHARED_DEFAULT_EMISSIVE_ID, emissivePixel, 1, 1, 4)) {
std::cerr << "Failed to create shared default emissive texture" << std::endl;
return false;
}
// Create shared bright red texture for ball visibility
unsigned char brightRedPixel[4] = {255, 0, 0, 255}; // Bright red (R=255, G=0, B=0, A=255)
if (!LoadTextureFromMemory(SHARED_BRIGHT_RED_ID, brightRedPixel, 1, 1, 4)) {
std::cerr << "Failed to create shared bright red texture" << std::endl;
return false;
}
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create shared default PBR textures: " << e.what() << std::endl;
return false;
}
}
// Create default texture resources (1x1 white texture)
bool Renderer::createDefaultTextureResources() {
try {
// Create a 1x1 white texture
const uint32_t width = 1;
const uint32_t height = 1;
const uint32_t pixelSize = 4; // RGBA
const std::vector<uint8_t> pixels = {255, 255, 255, 255}; // White pixel (RGBA)
// Create staging buffer
vk::DeviceSize imageSize = width * height * pixelSize;
auto [stagingBuffer, stagingBufferMemory] = createBuffer(
imageSize,
vk::BufferUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// Copy pixel data to staging buffer
void* data = stagingBufferMemory.mapMemory(0, imageSize);
memcpy(data, pixels.data(), static_cast<size_t>(imageSize));
stagingBufferMemory.unmapMemory();
// Create texture image using memory pool
auto [textureImg, textureImgAllocation] = createImagePooled(
width,
height,
vk::Format::eR8G8B8A8Srgb,
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
vk::MemoryPropertyFlagBits::eDeviceLocal
);
defaultTextureResources.textureImage = std::move(textureImg);
defaultTextureResources.textureImageAllocation = std::move(textureImgAllocation);
// Transition image layout for copy
transitionImageLayout(
*defaultTextureResources.textureImage,
vk::Format::eR8G8B8A8Srgb,
vk::ImageLayout::eUndefined,
vk::ImageLayout::eTransferDstOptimal
);
// Copy buffer to image
std::vector<vk::BufferImageCopy> regions = {{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1
},
.imageOffset = {0, 0, 0},
.imageExtent = {width, height, 1}
}};
copyBufferToImage(
*stagingBuffer,
*defaultTextureResources.textureImage,
width,
height,
regions
);
// Transition image layout for shader access
transitionImageLayout(
*defaultTextureResources.textureImage,
vk::Format::eR8G8B8A8Srgb,
vk::ImageLayout::eTransferDstOptimal,
vk::ImageLayout::eShaderReadOnlyOptimal
);
// Create texture image view
defaultTextureResources.textureImageView = createImageView(
defaultTextureResources.textureImage,
vk::Format::eR8G8B8A8Srgb,
vk::ImageAspectFlagBits::eColor
);
// Create texture sampler
return createTextureSampler(defaultTextureResources);
} catch (const std::exception& e) {
std::cerr << "Failed to create default texture resources: " << e.what() << std::endl;
return false;
}
}
// Create texture sampler
bool Renderer::createTextureSampler(TextureResources& resources) {
try {
ensureThreadLocalVulkanInit();
// Get physical device properties
vk::PhysicalDeviceProperties properties = physicalDevice.getProperties();
// Create sampler (mipmapping disabled)
vk::SamplerCreateInfo samplerInfo{
.magFilter = vk::Filter::eLinear,
.minFilter = vk::Filter::eLinear,
.mipmapMode = vk::SamplerMipmapMode::eNearest, // Disable mipmap filtering
.addressModeU = vk::SamplerAddressMode::eRepeat,
.addressModeV = vk::SamplerAddressMode::eRepeat,
.addressModeW = vk::SamplerAddressMode::eRepeat,
.mipLodBias = 0.0f,
.anisotropyEnable = VK_TRUE,
.maxAnisotropy = std::min(properties.limits.maxSamplerAnisotropy, 8.0f),
.compareEnable = VK_FALSE,
.compareOp = vk::CompareOp::eAlways,
.minLod = 0.0f,
.maxLod = 0.0f, // Force single mip level (no mipmapping)
.borderColor = vk::BorderColor::eIntOpaqueBlack,
.unnormalizedCoordinates = VK_FALSE
};
resources.textureSampler = vk::raii::Sampler(device, samplerInfo);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create texture sampler: " << e.what() << std::endl;
return false;
}
}
// Load texture from file (public wrapper for createTextureImage)
bool Renderer::LoadTexture(const std::string& texturePath) {
ensureThreadLocalVulkanInit();
if (texturePath.empty()) {
std::cerr << "LoadTexture: Empty texture path provided" << std::endl;
return false;
}
// Resolve aliases (canonical ID -> actual key)
const std::string resolvedId = ResolveTextureId(texturePath);
// Check if texture is already loaded
{
std::shared_lock<std::shared_mutex> texLock(textureResourcesMutex);
auto it = textureResources.find(resolvedId);
if (it != textureResources.end()) {
// Texture already loaded
return true;
}
}
// Create temporary texture resources (unused output; cache will be populated internally)
TextureResources tempResources;
// Use existing createTextureImage method (it inserts into textureResources on success)
bool success = createTextureImage(resolvedId, tempResources);
if (!success) {
std::cerr << "Failed to load texture: " << texturePath << std::endl;
}
return success;
}
// Determine appropriate texture format based on texture type
vk::Format Renderer::determineTextureFormat(const std::string& textureId) {
// Determine sRGB vs Linear in a case-insensitive way
std::string idLower = textureId;
std::ranges::transform(idLower, idLower.begin(), [](unsigned char c){ return static_cast<char>(std::tolower(c)); });
// BaseColor/Albedo/Diffuse & SpecGloss RGB should be sRGB for proper gamma correction
if (idLower.find("basecolor") != std::string::npos ||
idLower.find("base_color") != std::string::npos ||
idLower.find("albedo") != std::string::npos ||
idLower.find("diffuse") != std::string::npos ||
idLower.find("specgloss") != std::string::npos ||
idLower.find("specularglossiness") != std::string::npos ||
textureId == Renderer::SHARED_DEFAULT_ALBEDO_ID) {
return vk::Format::eR8G8B8A8Srgb;
}
// Emissive is color data and should be sampled in sRGB
if (idLower.find("emissive") != std::string::npos ||
textureId == Renderer::SHARED_DEFAULT_EMISSIVE_ID) {
return vk::Format::eR8G8B8A8Srgb;
}
// Shared bright red (ball) is a color texture; ensure sRGB for vivid appearance
if (textureId == Renderer::SHARED_BRIGHT_RED_ID) {
return vk::Format::eR8G8B8A8Srgb;
}
// All other PBR textures (normal, metallic-roughness, occlusion) should be linear
// because they contain non-color data that shouldn't be gamma corrected
return vk::Format::eR8G8B8A8Unorm;
}
// Load texture from raw image data in memory
bool Renderer::LoadTextureFromMemory(const std::string& textureId, const unsigned char* imageData,
int width, int height, int channels) {
ensureThreadLocalVulkanInit();
const std::string resolvedId = ResolveTextureId(textureId);
std::cout << "[LoadTextureFromMemory] start id=" << textureId << " -> resolved=" << resolvedId << " size=" << width << "x" << height << " ch=" << channels << std::endl;
if (resolvedId.empty() || !imageData || width <= 0 || height <= 0 || channels <= 0) {
std::cerr << "LoadTextureFromMemory: Invalid parameters" << std::endl;
return false;
}
// Check if texture is already loaded
{
std::shared_lock<std::shared_mutex> texLock(textureResourcesMutex);
auto it = textureResources.find(resolvedId);
if (it != textureResources.end()) {
// Texture already loaded
return true;
}
}
// Per-texture de-duplication (serialize loads of the same texture ID only)
{
std::unique_lock<std::mutex> lk(textureLoadStateMutex);
while (texturesLoading.contains(resolvedId)) {
textureLoadStateCv.wait(lk);
}
}
// Double-check cache after the wait
{
std::shared_lock<std::shared_mutex> texLock(textureResourcesMutex);
auto it2 = textureResources.find(resolvedId);
if (it2 != textureResources.end()) {
return true;
}
}
// Mark as loading and ensure we notify on all exit paths
{
std::lock_guard<std::mutex> lk(textureLoadStateMutex);
texturesLoading.insert(resolvedId);
}
auto _loadingGuard = std::unique_ptr<void, std::function<void(void*)>>(reinterpret_cast<void *>(1), [this, resolvedId](void*){
std::lock_guard<std::mutex> lk(textureLoadStateMutex);
texturesLoading.erase(resolvedId);
textureLoadStateCv.notify_all();
});
try {
TextureResources resources;
// Calculate image size (ensure 4 channels for RGBA)
int targetChannels = 4; // Always use RGBA for consistency
vk::DeviceSize imageSize = width * height * targetChannels;
// Create a staging buffer
auto [stagingBuffer, stagingBufferMemory] = createBuffer(
imageSize,
vk::BufferUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// Copy and convert pixel data to staging buffer
void* data = stagingBufferMemory.mapMemory(0, imageSize);
auto* stagingData = static_cast<unsigned char*>(data);
if (channels == 4) {
// Already RGBA, direct copy
memcpy(stagingData, imageData, imageSize);
} else if (channels == 3) {
// RGB to RGBA conversion
for (int i = 0; i < width * height; ++i) {
stagingData[i * 4 + 0] = imageData[i * 3 + 0]; // R
stagingData[i * 4 + 1] = imageData[i * 3 + 1]; // G
stagingData[i * 4 + 2] = imageData[i * 3 + 2]; // B
stagingData[i * 4 + 3] = 255; // A
}
} else if (channels == 2) {
// Grayscale + Alpha to RGBA conversion
for (int i = 0; i < width * height; ++i) {
stagingData[i * 4 + 0] = imageData[i * 2 + 0]; // R (grayscale)
stagingData[i * 4 + 1] = imageData[i * 2 + 0]; // G (grayscale)
stagingData[i * 4 + 2] = imageData[i * 2 + 0]; // B (grayscale)
stagingData[i * 4 + 3] = imageData[i * 2 + 1]; // A (alpha)
}
} else if (channels == 1) {
// Grayscale to RGBA conversion
for (int i = 0; i < width * height; ++i) {
stagingData[i * 4 + 0] = imageData[i]; // R
stagingData[i * 4 + 1] = imageData[i]; // G
stagingData[i * 4 + 2] = imageData[i]; // B
stagingData[i * 4 + 3] = 255; // A
}
} else {
std::cerr << "LoadTextureFromMemory: Unsupported channel count: " << channels << std::endl;
stagingBufferMemory.unmapMemory();
return false;
}
// Analyze alpha to set alphaMaskedHint (treat as masked if any pixel alpha < ~1.0)
bool alphaMaskedHint = false;
for (int i = 0, n = width * height; i < n; ++i) {
if (stagingData[i * 4 + 3] < 250) { alphaMaskedHint = true; break; }
}
stagingBufferMemory.unmapMemory();
// Determine the appropriate texture format based on the texture type
vk::Format textureFormat = determineTextureFormat(textureId);
// Create texture image using memory pool
auto [textureImg, textureImgAllocation] = createImagePooled(
width,
height,
textureFormat,
vk::ImageTiling::eOptimal,
vk::ImageUsageFlagBits::eTransferDst | vk::ImageUsageFlagBits::eSampled,
vk::MemoryPropertyFlagBits::eDeviceLocal
);
resources.textureImage = std::move(textureImg);
resources.textureImageAllocation = std::move(textureImgAllocation);
// GPU upload. Copy buffer to image in a single submit.
std::vector<vk::BufferImageCopy> regions = {{
.bufferOffset = 0,
.bufferRowLength = 0,
.bufferImageHeight = 0,
.imageSubresource = {
.aspectMask = vk::ImageAspectFlagBits::eColor,
.mipLevel = 0,
.baseArrayLayer = 0,
.layerCount = 1
},
.imageOffset = {0, 0, 0},
.imageExtent = {static_cast<uint32_t>(width), static_cast<uint32_t>(height), 1}
}};
uploadImageFromStaging(*stagingBuffer, *resources.textureImage, textureFormat, regions, 1);
// Store the format for createTextureImageView
resources.format = textureFormat;
resources.alphaMaskedHint = alphaMaskedHint;
// Use resolvedId as the cache key to avoid duplicates
const std::string& cacheId = resolvedId;
// Create texture image view
resources.textureImageView = createImageView(
resources.textureImage,
textureFormat,
vk::ImageAspectFlagBits::eColor
);
// Create texture sampler
if (!createTextureSampler(resources)) {
return false;
}
// Add to texture resources map (guarded)
{
std::unique_lock<std::shared_mutex> texLock(textureResourcesMutex);
textureResources[cacheId] = std::move(resources);
}
std::cout << "Successfully loaded texture from memory: " << cacheId
<< " (" << width << "x" << height << ", " << channels << " channels)" << std::endl;
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to load texture from memory: " << e.what() << std::endl;
return false;
}
}
// Create mesh resources
bool Renderer::createMeshResources(MeshComponent* meshComponent, bool deferUpload) {
ensureThreadLocalVulkanInit();
try {
// If resources already exist, no need to recreate them.
auto it = meshResources.find(meshComponent);
if (it != meshResources.end()) {
return true;
}
// Get mesh data
const auto& vertices = meshComponent->GetVertices();
const auto& indices = meshComponent->GetIndices();
if (vertices.empty() || indices.empty()) {
std::cerr << "Mesh has no vertices or indices" << std::endl;
return false;
}
// --- 1. Create and fill per-mesh staging buffers on the host ---
vk::DeviceSize vertexBufferSize = sizeof(vertices[0]) * vertices.size();
auto [stagingVertexBuffer, stagingVertexBufferMemory] = createBuffer(
vertexBufferSize,
vk::BufferUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
void* vertexData = stagingVertexBufferMemory.mapMemory(0, vertexBufferSize);
std::memcpy(vertexData, vertices.data(), static_cast<size_t>(vertexBufferSize));
stagingVertexBufferMemory.unmapMemory();
vk::DeviceSize indexBufferSize = sizeof(indices[0]) * indices.size();
auto [stagingIndexBuffer, stagingIndexBufferMemory] = createBuffer(
indexBufferSize,
vk::BufferUsageFlagBits::eTransferSrc,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
void* indexData = stagingIndexBufferMemory.mapMemory(0, indexBufferSize);
std::memcpy(indexData, indices.data(), static_cast<size_t>(indexBufferSize));
stagingIndexBufferMemory.unmapMemory();
// --- 2. Create device-local vertex and index buffers via the memory pool ---
auto [vertexBuffer, vertexBufferAllocation] = createBufferPooled(
vertexBufferSize,
vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eVertexBuffer,
vk::MemoryPropertyFlagBits::eDeviceLocal
);
auto [indexBuffer, indexBufferAllocation] = createBufferPooled(
indexBufferSize,
vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eIndexBuffer,
vk::MemoryPropertyFlagBits::eDeviceLocal
);
// --- 3. Either copy now (legacy path) or defer copies for batched submission ---
MeshResources resources;
resources.vertexBuffer = std::move(vertexBuffer);
resources.vertexBufferAllocation = std::move(vertexBufferAllocation);
resources.indexBuffer = std::move(indexBuffer);
resources.indexBufferAllocation = std::move(indexBufferAllocation);
resources.indexCount = static_cast<uint32_t>(indices.size());
if (deferUpload) {
// Keep staging buffers alive and record their sizes; copies will be
// performed later by preAllocateEntityResourcesBatch().
resources.stagingVertexBuffer = std::move(stagingVertexBuffer);
resources.stagingVertexBufferMemory = std::move(stagingVertexBufferMemory);
resources.vertexBufferSizeBytes = vertexBufferSize;
resources.stagingIndexBuffer = std::move(stagingIndexBuffer);
resources.stagingIndexBufferMemory = std::move(stagingIndexBufferMemory);
resources.indexBufferSizeBytes = indexBufferSize;
} else {
// Immediate upload path used by preAllocateEntityResources() and other
// small-object callers. This preserves existing behaviour.
copyBuffer(stagingVertexBuffer, resources.vertexBuffer, vertexBufferSize);
copyBuffer(stagingIndexBuffer, resources.indexBuffer, indexBufferSize);
// staging* buffers are RAII objects and will be destroyed on scope exit.
}
// Add to mesh resources map
meshResources[meshComponent] = std::move(resources);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create mesh resources: " << e.what() << std::endl;
return false;
}
}
// Create uniform buffers
bool Renderer::createUniformBuffers(Entity* entity) {
ensureThreadLocalVulkanInit();
try {
// Check if entity resources already exist
auto it = entityResources.find(entity);
if (it != entityResources.end()) {
return true;
}
// Create entity resources
EntityResources resources;
// Create uniform buffers using memory pool
vk::DeviceSize bufferSize = sizeof(UniformBufferObject);
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
auto [buffer, bufferAllocation] = createBufferPooled(
bufferSize,
vk::BufferUsageFlagBits::eUniformBuffer,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// Use the memory pool's mapped pointer if available
void* mappedMemory = bufferAllocation->mappedPtr;
if (!mappedMemory) {
std::cerr << "Warning: Uniform buffer allocation is not mapped" << std::endl;
}
resources.uniformBuffers.emplace_back(std::move(buffer));
resources.uniformBufferAllocations.emplace_back(std::move(bufferAllocation));
resources.uniformBuffersMapped.emplace_back(mappedMemory);
}
// Create instance buffer for all entities (shaders always expect instance data)
auto* meshComponent = entity->GetComponent<MeshComponent>();
if (meshComponent) {
std::vector<InstanceData> instanceData;
// CRITICAL FIX: Check if entity has any instance data first
if (meshComponent->GetInstanceCount() > 0) {
// Use existing instance data from GLTF loading (whether 1 or many instances)
instanceData = meshComponent->GetInstances();
} else {
// Create single instance data using IDENTITY matrix to avoid double-transform with UBO.model
InstanceData singleInstance;
singleInstance.setModelMatrix(glm::mat4(1.0f));
instanceData = {singleInstance};
}
vk::DeviceSize instanceBufferSize = sizeof(InstanceData) * instanceData.size();
auto [instanceBuffer, instanceBufferAllocation] = createBufferPooled(
instanceBufferSize,
vk::BufferUsageFlagBits::eVertexBuffer,
vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent
);
// Copy instance data to buffer
void* instanceMappedMemory = instanceBufferAllocation->mappedPtr;
if (instanceMappedMemory) {
std::memcpy(instanceMappedMemory, instanceData.data(), instanceBufferSize);
} else {
std::cerr << "Warning: Instance buffer allocation is not mapped" << std::endl;
}
resources.instanceBuffer = std::move(instanceBuffer);
resources.instanceBufferAllocation = std::move(instanceBufferAllocation);
resources.instanceBufferMapped = instanceMappedMemory;
}
// Add to entity resources map
entityResources[entity] = std::move(resources);
return true;
} catch (const std::exception& e) {
std::cerr << "Failed to create uniform buffers: " << e.what() << std::endl;
return false;
}
}
// Create descriptor pool
bool Renderer::createDescriptorPool() {
try {
// Calculate pool sizes for all Bistro materials plus additional entities
// The Bistro model creates many more entities than initially expected
// Each entity needs descriptor sets for both basic and PBR pipelines
// PBR pipeline needs 7 descriptors per set (1 UBO + 5 PBR textures + 1 shadow map array with 16 shadow maps)
// Basic pipeline needs 2 descriptors per set (1 UBO + 1 texture)
const uint32_t maxEntities = 20000; // Increased to 20k entities to handle large scenes like Bistro reliably
const uint32_t maxDescriptorSets = MAX_FRAMES_IN_FLIGHT * maxEntities * 2; // 2 pipeline types per entity
// Calculate descriptor counts
// UBO descriptors: 1 per descriptor set