SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanRenderer.hpp
Go to the documentation of this file.
1#ifndef VULKANRENDERER_HPP
2#define VULKANRENDERER_HPP
3
4#include <backends/imgui_impl_vulkan.h>
5#include <imgui.h>
6#include <vulkan/vulkan.h>
7
10#include <array>
11#include <cstdint>
12#include <set>
13#include <unordered_map>
14#include <vector>
15
18#include "Core/Logger.hpp"
22
23// Shadow caster depth bias
24#define SHADOW_DEPTH_BIAS_CONSTANT 1.25f
25#define SHADOW_DEPTH_BIAS_SLOPE 1.75f
26// WVP + World matrices
27#define PUSH_CONSTANT_BYTES (sizeof(float) * 16 * 2)
28
29namespace Sleak {
30class ENGINE_API Window;
31 namespace RenderEngine {
32
34 uint32_t GraphicsIndex = UINT32_MAX;
35 uint32_t ComputeIndex = UINT32_MAX;
36 uint32_t TransferIndex = UINT32_MAX;
37 uint32_t PresentIndex = UINT32_MAX;
38
39 const float GraphicsPriority = 0.9f;
40 const float ComputePriority = 0.8f;
41 const float TransferPriority = 0.7f;
42 const float PresentPriority = 1.0f;
43
44 bool isComplete() {
45 return GraphicsIndex != UINT32_MAX && PresentIndex != UINT32_MAX;
46 }
47};
48
50 VkSurfaceCapabilitiesKHR caps;
51 std::vector<VkSurfaceFormatKHR> formats;
52 std::vector<VkPresentModeKHR> presentModes;
53};
54
55/// Vulkan backend for Renderer/RenderContext: owns the device, swapchain,
56/// and per-frame command recording. Implementation spans this file plus
57/// the Vulkan* subsystem TUs (Device, Swapchain, Pipelines, Shadow, etc.).
58class ENGINE_API VulkanRenderer : public Renderer, public RenderContext {
59public:
60 /// Constructs the renderer, sets the clear color, and registers
61 /// ResourceManager factory callbacks.
62 VulkanRenderer(Window* window);
63 /// Calls Cleanup() to tear down all Vulkan resources.
65
66 /// Runs the full Vulkan bring-up sequence: instance, device, swapchain,
67 /// pipelines, and sync objects.
68 virtual bool Initialize() override;
69 /// Acquires a swapchain image and begins the shadow/GBuffer/forward
70 /// passes; drawing happens via the RenderContext methods below.
71 virtual void BeginRender() override;
72 /// Ends the active render pass, submits the command buffer, and presents.
73 virtual void EndRender() override;
74 /// Tears down every Vulkan resource in reverse dependency order.
75 virtual void Cleanup() override;
76 /// Blocks until the device finishes all submitted GPU work.
77 virtual void WaitIdle() override;
78 /// Submits the open upload batch for this frame. A frame that failed to
79 /// start leaves it open, so it rides along with the next submitted frame.
80 virtual void FlushPendingTransfers() override;
81
82 // GPU memory tracking
83 /// Returns total bytes currently allocated by VulkanBuffer.
84 virtual size_t GetGPUMemoryUsed() const override;
85 /// Returns the device-local heap size reported by the allocator.
86 virtual size_t GetGPUMemoryBudget() const override;
87
88 /// Recreates the swapchain for the new window dimensions.
89 virtual void Resize(uint32_t width, uint32_t height) override;
90
91 inline void SetRender(bool value) { bRender = value; }
92 inline bool GetRender() { return bRender; }
93
94 /// Initializes ImGui and its Vulkan backend against the active render pass.
95 virtual bool CreateImGUI() override;
96
97 virtual RenderContext* GetContext() override { return this; }
98
99 // Feature capability mask
100 virtual uint32_t GetFeatureCaps() const override {
103 }
104
105 // RenderContext interface
106 /// Issues a non-indexed draw call and updates the vertex/triangle counters.
107 virtual void Draw(uint32_t vertexCount) override;
108 /// Non-indexed draw starting at firstVertex.
109 virtual void Draw(uint32_t vertexCount, uint32_t firstVertex) override;
110 /// Issues an indexed draw call and updates the vertex/triangle counters.
111 virtual void DrawIndexed(uint32_t indexCount) override;
112 /// Indexed draw starting at firstIndex with a base vertex offset.
113 virtual void DrawIndexed(uint32_t indexCount, uint32_t firstIndex,
114 int32_t baseVertex) override;
115 /// Issues an instanced, non-indexed draw call.
116 virtual void DrawInstance(uint32_t instanceCount,
117 uint32_t vertexPerInstance) override;
118 /// Issues an instanced, indexed draw call.
119 virtual void DrawIndexedInstance(uint32_t instanceCount,
120 uint32_t indexPerInstance) override;
121 /// Instanced indexed draw starting at firstIndex with a base vertex offset.
122 virtual void DrawIndexedInstance(uint32_t instanceCount,
123 uint32_t indexPerInstance,
124 uint32_t firstIndex,
125 int32_t baseVertex) override;
126
127 /// Stores the cull face for the next pipeline rebuild (Vulkan state is baked).
128 virtual void SetRenderFace(RenderFace face) override;
129 /// Stores the polygon mode for the next pipeline rebuild (Vulkan state is baked).
130 virtual void SetRenderMode(RenderMode mode) override;
131 /// Sets the dynamic viewport on the active command buffer.
132 virtual void SetViewport(float x, float y, float width, float height,
133 float minDepth = 0.0f,
134 float maxDepth = 1.0f) override;
135 /// Stores the clear color used by the next BeginRender.
136 virtual void ClearRenderTarget(float r, float g, float b,
137 float a) override;
138 /// No-op; depth/stencil clears are driven by the render pass clear values.
139 virtual void ClearDepthStencil(bool clearDepth, bool clearStencil,
140 float depth, uint8_t stencil) override;
141
142 /// Binds a vertex buffer slot, switching to the pipeline built for the
143 /// buffer's registered vertex format.
144 virtual void BindVertexBuffer(RefPtr<BufferBase> buffer,
145 uint32_t slot = 0) override;
146 /// Binds a 32-bit index buffer.
147 virtual void BindIndexBuffer(RefPtr<BufferBase> buffer,
148 uint32_t slot = 0) override;
149 /// Pushes constant-buffer data via push constants, applying TAA jitter
150 /// or the shadow push-constant cache as needed.
151 virtual void BindConstantBuffer(RefPtr<BufferBase> buffer,
152 uint32_t slot = 0) override;
153
154 /// Allocates and initializes a VulkanBuffer.
155 virtual BufferBase* CreateBuffer(BufferType Type, uint32_t size,
156 void* data) override;
157 /// Compiles a VulkanShader from source.
158 virtual Shader* CreateShader(const std::string& shaderSource) override;
159 /// Loads a texture from disk and writes its descriptor sets.
160 virtual Texture* CreateTexture(const std::string& TexturePath) override;
161 /// Loads a texture from an in-memory RGBA8 buffer.
162 virtual Texture* CreateTextureFromData(uint32_t width, uint32_t height,
163 void* data) override;
164
165 /// Loads a cubemap from six face images and writes it into the skybox descriptor sets.
166 Texture* CreateCubemapTexture(const std::array<std::string, 6>& facePaths);
167 /// Loads an equirectangular panorama as a cubemap and writes it into the skybox descriptor sets.
168 Texture* CreateCubemapTextureFromPanorama(const std::string& panoramaPath);
169
170 /// Binds a texture's descriptor set at slot 0, skipping cubemaps and the GBuffer geometry pass.
171 virtual void BindTexture(RefPtr<Sleak::Texture> texture, uint32_t slot = 0) override;
172 /// Raw-pointer variant of BindTexture.
173 virtual void BindTextureRaw(Sleak::Texture* texture, uint32_t slot = 0) override;
174 /// Binds the skybox pipeline and its descriptor set for the current frame.
175 virtual void BeginSkyboxPass() override;
176 /// Restores the previous pipeline and descriptor set after the skybox draw.
177 virtual void EndSkyboxPass() override;
178 /// Copies bone matrices into their own bone ring slot and binds it.
179 virtual void BindBoneBuffer(RefPtr<BufferBase> buffer) override;
180 /// Binds the skinned pipeline matching the currently active render pass.
181 virtual void BeginSkinnedPass() override;
182 /// Restores the previous pipeline after skinned draws.
183 virtual void EndSkinnedPass() override;
184 /// Binds the custom-format pipeline matching the currently active render pass.
185 virtual void BeginCustomFormatPass(VertexFormatHandle format) override;
186 /// Restores the previous pipeline and descriptor set after custom-format draws.
187 virtual void EndCustomFormatPass() override;
188 /// Binds the debug line pipeline for the current frame.
189 virtual void BeginDebugLinePass() override;
190 /// Restores the previous pipeline and descriptor set after debug line draws.
191 virtual void EndDebugLinePass() override;
192
193 // Shadow pass support
194 /// Marks the shadow pass active and invalidates the push constant cache.
195 virtual void BeginShadowPass() override;
196 /// Marks the shadow pass inactive.
197 virtual void EndShadowPass() override;
198 virtual bool IsShadowPassActive() const override { return m_shadowPassActive; }
199
200 // Light UBO update (called by LightManager)
201 /// Copies light and shadow data into the current frame's mapped UBO.
202 void UpdateShadowLightUBO(const void* data, uint32_t size) override;
203 /// Stages the light view-projection matrix for commit at the next BeginRender.
204 void SetLightVP(const float* lightVP) override;
205
206 // Deferred rendering overrides
207 virtual bool IsDeferredEnabled() const override { return m_deferredEnabled && m_gbufferResourcesCreated; }
208 virtual bool IsInGeometryPass() const override { return m_inGeometryPass; }
209 /// Binds the GBuffer pipeline and marks the geometry pass active.
210 /// Called by RenderCommandQueue when deferred is active.
211 virtual void BindGBufferShader() override;
212 /// Writes a material's textures and params into its ring slot and binds it at set 0.
213 virtual void BindPBRMaterial(Sleak::Material* material) override;
214 /// Runs the deferred lighting pass, reading the GBuffer and writing the HDR scene image.
215 virtual void ExecuteDeferredLightingPass() override;
216 /// Begins the forward transparent render pass over the HDR scene image.
217 virtual void BeginForwardTransparentPass() override;
218 /// Marks the forward transparent pass ended; EndRender closes the actual render pass.
219 virtual void EndForwardTransparentPass() override;
220 /// Copies deferred CB data into the current frame's UBO and snapshots the camera matrices.
221 virtual void UpdateDeferredCB(const void* data, uint32_t size) override;
222
223 // MSAA
224 /// Rebuilds the swapchain-dependent pipelines and render pass for a
225 /// queued MSAA sample count change.
226 void ApplyMSAAChange() override;
227 /// Recreates the swapchain to apply a queued VSync toggle.
228 void ApplyVSyncChange() override;
229 /// Recreates the extent-dependent shadow map objects at the queued resolution.
230 void ApplyShadowResolutionChange() override;
231
232#ifdef SLEAK_HOT_RELOAD
233 /// Rebuilds every pipeline from the SPIR-V on disk; a pipeline that fails
234 /// to rebuild keeps its previous version.
235 bool ReloadShaders(const std::vector<std::string>& stems) override;
236#endif
237
238 // Measurement
239 /// Adds per-pass GPU millisecond columns when --gpuprofile is on.
240 void RegisterBenchmarkMetrics(Benchmark& bench) override;
241 /// Arms a UI-free readback of the next presented frame into a binary PPM.
242 bool RequestFrameCapture(const std::string& path) override;
243 /// True while an armed capture has not been written yet.
244 bool IsFrameCapturePending() const override {
245 return !m_capturePath.empty();
246 }
247
248 private:
249 /// Compiles the skybox shaders on first use, sizes the skybox descriptor
250 /// sets to the swapchain image count, and creates the skybox pipeline.
251 bool CreateSkyboxPipeline();
252 /// Compiles the skinned shaders on first use and creates the forward
253 /// skinned pipeline.
254 bool CreateSkinnedPipeline();
255
256 // Deferred rendering
257 /// Creates the GBuffer color images, render passes, descriptors, and
258 /// pipelines that make up the deferred lighting path.
259 bool CreateGBufferResources();
260 /// Creates the GBuffer render pass with its three color attachments and
261 /// depth.
262 bool CreateGBufferRenderPass();
263 /// Creates the GBuffer framebuffer binding the GBuffer images and depth.
264 bool CreateGBufferFramebuffer();
265 /// Compiles the GBuffer shaders and creates the geometry pipeline, reusing
266 /// pipelineLay.
267 bool CreateGBufferPipeline();
268 /// Compiles the skinned GBuffer shaders so skinned meshes write into the
269 /// GBuffer.
270 bool CreateSkinnedGbufferPipeline();
271 /// Creates the deferred lighting render pass with a single color
272 /// attachment.
273 bool CreateLightingRenderPass();
274 /// Creates one lighting pass framebuffer per swapchain image, all aliasing
275 /// the HDR target.
276 bool CreateLightingFramebuffers();
277 /// Compiles the lighting shaders and creates the fullscreen lighting
278 /// pipeline.
279 bool CreateLightingPipeline();
280 /// Creates the forward transparent render pass writing into the HDR scene
281 /// image.
282 bool CreateForwardRenderPass();
283 /// Creates one forward transparent framebuffer per swapchain image, all
284 /// aliasing the HDR target.
285 bool CreateForwardFramebuffers();
286 /// Creates the GBuffer sampler descriptor set layout, pool, and per-frame
287 /// sets.
288 bool CreateGBufferDescriptorSets();
289 /// Creates the per-frame deferred constant buffer holding InvViewProj and
290 /// screen size.
291 bool CreateDeferredCBResources();
292 /// Creates the PBR material descriptor layout, pool, ring of sets, and
293 /// GBuffer geometry pipeline layout.
294 bool CreatePBRMaterialResources();
295 /// Appends one chunk of PBR material sets and UBO slots to a frame's ring.
296 bool AddPBRMaterialChunk(uint32_t frame);
297 /// Destroys every PBR material chunk of every frame.
298 void DestroyPBRMaterialChunks();
299 /// Creates stub IBL irradiance, prefilter, and BRDF LUT images, samplers,
300 /// and descriptor set.
301 bool CreateIBLResources();
302 /// Destroys all GBuffer, lighting, and forward transparent pass resources.
303 void CleanupGBufferResources();
304 /// Destroys the IBL images, samplers, and descriptor resources.
305 void CleanupIBLResources();
306 /// Writes the GBuffer, depth, and shadow images into the sampler descriptor
307 /// sets before the lighting pass.
308 void UpdateGBufferDescriptors();
309
310 // Shadow mapping
311 /// Creates the shadow depth image, sampler, render pass, and framebuffer.
312 bool CreateShadowResources();
313 /// Compiles the shadow depth shader and creates the shadow pass pipeline.
314 bool CreateShadowPipeline();
315 /// Creates the per-frame light and shadow UBO buffers and descriptor sets.
316 bool CreateShadowLightUBOResources();
317 /// Destroys the shadow map image, pipeline, render pass, and light UBO
318 /// resources.
319 void CleanupShadowResources();
320 /// Creates the Vulkan instance. The validation layer is on in Debug builds
321 /// or with --validate, and --syncval adds synchronization validation.
322 bool InitVulkan();
323 /// Creates the SDL-backed Vulkan presentation surface.
324 bool CreateSurface();
325 /// Selects the physical GPU and creates the logical device and queues.
326 bool CreateDevice();
327 /// Creates the swapchain from the queried surface capabilities.
328 bool CreateSwapChain();
329 /// Rebuilds the swapchain and its dependents after resize or resolution
330 /// change.
331 bool RecreateSwapChain();
332 /// True when the surface wants a different extent than the swapchain.
333 bool SurfaceExtentChanged();
334 /// Creates an image view for each swapchain image.
335 bool CreateImageViews();
336 /// Creates the layout shared by the forward, skybox, debug line, skinned,
337 /// and shadow pipelines.
338 bool CreateMainPipelineLayout();
339 /// Creates the main forward graphics pipeline, plus its layout and shader
340 /// on first use.
341 bool CreateGraphicsPipeline();
342 /// Creates the pipeline cache, seeded from disk when the saved blob was
343 /// written by this device and driver.
344 void CreatePipelineCache();
345 /// Saves the pipeline cache to disk when it changed, then destroys it.
346 void DestroyPipelineCache();
347 /// Creates the main forward render pass with optional MSAA color and
348 /// resolve attachments.
349 bool CreateRenderPass();
350 /// Creates one framebuffer per swapchain image for the main render pass.
351 bool CreateFrameBuffer();
352 /// Creates the graphics command pool.
353 bool CreateCommandPool();
354 /// Allocates one primary command buffer per frame in flight.
355 bool CreateCommandBuffer();
356 /// Creates the per-swapchain-image semaphores and per-frame fences and
357 /// transfer semaphores.
358 bool CreateSyncObjects();
359 /// Grows the per-image semaphores to the swapchain image count and
360 /// clears the image-to-fence table.
361 bool CreateImageSyncObjects();
362 /// Creates the depth image, memory, and image view.
363 bool CreateDepthResources();
364 /// Creates the texture, bone UBO, light UBO, and shadow sampler descriptor
365 /// set layouts.
366 bool CreateDescriptorSetLayout();
367 /// Creates the descriptor pool backing the per-texture descriptor sets.
368 bool CreateDescriptorPool();
369 /// Allocates one texture descriptor set per swapchain image.
370 bool AllocateDescriptorSets();
371 /// Creates the fallback 1x1 white texture and writes it into the global
372 /// descriptor sets.
373 bool CreateDefaultTexture();
374 /// Allocates and writes a per-texture descriptor set for the given texture.
375 void WriteTextureDescriptors(VulkanTexture* texture);
376 /// Registers the debug messenger callback when the validation layer is on.
377 bool SetupDebugMessenger();
378
379 /// Destroys the swapchain, its image views, and framebuffers.
380 void CleanupSwapChain();
381 /// Destroys the depth image, memory, and image view.
382 void CleanupDepthResources();
383
384 // MSAA resources
385 /// Creates the MSAA color image used as the multisampled render target.
386 bool CreateMSAAColorResources();
387 /// Destroys the MSAA color image, view, and memory.
388 void CleanupMSAAColorResources();
389 /// Queries the highest MSAA sample count the GPU supports.
390 VkSampleCountFlagBits GetMaxUsableSampleCount();
391
392 /// No-op; Vulkan polygon mode changes require pipeline recreation.
393 virtual void ConfigureRenderMode() override;
394 /// No-op; Vulkan cull mode changes require pipeline recreation.
395 virtual void ConfigureRenderFace() override;
396
397 /// Builds one queue create info per unique queue family index.
398 std::vector<VkDeviceQueueCreateInfo> GetUniqueQueueCreateInfos();
399
400 /// Queries surface capabilities, formats, and present modes.
401 std::optional<SwapchainDetails> QuerySwapchain();
402
403 /// Picks a UNORM surface format to avoid double sRGB encoding.
404 VkSurfaceFormatKHR ChooseFormat(
405 const std::vector<VkSurfaceFormatKHR>& formats);
406 /// Picks FIFO when VSync is on, otherwise MAILBOX or IMMEDIATE.
407 VkPresentModeKHR ChoosePresentMode(
408 const std::vector<VkPresentModeKHR>& modes);
409 /// Clamps the window size to the surface's supported extent.
410 VkExtent2D ChooseExtend(const VkSurfaceCapabilitiesKHR& caps);
411
412 /// Picks the first supported depth-stencil format from the candidate list.
413 VkFormat FindDepthFormat();
414 /// Finds a memory type index matching the filter and property flags.
415 uint32_t FindMemoryType(uint32_t typeFilter,
416 VkMemoryPropertyFlags properties);
417
418 /// Fills the debug messenger create info with severity and callback.
419 void PopulateDebugMessengerCreateInfo(
420 VkDebugUtilsMessengerCreateInfoEXT& createInfo);
421
422 /// Debug messenger callback that routes Vulkan messages to the logger.
423 static VkBool32 Validation(
424 VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
425 VkDebugUtilsMessageTypeFlagsEXT messageTypes,
426 const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
427 void* pUserData);
428
429 bool bRender = true;
430 bool bFrameStarted = false;
431
432 static constexpr uint32_t MAX_FRAMES_IN_FLIGHT = 2;
433 uint32_t currentFrame = 0;
434 uint32_t CurrentFrameIndex = 0;
435 uint32_t m_semaphoreIndex = 0; // cycles through swapchain image count
436 VkInstance instance = VK_NULL_HANDLE;
437 VkSurfaceKHR surface = VK_NULL_HANDLE;
438 VkRenderPass renderPass = VK_NULL_HANDLE;
439 VkSwapchainKHR swapChain = VK_NULL_HANDLE;
440 VkCommandPool commands = VK_NULL_HANDLE;
441 std::vector<VkCommandBuffer> commandBuffers;
442 VkCommandBuffer command =
443 VK_NULL_HANDLE; // alias for commandBuffers[currentFrame]
444 std::vector<VkFramebuffer> swapChainFramebuffers;
445 std::vector<VkImage> swapChainImages;
446 std::vector<VkImageView> swapChainImageViews;
447 VkFormat scImageFormat;
448 VkExtent2D scExtent;
449 VkDevice device = VK_NULL_HANDLE;
450 VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
451 std::vector<VkPhysicalDevice> GPUs;
452 VkPipeline pipeline = VK_NULL_HANDLE;
453 VkPipelineLayout pipelineLay = VK_NULL_HANDLE;
454 VkPipelineCache m_pipelineCache = VK_NULL_HANDLE;
455 // Loaded blob size and hash, so an unchanged cache is not rewritten
456 size_t m_pipelineCacheLoadedSize = 0;
457 uint64_t m_pipelineCacheLoadedHash = 0;
458 std::vector<VkSemaphore> imageAvailableSemaphores;
459 std::vector<VkSemaphore> renderFinishedSemaphores;
460 std::vector<VkFence> inFlightFences;
461 std::vector<VkFence> imagesInFlight;
462 // Submission serial of the last frame recorded in each frame slot
463 std::array<uint64_t, MAX_FRAMES_IN_FLIGHT> m_slotSerial{};
464 uint64_t m_submitSerial = 0;
465 VulkanShader* simpleShader = nullptr;
466 VkClearValue clearColor;
467
468 // Depth buffer
469 VkImage depthImage = VK_NULL_HANDLE;
470 VkDeviceMemory depthImageMemory = VK_NULL_HANDLE;
471 VkImageView depthImageView = VK_NULL_HANDLE;
472 VkFormat depthFormat;
473
474 // MSAA color buffer (multisample resolve target)
475 VkSampleCountFlagBits m_msaaSamples = VK_SAMPLE_COUNT_1_BIT;
476 VkImage m_msaaColorImage = VK_NULL_HANDLE;
477 VkDeviceMemory m_msaaColorImageMemory = VK_NULL_HANDLE;
478 VkImageView m_msaaColorImageView = VK_NULL_HANDLE;
479
480 // Descriptor sets for uniform buffers
481 VkDescriptorSetLayout descriptorSetLayout = VK_NULL_HANDLE;
482 VkDescriptorPool descriptorPool = VK_NULL_HANDLE;
483 std::vector<VkDescriptorSet> descriptorSets;
484
485 QueueIndices QueueIDs;
486 VkQueue graphicsQueue = VK_NULL_HANDLE;
487 VkQueue computeQueue = VK_NULL_HANDLE;
488 VkQueue transferQueue = VK_NULL_HANDLE;
489 VkQueue presentQueue = VK_NULL_HANDLE;
490
491 VkDebugUtilsMessengerEXT debugMessenger = VK_NULL_HANDLE;
492 PFN_vkDestroyDebugUtilsMessengerEXT vkDestroyDebugUtilsMessengerEXT =
493 nullptr;
494 bool m_validationEnabled = false;
495
496 Window* sdlWindow;
497
498 // Texture binding
499 bool m_textureDescriptorsWritten = false;
500 VulkanTexture* m_defaultTexture = nullptr;
501
502 // Skybox pipeline
503 VkPipeline skyboxPipeline = VK_NULL_HANDLE;
504 VulkanShader* skyboxShader = nullptr;
505 VkDescriptorPool skyboxDescriptorPool = VK_NULL_HANDLE;
506 std::vector<VkDescriptorSet> skyboxDescriptorSets;
507 bool m_skyboxDescriptorsWritten = false;
508 VkImageView m_skyboxCubemapView =
509 VK_NULL_HANDLE; // cached for MSAA re-bind
510 VkSampler m_skyboxCubemapSampler =
511 VK_NULL_HANDLE; // cached for MSAA re-bind
512 uint32_t m_skyboxViewSerial = 0; // bumped whenever the cached view changes
513
514 // Skinned pipeline (uses skinned shaders with bone UBO)
515 VkPipeline skinnedPipeline = VK_NULL_HANDLE;
516 VulkanShader* skinnedShader = nullptr;
517
518 // Debug line pipeline
519 VkPipeline debugLinePipeline = VK_NULL_HANDLE;
520 VulkanShader* debugLineShader = nullptr;
521 /// Compiles the debug line shaders and creates the line-list pipeline.
522 bool CreateDebugLinePipeline();
523
524 // Custom vertex format pipelines (one per registered VertexFormatHandle)
525 /// Render pass a custom-format pipeline variant is built for.
526 enum class CustomPass : uint8_t {
527 Main,
528 Shadow,
529 GBuffer,
531 Count
532 };
533 static constexpr size_t CUSTOM_PASS_COUNT =
534 static_cast<size_t>(CustomPass::Count);
535 /// The pipeline variants a registered vertex layout can drive, indexed by
536 /// CustomPass. A failed flag marks a variant as permanently absent so
537 /// draws skip it instead of retrying compilation every frame.
538 struct CustomFormatPipelines {
539 std::array<VkPipeline, CUSTOM_PASS_COUNT> pipelines{};
540 std::array<bool, CUSTOM_PASS_COUNT> failed{};
541 };
542 // Indexed by handle - 1 (handles are dense and start at 1)
543 std::vector<CustomFormatPipelines> m_customFormatPipelines;
544 // Registered formats whose active-path variants were prebuilt
545 VertexFormatHandle m_customFormatsPrebuilt = 0;
546 VertexFormatHandle m_activeCustomFormat = 0;
547 /// Set while the active custom format has no pipeline for the current pass;
548 /// draws are dropped rather than issued against a mismatched vertex layout.
549 bool m_customFormatUnbound = false;
550 /// True while the bound vertex buffer's format has no pipeline for this
551 /// pass.
552 bool CustomFormatDrawsSuppressed() const;
553 /// True when the render pass a custom-format variant targets exists.
554 bool CustomPassAvailable(CustomPass pass) const;
555 /// Returns a format's pipeline for a pass, compiling it on first request.
556 VkPipeline GetCustomFormatPipeline(VertexFormatHandle format,
557 CustomPass pass);
558 /// Compiles one pipeline variant of a registered layout; returns
559 /// VK_NULL_HANDLE when its stem is empty or compilation fails.
560 VkPipeline BuildCustomFormatPipeline(VertexFormatHandle format,
561 const VertexLayoutDesc& desc,
562 CustomPass pass);
563 /// Compiles the variants the active render path draws with for every
564 /// registered format not prebuilt yet.
565 void PrebuildCustomFormatPipelines();
566 /// Destroys every cached custom-format pipeline (all variants, all
567 /// formats).
568 void DestroyCustomFormatPipelines();
569
570#ifdef SLEAK_HOT_RELOAD
571 // Shader hot reload
572 /// The pipelines, layouts, and shaders one create function writes, swapped
573 /// as a unit when shaders reload.
574 struct PipelineGroup {
575 const char* name;
576 std::vector<VkPipeline*> pipelines;
577 std::vector<VkPipelineLayout*> layouts;
578 std::vector<VulkanShader**> shaders;
579 bool (VulkanRenderer::*create)();
580 };
581 /// Rebuilds a live group through its create function, keeping the old
582 /// objects when the rebuild fails.
583 void ReloadPipelineGroup(const PipelineGroup& group);
584 /// Rebuilds every cached custom-format variant, keeping the old pipeline of
585 /// a variant that fails.
586 void ReloadCustomFormatPipelines();
587#endif
588
589 // Bone palette ring (set 1, binding 0, dynamic offset per bind)
590 struct BoneUBOChunk {
591 VkDescriptorPool pool = VK_NULL_HANDLE;
592 VkDescriptorSet set = VK_NULL_HANDLE;
593 VkBuffer buffer = VK_NULL_HANDLE;
594 VkDeviceMemory memory = VK_NULL_HANDLE;
595 void* mapped = nullptr;
596 };
597 static constexpr uint32_t BONE_MATRIX_BYTES = sizeof(float) * 16;
598 static constexpr uint32_t BONE_PALETTE_BYTES =
599 MAX_BONES * BONE_MATRIX_BYTES;
600 static constexpr uint32_t BONE_SLOTS_PER_CHUNK = 32;
601 VkDescriptorSetLayout boneDescriptorSetLayout = VK_NULL_HANDLE;
602 std::array<std::vector<BoneUBOChunk>, MAX_FRAMES_IN_FLIGHT> m_boneChunks;
603 VkDeviceSize m_boneSlotStride = BONE_PALETTE_BYTES;
604 uint32_t m_boneSlot[MAX_FRAMES_IN_FLIGHT] = {};
605 bool m_boneUBOCreated = false;
606 /// Creates each frame's first bone ring chunk; slot 0 holds identity.
607 bool CreateBoneUBOResources();
608 /// Appends BONE_SLOTS_PER_CHUNK palette slots to one frame's bone ring.
609 bool AddBoneUBOChunk(uint32_t frame);
610 /// Destroys every bone ring chunk of every frame.
611 void CleanupBoneUBOResources();
612 /// Binds the identity palette (ring slot 0) at set 1.
613 void BindIdentityBonePalette(VkPipelineLayout layout);
614
615 // ImGUI
616 VkDescriptorPool imguiDescriptorPool = VK_NULL_HANDLE;
617
618 // Shadow mapping resources
619 VkImage m_shadowImage = VK_NULL_HANDLE;
620 VkDeviceMemory m_shadowImageMemory = VK_NULL_HANDLE;
621 VkImageView m_shadowImageView = VK_NULL_HANDLE;
622 VkSampler m_shadowSampler =
623 VK_NULL_HANDLE; // compare sampler (hardware PCF)
624 VkSampler m_shadowRawSampler =
625 VK_NULL_HANDLE; // non-compare sampler (PCSS blocker search)
626 VkRenderPass m_shadowRenderPass = VK_NULL_HANDLE;
627 VkFramebuffer m_shadowFramebuffer = VK_NULL_HANDLE;
628 VkPipeline m_shadowPipeline = VK_NULL_HANDLE;
629 VulkanShader* m_shadowShader = nullptr;
630 bool m_shadowPassActive = false;
631 // m_shadowResourcesCreated lives in the Renderer base (shared with the
632 // shadow-resolution change-request logic)
633
634 // Shadow push-constant memo: LightVP*World is frame-constant per unique
635 // World, so cache it and skip the matmul when consecutive casters (all
636 // draws share the identity transform) reuse the same World matrix.
637 float m_shadowWorldCache[16] = {};
638 float m_shadowPCCache[32] = {};
639 bool m_shadowPCCacheValid = false;
640 // Layout m_shadowPCCache was last pushed with in this shadow pass, or
641 // null once anything else overwrote the push constants.
642 VkPipelineLayout m_shadowPCPushedLayout = VK_NULL_HANDLE;
643
644 // Light VP matrix (stored as raw floats for push constant computation)
645 float m_lightVP[16] = {};
646 // Staging slot: SetLightVP writes here; BeginRender copies it to
647 // m_lightVP before the shadow pass. Keeps m_lightVP stable for the
648 // entire frame so shadow pass and main pass agree on the transform.
649 float m_pendingLightVP[16] = {};
650 bool m_hasPendingLightVP = false;
651 // Matrix the shadow map was last rendered with
652 float m_shadowMapLightVP[16] = {};
653 bool m_shadowMapRendered = false;
654
655 // Light/Shadow UBO (set 2, binding 0)
656 VkDescriptorSetLayout m_lightUBODescriptorSetLayout = VK_NULL_HANDLE;
657 VkDescriptorPool m_lightUBODescriptorPool = VK_NULL_HANDLE;
658 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_lightUBOBuffers = {};
659 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_lightUBOMemory = {};
660 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_lightUBOMapped = {};
661 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_lightUBODescriptorSets =
662 {};
663
664 // Shadow map sampler descriptor (set 3, binding 0)
665 VkDescriptorSetLayout m_shadowSamplerDescriptorSetLayout = VK_NULL_HANDLE;
666 VkDescriptorPool m_shadowSamplerDescriptorPool = VK_NULL_HANDLE;
667 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT>
668 m_shadowSamplerDescriptorSets = {};
669 bool m_lightUBOCreated = false;
670
671 // Async buffer transfer (zero-CPU-blocking GPU uploads)
672 std::array<VkSemaphore, MAX_FRAMES_IN_FLIGHT> m_transferSemaphores = {};
673 std::array<VulkanBuffer::AsyncFlushResult, MAX_FRAMES_IN_FLIGHT>
674 m_asyncFlush;
675
676 // ---- Deferred GBuffer ----
677 // 3 color attachments: RT0=AlbedoAO, RT1=NormalRough, RT2=MetalEmit.
678 // World position is reconstructed from the depth buffer + InvViewProj in
679 // the lighting/SSAO/SSR passes (no RGBA32F worldpos RT) to cut GBuffer
680 // bandwidth on a fill-bound renderer.
681 static constexpr uint32_t GBUFFER_COUNT = 3;
682 VkImage m_gbufferImages[GBUFFER_COUNT] = {};
683 VkDeviceMemory m_gbufferMemory[GBUFFER_COUNT] = {};
684 VkImageView m_gbufferViews[GBUFFER_COUNT] = {};
685 /// GBuffer attachment formats: RT0 AlbedoAO, RT1 NormalRough, RT2
686 /// MetalEmit. Defined in VulkanDeferred.cpp.
687 static const VkFormat m_gbufferFormats[GBUFFER_COUNT];
688 VkRenderPass m_gbufferRenderPass = VK_NULL_HANDLE;
689 VkFramebuffer m_gbufferFramebuffer = VK_NULL_HANDLE;
690 VkPipeline m_gbufferPipeline = VK_NULL_HANDLE;
691 VkPipeline m_skinnedGbufferPipeline = VK_NULL_HANDLE;
692 VkPipelineLayout m_gbufferPipelineLayout = VK_NULL_HANDLE;
693 VulkanShader* m_gbufferShader = nullptr;
694 bool m_gbufferResourcesCreated = false;
695 bool m_inGeometryPass = false;
696
697 // Lighting pass
698 VkRenderPass m_lightingRenderPass = VK_NULL_HANDLE;
699 std::vector<VkFramebuffer>
700 m_lightingFramebuffers; // one per swapchain image
701 VkPipeline m_lightingPipeline = VK_NULL_HANDLE;
702 VkPipelineLayout m_lightingPipelineLayout = VK_NULL_HANDLE;
703 VulkanShader* m_lightingShader = nullptr;
704
705 // Forward transparent pass
706 VkRenderPass m_forwardRenderPass = VK_NULL_HANDLE;
707 std::vector<VkFramebuffer>
708 m_forwardFramebuffers; // one per swapchain image (color+depth,
709 // non-MSAA)
710 bool m_inForwardTransparentPass = false;
711 bool m_forwardPassOpen =
712 false; // true when forward RP is currently recording
713
714 // GBuffer sampler descriptor set (set 0 in lighting pass)
715 VkDescriptorSetLayout m_gbufferSamplerDSL = VK_NULL_HANDLE;
716 VkDescriptorPool m_gbufferSamplerPool = VK_NULL_HANDLE;
717 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_gbufferSamplerSets = {};
718 VkSampler m_gbufferSampler = VK_NULL_HANDLE;
719 VkSampler m_depthSampler = VK_NULL_HANDLE;
720
721 // Deferred CB UBO (set 1 in lighting pass): InvViewProj + screenSize +
722 // near/far
723 struct DeferredCBData {
724 float InvViewProj[16];
725 float ScreenW, ScreenH, NearP, FarP;
726 };
727 VkDescriptorSetLayout m_deferredCBDSL = VK_NULL_HANDLE;
728 VkDescriptorPool m_deferredCBPool = VK_NULL_HANDLE;
729 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_deferredCBBuffers = {};
730 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_deferredCBMemory = {};
731 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_deferredCBMapped = {};
732 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_deferredCBSets = {};
733 bool m_deferredCBCreated = false;
734
735 // PBR material descriptor resources (GBuffer geometry pass, set 0)
736 // One per-frame descriptor set updated with each BindPBRMaterial() call.
737 struct alignas(16) PBRMaterialParams {
738 float albedoFactorR, albedoFactorG, albedoFactorB, albedoFactorA; // vec4
739 float metallicFactor, roughnessFactor, aoFactor, normalIntensity; // 4 floats
740 float emissiveR, emissiveG, emissiveB, emissiveIntensity; // vec4
741 float tilingX, tilingY, offsetX, offsetY; // 4 floats
742 uint32_t hasNormalMap, hasMetallicMap, hasRoughnessMap, hasAOMap; // 4 uints
743 uint32_t hasEmissiveMap; float _pad0, _pad1, _pad2; // 4 floats
744 };
745 // Per-frame RING of PBR material sets: each material drawn in a frame gets
746 // its own set + its own UBO sub-region, so a set/region is never rewritten
747 // while already bound in the recording command buffer (UPDATE_AFTER_BIND
748 // VUID). The ring grows by one chunk when a frame runs out of slots.
749 static constexpr uint32_t PBR_SETS_PER_FRAME = 64;
750 struct PBRMaterialChunk {
751 VkDescriptorPool pool = VK_NULL_HANDLE;
752 std::array<VkDescriptorSet, PBR_SETS_PER_FRAME> sets = {};
753 VkBuffer ubo = VK_NULL_HANDLE;
754 VkDeviceMemory memory = VK_NULL_HANDLE;
755 void* mapped = nullptr;
756 };
757 VkDescriptorSetLayout m_pbrMaterialDSL = VK_NULL_HANDLE;
758 std::array<std::vector<PBRMaterialChunk>, MAX_FRAMES_IN_FLIGHT>
759 m_pbrMaterialChunks;
760 VkDeviceSize m_pbrMaterialUBOStride = 0;
761 uint32_t m_pbrMaterialSlot[MAX_FRAMES_IN_FLIGHT] = {};
762 static constexpr uint32_t PBR_TEXTURE_COUNT = 6;
763 /// A material's written set contents, reused when it is bound again this
764 /// frame.
765 struct PBRMaterialBinding {
766 PBRMaterialParams params{};
767 std::array<VkDescriptorImageInfo, PBR_TEXTURE_COUNT> images{};
768 VkDescriptorSet set = VK_NULL_HANDLE;
769 };
770 std::array<std::unordered_map<const Sleak::Material*, PBRMaterialBinding>,
771 MAX_FRAMES_IN_FLIGHT>
772 m_pbrMaterialBindings;
773 bool m_pbrMaterialResourcesCreated = false;
774 VkPipelineLayout m_gbufferGeomLayout = VK_NULL_HANDLE;
775
776 // IBL resources (lighting pass, set 3)
777 VkImage m_iblIrradianceImage = VK_NULL_HANDLE;
778 VkDeviceMemory m_iblIrradianceMemory = VK_NULL_HANDLE;
779 VkImageView m_iblIrradianceView = VK_NULL_HANDLE;
780 VkSampler m_iblIrradianceSampler = VK_NULL_HANDLE;
781
782 VkImage m_iblPrefilterImage = VK_NULL_HANDLE;
783 VkDeviceMemory m_iblPrefilterMemory = VK_NULL_HANDLE;
784 VkImageView m_iblPrefilterView = VK_NULL_HANDLE;
785 VkSampler m_iblPrefilterSampler = VK_NULL_HANDLE;
786 static constexpr uint32_t IBL_PREFILTER_MIP_LEVELS = 5;
787
788 VkImage m_iblBrdfLutImage = VK_NULL_HANDLE;
789 VkDeviceMemory m_iblBrdfLutMemory = VK_NULL_HANDLE;
790 VkImageView m_iblBrdfLutView = VK_NULL_HANDLE;
791 VkSampler m_iblBrdfLutSampler = VK_NULL_HANDLE;
792
793 VkDescriptorSetLayout m_iblDSL = VK_NULL_HANDLE;
794 VkDescriptorPool m_iblPool = VK_NULL_HANDLE;
795 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_iblSettingsBuffers = {};
796 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_iblSettingsMemory = {};
797 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_iblSettingsMapped = {};
798 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_iblSets = {};
799 bool m_iblResourcesCreated = false;
800 bool m_iblReady = false;
801
802 // ---- SSAO resources ----
803 // Half-resolution R8 occlusion buffer (raw SSAO + blurred).
804 static constexpr uint32_t SSAO_KERNEL_SIZE = 32;
805 static constexpr uint32_t SSAO_NOISE_SIZE = 4;
806 bool m_ssaoResourcesCreated = false;
807 VkExtent2D m_ssaoExtent = {0, 0};
808 VkFormat m_ssaoFormat = VK_FORMAT_R8_UNORM;
809
810 VkImage m_ssaoRawImage = VK_NULL_HANDLE;
811 VkDeviceMemory m_ssaoRawMemory = VK_NULL_HANDLE;
812 VkImageView m_ssaoRawView = VK_NULL_HANDLE;
813 VkFramebuffer m_ssaoRawFramebuffer = VK_NULL_HANDLE;
814
815 VkImage m_ssaoBlurImage = VK_NULL_HANDLE;
816 VkDeviceMemory m_ssaoBlurMemory = VK_NULL_HANDLE;
817 VkImageView m_ssaoBlurView = VK_NULL_HANDLE;
818 VkFramebuffer m_ssaoBlurFramebuffer = VK_NULL_HANDLE;
819
820 VkRenderPass m_ssaoRenderPass = VK_NULL_HANDLE; // shared for raw + blur
821 VkPipeline m_ssaoPipeline = VK_NULL_HANDLE;
822 VkPipeline m_ssaoBlurPipeline = VK_NULL_HANDLE;
823 VkPipelineLayout m_ssaoPipelineLayout = VK_NULL_HANDLE;
824 VkPipelineLayout m_ssaoBlurPipelineLayout = VK_NULL_HANDLE;
825 VulkanShader* m_ssaoShader = nullptr;
826 VulkanShader* m_ssaoBlurShader = nullptr;
827
828 VkSampler m_ssaoSampler = VK_NULL_HANDLE; // linear clamp
829 VkSampler m_ssaoPointSampler = VK_NULL_HANDLE; // nearest clamp for depth
830
831 // SSAO noise texture (4x4 RGBA random rotation vectors)
832 VkImage m_ssaoNoiseImage = VK_NULL_HANDLE;
833 VkDeviceMemory m_ssaoNoiseMemory = VK_NULL_HANDLE;
834 VkImageView m_ssaoNoiseView = VK_NULL_HANDLE;
835 VkSampler m_ssaoNoiseSampler = VK_NULL_HANDLE;
836
837 // SSAO pass descriptor sets
838 struct alignas(16) SSAOParams {
839 float View[16];
840 float Projection[16];
841 float InvViewProj[16]; // inverse(View*Proj) for depth recon
842 float Kernel[SSAO_KERNEL_SIZE][4]; // xyz=dir, w=pad
843 float ScreenW, ScreenH;
844 float NoiseScaleX, NoiseScaleY;
845 float Radius, Bias, Power, Intensity;
846 uint32_t KernelSize;
847 float _pad0, _pad1, _pad2;
848 };
849 VkDescriptorSetLayout m_ssaoInputDSL = VK_NULL_HANDLE; // set 0: samplers
850 VkDescriptorSetLayout m_ssaoUboDSL = VK_NULL_HANDLE; // set 1: UBO
851 VkDescriptorSetLayout m_ssaoBlurDSL = VK_NULL_HANDLE; // set 0: blur input + depth
852 VkDescriptorPool m_ssaoDescriptorPool = VK_NULL_HANDLE;
853 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_ssaoInputSets = {};
854 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_ssaoUboSets = {};
855 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_ssaoBlurSets = {};
856 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_ssaoUboBuffers = {};
857 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_ssaoUboMemory = {};
858 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_ssaoUboMapped = {};
859
860 // Cached camera state for SSAO UBO fill (set from SetViewProj or inferred
861 // from DeferredCB's InvViewProj). We populate View+Projection at SSAO time.
862 float m_cachedView[16] = {};
863 float m_cachedProjection[16] = {};
864 // inverse(View*Proj) snapshot from the lighting DeferredCB — reused by the
865 // SSAO/SSR passes to reconstruct world position from the depth buffer.
866 float m_cachedInvViewProj[16] = {};
867
868 /// Creates all SSAO images, render pass, framebuffers, descriptors, and pipelines.
869 bool CreateSSAOResources();
870 /// Primes the disabled-effect fallback images (ssaoBlur=white, ssr=black, bloom
871 /// mip0=black) once after (re)creation, leaving them SHADER_READ_ONLY. Per-frame
872 /// disabled paths then skip the redundant clear since the content is static.
873 void InitDisabledEffectFallbacks();
874 /// Destroys all SSAO pipelines, framebuffers, descriptors, images, and samplers.
875 void CleanupSSAOResources();
876 /// Creates the full-res raw and blurred SSAO color images, views, and samplers.
877 bool CreateSSAOImages();
878 /// Creates the shared SSAO render pass (R8 color, DONT_CARE load, shader-read-only output).
879 bool CreateSSAORenderPass();
880 /// Creates the raw and blur SSAO framebuffers.
881 bool CreateSSAOFramebuffers();
882 /// Compiles the SSAO and SSAO-blur shaders and creates their pipelines.
883 bool CreateSSAOPipelines();
884 /// Creates the SSAO input/UBO/blur descriptor layouts, pool, sets, and UBO buffers.
885 bool CreateSSAODescriptorResources();
886 /// Generates and uploads the 4x4 tangent-plane rotation noise texture.
887 bool CreateSSAONoiseTexture();
888 /// Writes the GBuffer, depth, and noise samplers into the SSAO input and blur descriptor sets.
889 void UpdateSSAODescriptors();
890 /// Fills the SSAO UBO with the cached camera matrices and a cosine-weighted hemisphere kernel.
891 void UpdateSSAOUBO();
892 /// Runs the raw SSAO and bilateral blur passes, or clears the blur target when SSAO is disabled.
893 void RenderSSAOPasses();
894
895 // ---- SSR (Screen-Space Reflections) resources ----
896 // Full-resolution R16G16B16A16 premultiplied reflection buffer. Rendered
897 // after the forward pass, added into the HDR scene by the bloom composite.
898 struct alignas(16) SSRParams {
899 float View[16];
900 float Projection[16];
901 float InvViewProj[16]; // inverse(View*Proj) for depth recon
902 float CameraPos[4]; // xyz = world pos, w = pad
903 float ScreenW, ScreenH;
904 float MaxDistance; // view-space ray march distance
905 float Thickness; // depth intersection thickness
906 int NumSteps; // coarse steps
907 int NumBinarySteps; // refinement steps
908 float RoughnessThreshold; // beyond this, no reflections
909 float _pad;
910 };
911
912 bool m_ssrResourcesCreated = false;
913 // m_ssrEnabled is inherited from RenderEngine::Renderer (base class).
914 VkFormat m_ssrFormat = VK_FORMAT_R16G16B16A16_SFLOAT;
915
916 VkImage m_ssrImage = VK_NULL_HANDLE;
917 VkDeviceMemory m_ssrMemory = VK_NULL_HANDLE;
918 VkImageView m_ssrView = VK_NULL_HANDLE;
919 VkSampler m_ssrSampler = VK_NULL_HANDLE;
920 VkRenderPass m_ssrRenderPass = VK_NULL_HANDLE;
921 VkFramebuffer m_ssrFramebuffer = VK_NULL_HANDLE;
922 VkPipeline m_ssrPipeline = VK_NULL_HANDLE;
923 VkPipelineLayout m_ssrPipelineLayout = VK_NULL_HANDLE;
924 VulkanShader* m_ssrShader = nullptr;
925
926 VkDescriptorSetLayout m_ssrInputDSL = VK_NULL_HANDLE; // set 0: 6 samplers
927 VkDescriptorSetLayout m_ssrUboDSL = VK_NULL_HANDLE; // set 1: UBO
928 VkDescriptorPool m_ssrPool = VK_NULL_HANDLE;
929
930 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_ssrInputSets{};
931 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_ssrUboSets{};
932 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_ssrUboBuffers{};
933 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_ssrUboMemory{};
934 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_ssrUboMapped{};
935
936 /// Creates the SSR image, render pass, framebuffer, descriptors, UBOs, and pipeline.
937 bool CreateSSRResources();
938 /// Compiles the SSR shaders and creates the SSR pipeline.
939 bool CreateSSRPipeline();
940 /// Destroys the SSR pipeline, framebuffer, descriptors, image, and sampler.
941 void CleanupSSRResources();
942 /// Fills the SSR UBO with the cached camera matrices, camera position, and ray march parameters.
943 void UpdateSSRUBO();
944 /// Writes the GBuffer and HDR scene samplers into the SSR input descriptor sets.
945 void UpdateSSRDescriptors();
946 /// Ray marches screen-space reflections into the SSR buffer, or clears it when SSR is disabled.
947 void RenderSSRPass();
948
949 // ---- TAA (Temporal Anti-Aliasing) resources ----
950 // Ping-pong history accumulation with depth-based reprojection
951 // and 3x3 YCoCg variance clipping.
952 struct alignas(16) TAAParams {
953 float CurrentToPrevClip[16]; // inverse(current VP) * previous VP,
954 // unjittered
955 float ScreenW, ScreenH;
956 float BlendFactor;
957 float _pad;
958 };
959
960 bool m_taaResourcesCreated = false;
961 // m_taaEnabled is inherited from RenderEngine::Renderer (base class).
962 uint64_t m_taaFrameIdx = 0; // global counter; ping-pong = idx % 2
963 bool m_taaRanLastFrame = false; // false restarts accumulation
964
965 VkImage m_taaImages[2] = {};
966 VkDeviceMemory m_taaMemory[2] = {};
967 VkImageView m_taaViews[2] = {};
968 VkRenderPass m_taaRenderPass = VK_NULL_HANDLE;
969 VkFramebuffer m_taaFramebufs[2] = {};
970 VkSampler m_taaSampler = VK_NULL_HANDLE;
971
972 VkImageView m_taaResolvedView = VK_NULL_HANDLE; // null if TAA is off
973
974 VkDescriptorSetLayout m_taaInputDSL = VK_NULL_HANDLE;
975 VkDescriptorSetLayout m_taaUboDSL = VK_NULL_HANDLE;
976 VkDescriptorPool m_taaPool = VK_NULL_HANDLE;
977
978 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_taaInputSets{};
979 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_taaUboSets{};
980 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_taaUboBuffers{};
981 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_taaUboMemory{};
982 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_taaUboMapped{};
983
984 VkPipelineLayout m_taaPipelineLayout = VK_NULL_HANDLE;
985 VkPipeline m_taaPipeline = VK_NULL_HANDLE;
986 VulkanShader* m_taaShader = nullptr;
987
988 double m_prevViewProj[16] = {}; // previous frame unjittered VP (row-major)
989 float m_taaJitter[2] = {}; // current frame jitter in UV space
990
991 /// Creates the ping-pong TAA history images, render pass, framebuffers, descriptors, and pipeline.
992 bool CreateTAAResources();
993 /// Compiles the TAA shaders and creates the TAA resolve pipeline.
994 bool CreateTAAPipeline();
995 /// Destroys the TAA pipeline, framebuffers, descriptors, images, and sampler.
996 void CleanupTAAResources();
997 /// Computes the inverse current view-projection and reprojection blend factor into the TAA UBO.
998 void UpdateTAAUBO();
999 /// Resolves the frame against TAA history into the ping-pong target.
1000 void RenderTAAPass();
1001 /// HDR scene color for the post passes: the TAA resolve when TAA ran.
1002 VkImageView PostSceneView() const;
1003
1004 // Per-image "fallback content is valid" flags. Set true once the image is
1005 // primed (static black/white in SHADER_READ_ONLY) by either
1006 // InitDisabledEffectFallbacks or a disabled-path clear; set false whenever
1007 // the enabled path renders into the image (dirtying it). When true, the
1008 // disabled path skips its redundant per-frame clear. This stays correct
1009 // across runtime enable->disable toggles: the first disabled frame after a
1010 // toggle re-primes, then subsequent disabled frames skip.
1011 bool m_ssaoFallbackPrimed = false;
1012 bool m_ssrFallbackPrimed = false;
1013 bool m_bloomFallbackPrimed = false;
1014
1015 // ---- Bloom + HDR post-processing resources ----
1016 // We render the lighting pass into an HDR scene-color image (not the
1017 // swapchain). Then we run the bloom pyramid and a final composite that
1018 // tonemaps + combines bloom into the swapchain.
1019 static constexpr uint32_t BLOOM_MIP_COUNT = 6;
1020 bool m_bloomResourcesCreated = false;
1021 VkFormat m_hdrSceneFormat = VK_FORMAT_R16G16B16A16_SFLOAT;
1022
1023 // HDR scene color image (lighting pass target)
1024 VkImage m_hdrSceneImage = VK_NULL_HANDLE;
1025 VkDeviceMemory m_hdrSceneMemory = VK_NULL_HANDLE;
1026 VkImageView m_hdrSceneView = VK_NULL_HANDLE;
1027 VkFramebuffer m_hdrSceneFramebuffer = VK_NULL_HANDLE;
1028 VkRenderPass m_hdrLightingRenderPass = VK_NULL_HANDLE;
1029
1030 // Bloom mip chain — single image with BLOOM_MIP_COUNT mip levels; each
1031 // level gets its own VkImageView so we can render into/out of it.
1032 VkImage m_bloomImage = VK_NULL_HANDLE;
1033 VkDeviceMemory m_bloomMemory = VK_NULL_HANDLE;
1034 std::array<VkImageView, BLOOM_MIP_COUNT> m_bloomMipViews = {};
1035 std::array<VkFramebuffer, BLOOM_MIP_COUNT> m_bloomMipFramebuffers = {};
1036 std::array<VkExtent2D, BLOOM_MIP_COUNT> m_bloomMipExtents = {};
1037
1038 VkRenderPass m_bloomRenderPass = VK_NULL_HANDLE; // shared, loadOp=DONT_CARE, color output
1039 VkRenderPass m_bloomAddRenderPass = VK_NULL_HANDLE; // LOAD, blend-add
1040 VkRenderPass m_bloomCompositeRenderPass = VK_NULL_HANDLE; // swapchain target (DONT_CARE -> PRESENT_SRC)
1041 std::vector<VkFramebuffer> m_bloomCompositeFramebuffers; // one per swapchain image
1042
1043 VkPipeline m_bloomThresholdPipeline = VK_NULL_HANDLE;
1044 VkPipeline m_bloomDownsamplePipeline = VK_NULL_HANDLE;
1045 VkPipeline m_bloomUpsamplePipeline = VK_NULL_HANDLE;
1046 VkPipeline m_bloomCompositePipeline = VK_NULL_HANDLE;
1047 VkPipelineLayout m_bloomFilterPipelineLayout = VK_NULL_HANDLE; // src-only + push constant
1048 VkPipelineLayout m_bloomCompositePipelineLayout = VK_NULL_HANDLE; // two inputs + push constant
1049 VulkanShader* m_bloomThresholdShader = nullptr;
1050 VulkanShader* m_bloomDownsampleShader = nullptr;
1051 VulkanShader* m_bloomUpsampleShader = nullptr;
1052 VulkanShader* m_bloomCompositeShader = nullptr;
1053
1054 // One descriptor set per bloom transition (threshold + BLOOM_MIP_COUNT-1
1055 // downsamples + BLOOM_MIP_COUNT-1 upsamples) per frame slot.
1056 // Simpler: allocate a pool with enough sets for all transitions and
1057 // re-write them each frame.
1058 VkDescriptorSetLayout m_bloomFilterDSL = VK_NULL_HANDLE; // 1 sampler
1059 VkDescriptorSetLayout m_bloomCompositeDSL = VK_NULL_HANDLE; // 2 samplers
1060 VkDescriptorPool m_bloomDescriptorPool = VK_NULL_HANDLE;
1061
1062 // Pre-allocated descriptor sets (per frame slot, per transition)
1063 // transitions = 1 (threshold -> mip0) + (BLOOM_MIP_COUNT-1) downsample
1064 // + (BLOOM_MIP_COUNT-1) upsample
1065 static constexpr uint32_t BLOOM_TRANSITION_COUNT = 1 + (BLOOM_MIP_COUNT - 1) + (BLOOM_MIP_COUNT - 1);
1066 std::array<std::array<VkDescriptorSet, BLOOM_TRANSITION_COUNT>, MAX_FRAMES_IN_FLIGHT> m_bloomFilterSets = {};
1067 std::array<VkDescriptorSet, MAX_FRAMES_IN_FLIGHT> m_bloomCompositeSets = {};
1068
1069 VkSampler m_bloomSampler = VK_NULL_HANDLE; // linear clamp
1070
1071 /// Creates the HDR scene, bloom mip chain, passes, descriptors, pipelines, and TAA resources.
1072 bool CreateBloomResources();
1073 /// Destroys all bloom and HDR scene resources, then cleans up TAA resources.
1074 void CleanupBloomResources();
1075 /// Creates the HDR scene color image, view, and the shared bloom-source sampler.
1076 bool CreateHDRSceneResources();
1077 /// Creates the multi-mip bloom image and a per-mip image view.
1078 bool CreateBloomImages();
1079 /// Creates the bloom threshold/downsample, additive-upsample, and composite render passes.
1080 bool CreateBloomRenderPasses();
1081 /// Creates the per-mip bloom framebuffers and one composite framebuffer per swapchain image.
1082 bool CreateBloomFramebuffers();
1083 /// Compiles the bloom threshold/downsample/upsample/composite shaders and creates their pipelines.
1084 bool CreateBloomPipelines();
1085 /// Creates the bloom filter and composite descriptor layouts, pool, and sets.
1086 bool CreateBloomDescriptorResources();
1087 /// Runs the threshold, downsample, and additive-upsample bloom mip chain, or clears mip 0 when bloom is disabled.
1088 void RenderBloomPass();
1089 /// Tonemaps and composites the HDR scene, bloom, and SSR into the swapchain image, then draws ImGui.
1090 void RenderBloomCompositePass();
1091
1092 /// Sets the dynamic viewport and scissor to fill the given extent. Defined in VulkanBloom.cpp (most call sites of the four post-effect TUs).
1093 static void FillFullscreenViewportScissor(VkCommandBuffer cmd, VkExtent2D ext);
1094
1095 // ---- GPU timestamp profiler (--gpuprofile) ----
1096 /// Frame passes bracketed by timestamp pairs, in log-table order.
1097 enum class GpuPass : uint8_t {
1098 Shadow,
1099 GBuffer,
1100 SSAO,
1101 Lighting,
1102 Forward,
1103 TAA,
1104 SSR,
1105 Bloom,
1106 Tonemap,
1107 UI,
1108 Count
1109 };
1110 static constexpr uint32_t GPU_PASS_COUNT =
1111 static_cast<uint32_t>(GpuPass::Count);
1112 static constexpr uint32_t GPU_ROW_OTHER = GPU_PASS_COUNT;
1113 static constexpr uint32_t GPU_ROW_TOTAL = GPU_PASS_COUNT + 1;
1114 static constexpr uint32_t GPU_ROW_COUNT = GPU_PASS_COUNT + 2;
1115 static constexpr uint32_t GPU_MAX_PAIRS = 16;
1116 static constexpr uint32_t GPU_QUERIES_PER_FRAME = 2 + 2 * GPU_MAX_PAIRS;
1117
1118 /// Timestamp pairs recorded into one frame-in-flight slot of the pool.
1119 struct GpuProfileSlot {
1120 std::array<GpuPass, GPU_MAX_PAIRS> pairPass{};
1121 uint32_t pairCount = 0;
1122 bool pairOpen = false;
1123 bool recording = false;
1124 bool submitted = false;
1125 };
1126
1127 VkQueryPool m_gpuQueryPool = VK_NULL_HANDLE;
1128 bool m_gpuProfilerEnabled = false;
1129 double m_gpuTickNs = 0.0;
1130 uint64_t m_gpuTickMask = 0;
1131 std::array<GpuProfileSlot, MAX_FRAMES_IN_FLIGHT> m_gpuSlots{};
1132 std::array<double, GPU_ROW_COUNT> m_gpuSumMs{};
1133 std::array<float, GPU_ROW_COUNT> m_gpuMaxMs{};
1134 std::array<uint32_t, GPU_ROW_COUNT> m_gpuRuns{};
1135 std::array<float, GPU_ROW_COUNT> m_gpuLastMs{};
1136 uint32_t m_gpuWindowFrames = 0;
1137 Timer m_gpuWindowTimer;
1138
1139 /// Creates the timestamp query pool; leaves profiling off when the
1140 /// graphics queue has no timestamp support.
1141 bool CreateGpuProfiler();
1142 /// Destroys the timestamp query pool.
1143 void CleanupGpuProfiler();
1144 /// Folds this slot's finished timestamps into the running window and
1145 /// logs the table once the window elapses. Call after the slot's fence.
1146 void CollectGpuProfile();
1147 /// Resets this slot's queries and stamps the frame start.
1148 void BeginGpuFrame();
1149 /// Closes any pass left open and stamps the frame end.
1150 void EndGpuFrame();
1151 /// Flags this slot's queries for readback on its next fence wait.
1152 void MarkGpuFrameSubmitted();
1153 /// Stamps the start of a pass.
1154 void BeginGpuPass(GpuPass pass);
1155 /// Stamps the end of the pass opened by the matching BeginGpuPass.
1156 void EndGpuPass(GpuPass pass);
1157 /// Logs the averaged per-pass table for the current window.
1158 void LogGpuProfile(float seconds) const;
1159
1160 // ---- Frame capture (-capture) ----
1161 bool m_captureMode = false;
1162 bool m_swapchainTransferSrc = false;
1163 std::string m_capturePath;
1164 bool m_captureRecorded = false;
1165 VkBuffer m_captureBuffer = VK_NULL_HANDLE;
1166 VkDeviceMemory m_captureMemory = VK_NULL_HANDLE;
1167 VkExtent2D m_captureExtent = {0, 0};
1168 VkFormat m_captureFormat = VK_FORMAT_UNDEFINED;
1169
1170 /// Records the swapchain-image-to-buffer copy for an armed capture.
1171 void RecordFrameCaptureCopy();
1172 /// Waits for the captured frame, writes the PPM, and disarms the capture.
1173 void FinishFrameCapture();
1174 /// Frees the capture readback buffer.
1175 void CleanupFrameCapture();
1176
1177 // ---- Scene read for transparent formats (set 3, bindings 2-5) ----
1178 // Set 3 holds the shadow map samplers first, then the scene-read inputs
1179 static constexpr uint32_t SCENE_COLOR_BINDING = 2;
1180 static constexpr uint32_t SCENE_DEPTH_BINDING = 3;
1181 static constexpr uint32_t SCENE_SKY_BINDING = 4;
1182 static constexpr uint32_t SCENE_UBO_BINDING = 5;
1183 static constexpr uint32_t SET3_BINDING_COUNT = SCENE_UBO_BINDING + 1;
1184 // Every set 3 binding but the UBO is a combined image sampler
1185 static constexpr uint32_t SET3_SAMPLER_COUNT = SET3_BINDING_COUNT - 1;
1186 static constexpr uint32_t SCENE_READ_IMAGE_COUNT =
1187 SCENE_UBO_BINDING - SCENE_COLOR_BINDING;
1188 // Light pool uniform buffers per frame: set 2 light UBO, set 3 SceneReadUBO
1189 static constexpr uint32_t LIGHT_POOL_UBOS_PER_FRAME = 2;
1190 // Snapshots of the HDR scene and depth taken mid forward pass
1191 VkImage m_sceneColorCopyImage = VK_NULL_HANDLE;
1192 VkDeviceMemory m_sceneColorCopyMemory = VK_NULL_HANDLE;
1193 VkImageView m_sceneColorCopyView = VK_NULL_HANDLE;
1194 VkImage m_sceneDepthCopyImage = VK_NULL_HANDLE;
1195 VkDeviceMemory m_sceneDepthCopyMemory = VK_NULL_HANDLE;
1196 VkImageView m_sceneDepthCopyView = VK_NULL_HANDLE;
1197 // 1x1 stand-ins bound while there is no snapshot or sky
1198 VkImage m_sceneFallbackImage = VK_NULL_HANDLE;
1199 VkDeviceMemory m_sceneFallbackMemory = VK_NULL_HANDLE;
1200 VkImageView m_sceneFallbackView = VK_NULL_HANDLE;
1201 VkImage m_sceneFallbackCubeImage = VK_NULL_HANDLE;
1202 VkDeviceMemory m_sceneFallbackCubeMemory = VK_NULL_HANDLE;
1203 VkImageView m_sceneFallbackCubeView = VK_NULL_HANDLE;
1204 VkSampler m_sceneLinearSampler = VK_NULL_HANDLE;
1205 VkSampler m_scenePointSampler = VK_NULL_HANDLE;
1206 std::array<VkBuffer, MAX_FRAMES_IN_FLIGHT> m_sceneReadUBOBuffers{};
1207 std::array<VkDeviceMemory, MAX_FRAMES_IN_FLIGHT> m_sceneReadUBOMemory{};
1208 std::array<void*, MAX_FRAMES_IN_FLIGHT> m_sceneReadUBOMapped{};
1209 /// What one frame's set 3 bindings 2-4 last pointed at; a cleared entry
1210 /// forces a rewrite.
1211 struct SceneReadViews {
1212 VkImageView color = VK_NULL_HANDLE;
1213 VkImageView depth = VK_NULL_HANDLE;
1214 VkImageView sky = VK_NULL_HANDLE;
1215 uint32_t skySerial = 0;
1216 };
1217 std::array<SceneReadViews, MAX_FRAMES_IN_FLIGHT> m_sceneReadWritten{};
1218 bool m_sceneReadCreated = false;
1219 bool m_sceneReadPrepared = false; // UBO filled (and copy taken) this frame
1220 float m_cachedNearPlane = 0.0f;
1221 float m_cachedFarPlane = 0.0f;
1222
1223 /// Creates the scene-read samplers, stand-in images, and per-frame UBOs
1224 /// and writes them into both frames' set 3.
1225 bool CreateSceneReadResources();
1226 /// Destroys everything CreateSceneReadResources made plus the snapshots.
1227 void CleanupSceneReadResources();
1228 /// Creates the extent-sized scene color and depth snapshot images.
1229 bool CreateSceneCopyImages();
1230 /// Destroys the snapshot images and forces a set 3 rewrite.
1231 void CleanupSceneCopyImages();
1232 /// Points a frame's set 3 bindings 2-4 at the current snapshot and sky.
1233 void UpdateSceneReadDescriptors(uint32_t frame);
1234 /// Fills this frame's SceneReadUBO and, inside the forward pass, splits it
1235 /// to copy the scene. Runs once per frame on the first scene-reading draw.
1236 void PrepareSceneRead();
1237 /// Records the scene color and depth copies between two forward passes.
1238 void RecordSceneCopy();
1239};
1240
1241} // namespace RenderEngine
1242} // namespace Sleak
1243
1244#endif // VULKANRENDERER_HPP
int width
int height
Backend-agnostic GPU buffer: vertex, index, constant, or resource view target.
Abstract interface for high-level graphics command execution and resource management.
Abstract render backend: swapchain, frame lifecycle, and post-effect toggles.
Definition Renderer.hpp:41
Backend-agnostic compiled shader program.
Definition Shader.hpp:11
virtual bool IsShadowPassActive() const override
virtual size_t GetGPUMemoryBudget() const override
Returns the device-local heap size reported by the allocator.
virtual RenderContext * GetContext() override
Returns the backend's command-recording interface.
virtual size_t GetGPUMemoryUsed() const override
Returns total bytes currently allocated by VulkanBuffer.
virtual bool IsInGeometryPass() const override
bool IsFrameCapturePending() const override
True while an armed capture has not been written yet.
virtual bool IsDeferredEnabled() const override
virtual void FlushPendingTransfers() override
virtual void WaitIdle() override
Blocks until the device finishes all submitted GPU work.
virtual void Cleanup() override
Tears down every Vulkan resource in reverse dependency order.
virtual void EndRender() override
Ends the active render pass, submits the command buffer, and presents.
virtual void Resize(uint32_t width, uint32_t height) override
Recreates the swapchain for the new window dimensions.
virtual uint32_t GetFeatureCaps() const override
Feature capability mask; backends override with the audited truth.
Vulkan 2D texture: image + view + sampler, with per-swapchain-image descriptor sets.
Backend-facing rendering layer shared by the four graphics backends.
RenderMode
Rasterizer fill style for a draw.
BufferType
GPU buffer usage kind, drives backend binding flags and layout.
RenderFace
Which triangle winding gets culled.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
uint32_t VertexFormatHandle
std::vector< VkSurfaceFormatKHR > formats
std::vector< VkPresentModeKHR > presentModes