SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanDeferred.cpp
Go to the documentation of this file.
4
6#include <algorithm>
7#include <array>
8#include <cstring>
9#include <vector>
10#include "Core/Logger.hpp"
11#include "Camera/Camera.hpp"
12#include "Math/Matrix.hpp"
13
14namespace Sleak {
15 namespace RenderEngine {
16
17/// GBuffer attachment formats: RT0 AlbedoAO, RT1 NormalRough, RT2 MetalEmit.
18const VkFormat VulkanRenderer::m_gbufferFormats[VulkanRenderer::GBUFFER_COUNT] = {
19 VK_FORMAT_R8G8B8A8_UNORM, // RT0: AlbedoAO
20 VK_FORMAT_R16G16B16A16_SFLOAT, // RT1: NormalRough
21 VK_FORMAT_R16G16B16A16_SFLOAT, // RT2: MetalEmit (HDR emissive needs float)
22};
23
24/// Creates the GBuffer render pass with its three color attachments and depth.
25bool VulkanRenderer::CreateGBufferRenderPass() {
26 // Attachment 0-2: GBuffer color RTs (CLEAR → SHADER_READ_ONLY)
27 VkAttachmentDescription colorAtts[GBUFFER_COUNT] = {};
28 VkAttachmentReference colorRefs[GBUFFER_COUNT] = {};
29
30 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) {
31 colorAtts[i].format = m_gbufferFormats[i];
32 colorAtts[i].samples = VK_SAMPLE_COUNT_1_BIT;
33 colorAtts[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
34 colorAtts[i].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
35 colorAtts[i].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
36 colorAtts[i].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
37 colorAtts[i].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
38 colorAtts[i].finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
39
40 colorRefs[i].attachment = i;
41 colorRefs[i].layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
42 }
43
44 // Attachment 3: Depth (CLEAR → DEPTH_STENCIL_READ_ONLY)
45 VkAttachmentDescription depthAtt{};
46 depthAtt.format = depthFormat;
47 depthAtt.samples = VK_SAMPLE_COUNT_1_BIT;
48 depthAtt.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
49 depthAtt.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
50 depthAtt.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
51 depthAtt.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
52 depthAtt.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
53 depthAtt.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
54
55 VkAttachmentReference depthRef{};
56 depthRef.attachment = GBUFFER_COUNT; // depth slot follows the color RTs
57 depthRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
58
59 VkSubpassDescription subpass{};
60 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
61 subpass.colorAttachmentCount = GBUFFER_COUNT;
62 subpass.pColorAttachments = colorRefs;
63 subpass.pDepthStencilAttachment = &depthRef;
64
65 // Two external dependencies:
66 // 1. External → subpass (color attachment write)
67 // 2. Subpass → external (shader read in lighting pass)
68 std::array<VkSubpassDependency, 2> deps{};
69
70 deps[0].srcSubpass = VK_SUBPASS_EXTERNAL;
71 deps[0].dstSubpass = 0;
72 deps[0].srcStageMask = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT;
73 deps[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
74 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
75 deps[0].srcAccessMask = VK_ACCESS_MEMORY_READ_BIT;
76 deps[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
77 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
78 deps[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
79
80 deps[1].srcSubpass = 0;
81 deps[1].dstSubpass = VK_SUBPASS_EXTERNAL;
82 deps[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
83 VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
84 deps[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
85 deps[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
86 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
87 deps[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
88 deps[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
89
90 std::array<VkAttachmentDescription, GBUFFER_COUNT + 1> attachments;
91 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) attachments[i] = colorAtts[i];
92 attachments[GBUFFER_COUNT] = depthAtt;
93
94 VkRenderPassCreateInfo rpInfo{};
95 rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
96 rpInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
97 rpInfo.pAttachments = attachments.data();
98 rpInfo.subpassCount = 1;
99 rpInfo.pSubpasses = &subpass;
100 rpInfo.dependencyCount = static_cast<uint32_t>(deps.size());
101 rpInfo.pDependencies = deps.data();
102
103 return vkCreateRenderPass(device, &rpInfo, nullptr, &m_gbufferRenderPass) == VK_SUCCESS;
104}
105
106/// Creates the GBuffer framebuffer binding the GBuffer images and depth.
107bool VulkanRenderer::CreateGBufferFramebuffer() {
108 std::array<VkImageView, GBUFFER_COUNT + 1> views;
109 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) views[i] = m_gbufferViews[i];
110 views[GBUFFER_COUNT] = depthImageView;
111
112 VkFramebufferCreateInfo fbInfo{};
113 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
114 fbInfo.renderPass = m_gbufferRenderPass;
115 fbInfo.attachmentCount = static_cast<uint32_t>(views.size());
116 fbInfo.pAttachments = views.data();
117 fbInfo.width = scExtent.width;
118 fbInfo.height = scExtent.height;
119 fbInfo.layers = 1;
120
121 return vkCreateFramebuffer(device, &fbInfo, nullptr, &m_gbufferFramebuffer) == VK_SUCCESS;
122}
123
124/// Compiles the GBuffer shaders and creates the geometry pipeline, reusing pipelineLay.
125bool VulkanRenderer::CreateGBufferPipeline() {
126 m_gbufferShader = new VulkanShader(device);
127 if (!m_gbufferShader->compile("assets/shaders/gbuffer.vert.spv",
128 "assets/shaders/gbuffer.frag.spv")) {
129 SLEAK_ERROR("GBuffer: Failed to compile gbuffer shaders!");
130 delete m_gbufferShader;
131 m_gbufferShader = nullptr;
132 return false;
133 }
134
135 VkPipelineShaderStageCreateInfo shaderStages[] = {
136 m_gbufferShader->GetVertexInfo(),
137 m_gbufferShader->GetFragInfo()
138 };
139
140 // Dynamic state
141 std::vector<VkDynamicState> dynamicStates = {
142 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
143 VkPipelineDynamicStateCreateInfo dynamicState{};
144 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
145 dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
146 dynamicState.pDynamicStates = dynamicStates.data();
147
148 // Vertex input — identical to main pipeline
149 VkVertexInputBindingDescription bindingDesc{};
150 bindingDesc.binding = 0;
151 bindingDesc.stride = sizeof(Vertex);
152 bindingDesc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
153
154 std::array<VkVertexInputAttributeDescription, 7> attrDescs{};
155 attrDescs[0] = {0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, px)};
156 attrDescs[1] = {1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, nx)};
157 attrDescs[2] = {2, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, tx)};
158 attrDescs[3] = {3, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, r)};
159 attrDescs[4] = {4, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(Vertex, u)};
160 attrDescs[5] = {5, 0, VK_FORMAT_R32G32B32A32_SINT, offsetof(Vertex, boneIDs)};
161 attrDescs[6] = {6, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, boneWeights)};
162
163 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
164 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
165 vertexInputInfo.vertexBindingDescriptionCount = 1;
166 vertexInputInfo.pVertexBindingDescriptions = &bindingDesc;
167 vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attrDescs.size());
168 vertexInputInfo.pVertexAttributeDescriptions = attrDescs.data();
169
170 VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
171 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
172 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
173 inputAssembly.primitiveRestartEnable = VK_FALSE;
174
175 VkPipelineViewportStateCreateInfo viewportState{};
176 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
177 viewportState.viewportCount = 1;
178 viewportState.scissorCount = 1;
179
180 VkPipelineRasterizationStateCreateInfo rasterizer{};
181 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
182 rasterizer.depthClampEnable = VK_FALSE;
183 rasterizer.rasterizerDiscardEnable = VK_FALSE;
184 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
185 rasterizer.lineWidth = 1.0f;
186 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
187 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
188 rasterizer.depthBiasEnable = VK_FALSE;
189
190 VkPipelineMultisampleStateCreateInfo msaa{};
191 msaa.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
192 msaa.sampleShadingEnable = VK_FALSE;
193 msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; // GBuffer is always 1 sample
194
195 VkPipelineDepthStencilStateCreateInfo depthStencil{};
196 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
197 depthStencil.depthTestEnable = VK_TRUE;
198 depthStencil.depthWriteEnable = VK_TRUE;
199 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
200 depthStencil.depthBoundsTestEnable = VK_FALSE;
201 depthStencil.stencilTestEnable = VK_FALSE;
202
203 // GBUFFER_COUNT color blend attachments — opaque, no blending
204 VkPipelineColorBlendAttachmentState opaqueBlend{};
205 opaqueBlend.blendEnable = VK_FALSE;
206 opaqueBlend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
207 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
208
209 std::array<VkPipelineColorBlendAttachmentState, GBUFFER_COUNT> colorBlendAtts;
210 colorBlendAtts.fill(opaqueBlend);
211
212 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
213 colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
214 colorBlendInfo.logicOpEnable = VK_FALSE;
215 colorBlendInfo.attachmentCount = static_cast<uint32_t>(colorBlendAtts.size());
216 colorBlendInfo.pAttachments = colorBlendAtts.data();
217
218 // Use the dedicated GBuffer geometry layout (PBR material DSL at set 0)
219 m_gbufferPipelineLayout = m_gbufferGeomLayout;
220
221 VkGraphicsPipelineCreateInfo pipelineInfo{};
222 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
223 pipelineInfo.stageCount = 2;
224 pipelineInfo.pStages = shaderStages;
225 pipelineInfo.pVertexInputState = &vertexInputInfo;
226 pipelineInfo.pInputAssemblyState = &inputAssembly;
227 pipelineInfo.pViewportState = &viewportState;
228 pipelineInfo.pRasterizationState = &rasterizer;
229 pipelineInfo.pMultisampleState = &msaa;
230 pipelineInfo.pDepthStencilState = &depthStencil;
231 pipelineInfo.pColorBlendState = &colorBlendInfo;
232 pipelineInfo.pDynamicState = &dynamicState;
233 pipelineInfo.layout = m_gbufferPipelineLayout;
234 pipelineInfo.renderPass = m_gbufferRenderPass;
235 pipelineInfo.subpass = 0;
236 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
237 pipelineInfo.basePipelineIndex = -1;
238
239 VkResult result = vkCreateGraphicsPipelines(
240 device, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_gbufferPipeline);
241 if (result != VK_SUCCESS) {
242 SLEAK_ERROR("GBuffer: Failed to create GBuffer pipeline!");
243 return false;
244 }
245
246 SLEAK_INFO("VulkanRenderer: GBuffer pipeline created");
247 return true;
248}
249
250/// Compiles the skinned GBuffer shaders so skinned meshes write into the GBuffer.
251bool VulkanRenderer::CreateSkinnedGbufferPipeline() {
252 if (m_skinnedGbufferPipeline != VK_NULL_HANDLE) return true;
253
254 // Load skinned vert + gbuffer frag (SPIR-V already on disk)
255 VulkanShader* sh = new VulkanShader(device);
256 if (!sh->compile("assets/shaders/skinned_shader.vert.spv",
257 "assets/shaders/gbuffer.frag.spv")) {
258 SLEAK_ERROR("GBuffer: Failed to compile skinned gbuffer shaders!");
259 delete sh;
260 return false;
261 }
262
263 VkPipelineShaderStageCreateInfo stages[] = {
264 sh->GetVertexInfo(), sh->GetFragInfo()
265 };
266
267 std::vector<VkDynamicState> dynStates = {
268 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
269 VkPipelineDynamicStateCreateInfo dynState{};
270 dynState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
271 dynState.dynamicStateCount = static_cast<uint32_t>(dynStates.size());
272 dynState.pDynamicStates = dynStates.data();
273
274 // 7-attribute vertex layout (identical to static GBuffer pipeline)
275 VkVertexInputBindingDescription bindDesc{};
276 bindDesc.binding = 0;
277 bindDesc.stride = sizeof(Vertex);
278 bindDesc.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
279
280 std::array<VkVertexInputAttributeDescription, 7> attrs{};
281 attrs[0] = {0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, px)};
282 attrs[1] = {1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, nx)};
283 attrs[2] = {2, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, tx)};
284 attrs[3] = {3, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, r)};
285 attrs[4] = {4, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(Vertex, u)};
286 attrs[5] = {5, 0, VK_FORMAT_R32G32B32A32_SINT, offsetof(Vertex, boneIDs)};
287 attrs[6] = {6, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, boneWeights)};
288
289 VkPipelineVertexInputStateCreateInfo vi{};
290 vi.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
291 vi.vertexBindingDescriptionCount = 1;
292 vi.pVertexBindingDescriptions = &bindDesc;
293 vi.vertexAttributeDescriptionCount = static_cast<uint32_t>(attrs.size());
294 vi.pVertexAttributeDescriptions = attrs.data();
295
296 VkPipelineInputAssemblyStateCreateInfo ia{};
297 ia.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
298 ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
299
300 VkPipelineViewportStateCreateInfo vps{};
301 vps.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
302 vps.viewportCount = 1;
303 vps.scissorCount = 1;
304
305 VkPipelineRasterizationStateCreateInfo rast{};
306 rast.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
307 rast.polygonMode = VK_POLYGON_MODE_FILL;
308 rast.lineWidth = 1.0f;
309 rast.cullMode = VK_CULL_MODE_BACK_BIT;
310 rast.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
311
312 VkPipelineMultisampleStateCreateInfo ms{};
313 ms.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
314 ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
315
316 VkPipelineDepthStencilStateCreateInfo ds{};
317 ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
318 ds.depthTestEnable = VK_TRUE;
319 ds.depthWriteEnable = VK_TRUE;
320 ds.depthCompareOp = VK_COMPARE_OP_LESS;
321
322 VkPipelineColorBlendAttachmentState opaqueBlend{};
323 opaqueBlend.blendEnable = VK_FALSE;
324 opaqueBlend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
325 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
326
327 std::array<VkPipelineColorBlendAttachmentState, GBUFFER_COUNT> blendAtts;
328 blendAtts.fill(opaqueBlend);
329
330 VkPipelineColorBlendStateCreateInfo cb{};
331 cb.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
332 cb.attachmentCount = static_cast<uint32_t>(blendAtts.size());
333 cb.pAttachments = blendAtts.data();
334
335 VkGraphicsPipelineCreateInfo pi{};
336 pi.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
337 pi.stageCount = 2;
338 pi.pStages = stages;
339 pi.pVertexInputState = &vi;
340 pi.pInputAssemblyState = &ia;
341 pi.pViewportState = &vps;
342 pi.pRasterizationState = &rast;
343 pi.pMultisampleState = &ms;
344 pi.pDepthStencilState = &ds;
345 pi.pColorBlendState = &cb;
346 pi.pDynamicState = &dynState;
347 pi.layout = m_gbufferGeomLayout;
348 pi.renderPass = m_gbufferRenderPass;
349 pi.subpass = 0;
350 pi.basePipelineHandle = VK_NULL_HANDLE;
351 pi.basePipelineIndex = -1;
352
353 VkResult res = vkCreateGraphicsPipelines(
354 device, m_pipelineCache, 1, &pi, nullptr, &m_skinnedGbufferPipeline);
355 delete sh;
356 if (res != VK_SUCCESS) {
357 SLEAK_ERROR("GBuffer: Failed to create skinned GBuffer pipeline!");
358 return false;
359 }
360
361 SLEAK_INFO("VulkanRenderer: Skinned GBuffer pipeline created");
362 return true;
363}
364
365/// Creates the deferred lighting render pass with a single color attachment.
366bool VulkanRenderer::CreateLightingRenderPass() {
367 VkAttachmentDescription colorAtt{};
368 // Target the HDR scene color image (R16G16B16A16_SFLOAT) so the lighting
369 // pass outputs linear HDR. The composite pass later tonemaps + bloom-blends.
370 colorAtt.format = m_hdrSceneFormat;
371 colorAtt.samples = VK_SAMPLE_COUNT_1_BIT;
372 colorAtt.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
373 colorAtt.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
374 colorAtt.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
375 colorAtt.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
376 colorAtt.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
377 colorAtt.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
378
379 VkAttachmentReference colorRef{};
380 colorRef.attachment = 0;
381 colorRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
382
383 VkSubpassDescription subpass{};
384 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
385 subpass.colorAttachmentCount = 1;
386 subpass.pColorAttachments = &colorRef;
387
388 std::array<VkSubpassDependency, 2> deps{};
389 deps[0].srcSubpass = VK_SUBPASS_EXTERNAL;
390 deps[0].dstSubpass = 0;
391 deps[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
392 deps[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
393 deps[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
394 deps[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
395 deps[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
396
397 deps[1].srcSubpass = 0;
398 deps[1].dstSubpass = VK_SUBPASS_EXTERNAL;
399 deps[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
400 deps[1].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
401 deps[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
402 deps[1].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT;
403 deps[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
404
405 VkRenderPassCreateInfo rpInfo{};
406 rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
407 rpInfo.attachmentCount = 1;
408 rpInfo.pAttachments = &colorAtt;
409 rpInfo.subpassCount = 1;
410 rpInfo.pSubpasses = &subpass;
411 rpInfo.dependencyCount = static_cast<uint32_t>(deps.size());
412 rpInfo.pDependencies = deps.data();
413
414 return vkCreateRenderPass(device, &rpInfo, nullptr, &m_lightingRenderPass) == VK_SUCCESS;
415}
416
417/// Creates one lighting pass framebuffer per swapchain image, all aliasing the HDR target.
418bool VulkanRenderer::CreateLightingFramebuffers() {
419 if (m_hdrSceneView == VK_NULL_HANDLE) {
420 SLEAK_ERROR("GBuffer: HDR scene image view is null when creating lighting framebuffers!");
421 return false;
422 }
423
424 VkFramebufferCreateInfo fbInfo{};
425 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
426 fbInfo.renderPass = m_lightingRenderPass;
427 fbInfo.attachmentCount = 1;
428 fbInfo.pAttachments = &m_hdrSceneView;
429 fbInfo.width = scExtent.width;
430 fbInfo.height = scExtent.height;
431 fbInfo.layers = 1;
432
433 m_lightingFramebuffers.resize(swapChainImageViews.size());
434 for (size_t i = 0; i < swapChainImageViews.size(); ++i) {
435 if (vkCreateFramebuffer(device, &fbInfo, nullptr, &m_lightingFramebuffers[i]) != VK_SUCCESS) {
436 SLEAK_ERROR("GBuffer: Failed to create lighting framebuffer {}!", i);
437 return false;
438 }
439 }
440 return true;
441}
442
443/// Compiles the lighting shaders and creates the fullscreen lighting pipeline.
444bool VulkanRenderer::CreateLightingPipeline() {
445 m_lightingShader = new VulkanShader(device);
446 if (!m_lightingShader->compile("assets/shaders/lighting_pass.vert.spv",
447 "assets/shaders/lighting_pass.frag.spv")) {
448 SLEAK_ERROR("GBuffer: Failed to compile lighting pass shaders!");
449 delete m_lightingShader;
450 m_lightingShader = nullptr;
451 return false;
452 }
453
454 VkPipelineShaderStageCreateInfo shaderStages[] = {
455 m_lightingShader->GetVertexInfo(),
456 m_lightingShader->GetFragInfo()
457 };
458
459 // No vertex input — fullscreen triangle from gl_VertexIndex
460 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
461 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
462
463 VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
464 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
465 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
466 inputAssembly.primitiveRestartEnable = VK_FALSE;
467
468 std::vector<VkDynamicState> dynamicStates = {
469 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
470 VkPipelineDynamicStateCreateInfo dynamicState{};
471 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
472 dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
473 dynamicState.pDynamicStates = dynamicStates.data();
474
475 VkPipelineViewportStateCreateInfo viewportState{};
476 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
477 viewportState.viewportCount = 1;
478 viewportState.scissorCount = 1;
479
480 VkPipelineRasterizationStateCreateInfo rasterizer{};
481 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
482 rasterizer.depthClampEnable = VK_FALSE;
483 rasterizer.rasterizerDiscardEnable = VK_FALSE;
484 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
485 rasterizer.lineWidth = 1.0f;
486 rasterizer.cullMode = VK_CULL_MODE_NONE;
487 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
488 rasterizer.depthBiasEnable = VK_FALSE;
489
490 VkPipelineMultisampleStateCreateInfo msaa{};
491 msaa.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
492 msaa.sampleShadingEnable = VK_FALSE;
493 msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
494
495 // Depth test OFF, depth write OFF
496 VkPipelineDepthStencilStateCreateInfo depthStencil{};
497 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
498 depthStencil.depthTestEnable = VK_FALSE;
499 depthStencil.depthWriteEnable = VK_FALSE;
500 depthStencil.stencilTestEnable = VK_FALSE;
501
502 VkPipelineColorBlendAttachmentState colorBlendAtt{};
503 colorBlendAtt.blendEnable = VK_FALSE;
504 colorBlendAtt.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
505 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
506
507 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
508 colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
509 colorBlendInfo.logicOpEnable = VK_FALSE;
510 colorBlendInfo.attachmentCount = 1;
511 colorBlendInfo.pAttachments = &colorBlendAtt;
512
513 // Build lighting pipeline layout:
514 // Set 0: m_gbufferSamplerDSL (7 combined image samplers: GBuffer RTs + shadow maps)
515 // Set 1: m_deferredCBDSL (1 UBO: InvViewProj + screen size)
516 // Set 2: m_lightUBODescriptorSetLayout (1 UBO: directional light + shadow + fog)
517 // Set 3: m_iblDSL (3 samplerCubes + 1 sampler2D + 1 UBO: IBL)
518 std::array<VkDescriptorSetLayout, 4> setLayouts = {
519 m_gbufferSamplerDSL,
520 m_deferredCBDSL,
521 m_lightUBODescriptorSetLayout,
522 m_iblDSL
523 };
524
525 VkPipelineLayoutCreateInfo layoutInfo{};
526 layoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
527 layoutInfo.setLayoutCount = static_cast<uint32_t>(setLayouts.size());
528 layoutInfo.pSetLayouts = setLayouts.data();
529
530 if (vkCreatePipelineLayout(device, &layoutInfo, nullptr, &m_lightingPipelineLayout) != VK_SUCCESS) {
531 SLEAK_ERROR("GBuffer: Failed to create lighting pipeline layout!");
532 return false;
533 }
534
535 VkGraphicsPipelineCreateInfo pipelineInfo{};
536 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
537 pipelineInfo.stageCount = 2;
538 pipelineInfo.pStages = shaderStages;
539 pipelineInfo.pVertexInputState = &vertexInputInfo;
540 pipelineInfo.pInputAssemblyState = &inputAssembly;
541 pipelineInfo.pViewportState = &viewportState;
542 pipelineInfo.pRasterizationState = &rasterizer;
543 pipelineInfo.pMultisampleState = &msaa;
544 pipelineInfo.pDepthStencilState = &depthStencil;
545 pipelineInfo.pColorBlendState = &colorBlendInfo;
546 pipelineInfo.pDynamicState = &dynamicState;
547 pipelineInfo.layout = m_lightingPipelineLayout;
548 pipelineInfo.renderPass = m_lightingRenderPass;
549 pipelineInfo.subpass = 0;
550 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
551 pipelineInfo.basePipelineIndex = -1;
552
553 VkResult result =
554 vkCreateGraphicsPipelines(device, m_pipelineCache, 1, &pipelineInfo,
555 nullptr, &m_lightingPipeline);
556 if (result != VK_SUCCESS) {
557 SLEAK_ERROR("GBuffer: Failed to create lighting pipeline!");
558 return false;
559 }
560
561 SLEAK_INFO("VulkanRenderer: Lighting pass pipeline created");
562 return true;
563}
564
565/// Creates the forward transparent render pass writing into the HDR scene image.
566bool VulkanRenderer::CreateForwardRenderPass() {
567 VkAttachmentDescription colorAtt{};
568 colorAtt.format = m_hdrSceneFormat;
569 colorAtt.samples = VK_SAMPLE_COUNT_1_BIT;
570 colorAtt.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
571 colorAtt.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
572 colorAtt.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
573 colorAtt.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
574 colorAtt.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
575 colorAtt.finalLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
576
577 VkAttachmentDescription depthAtt{};
578 depthAtt.format = depthFormat;
579 depthAtt.samples = VK_SAMPLE_COUNT_1_BIT;
580 depthAtt.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
581 depthAtt.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
582 depthAtt.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
583 depthAtt.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
584 depthAtt.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
585 depthAtt.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
586
587 VkAttachmentReference colorRef{};
588 colorRef.attachment = 0;
589 colorRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
590
591 VkAttachmentReference depthRef{};
592 depthRef.attachment = 1;
593 depthRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
594
595 VkSubpassDescription subpass{};
596 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
597 subpass.colorAttachmentCount = 1;
598 subpass.pColorAttachments = &colorRef;
599 subpass.pDepthStencilAttachment = &depthRef;
600
601 std::array<VkSubpassDependency, 2> deps{};
602 deps[0].srcSubpass = VK_SUBPASS_EXTERNAL;
603 deps[0].dstSubpass = 0;
604 deps[0].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
605 deps[0].dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
606 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
607 deps[0].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
608 deps[0].dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
609 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
610
611 // Feeds the post passes
612 deps[1].srcSubpass = 0;
613 deps[1].dstSubpass = VK_SUBPASS_EXTERNAL;
614 deps[1].srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
615 VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
616 deps[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT |
617 VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
618 deps[1].srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
619 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
620 deps[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
621
622 std::array<VkAttachmentDescription, 2> attachments = {colorAtt, depthAtt};
623
624 VkRenderPassCreateInfo rpInfo{};
625 rpInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
626 rpInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
627 rpInfo.pAttachments = attachments.data();
628 rpInfo.subpassCount = 1;
629 rpInfo.pSubpasses = &subpass;
630 rpInfo.dependencyCount = static_cast<uint32_t>(deps.size());
631 rpInfo.pDependencies = deps.data();
632
633 return vkCreateRenderPass(device, &rpInfo, nullptr, &m_forwardRenderPass) == VK_SUCCESS;
634}
635
636/// Creates one forward transparent framebuffer per swapchain image, all aliasing the HDR target.
637bool VulkanRenderer::CreateForwardFramebuffers() {
638 if (m_hdrSceneView == VK_NULL_HANDLE) {
639 SLEAK_ERROR("GBuffer: HDR scene image view is null when creating forward framebuffers!");
640 return false;
641 }
642
643 m_forwardFramebuffers.resize(swapChainImageViews.size());
644
645 for (size_t i = 0; i < swapChainImageViews.size(); ++i) {
646 std::array<VkImageView, 2> views = {m_hdrSceneView, depthImageView};
647
648 VkFramebufferCreateInfo fbInfo{};
649 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
650 fbInfo.renderPass = m_forwardRenderPass;
651 fbInfo.attachmentCount = static_cast<uint32_t>(views.size());
652 fbInfo.pAttachments = views.data();
653 fbInfo.width = scExtent.width;
654 fbInfo.height = scExtent.height;
655 fbInfo.layers = 1;
656
657 if (vkCreateFramebuffer(device, &fbInfo, nullptr, &m_forwardFramebuffers[i]) != VK_SUCCESS) {
658 SLEAK_ERROR("GBuffer: Failed to create forward framebuffer {}!", i);
659 return false;
660 }
661 }
662 return true;
663}
664
665/// Creates the GBuffer sampler descriptor set layout, pool, and per-frame sets.
666bool VulkanRenderer::CreateGBufferDescriptorSets() {
667 // Create GBuffer sampler (nearest for encoded data reads in lighting pass)
668 VkSamplerCreateInfo samplerInfo{};
669 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
670 samplerInfo.magFilter = VK_FILTER_NEAREST;
671 samplerInfo.minFilter = VK_FILTER_NEAREST;
672 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
673 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
674 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
675 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
676 samplerInfo.minLod = 0.0f;
677 samplerInfo.maxLod = 1.0f;
678
679 if (vkCreateSampler(device, &samplerInfo, nullptr, &m_gbufferSampler) != VK_SUCCESS) {
680 SLEAK_ERROR("GBuffer: Failed to create gbuffer sampler!");
681 return false;
682 }
683
684 // Depth sampler — nearest, no comparison (we read raw depth to reconstruct position)
685 VkSamplerCreateInfo depthSamplerInfo{};
686 depthSamplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
687 depthSamplerInfo.magFilter = VK_FILTER_NEAREST;
688 depthSamplerInfo.minFilter = VK_FILTER_NEAREST;
689 depthSamplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
690 depthSamplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
691 depthSamplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
692 depthSamplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
693 depthSamplerInfo.minLod = 0.0f;
694 depthSamplerInfo.maxLod = 1.0f;
695
696 if (vkCreateSampler(device, &depthSamplerInfo, nullptr, &m_depthSampler) != VK_SUCCESS) {
697 SLEAK_ERROR("GBuffer: Failed to create depth sampler!");
698 return false;
699 }
700
701 // DSL for set 0 of lighting pass:
702 // binding 0: RT0, 1: RT1, 2: RT2, 3: depth,
703 // binding 4: shadow compare sampler (hardware PCF),
704 // binding 5: shadow raw sampler (PCSS blocker search)
705 // binding 6: screen-space AO (R8, bilateral blurred)
706 // (world position is reconstructed from depth binding 3 + InvViewProj)
707 std::array<VkDescriptorSetLayoutBinding, 7> bindings{};
708 for (uint32_t b = 0; b < 7; ++b) {
709 bindings[b].binding = b;
710 bindings[b].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
711 bindings[b].descriptorCount = 1;
712 bindings[b].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
713 }
714
715 VkDescriptorSetLayoutCreateInfo dslInfo{};
716 dslInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
717 dslInfo.bindingCount = static_cast<uint32_t>(bindings.size());
718 dslInfo.pBindings = bindings.data();
719
720 if (vkCreateDescriptorSetLayout(device, &dslInfo, nullptr, &m_gbufferSamplerDSL) != VK_SUCCESS) {
721 SLEAK_ERROR("GBuffer: Failed to create gbuffer sampler DSL!");
722 return false;
723 }
724
725 // Pool: 7 samplers × MAX_FRAMES_IN_FLIGHT sets
726 VkDescriptorPoolSize poolSize{};
727 poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
728 poolSize.descriptorCount = 7 * MAX_FRAMES_IN_FLIGHT;
729
730 VkDescriptorPoolCreateInfo poolInfo{};
731 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
732 poolInfo.poolSizeCount = 1;
733 poolInfo.pPoolSizes = &poolSize;
734 poolInfo.maxSets = MAX_FRAMES_IN_FLIGHT;
735
736 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &m_gbufferSamplerPool) != VK_SUCCESS) {
737 SLEAK_ERROR("GBuffer: Failed to create gbuffer sampler pool!");
738 return false;
739 }
740
741 std::array<VkDescriptorSetLayout, MAX_FRAMES_IN_FLIGHT> layouts;
742 layouts.fill(m_gbufferSamplerDSL);
743
744 VkDescriptorSetAllocateInfo allocInfo{};
745 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
746 allocInfo.descriptorPool = m_gbufferSamplerPool;
747 allocInfo.descriptorSetCount = MAX_FRAMES_IN_FLIGHT;
748 allocInfo.pSetLayouts = layouts.data();
749
750 if (vkAllocateDescriptorSets(device, &allocInfo, m_gbufferSamplerSets.data()) != VK_SUCCESS) {
751 SLEAK_ERROR("GBuffer: Failed to allocate gbuffer sampler descriptor sets!");
752 return false;
753 }
754
755 // Initial write — no rendering is in flight yet, so update all frames.
756 // After this, per-frame updates happen in UpdateGBufferDescriptors().
757 for (uint32_t f = 0; f < MAX_FRAMES_IN_FLIGHT; ++f) {
758 uint32_t saved = currentFrame;
759 currentFrame = f;
760 UpdateGBufferDescriptors();
761 currentFrame = saved;
762 }
763
764 return true;
765}
766
767/// Writes the GBuffer, depth, and shadow images into the sampler descriptor sets before the lighting pass.
768void VulkanRenderer::UpdateGBufferDescriptors() {
769 // Only update the descriptor set for the current frame slot.
770 // BeginRender() already waited on this frame's fence, so its
771 // descriptor set is safe to update. Updating other slots would
772 // race with the GPU still consuming them.
773 uint32_t f = currentFrame;
774 std::array<VkDescriptorImageInfo, 7> imageInfos{};
775
776 // RT0..RT2 (AlbedoAO, NormalRough, MetalEmit)
777 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) {
778 imageInfos[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
779 imageInfos[i].imageView = m_gbufferViews[i];
780 imageInfos[i].sampler = m_gbufferSampler;
781 }
782
783 // Depth (binding 3) — used to reconstruct world position
784 imageInfos[3].imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
785 imageInfos[3].imageView = depthImageView;
786 imageInfos[3].sampler = m_depthSampler;
787
788 // Shadow map (binding 4) — compare sampler for hardware PCF.
789 // Depth images must use DEPTH_STENCIL_READ_ONLY_OPTIMAL (not SHADER_READ_ONLY_OPTIMAL)
790 // when accessed as a sampler; using the wrong layout causes VK_ERROR_DEVICE_LOST.
791 // Fall back to the default 1x1 white texture when no shadow map is available.
792 if (m_shadowImageView) {
793 imageInfos[4].imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
794 imageInfos[4].imageView = m_shadowImageView;
795 imageInfos[4].sampler = m_shadowSampler ? m_shadowSampler
796 : (m_defaultTexture ? m_defaultTexture->GetSampler() : VK_NULL_HANDLE);
797 } else if (m_defaultTexture) {
798 imageInfos[4].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
799 imageInfos[4].imageView = m_defaultTexture->GetImageView();
800 imageInfos[4].sampler = m_defaultTexture->GetSampler();
801 }
802
803 // Shadow map raw (binding 5) — non-compare sampler for PCSS blocker search
804 if (m_shadowImageView) {
805 imageInfos[5].imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
806 imageInfos[5].imageView = m_shadowImageView;
807 imageInfos[5].sampler = m_shadowRawSampler ? m_shadowRawSampler
808 : (m_defaultTexture ? m_defaultTexture->GetSampler() : VK_NULL_HANDLE);
809 } else if (m_defaultTexture) {
810 imageInfos[5].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
811 imageInfos[5].imageView = m_defaultTexture->GetImageView();
812 imageInfos[5].sampler = m_defaultTexture->GetSampler();
813 }
814
815 // SSAO (binding 6) — fallback to default white texture when SSAO isn't ready,
816 // so the lighting shader multiplies by 1.0 (no occlusion) as a safe default.
817 if (m_ssaoBlurView != VK_NULL_HANDLE && m_ssaoSampler != VK_NULL_HANDLE) {
818 imageInfos[6].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
819 imageInfos[6].imageView = m_ssaoBlurView;
820 imageInfos[6].sampler = m_ssaoSampler;
821 } else if (m_defaultTexture) {
822 imageInfos[6].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
823 imageInfos[6].imageView = m_defaultTexture->GetImageView();
824 imageInfos[6].sampler = m_defaultTexture->GetSampler();
825 }
826
827 std::array<VkWriteDescriptorSet, 7> writes{};
828 for (uint32_t b = 0; b < 7; ++b) {
829 writes[b].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
830 writes[b].dstSet = m_gbufferSamplerSets[f];
831 writes[b].dstBinding = b;
832 writes[b].dstArrayElement = 0;
833 writes[b].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
834 writes[b].descriptorCount = 1;
835 writes[b].pImageInfo = &imageInfos[b];
836 }
837 vkUpdateDescriptorSets(device, static_cast<uint32_t>(writes.size()),
838 writes.data(), 0, nullptr);
839}
840
841/// Creates the per-frame deferred constant buffer holding InvViewProj and screen size.
842bool VulkanRenderer::CreateDeferredCBResources() {
843 if (m_deferredCBCreated) return true;
844
845 static constexpr VkDeviceSize uboSize = sizeof(DeferredCBData);
846
847 // Per-frame UBO buffers
848 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
849 VkBufferCreateInfo bufInfo{};
850 bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
851 bufInfo.size = uboSize;
852 bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
853 bufInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
854
855 if (vkCreateBuffer(device, &bufInfo, nullptr, &m_deferredCBBuffers[i]) != VK_SUCCESS) {
856 SLEAK_ERROR("GBuffer: Failed to create deferred CB buffer!");
857 return false;
858 }
859
860 VkMemoryRequirements memReqs;
861 vkGetBufferMemoryRequirements(device, m_deferredCBBuffers[i], &memReqs);
862
863 VkMemoryAllocateInfo allocInfo{};
864 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
865 allocInfo.allocationSize = memReqs.size;
866 allocInfo.memoryTypeIndex = FindMemoryType(memReqs.memoryTypeBits,
867 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
868
869 if (vkAllocateMemory(device, &allocInfo, nullptr, &m_deferredCBMemory[i]) != VK_SUCCESS) {
870 SLEAK_ERROR("GBuffer: Failed to allocate deferred CB memory!");
871 return false;
872 }
873
874 vkBindBufferMemory(device, m_deferredCBBuffers[i], m_deferredCBMemory[i], 0);
875 vkMapMemory(device, m_deferredCBMemory[i], 0, uboSize, 0, &m_deferredCBMapped[i]);
876 memset(m_deferredCBMapped[i], 0, uboSize);
877 }
878
879 // DSL: binding 0 = uniform buffer
880 VkDescriptorSetLayoutBinding uboBinding{};
881 uboBinding.binding = 0;
882 uboBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
883 uboBinding.descriptorCount = 1;
884 uboBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
885
886 VkDescriptorSetLayoutCreateInfo dslInfo{};
887 dslInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
888 dslInfo.bindingCount = 1;
889 dslInfo.pBindings = &uboBinding;
890
891 if (vkCreateDescriptorSetLayout(device, &dslInfo, nullptr, &m_deferredCBDSL) != VK_SUCCESS) {
892 SLEAK_ERROR("GBuffer: Failed to create deferred CB DSL!");
893 return false;
894 }
895
896 VkDescriptorPoolSize poolSize{};
897 poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
898 poolSize.descriptorCount = MAX_FRAMES_IN_FLIGHT;
899
900 VkDescriptorPoolCreateInfo poolInfo{};
901 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
902 poolInfo.poolSizeCount = 1;
903 poolInfo.pPoolSizes = &poolSize;
904 poolInfo.maxSets = MAX_FRAMES_IN_FLIGHT;
905
906 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &m_deferredCBPool) != VK_SUCCESS) {
907 SLEAK_ERROR("GBuffer: Failed to create deferred CB pool!");
908 return false;
909 }
910
911 std::array<VkDescriptorSetLayout, MAX_FRAMES_IN_FLIGHT> layouts;
912 layouts.fill(m_deferredCBDSL);
913
914 VkDescriptorSetAllocateInfo dsAllocInfo{};
915 dsAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
916 dsAllocInfo.descriptorPool = m_deferredCBPool;
917 dsAllocInfo.descriptorSetCount = MAX_FRAMES_IN_FLIGHT;
918 dsAllocInfo.pSetLayouts = layouts.data();
919
920 if (vkAllocateDescriptorSets(device, &dsAllocInfo, m_deferredCBSets.data()) != VK_SUCCESS) {
921 SLEAK_ERROR("GBuffer: Failed to allocate deferred CB descriptor sets!");
922 return false;
923 }
924
925 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
926 VkDescriptorBufferInfo bufInfo{};
927 bufInfo.buffer = m_deferredCBBuffers[i];
928 bufInfo.offset = 0;
929 bufInfo.range = uboSize;
930
931 VkWriteDescriptorSet write{};
932 write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
933 write.dstSet = m_deferredCBSets[i];
934 write.dstBinding = 0;
935 write.dstArrayElement = 0;
936 write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
937 write.descriptorCount = 1;
938 write.pBufferInfo = &bufInfo;
939
940 vkUpdateDescriptorSets(device, 1, &write, 0, nullptr);
941 }
942
943 m_deferredCBCreated = true;
944 return true;
945}
946
947/// Destroys all GBuffer, lighting, and forward transparent pass resources.
948void VulkanRenderer::CleanupGBufferResources() {
949 if (!m_gbufferResourcesCreated) return;
950
951 // If a frame is currently being recorded (command buffer is open), wait for
952 // the GPU to finish all pending work before destroying resources that may be
953 // referenced by the in-flight command buffer.
954 if (bFrameStarted) {
955 SLEAK_WARN("CleanupGBufferResources called while frame recording is active — forcing device idle");
956 vkDeviceWaitIdle(device);
957 bFrameStarted = false;
958 }
959
960 // GBuffer pipeline
961 if (m_gbufferPipeline) {
962 vkDestroyPipeline(device, m_gbufferPipeline, nullptr);
963 m_gbufferPipeline = VK_NULL_HANDLE;
964 }
965 // Every cached variant is built against a render pass destroyed below
966 // (GBuffer or forward); drop them all and let the next draw rebuild.
967 DestroyCustomFormatPipelines();
968 if (m_skinnedGbufferPipeline) {
969 vkDestroyPipeline(device, m_skinnedGbufferPipeline, nullptr);
970 m_skinnedGbufferPipeline = VK_NULL_HANDLE;
971 }
972 // m_gbufferPipelineLayout aliases m_gbufferGeomLayout — cleaned up below
973 m_gbufferPipelineLayout = VK_NULL_HANDLE;
974 delete m_gbufferShader;
975 m_gbufferShader = nullptr;
976
977 // Lighting pipeline
978 if (m_lightingPipeline) {
979 vkDestroyPipeline(device, m_lightingPipeline, nullptr);
980 m_lightingPipeline = VK_NULL_HANDLE;
981 }
982 if (m_lightingPipelineLayout) {
983 vkDestroyPipelineLayout(device, m_lightingPipelineLayout, nullptr);
984 m_lightingPipelineLayout = VK_NULL_HANDLE;
985 }
986 delete m_lightingShader;
987 m_lightingShader = nullptr;
988
989 // Lighting framebuffers
990 for (auto& fb : m_lightingFramebuffers) {
991 if (fb) vkDestroyFramebuffer(device, fb, nullptr);
992 }
993 m_lightingFramebuffers.clear();
994
995 // Lighting render pass
996 if (m_lightingRenderPass) {
997 vkDestroyRenderPass(device, m_lightingRenderPass, nullptr);
998 m_lightingRenderPass = VK_NULL_HANDLE;
999 }
1000
1001 // GBuffer framebuffer
1002 if (m_gbufferFramebuffer) {
1003 vkDestroyFramebuffer(device, m_gbufferFramebuffer, nullptr);
1004 m_gbufferFramebuffer = VK_NULL_HANDLE;
1005 }
1006
1007 // GBuffer render pass
1008 if (m_gbufferRenderPass) {
1009 vkDestroyRenderPass(device, m_gbufferRenderPass, nullptr);
1010 m_gbufferRenderPass = VK_NULL_HANDLE;
1011 }
1012
1013 // Forward framebuffers
1014 for (auto& fb : m_forwardFramebuffers) {
1015 if (fb) vkDestroyFramebuffer(device, fb, nullptr);
1016 }
1017 m_forwardFramebuffers.clear();
1018
1019 // Forward render pass
1020 if (m_forwardRenderPass) {
1021 vkDestroyRenderPass(device, m_forwardRenderPass, nullptr);
1022 m_forwardRenderPass = VK_NULL_HANDLE;
1023 }
1024
1025 // GBuffer sampler descriptor resources
1026 if (m_gbufferSamplerPool) {
1027 vkDestroyDescriptorPool(device, m_gbufferSamplerPool, nullptr);
1028 m_gbufferSamplerPool = VK_NULL_HANDLE;
1029 }
1030 if (m_gbufferSamplerDSL) {
1031 vkDestroyDescriptorSetLayout(device, m_gbufferSamplerDSL, nullptr);
1032 m_gbufferSamplerDSL = VK_NULL_HANDLE;
1033 }
1034 if (m_gbufferSampler) {
1035 vkDestroySampler(device, m_gbufferSampler, nullptr);
1036 m_gbufferSampler = VK_NULL_HANDLE;
1037 }
1038 if (m_depthSampler) {
1039 vkDestroySampler(device, m_depthSampler, nullptr);
1040 m_depthSampler = VK_NULL_HANDLE;
1041 }
1042
1043 // Deferred CB resources
1044 if (m_deferredCBCreated) {
1045 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
1046 if (m_deferredCBMapped[i]) {
1047 vkUnmapMemory(device, m_deferredCBMemory[i]);
1048 m_deferredCBMapped[i] = nullptr;
1049 }
1050 if (m_deferredCBBuffers[i]) {
1051 vkDestroyBuffer(device, m_deferredCBBuffers[i], nullptr);
1052 m_deferredCBBuffers[i] = VK_NULL_HANDLE;
1053 }
1054 if (m_deferredCBMemory[i]) {
1055 vkFreeMemory(device, m_deferredCBMemory[i], nullptr);
1056 m_deferredCBMemory[i] = VK_NULL_HANDLE;
1057 }
1058 }
1059 m_deferredCBCreated = false;
1060 }
1061 if (m_deferredCBPool) {
1062 vkDestroyDescriptorPool(device, m_deferredCBPool, nullptr);
1063 m_deferredCBPool = VK_NULL_HANDLE;
1064 }
1065 if (m_deferredCBDSL) {
1066 vkDestroyDescriptorSetLayout(device, m_deferredCBDSL, nullptr);
1067 m_deferredCBDSL = VK_NULL_HANDLE;
1068 }
1069
1070 // GBuffer images
1071 for (uint32_t i = 0; i < GBUFFER_COUNT; ++i) {
1072 if (m_gbufferViews[i]) {
1073 vkDestroyImageView(device, m_gbufferViews[i], nullptr);
1074 m_gbufferViews[i] = VK_NULL_HANDLE;
1075 }
1076 if (m_gbufferImages[i]) {
1077 vkDestroyImage(device, m_gbufferImages[i], nullptr);
1078 m_gbufferImages[i] = VK_NULL_HANDLE;
1079 }
1080 if (m_gbufferMemory[i]) {
1081 vkFreeMemory(device, m_gbufferMemory[i], nullptr);
1082 m_gbufferMemory[i] = VK_NULL_HANDLE;
1083 }
1084 }
1085
1086 // PBR material resources (GBuffer set 0)
1087 DestroyPBRMaterialChunks();
1088 m_pbrMaterialResourcesCreated = false;
1089 if (m_pbrMaterialDSL) {
1090 vkDestroyDescriptorSetLayout(device, m_pbrMaterialDSL, nullptr);
1091 m_pbrMaterialDSL = VK_NULL_HANDLE;
1092 }
1093 if (m_gbufferGeomLayout) {
1094 vkDestroyPipelineLayout(device, m_gbufferGeomLayout, nullptr);
1095 m_gbufferGeomLayout = VK_NULL_HANDLE;
1096 }
1097
1098 // IBL resources
1099 CleanupIBLResources();
1100
1101 // SSAO + SSR + Bloom + HDR scene (owned by the deferred pipeline)
1102 CleanupSSAOResources();
1103 CleanupSSRResources();
1104 CleanupBloomResources();
1105 CleanupSceneCopyImages();
1106
1107 m_gbufferResourcesCreated = false;
1108 m_inGeometryPass = false;
1109 m_inForwardTransparentPass = false;
1110}
1111
1112/// Binds the GBuffer pipeline and marks the geometry pass active.
1113/// Called by RenderCommandQueue when deferred is active.
1115 if (!bFrameStarted || !m_gbufferResourcesCreated) return;
1116 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_gbufferPipeline);
1117 // This binds the default GBuffer pipeline (96-byte Vertex stride). Without
1118 // the reset, the next custom-format draw's BindVertexBuffer sees its format
1119 // already active, skips the pipeline switch, and feeds the compact vertices
1120 // to a 96-byte stride.
1121 m_activeCustomFormat = 0;
1122}
1123
1124/// Runs the deferred lighting pass, reading the GBuffer and writing the HDR scene image.
1126 if (!bFrameStarted || !m_gbufferResourcesCreated) return;
1127
1128 // 1. End GBuffer render pass — transitions color RTs → SHADER_READ_ONLY,
1129 // depth → DEPTH_STENCIL_READ_ONLY via finalLayout in CreateGBufferRenderPass
1130 vkCmdEndRenderPass(command);
1131 EndGpuPass(GpuPass::GBuffer);
1132 m_inGeometryPass = false;
1133 m_activeCustomFormat = 0; // geometry pass is over; pipeline state doesn't survive across render passes
1134
1135 // 2. Run SSAO (raw + bilateral blur) using GBuffer normal + depth.
1136 // This writes to m_ssaoBlurImage which the lighting pass binding 7 reads.
1137 RenderSSAOPasses();
1138
1139 // 3. Update GBuffer sampler descriptor sets for current frame
1140 UpdateGBufferDescriptors();
1141
1142 // 4. Begin lighting render pass
1143 VkClearValue clearVal{};
1144 clearVal.color = {0.0f, 0.0f, 0.0f, 1.0f};
1145
1146 VkRenderPassBeginInfo rpBegin{};
1147 rpBegin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1148 rpBegin.renderPass = m_lightingRenderPass;
1149 rpBegin.framebuffer = m_lightingFramebuffers[CurrentFrameIndex];
1150 rpBegin.renderArea.offset = {0, 0};
1151 rpBegin.renderArea.extent = scExtent;
1152 rpBegin.clearValueCount = 1;
1153 rpBegin.pClearValues = &clearVal;
1154
1155 BeginGpuPass(GpuPass::Lighting);
1156 vkCmdBeginRenderPass(command, &rpBegin, VK_SUBPASS_CONTENTS_INLINE);
1157
1158 // 4. Set viewport and scissor
1159 VkViewport viewport{};
1160 viewport.x = 0.0f;
1161 viewport.y = 0.0f;
1162 viewport.width = static_cast<float>(scExtent.width);
1163 viewport.height = static_cast<float>(scExtent.height);
1164 viewport.minDepth = 0.0f;
1165 viewport.maxDepth = 1.0f;
1166 vkCmdSetViewport(command, 0, 1, &viewport);
1167
1168 VkRect2D scissor{};
1169 scissor.offset = {0, 0};
1170 scissor.extent = scExtent;
1171 vkCmdSetScissor(command, 0, 1, &scissor);
1172
1173 // 5. Bind lighting pipeline
1174 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_lightingPipeline);
1175
1176 // IBL is not baked here
1177 static bool iblWarned = false;
1178 if (m_iblEnabled && !iblWarned) {
1179 SLEAK_WARN("Vulkan: IBL is not implemented, using hemisphere ambient");
1180 iblWarned = true;
1181 }
1182
1183 // 6. Bind descriptor sets:
1184 // set 0: GBuffer samplers (RTs + shadow maps)
1185 // set 1: DeferredCB (InvViewProj + screen size)
1186 // set 2: LightUBO (directional light + shadow params + fog)
1187 // set 3: IBL (irradiance + prefilter + BRDF LUT + settings)
1188 VkDescriptorSet lightingSets[4] = {
1189 m_gbufferSamplerSets[currentFrame],
1190 m_deferredCBSets[currentFrame],
1191 m_lightUBODescriptorSets[currentFrame],
1192 m_iblSets[currentFrame]
1193 };
1194 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1195 m_lightingPipelineLayout, 0, 4,
1196 lightingSets, 0, nullptr);
1197
1198 // 7. Fullscreen triangle draw (3 vertices, no VBO)
1199 vkCmdDraw(command, 3, 1, 0, 0);
1200
1201 // 8. End lighting render pass
1202 vkCmdEndRenderPass(command);
1203 EndGpuPass(GpuPass::Lighting);
1204
1205 // 9. Transition depth back to DEPTH_STENCIL_ATTACHMENT_OPTIMAL for forward pass
1206 VkImageMemoryBarrier depthBarrier{};
1207 depthBarrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1208 depthBarrier.oldLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
1209 depthBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
1210 depthBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1211 depthBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1212 depthBarrier.srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
1213 depthBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
1214 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
1215 depthBarrier.image = depthImage;
1216 depthBarrier.subresourceRange = {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1};
1217
1218 vkCmdPipelineBarrier(command,
1219 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
1220 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT,
1221 0, 0, nullptr, 0, nullptr, 1, &depthBarrier);
1222}
1223
1224/// Begins the forward transparent render pass over the HDR scene image.
1226 if (!bFrameStarted || !m_gbufferResourcesCreated) return;
1227
1228 VkRenderPassBeginInfo rpBegin{};
1229 rpBegin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1230 rpBegin.renderPass = m_forwardRenderPass;
1231 rpBegin.framebuffer = m_forwardFramebuffers[CurrentFrameIndex];
1232 rpBegin.renderArea.offset = {0, 0};
1233 rpBegin.renderArea.extent = scExtent;
1234 rpBegin.clearValueCount = 0; // LOAD_OP — no clear needed
1235
1236 BeginGpuPass(GpuPass::Forward);
1237 vkCmdBeginRenderPass(command, &rpBegin, VK_SUBPASS_CONTENTS_INLINE);
1238
1239 VkViewport viewport{};
1240 viewport.x = 0.0f;
1241 viewport.y = 0.0f;
1242 viewport.width = static_cast<float>(scExtent.width);
1243 viewport.height = static_cast<float>(scExtent.height);
1244 viewport.minDepth = 0.0f;
1245 viewport.maxDepth = 1.0f;
1246 vkCmdSetViewport(command, 0, 1, &viewport);
1247
1248 VkRect2D scissor{};
1249 scissor.offset = {0, 0};
1250 scissor.extent = scExtent;
1251 vkCmdSetScissor(command, 0, 1, &scissor);
1252
1253 // Default to the forward pipeline; a custom vertex format with a
1254 // transparent variant swaps to it when its vertex buffer is bound.
1255 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
1256
1257 // Bind descriptor sets 0-3 (same as normal forward pass)
1258 if (m_textureDescriptorsWritten && CurrentFrameIndex < descriptorSets.size()) {
1259 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1260 pipelineLay, 0, 1,
1261 &descriptorSets[CurrentFrameIndex], 0, nullptr);
1262 }
1263 BindIdentityBonePalette(pipelineLay);
1264 if (m_lightUBOCreated) {
1265 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1266 pipelineLay, 2, 1,
1267 &m_lightUBODescriptorSets[currentFrame], 0, nullptr);
1268 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1269 pipelineLay, 3, 1,
1270 &m_shadowSamplerDescriptorSets[currentFrame], 0, nullptr);
1271 }
1272
1273 m_inForwardTransparentPass = true;
1274 m_forwardPassOpen = true;
1275 m_activeCustomFormat = 0; // new render pass; cached pipeline state is stale
1276}
1277
1278/// Marks the forward transparent pass ended; EndRender closes the actual render pass.
1280 m_inForwardTransparentPass = false;
1281 // m_forwardPassOpen stays true — the RP remains open until EndRender
1282}
1283
1284/// Copies deferred CB data into the current frame's UBO and snapshots the camera matrices.
1285void VulkanRenderer::UpdateDeferredCB(const void* data, uint32_t size) {
1286 if (!m_deferredCBCreated || !data) return;
1287 uint32_t copySize = std::min(size, static_cast<uint32_t>(sizeof(DeferredCBData)));
1288 memcpy(m_deferredCBMapped[currentFrame], data, copySize);
1289
1290 // Snapshot current camera View / Projection for SSAO/SSR/TAA UBO population.
1293 memcpy(m_cachedView, &V(0, 0), sizeof(m_cachedView));
1294 memcpy(m_cachedProjection, &P(0, 0), sizeof(m_cachedProjection));
1295
1296 // Snapshot InvViewProj (first mat4 of DeferredCBData) so SSAO/SSR reuse the
1297 // exact inverse the lighting pass uses to reconstruct world from depth.
1298 if (copySize >= sizeof(m_cachedInvViewProj))
1299 memcpy(m_cachedInvViewProj, data, sizeof(m_cachedInvViewProj));
1300 if (copySize >= sizeof(DeferredCBData)) {
1301 const auto* cb = static_cast<const DeferredCBData*>(data);
1302 m_cachedNearPlane = cb->NearP;
1303 m_cachedFarPlane = cb->FarP;
1304 }
1305
1306 // Compute sub-pixel Halton jitter for this frame (UV space).
1307 // Applied to WVP push constants in BindConstantBuffer during the geometry pass
1308 // so each frame samples a slightly different sub-pixel location — the temporal
1309 // accumulation in TAA then converges to full-resolution anti-aliased output.
1310 if (m_taaResourcesCreated && m_taaEnabled && scExtent.width > 0) {
1311 const uint32_t haltonIdx = static_cast<uint32_t>((m_taaFrameIdx % 8) + 1);
1312 m_taaJitter[0] = (HaltonSeq(haltonIdx, 2) - 0.5f) / static_cast<float>(scExtent.width);
1313 m_taaJitter[1] = (HaltonSeq(haltonIdx, 3) - 0.5f) / static_cast<float>(scExtent.height);
1314 } else {
1315 m_taaJitter[0] = m_taaJitter[1] = 0.0f;
1316 }
1317}
1318
1319} // namespace RenderEngine
1320} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
static const Math::Matrix4 & GetMainProjectionMatrix()
Definition Camera.hpp:107
static const Math::Matrix4 & GetMainViewMatrix()
Definition Camera.hpp:103
virtual void ExecuteDeferredLightingPass() override
Runs the deferred lighting pass, reading the GBuffer and writing the HDR scene image.
virtual void EndForwardTransparentPass() override
Marks the forward transparent pass ended; EndRender closes the actual render pass.
virtual void UpdateDeferredCB(const void *data, uint32_t size) override
Copies deferred CB data into the current frame's UBO and snapshots the camera matrices.
virtual void BeginForwardTransparentPass() override
Begins the forward transparent render pass over the HDR scene image.
virtual void BindGBufferShader() override
Matrix< float, 4, 4 > Matrix4
Definition Matrix.hpp:404
Backend-facing rendering layer shared by the four graphics backends.
float HaltonSeq(int index, int base)
Halton low-discrepancy sequence value for TAA sub-pixel jitter.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10