forked from KhronosGroup/Vulkan-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrenderer.h
More file actions
1912 lines (1693 loc) · 83.8 KB
/
renderer.h
File metadata and controls
1912 lines (1693 loc) · 83.8 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) 2025 Holochip Corporation
*
* 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.
*/
#pragma once
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <deque>
#include <future>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <shared_mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <vulkan/vk_platform.h>
#include <vulkan/vulkan_hpp_macros.hpp>
#include <vulkan/vulkan_raii.hpp>
#include "camera_component.h"
#include "entity.h"
#include "memory_pool.h"
#include "mesh_component.h"
#include "model_loader.h"
#include "platform.h"
#include "thread_pool.h"
// Fallback defines for optional extension names (allow compiling against older headers)
#ifndef VK_EXT_ROBUSTNESS_2_EXTENSION_NAME
# define VK_EXT_ROBUSTNESS_2_EXTENSION_NAME "VK_EXT_robustness2"
#endif
#ifndef VK_KHR_DYNAMIC_RENDERING_LOCAL_READ_EXTENSION_NAME
# define VK_KHR_DYNAMIC_RENDERING_LOCAL_READ_EXTENSION_NAME "VK_KHR_dynamic_rendering_local_read"
#endif
#ifndef VK_EXT_SHADER_TILE_IMAGE_EXTENSION_NAME
# define VK_EXT_SHADER_TILE_IMAGE_EXTENSION_NAME "VK_EXT_shader_tile_image"
#endif
// Forward declarations
class ImGuiSystem;
/**
* @brief Structure for Vulkan queue family indices.
*/
struct QueueFamilyIndices {
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
std::optional<uint32_t> computeFamily;
std::optional<uint32_t> transferFamily; // optional dedicated transfer queue family
[[nodiscard]] bool isComplete() const {
return graphicsFamily.has_value() && presentFamily.has_value() && computeFamily.has_value();
}
};
/**
* @brief Structure for swap chain support details.
*/
struct SwapChainSupportDetails {
vk::SurfaceCapabilitiesKHR capabilities;
std::vector<vk::SurfaceFormatKHR> formats;
std::vector<vk::PresentModeKHR> presentModes;
};
/**
* @brief Structure for individual light data in the storage buffer.
*/
struct LightData {
alignas(16) glm::vec4 position; // Light position (w component used for direction vs position)
alignas(16) glm::vec4 color; // Light color and intensity
alignas(16) glm::mat4 lightSpaceMatrix; // Light space matrix for shadow mapping
alignas(16) glm::vec4 direction; // Light direction (for directional/spotlights)
alignas(4) int lightType; // 0=Point, 1=Directional, 2=Spot, 3=Emissive
alignas(4) float range; // Light range
alignas(4) float innerConeAngle; // For spotlights
alignas(4) float outerConeAngle; // For spotlights
};
struct ShadowUniforms {
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
};
struct ShadowPushConstants {
alignas(16) glm::mat4 model;
};
/**
* @brief Structure for the uniform buffer object (now without fixed light arrays).
*/
struct UniformBufferObject {
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
alignas(16) glm::vec4 camPos;
alignas(4) float exposure;
alignas(4) float gamma;
alignas(4) float prefilteredCubeMipLevels;
alignas(4) float scaleIBLAmbient;
alignas(4) int lightCount;
alignas(4) int padding0; // match shader UBO layout
alignas(4) float padding1; // match shader UBO layout
alignas(4) float padding2; // match shader UBO layout
alignas(8) glm::vec2 screenDimensions;
alignas(4) float nearZ;
alignas(4) float farZ;
alignas(4) float slicesZ;
alignas(4) float _uboPad3;
// Planar reflections
alignas(16) glm::mat4 reflectionVP; // projection * mirroredView
alignas(4) int reflectionEnabled; // 1 when sampling reflection in main pass
alignas(4) int reflectionPass; // 1 during reflection render pass
alignas(8) glm::vec2 _reflectPad0;
alignas(16) glm::vec4 clipPlaneWS; // world-space plane ax+by+cz+d=0
// Controls
alignas(4) float reflectionIntensity; // scales reflection mix in glass
alignas(4) int enableRayQueryReflections = 1; // 1 to enable reflections in ray query mode
alignas(4) int enableRayQueryTransparency = 1; // 1 to enable transparency/refraction in ray query mode
alignas(4) float _padReflect[1]{};
// Ray-query specific: number of per-instance geometry infos in buffer
alignas(4) int geometryInfoCount{0};
alignas(4) int _padGeo0{0};
alignas(4) int _padGeo1{0};
alignas(4) int _padGeo2{0};
alignas(16) glm::vec4 _rqReservedWorldPos{0.0f, 0.0f, 0.0f, 0.0f};
// Ray-query specific: number of materials in materialBuffer
alignas(4) int materialCount{0};
alignas(4) int _padMat0{0};
alignas(4) int _padMat1{0};
alignas(4) int _padMat2{0};
};
// Ray Query uses a dedicated uniform buffer with its own tightly-defined layout.
// This avoids relying on the (much larger) shared raster UBO layout and prevents
// CPU↔shader layout drift from breaking Ray Query-only fields.
//
// IMPORTANT: This layout must match `RayQueryUniforms` in `shaders/ray_query.slang`.
struct RayQueryUniformBufferObject {
alignas(16) glm::mat4 model;
alignas(16) glm::mat4 view;
alignas(16) glm::mat4 proj;
alignas(16) glm::vec4 camPos;
alignas(4) float exposure;
alignas(4) float gamma;
// Match raster UBO conventions so Ray Query can run the same lighting math.
alignas(4) float scaleIBLAmbient;
alignas(4) int lightCount;
alignas(4) int enableRayQueryReflections;
alignas(4) int enableRayQueryTransparency;
alignas(8) glm::vec2 screenDimensions;
alignas(4) int geometryInfoCount;
alignas(4) int materialCount;
alignas(4) int _pad0; // used for rayQueryMaxBounces
// Thick-glass controls (RQ-only)
alignas(4) int enableThickGlass; // 0/1 toggle
alignas(4) float thicknessClamp; // max thickness in meters
alignas(4) float absorptionScale; // scales sigma_a
alignas(4) int _pad1; // Ray Query: enable hard shadows for direct lighting (0/1)
// Ray Query soft shadows (area-light approximation)
alignas(4) int shadowSampleCount; // 1 = hard shadows; >1 = multi-sample
alignas(4) float shadowSoftness; // 0 = hard; otherwise scales effective light radius (fraction of range)
alignas(4) float reflectionIntensity; // User control for glass reflection strength
alignas(4) float _padShadow[2]{};
};
static_assert(sizeof(RayQueryUniformBufferObject) == 288, "RayQueryUniformBufferObject size must match shader layout");
static_assert(offsetof(RayQueryUniformBufferObject, model) == 0);
static_assert(offsetof(RayQueryUniformBufferObject, view) == 64);
static_assert(offsetof(RayQueryUniformBufferObject, proj) == 128);
static_assert(offsetof(RayQueryUniformBufferObject, camPos) == 192);
static_assert(offsetof(RayQueryUniformBufferObject, exposure) == 208);
static_assert(offsetof(RayQueryUniformBufferObject, gamma) == 212);
static_assert(offsetof(RayQueryUniformBufferObject, scaleIBLAmbient) == 216);
static_assert(offsetof(RayQueryUniformBufferObject, lightCount) == 220);
static_assert(offsetof(RayQueryUniformBufferObject, enableRayQueryReflections) == 224);
static_assert(offsetof(RayQueryUniformBufferObject, enableRayQueryTransparency) == 228);
static_assert(offsetof(RayQueryUniformBufferObject, screenDimensions) == 232);
static_assert(offsetof(RayQueryUniformBufferObject, geometryInfoCount) == 240);
static_assert(offsetof(RayQueryUniformBufferObject, materialCount) == 244);
static_assert(offsetof(RayQueryUniformBufferObject, _pad0) == 248);
static_assert(offsetof(RayQueryUniformBufferObject, enableThickGlass) == 252);
static_assert(offsetof(RayQueryUniformBufferObject, thicknessClamp) == 256);
static_assert(offsetof(RayQueryUniformBufferObject, absorptionScale) == 260);
static_assert(offsetof(RayQueryUniformBufferObject, _pad1) == 264);
static_assert(offsetof(RayQueryUniformBufferObject, shadowSampleCount) == 268);
static_assert(offsetof(RayQueryUniformBufferObject, shadowSoftness) == 272);
/**
* @brief Structure for PBR material properties.
* This structure must match the PushConstants structure in the PBR shader.
*/
struct MaterialProperties {
alignas(16) glm::vec4 baseColorFactor;
alignas(4) float metallicFactor;
alignas(4) float roughnessFactor;
alignas(4) int baseColorTextureSet;
alignas(4) int physicalDescriptorTextureSet;
alignas(4) int normalTextureSet;
alignas(4) int occlusionTextureSet;
alignas(4) int emissiveTextureSet;
alignas(4) float alphaMask;
alignas(4) float alphaMaskCutoff;
alignas(16) glm::vec3 emissiveFactor; // Emissive factor for HDR emissive sources
alignas(4) float emissiveStrength; // KHR_materials_emissive_strength extension
alignas(4) float transmissionFactor; // KHR_materials_transmission
alignas(4) int useSpecGlossWorkflow; // 1 if using KHR_materials_pbrSpecularGlossiness
alignas(4) float glossinessFactor; // SpecGloss glossiness scalar
alignas(16) glm::vec3 specularFactor; // SpecGloss specular color factor
alignas(4) float ior = 1.5f; // index of refraction
alignas(4) bool hasEmissiveStrengthExtension;
};
/**
* @brief Rendering mode selection
*/
enum class RenderMode {
Rasterization, // Traditional rasterization pipeline
RayQuery // Ray query compute shader
};
/**
* @brief Class for managing Vulkan rendering.
*
* This class implements the rendering pipeline as described in the Engine_Architecture chapter:
* @see en/Building_a_Simple_Engine/Engine_Architecture/05_rendering_pipeline.adoc
*/
class Renderer {
public:
/**
* @brief Constructor with a platform.
* @param platform The platform to use for rendering.
*/
explicit Renderer(Platform* platform);
/**
* @brief Destructor for proper cleanup.
*/
~Renderer();
/**
* @brief Initialize the renderer.
* @param appName The name of the application.
* @param enableValidationLayers Whether to enable validation layers.
* @return True if initialization was successful, false otherwise.
*/
bool Initialize(const std::string& appName, bool enableValidationLayers = true);
/**
* @brief Clean up renderer resources.
*/
void Cleanup();
/**
* @brief Render the scene.
* @param entities The entities to render.
* @param camera The camera to use for rendering.
* @param imguiSystem The ImGui system for UI rendering (optional).
*/
void Render(const std::vector<std::unique_ptr<Entity>>& entities, CameraComponent* camera, ImGuiSystem* imguiSystem = nullptr);
// Render overload that accepts a snapshot of raw entity pointers.
// This allows the Engine to release its entity-container lock before rendering
// (avoiding writer starvation of background loading/physics threads).
void Render(const std::vector<Entity *>& entities, CameraComponent* camera, ImGuiSystem* imguiSystem = nullptr);
/**
* @brief Wait for the device to be idle.
*/
void WaitIdle();
/**
* @brief Wait for fences with periodic watchdog kicks to prevent false hang detection.
* Must be called from the render thread.
*/
vk::Result waitForFencesSafe(const std::vector<vk::Fence>& fences, vk::Bool32 waitAll, uint64_t timeoutNs = 100'000'000ULL);
/**
* @brief Wait for fences with periodic watchdog kicks to prevent false hang detection.
* Must be called from the render thread. Overload for a single fence.
*/
vk::Result waitForFencesSafe(vk::Fence fence, vk::Bool32 waitAll, uint64_t timeoutNs = 100'000'000ULL);
/**
* @brief Dispatch a compute shader.
* @param groupCountX The number of local workgroups to dispatch in the X dimension.
* @param groupCountY The number of local workgroups to dispatch in the Y dimension.
* @param groupCountZ The number of local workgroups to dispatch in the Z dimension.
* @param inputBuffer The input buffer.
* @param outputBuffer The output buffer.
* @param hrtfBuffer The HRTF data buffer.
* @param paramsBuffer The parameters buffer.
* @return A fence that can be used to synchronize with the compute operation.
*/
vk::raii::Fence DispatchCompute(uint32_t groupCountX,
uint32_t groupCountY,
uint32_t groupCountZ,
vk::Buffer inputBuffer,
vk::Buffer outputBuffer,
vk::Buffer hrtfBuffer,
vk::Buffer paramsBuffer);
/**
* @brief Check if the renderer is initialized.
* @return True if the renderer is initialized, false otherwise.
*/
bool IsInitialized() const {
return initialized;
}
/**
* @brief Get the Vulkan device.
* @return The Vulkan device.
*/
vk::Device GetDevice() const {
return *device;
}
// Expose max frames in flight for per-frame resource duplication
uint32_t GetMaxFramesInFlight() const {
return MAX_FRAMES_IN_FLIGHT;
}
/**
* @brief Get the Vulkan RAII device.
* @return The Vulkan RAII device.
*/
const vk::raii::Device& GetRaiiDevice() const {
return device;
}
// Expose uploads timeline semaphore and last value for external waits
vk::Semaphore GetUploadsTimelineSemaphore() const {
return *uploadsTimeline;
}
uint64_t GetUploadsTimelineValue() const {
return uploadTimelineLastSubmitted.load(std::memory_order_relaxed);
}
/**
* @brief Get the compute queue.
* @return The compute queue.
*/
vk::Queue GetComputeQueue() const {
std::lock_guard<std::mutex> lock(queueMutex);
return *computeQueue;
}
/**
* @brief Find a suitable memory type.
* @param typeFilter The type filter.
* @param properties The memory properties.
* @return The memory type index.
*/
uint32_t FindMemoryType(uint32_t typeFilter, vk::MemoryPropertyFlags properties) const {
return findMemoryType(typeFilter, properties);
}
/**
* @brief Get the compute queue family index.
* @return The compute queue family index.
*/
uint32_t GetComputeQueueFamilyIndex() const {
if (queueFamilyIndices.computeFamily.has_value()) {
return queueFamilyIndices.computeFamily.value();
}
// Fallback to graphics family to avoid crashes on devices without a separate compute queue
return queueFamilyIndices.graphicsFamily.value();
}
/**
* @brief Submit a command buffer to the compute queue with proper dispatch loader preservation.
* @param commandBuffer The command buffer to submit.
* @param fence The fence to signal when the operation completes.
*/
void SubmitToComputeQueue(vk::CommandBuffer commandBuffer, vk::Fence fence) const {
// Use mutex to ensure thread-safe access to queues
vk::SubmitInfo submitInfo{
.commandBufferCount = 1,
.pCommandBuffers = &commandBuffer
};
std::lock_guard<std::mutex> lock(queueMutex);
// Prefer compute queue when available; otherwise, fall back to graphics queue to avoid crashes
if (*computeQueue) {
computeQueue.submit(submitInfo, fence);
} else {
graphicsQueue.submit(submitInfo, fence);
}
}
/**
* @brief Create a shader module from SPIR-V code.
* @param code The SPIR-V code.
* @return The shader module.
*/
vk::raii::ShaderModule CreateShaderModule(const std::vector<char>& code) {
return createShaderModule(code);
}
/**
* @brief Create a shader module from a file.
* @param filename The filename.
* @return The shader module.
*/
vk::raii::ShaderModule CreateShaderModule(const std::string& filename) {
auto code = readFile(filename);
return createShaderModule(code);
}
/**
* @brief Load a texture from a file.
* @param texturePath The path to the texture file.
* @return True if the texture was loaded successfully, false otherwise.
*/
bool LoadTexture(const std::string& texturePath);
// Asynchronous texture loading APIs (thread-pool backed).
// The 'critical' flag is used to front-load important textures (e.g.,
// baseColor/albedo) so the scene looks mostly correct before the loading
// screen disappears. Non-critical textures (normals, MR, AO, emissive)
// can stream in after geometry is visible.
std::future<bool> LoadTextureAsync(const std::string& texturePath, bool critical = false);
/**
* @brief Load a texture from raw image data in memory.
* @param textureId The identifier for the texture.
* @param imageData The raw image data.
* @param width The width of the image.
* @param height The height of the image.
* @param channels The number of channels in the image.
* @return True if the texture was loaded successfully, false otherwise.
*/
bool LoadTextureFromMemory(const std::string& textureId,
const unsigned char* imageData,
int width,
int height,
int channels);
// Asynchronous upload from memory (RGBA/RGB/other). Safe for concurrent calls.
std::future<bool> LoadTextureFromMemoryAsync(const std::string& textureId,
const unsigned char* imageData,
int width,
int height,
int channels,
bool critical = false);
// Progress query for UI
uint32_t GetTextureTasksScheduled() const {
return textureTasksScheduled.load();
}
uint32_t GetTextureTasksCompleted() const {
return textureTasksCompleted.load();
}
// GPU upload progress (per-texture jobs processed on the main thread).
uint32_t GetUploadJobsTotal() const {
return uploadJobsTotal.load();
}
uint32_t GetUploadJobsCompleted() const {
return uploadJobsCompleted.load();
}
// --- Acceleration structure build progress (for UI) ---
// Exposed so the loading overlay can show meaningful progress when
// BLAS/TLAS builds take a long time (>= ~10 seconds).
bool IsASBuildInProgress() const {
return asBuildUiActive.load(std::memory_order_relaxed);
}
float GetASBuildProgress() const {
return asBuildUiProgress.load(std::memory_order_relaxed);
}
uint32_t GetASBuildItemsDone() const {
return asBuildUiDone.load(std::memory_order_relaxed);
}
uint32_t GetASBuildItemsTotal() const {
return asBuildUiTotal.load(std::memory_order_relaxed);
}
const char* GetASBuildStage() const {
return asBuildUiStage.load(std::memory_order_relaxed);
}
double GetASBuildElapsedSeconds() const {
const uint64_t start = asBuildUiStartNs.load(std::memory_order_relaxed);
if (start == 0)
return 0.0;
const uint64_t now = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
if (now <= start)
return 0.0;
return static_cast<double>(now - start) / 1'000'000'000.0;
}
bool ShouldShowASBuildProgressInUI() const {
return IsASBuildInProgress() && GetASBuildElapsedSeconds() >= 10.0;
}
// Block until all currently-scheduled texture tasks have completed.
// Intended for use during initial scene loading so that descriptor
// creation sees the final textureResources instead of fallbacks.
void WaitForAllTextureTasks();
// Process pending texture GPU uploads on the calling thread.
// This should be invoked from the main/render thread so that all
// Vulkan work happens from a single thread while worker threads
// perform only CPU-side decoding.
//
// Parameters allow us to:
// - limit the number of jobs processed per call (for streaming), and
// - choose whether to include critical and/or non-critical jobs.
void ProcessPendingTextureJobs(uint32_t maxJobs = UINT32_MAX,
bool includeCritical = true,
bool includeNonCritical = true);
// Track which entities use a given texture ID so that descriptor sets
// can be refreshed when textures finish streaming in.
void RegisterTextureUser(const std::string& textureId, Entity* entity);
void OnTextureUploaded(const std::string& textureId);
// Global loading state (model/scene). Consider the scene "loading" while
// either the model is being parsed/instantiated OR there are still
// outstanding critical texture uploads (e.g., baseColor/albedo).
// Loading state: show blocking loading overlay only until the initial scene is ready.
// Background streaming may continue after that without blocking the scene.
enum class LoadingPhase : uint32_t {
Scene = 0,
Textures,
Physics,
AccelerationStructures,
Finalizing
};
LoadingPhase GetLoadingPhase() const {
return static_cast<LoadingPhase>(loadingPhase.load(std::memory_order_relaxed));
}
const char* GetLoadingPhaseName() const {
switch (GetLoadingPhase()) {
case LoadingPhase::Scene:
return "Scene";
case LoadingPhase::Textures:
return "Textures";
case LoadingPhase::Physics:
return "Physics";
case LoadingPhase::AccelerationStructures:
return "Acceleration Structures";
case LoadingPhase::Finalizing:
return "Finalizing";
default:
return "Loading";
}
}
float GetLoadingPhaseProgress() const {
return std::clamp(loadingPhaseProgress.load(std::memory_order_relaxed), 0.0f, 1.0f);
}
void SetLoadingPhase(LoadingPhase phase) {
loadingPhase.store(static_cast<uint32_t>(phase), std::memory_order_relaxed);
loadingPhaseProgress.store(0.0f, std::memory_order_relaxed);
}
void SetLoadingPhaseProgress(float v) {
loadingPhaseProgress.store(std::clamp(v, 0.0f, 1.0f), std::memory_order_relaxed);
}
void MarkInitialLoadComplete() {
initialLoadComplete.store(true, std::memory_order_relaxed);
SetLoadingPhase(LoadingPhase::Finalizing);
loadingPhaseProgress.store(1.0f, std::memory_order_relaxed);
}
bool IsLoading() const {
// Keep the blocking overlay visible until the engine has finished
// post-load blockers (AS build, descriptor cold-init, etc.).
return (loadingFlag.load(std::memory_order_relaxed) || criticalJobsOutstanding.load(std::memory_order_relaxed) > 0u ||
!initialLoadComplete.load(std::memory_order_relaxed));
}
// True only while the model/scene is still being constructed or while critical
// texture jobs remain outstanding. This excludes the "finalizing" stage where
// the render thread may still be doing post-load work (AS build, descriptor init).
//
// IMPORTANT: Do NOT use critical texture completion as a gate for starting TLAS/BLAS builds.
// AS builds depend on geometry buffers and instance transforms, not on texture readiness.
bool IsSceneLoaderActive() const {
return loadingFlag.load(std::memory_order_relaxed);
}
void SetLoading(bool v) {
loadingFlag.store(v, std::memory_order_relaxed);
if (v) {
// New load cycle starting
initialLoadComplete.store(false, std::memory_order_relaxed);
SetLoadingPhase(LoadingPhase::Scene);
}
}
// Descriptor set deferred update machinery
void MarkEntityDescriptorsDirty(Entity *entity);
void ProcessDirtyDescriptorsForFrame(uint32_t frameIndex);
// Texture aliasing: map canonical IDs to actual loaded keys (e.g., file paths) to avoid duplicates
inline void RegisterTextureAlias(const std::string& aliasId, const std::string& targetId) {
std::unique_lock<std::shared_mutex> lock(textureResourcesMutex);
if (aliasId.empty() || targetId.empty())
return;
// Resolve targetId without re-locking by walking the alias map directly
std::string resolved = targetId;
for (int i = 0; i < 8; ++i) {
auto it = textureAliases.find(resolved);
if (it == textureAliases.end())
break;
if (it->second == resolved)
break;
resolved = it->second;
}
if (aliasId == resolved) {
textureAliases.erase(aliasId);
} else {
textureAliases[aliasId] = resolved;
}
}
inline std::string ResolveTextureId(const std::string& id) const {
std::shared_lock<std::shared_mutex> lock(textureResourcesMutex);
std::string cur = id;
for (int i = 0; i < 8; ++i) {
// prevent pathological cycles
auto it = textureAliases.find(cur);
if (it == textureAliases.end())
break;
if (it->second == cur)
break; // self-alias guard
cur = it->second;
}
return cur;
}
/**
* @brief Transition an image layout.
* @param image The image.
* @param format The image format.
* @param oldLayout The old layout.
* @param newLayout The new layout.
*/
void TransitionImageLayout(vk::Image image, vk::Format format, vk::ImageLayout oldLayout, vk::ImageLayout newLayout) {
transitionImageLayout(image, format, oldLayout, newLayout);
}
/**
* @brief Copy a buffer to an image.
* @param buffer The buffer.
* @param image The image.
* @param width The image width.
* @param height The image height.
*/
void CopyBufferToImage(vk::Buffer buffer, vk::Image image, uint32_t width, uint32_t height) {
// Create a default single region for backward compatibility
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(buffer, image, width, height, regions);
}
/**
* @brief Get the current command buffer.
* @return The current command buffer.
*/
vk::raii::CommandBuffer& GetCurrentCommandBuffer() {
return commandBuffers[currentFrame];
}
/**
* @brief Get the swap chain image format.
* @return The swap chain image format.
*/
vk::Format GetSwapChainImageFormat() const {
return swapChainImageFormat;
}
/**
* @brief Set the framebuffer resized flag.
* This should be called when the window is resized to trigger swap chain recreation.
*/
void SetFramebufferResized() {
framebufferResized.store(true, std::memory_order_relaxed);
}
/**
* @brief Set the model loader reference for accessing extracted lights.
* @param _modelLoader Pointer to the model loader.
*/
void SetModelLoader(ModelLoader* _modelLoader) {
modelLoader = _modelLoader;
// Materials are resolved via ModelLoader; invalidate cached per-entity material info.
for (auto& kv : entityResources) {
kv.second.materialCacheValid = false;
kv.second.cachedMaterial = nullptr;
kv.second.cachedIsBlended = false;
kv.second.cachedIsGlass = false;
kv.second.cachedIsLiquid = false;
kv.second.cachedMaterialProps = MaterialProperties{};
}
}
/**
* @brief Set static lights loaded during model initialization.
* @param lights The lights to store statically.
*/
void SetStaticLights(const std::vector<ExtractedLight>& lights) {
staticLights = lights;
std::cout << "[Lights] staticLights set: " << staticLights.size() << " entries" << std::endl;
}
/**
* @brief Set the gamma correction value for PBR rendering.
* @param _gamma The gamma correction value (typically 2.2).
*/
void SetGamma(float _gamma) {
gamma = _gamma;
}
/**
* @brief Set the exposure value for HDR tone mapping.
* @param _exposure The exposure value (1.0 = no adjustment).
*/
void SetExposure(float _exposure) {
exposure = _exposure;
}
// Reflection intensity (UI + shader control)
void SetReflectionIntensity(float v) {
reflectionIntensity = v;
}
float GetReflectionIntensity() const {
return reflectionIntensity;
}
void SetPlanarReflectionsEnabled(bool enabled);
void TogglePlanarReflections();
bool IsPlanarReflectionsEnabled() const {
return enablePlanarReflections;
}
// Ray query rendering mode control
void SetRenderMode(RenderMode mode) {
currentRenderMode = mode;
}
RenderMode GetRenderMode() const {
return currentRenderMode;
}
void ToggleRenderMode() {
currentRenderMode = (currentRenderMode == RenderMode::Rasterization) ? RenderMode::RayQuery : RenderMode::Rasterization;
}
// Ray query capability getters
bool GetRayQueryEnabled() const {
return rayQueryEnabled;
}
bool GetAccelerationStructureEnabled() const {
return accelerationStructureEnabled;
}
// Ray Query static-only mode (disable animation/physics updates and TLAS refits to render a static opaque scene)
void SetRayQueryStaticOnly(bool v) {
rayQueryStaticOnly = v;
}
bool IsRayQueryStaticOnly() const {
return rayQueryStaticOnly;
}
/**
* @brief Request acceleration structure build at next safe frame point.
* Safe to call from any thread (e.g., background loading thread).
*/
void RequestAccelerationStructureBuild() {
if (!accelerationStructureEnabled || !rayQueryEnabled)
return;
// Record when the request was made so the render loop can enforce a bounded deferral
// policy (avoid getting stuck waiting for “perfect” readiness forever).
// NOTE: `asBuildRequested` may already be true due to other triggers; still ensure
// the request timestamp is armed so the timeout logic can work.
if (asBuildRequestStartNs.load(std::memory_order_relaxed) == 0) {
const uint64_t nowNs = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
asBuildRequestStartNs.store(nowNs, std::memory_order_relaxed);
}
// Allow AS build to take longer than the watchdog threshold (large scenes in Debug).
watchdogSuppressed.store(true, std::memory_order_relaxed);
asBuildRequested.store(true, std::memory_order_release);
}
// Overload with reason tracking for diagnostics
void RequestAccelerationStructureBuild(const char* reason) {
if (!accelerationStructureEnabled || !rayQueryEnabled)
return;
if (asBuildRequestStartNs.load(std::memory_order_relaxed) == 0) {
const uint64_t nowNs = static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch())
.count());
asBuildRequestStartNs.store(nowNs, std::memory_order_relaxed);
}
if (reason) {
lastASBuildRequestReason = reason;
std::cout << "[AS] Requesting rebuild. Reason: " << reason << std::endl;
} else {
lastASBuildRequestReason = "(no reason)";
}
// Explicit requests bypass the freeze to ensure dynamic objects (like balls) are added
asDevOverrideAllowRebuild = true;
watchdogSuppressed.store(true, std::memory_order_relaxed);
asBuildRequested.store(true, std::memory_order_release);
}
/**
* @brief Build acceleration structures for ray query rendering.
* @param entities The entities to include in the acceleration structures.
* @return True if successful, false otherwise.
*/
bool buildAccelerationStructures(const std::vector<Entity *>& entities);
// Refit/UPDATE the TLAS with latest entity transforms (no rebuild)
bool refitTopLevelAS(const std::vector<Entity *>& entities, CameraComponent* camera);
/**
* @brief Update ray query descriptor sets with current resources.
* @param frameIndex The frame index to update (or all frames if not specified).
* @return True if successful, false otherwise.
*/
bool updateRayQueryDescriptorSets(uint32_t frameIndex, const std::vector<Entity *>& entities);
/**
* @brief Create or resize light storage buffers to accommodate the given number of lights.
* @param lightCount The number of lights to accommodate.
* @return True if successful, false otherwise.
*/
bool createOrResizeLightStorageBuffers(size_t lightCount);
/**
* @brief Update the light storage buffer with current light data.
* @param frameIndex The current frame index.
* @param lights The light data to upload.
* @return True if successful, false otherwise.
*/
bool updateLightStorageBuffer(uint32_t frameIndex, const std::vector<ExtractedLight>& lights, CameraComponent* camera = nullptr);
/**
* @brief Update all existing descriptor sets with new light storage buffer references.
* Called when light storage buffers are recreated to ensure descriptor sets reference valid buffers.
*/
// Update PBR descriptor sets to point to the latest light SSBOs.
// When allFrames=true, refresh all frames (use only when the device is idle — e.g., after waitIdle()).
// Otherwise, refresh only the current frame at the frame safe point to avoid touching in‑flight frames.
void updateAllDescriptorSetsWithNewLightBuffers(bool allFrames = false);
// Upload helper: record both layout transitions and the copy in a single submit with a fence
void uploadImageFromStaging(vk::Buffer staging,
vk::Image image,
vk::Format format,
const std::vector<vk::BufferImageCopy>& regions,
uint32_t mipLevels = 1);
// Generate full mip chain for a 2D color image using GPU blits
void generateMipmaps(vk::Image image,
vk::Format format,
int32_t texWidth,
int32_t texHeight,
uint32_t mipLevels);
vk::Format findDepthFormat();
/**
* @brief Pre-allocate all Vulkan resources for an entity during scene loading.
* @param entity The entity to pre-allocate resources for.
* @return True if pre-allocation was successful, false otherwise.
*/
bool preAllocateEntityResources(Entity* entity);
/**
* @brief Pre-allocate Vulkan resources for a batch of entities, batching mesh uploads.
*
* This variant is optimized for large scene loads (e.g., GLTF Bistro). It will:
* - Create per-mesh GPU buffers as usual, but record all buffer copy commands
* into a single command buffer and submit them in one batch.
* - Then create uniform buffers and descriptor sets per entity.
*
* Callers that load many geometry entities at once (like GLTF scene loading)
* should prefer this over repeated preAllocateEntityResources() calls.
*/
bool preAllocateEntityResourcesBatch(const std::vector<Entity *>& entities);
// Thread-safe: enqueue entities that need GPU-side resource preallocation.
// The actual Vulkan work will be performed on the render thread at the frame-start safe point.
void EnqueueEntityPreallocationBatch(const std::vector<Entity *>& entities);
void EnqueueInstanceBufferRecreation(Entity* entity);
/**
* @brief Recreate the instance buffer for an entity that had its instances cleared.
*
* When an entity that was originally set up for instanced rendering needs to be
* converted to a single non-instanced entity (e.g., for animation), this method
* recreates the GPU instance buffer with a single identity instance.
*
* @param entity The entity whose instance buffer should be recreated.
* @return True if successful, false otherwise.
*/
bool recreateInstanceBuffer(Entity* entity);
// Shared default PBR texture identifiers (to avoid creating hundreds of identical textures)
static const std::string SHARED_DEFAULT_ALBEDO_ID;
static const std::string SHARED_DEFAULT_NORMAL_ID;
static const std::string SHARED_DEFAULT_METALLIC_ROUGHNESS_ID;
static const std::string SHARED_DEFAULT_OCCLUSION_ID;
static const std::string SHARED_DEFAULT_EMISSIVE_ID;
static const std::string SHARED_BRIGHT_RED_ID;
/**
* @brief Determine the appropriate texture format based on the texture type.
* @param textureId The texture identifier to analyze.
* @return The appropriate Vulkan format (sRGB for baseColor, linear for others).
*/
static vk::Format determineTextureFormat(const std::string& textureId);
private:
// Platform
Platform* platform = nullptr;
// Model loader reference for accessing extracted lights
class ModelLoader* modelLoader = nullptr;
// PBR rendering parameters
float gamma = 2.2f; // Gamma correction value
float exposure = 1.2f; // HDR exposure value (default tuned to avoid washout)
float reflectionIntensity = 1.0f; // User control for glass reflection strength
// Raster shadows (experimental): use ray queries in the raster PBR fragment shader.
// Wired through `UniformBufferObject.padding2` to avoid UBO layout churn.
bool enableRasterRayQueryShadows = false;
// Ray Query tuning
int rayQueryMaxBounces = 1; // 0 = no secondary rays, 1 = one-bounce reflection/refraction
bool enableRayQueryShadows = true; // Hard shadows for Ray Query direct lighting (shadow rays)
int rayQueryShadowSampleCount = 1; // 1 = hard; >1 enables soft-shadow sampling in the shader
float rayQueryShadowSoftness = 0.0f; // 0 = hard; otherwise scales effective light radius (fraction of range)
// Thick-glass controls (RQ-only)
bool enableThickGlass = true;
float thickGlassAbsorptionScale = 1.0f;
float thickGlassThicknessClamp = 0.2f; // meters
// Vulkan RAII context
vk::raii::Context context;
// Vulkan instance and debug messenger
vk::raii::Instance instance = nullptr;
vk::raii::DebugUtilsMessengerEXT debugMessenger = nullptr;
// Vulkan device
vk::raii::PhysicalDevice physicalDevice = nullptr;
vk::raii::Device device = nullptr;
// Memory pool for efficient memory management
std::unique_ptr<MemoryPool> memoryPool;
// Vulkan queues
vk::raii::Queue graphicsQueue = nullptr;
vk::raii::Queue presentQueue = nullptr;
vk::raii::Queue computeQueue = nullptr;
// Vulkan surface
vk::raii::SurfaceKHR surface = nullptr;
// Swap chain
vk::raii::SwapchainKHR swapChain = nullptr;
std::vector<vk::Image> swapChainImages;