SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanShadow.cpp
Go to the documentation of this file.
2#include <algorithm>
3#include <array>
4#include <cstddef>
5#include <cstring>
6#include <vector>
7
10#include "Core/Logger.hpp"
11
12namespace Sleak {
13 namespace RenderEngine {
14
15/// Creates the shadow depth image, sampler, render pass, and framebuffer.
16bool VulkanRenderer::CreateShadowResources() {
17 // 1. Create shadow depth image (2048x2048, D32_SFLOAT)
18 VkImageCreateInfo imageInfo{};
19 imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
20 imageInfo.imageType = VK_IMAGE_TYPE_2D;
21 imageInfo.extent = {m_shadowMapResolution, m_shadowMapResolution, 1};
22 imageInfo.mipLevels = 1;
23 imageInfo.arrayLayers = 1;
24 imageInfo.format = VK_FORMAT_D32_SFLOAT;
25 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
26 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
27 imageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
28 VK_IMAGE_USAGE_SAMPLED_BIT;
29 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
30 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
31
32 if (vkCreateImage(device, &imageInfo, nullptr, &m_shadowImage) != VK_SUCCESS) {
33 SLEAK_ERROR("Failed to create shadow map image!");
34 return false;
35 }
36
37 VkMemoryRequirements memReqs;
38 vkGetImageMemoryRequirements(device, m_shadowImage, &memReqs);
39
40 VkMemoryAllocateInfo allocInfo{};
41 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
42 allocInfo.allocationSize = memReqs.size;
43 allocInfo.memoryTypeIndex = FindMemoryType(memReqs.memoryTypeBits,
44 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
45
46 if (vkAllocateMemory(device, &allocInfo, nullptr, &m_shadowImageMemory) != VK_SUCCESS) {
47 SLEAK_ERROR("Failed to allocate shadow map memory!");
48 return false;
49 }
50
51 vkBindImageMemory(device, m_shadowImage, m_shadowImageMemory, 0);
52
53 // 2. Create image view (DEPTH aspect)
54 VkImageViewCreateInfo viewInfo{};
55 viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
56 viewInfo.image = m_shadowImage;
57 viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
58 viewInfo.format = VK_FORMAT_D32_SFLOAT;
59 viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
60 viewInfo.subresourceRange.baseMipLevel = 0;
61 viewInfo.subresourceRange.levelCount = 1;
62 viewInfo.subresourceRange.baseArrayLayer = 0;
63 viewInfo.subresourceRange.layerCount = 1;
64
65 if (vkCreateImageView(device, &viewInfo, nullptr, &m_shadowImageView) != VK_SUCCESS) {
66 SLEAK_ERROR("Failed to create shadow map image view!");
67 return false;
68 }
69
70 // 3. Create comparison sampler with bilinear filtering for smooth PCF
71 VkSamplerCreateInfo samplerInfo{};
72 samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
73 samplerInfo.magFilter = VK_FILTER_LINEAR;
74 samplerInfo.minFilter = VK_FILTER_LINEAR;
75 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
76 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
77 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
78 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER;
79 samplerInfo.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE;
80 samplerInfo.compareEnable = VK_TRUE;
81 samplerInfo.compareOp = VK_COMPARE_OP_LESS;
82 samplerInfo.minLod = 0.0f;
83 samplerInfo.maxLod = 1.0f;
84 samplerInfo.anisotropyEnable = VK_FALSE;
85
86 if (vkCreateSampler(device, &samplerInfo, nullptr, &m_shadowSampler) != VK_SUCCESS) {
87 SLEAK_ERROR("Failed to create shadow map sampler!");
88 return false;
89 }
90
91 // 3b. Create non-comparison sampler for PCSS blocker search.
92 // The blocker pass needs raw depth values to average, so compareEnable is off
93 // and we switch to nearest filtering to sample individual texels cleanly.
94 VkSamplerCreateInfo rawSamplerInfo = samplerInfo;
95 rawSamplerInfo.compareEnable = VK_FALSE;
96 rawSamplerInfo.magFilter = VK_FILTER_NEAREST;
97 rawSamplerInfo.minFilter = VK_FILTER_NEAREST;
98
99 if (vkCreateSampler(device, &rawSamplerInfo, nullptr, &m_shadowRawSampler) != VK_SUCCESS) {
100 SLEAK_ERROR("Failed to create shadow map raw sampler!");
101 return false;
102 }
103
104 // 4. Create depth-only render pass
105 VkAttachmentDescription depthAttachment{};
106 depthAttachment.format = VK_FORMAT_D32_SFLOAT;
107 depthAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
108 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
109 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
110 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
111 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
112 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
113 depthAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
114
115 VkAttachmentReference depthRef{};
116 depthRef.attachment = 0;
117 depthRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
118
119 VkSubpassDescription subpass{};
120 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
121 subpass.colorAttachmentCount = 0;
122 subpass.pDepthStencilAttachment = &depthRef;
123
124 // Dependencies for layout transitions
125 std::array<VkSubpassDependency, 2> dependencies{};
126
127 dependencies[0].srcSubpass = VK_SUBPASS_EXTERNAL;
128 dependencies[0].dstSubpass = 0;
129 dependencies[0].srcStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
130 dependencies[0].dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
131 dependencies[0].srcAccessMask = VK_ACCESS_SHADER_READ_BIT;
132 dependencies[0].dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
133 dependencies[0].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
134
135 dependencies[1].srcSubpass = 0;
136 dependencies[1].dstSubpass = VK_SUBPASS_EXTERNAL;
137 dependencies[1].srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
138 dependencies[1].dstStageMask = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
139 dependencies[1].srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
140 dependencies[1].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
141 dependencies[1].dependencyFlags = VK_DEPENDENCY_BY_REGION_BIT;
142
143 VkRenderPassCreateInfo renderPassInfo{};
144 renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
145 renderPassInfo.attachmentCount = 1;
146 renderPassInfo.pAttachments = &depthAttachment;
147 renderPassInfo.subpassCount = 1;
148 renderPassInfo.pSubpasses = &subpass;
149 renderPassInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
150 renderPassInfo.pDependencies = dependencies.data();
151
152 if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &m_shadowRenderPass) != VK_SUCCESS) {
153 SLEAK_ERROR("Failed to create shadow render pass!");
154 return false;
155 }
156
157 // 5. Create framebuffer
158 VkFramebufferCreateInfo fbInfo{};
159 fbInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
160 fbInfo.renderPass = m_shadowRenderPass;
161 fbInfo.attachmentCount = 1;
162 fbInfo.pAttachments = &m_shadowImageView;
163 fbInfo.width = m_shadowMapResolution;
164 fbInfo.height = m_shadowMapResolution;
165 fbInfo.layers = 1;
166
167 if (vkCreateFramebuffer(device, &fbInfo, nullptr, &m_shadowFramebuffer) != VK_SUCCESS) {
168 SLEAK_ERROR("Failed to create shadow framebuffer!");
169 return false;
170 }
171
172 // 6. Transition shadow image to DEPTH_STENCIL_READ_ONLY_OPTIMAL so the
173 // descriptor is valid even before the first shadow pass runs.
174 // Depth images must use this layout (not SHADER_READ_ONLY_OPTIMAL)
175 // for sampler access; the wrong layout causes VK_ERROR_DEVICE_LOST.
176 {
177 VkCommandBufferAllocateInfo cmdAllocInfo{};
178 cmdAllocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
179 cmdAllocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
180 cmdAllocInfo.commandPool = commands;
181 cmdAllocInfo.commandBufferCount = 1;
182
183 VkCommandBuffer cmdBuf;
184 vkAllocateCommandBuffers(device, &cmdAllocInfo, &cmdBuf);
185
186 VkCommandBufferBeginInfo cmdBeginInfo{};
187 cmdBeginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
188 cmdBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
189 vkBeginCommandBuffer(cmdBuf, &cmdBeginInfo);
190
191 // Clear to far depth
192 VkClearValue clear{};
193 clear.depthStencil = {1.0f, 0};
194 VkRenderPassBeginInfo clearPass{};
195 clearPass.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
196 clearPass.renderPass = m_shadowRenderPass;
197 clearPass.framebuffer = m_shadowFramebuffer;
198 clearPass.renderArea.extent = {m_shadowMapResolution,
200 clearPass.clearValueCount = 1;
201 clearPass.pClearValues = &clear;
202 vkCmdBeginRenderPass(cmdBuf, &clearPass, VK_SUBPASS_CONTENTS_INLINE);
203 vkCmdEndRenderPass(cmdBuf);
204
205 vkEndCommandBuffer(cmdBuf);
206
207 VkSubmitInfo layoutSubmit{};
208 layoutSubmit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
209 layoutSubmit.commandBufferCount = 1;
210 layoutSubmit.pCommandBuffers = &cmdBuf;
211
212 VkFenceCreateInfo layoutFenceInfo{};
213 layoutFenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
214 VkFence layoutFence;
215 vkCreateFence(device, &layoutFenceInfo, nullptr, &layoutFence);
216 vkQueueSubmit(graphicsQueue, 1, &layoutSubmit, layoutFence);
217 vkWaitForFences(device, 1, &layoutFence, VK_TRUE, UINT64_MAX);
218 vkDestroyFence(device, layoutFence, nullptr);
219 vkFreeCommandBuffers(device, commands, 1, &cmdBuf);
220 }
221
222 // 7. Create shadow pipeline
223 if (!CreateShadowPipeline()) {
224 SLEAK_ERROR("Failed to create shadow pipeline!");
225 return false;
226 }
227
228 // Write shadow sampler to set 3 descriptors (UBO resources already created).
229 // Binding 0 uses the compare sampler for hardware PCF; binding 1 uses the
230 // raw sampler so the PCSS blocker search can read un-compared depth values.
231 if (m_lightUBOCreated && m_shadowImageView && m_shadowSampler && m_shadowRawSampler) {
232 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
233 // Depth images must use DEPTH_STENCIL_READ_ONLY_OPTIMAL for sampler access.
234 VkDescriptorImageInfo compareInfo{};
235 compareInfo.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
236 compareInfo.imageView = m_shadowImageView;
237 compareInfo.sampler = m_shadowSampler;
238
239 VkDescriptorImageInfo rawInfo{};
240 rawInfo.imageLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL;
241 rawInfo.imageView = m_shadowImageView;
242 rawInfo.sampler = m_shadowRawSampler;
243
244 std::array<VkWriteDescriptorSet, 2> writes{};
245 writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
246 writes[0].dstSet = m_shadowSamplerDescriptorSets[i];
247 writes[0].dstBinding = 0;
248 writes[0].dstArrayElement = 0;
249 writes[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
250 writes[0].descriptorCount = 1;
251 writes[0].pImageInfo = &compareInfo;
252
253 writes[1] = writes[0];
254 writes[1].dstBinding = 1;
255 writes[1].pImageInfo = &rawInfo;
256
257 vkUpdateDescriptorSets(device, static_cast<uint32_t>(writes.size()),
258 writes.data(), 0, nullptr);
259 }
260 }
261
263 SLEAK_INFO("VulkanRenderer: Shadow mapping resources created ({}x{} shadow map)",
265 return true;
266}
267
268/// Compiles the shadow depth shader and creates the shadow pass pipeline.
269bool VulkanRenderer::CreateShadowPipeline() {
270 m_shadowShader = new VulkanShader(device);
271 if (!m_shadowShader->compileVertexOnly("assets/shaders/shadow_depth.vert.spv")) {
272 SLEAK_ERROR("VulkanRenderer: Failed to compile shadow depth shader");
273 delete m_shadowShader;
274 m_shadowShader = nullptr;
275 return false;
276 }
277
278 // Vertex-only pipeline (no fragment shader)
279 VkPipelineShaderStageCreateInfo shaderStage = m_shadowShader->GetVertexInfo();
280
281 std::vector<VkDynamicState> dynamicStates = {
282 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
283
284 VkPipelineDynamicStateCreateInfo dynamicState{};
285 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
286 dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
287 dynamicState.pDynamicStates = dynamicStates.data();
288
289 // Same vertex layout as main pipeline
290 VkVertexInputBindingDescription bindingDescription{};
291 bindingDescription.binding = 0;
292 bindingDescription.stride = sizeof(Vertex);
293 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
294
295 std::array<VkVertexInputAttributeDescription, 7> attributeDescs{};
296 attributeDescs[0] = {0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, px)};
297 attributeDescs[1] = {1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, nx)};
298 attributeDescs[2] = {2, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, tx)};
299 attributeDescs[3] = {3, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, r)};
300 attributeDescs[4] = {4, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(Vertex, u)};
301 attributeDescs[5] = {5, 0, VK_FORMAT_R32G32B32A32_SINT, offsetof(Vertex, boneIDs)};
302 attributeDescs[6] = {6, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, boneWeights)};
303
304 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
305 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
306 vertexInputInfo.vertexBindingDescriptionCount = 1;
307 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
308 vertexInputInfo.vertexAttributeDescriptionCount =
309 static_cast<uint32_t>(attributeDescs.size());
310 vertexInputInfo.pVertexAttributeDescriptions = attributeDescs.data();
311
312 VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
313 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
314 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
315 inputAssembly.primitiveRestartEnable = VK_FALSE;
316
317 VkPipelineViewportStateCreateInfo viewportState{};
318 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
319 viewportState.viewportCount = 1;
320 viewportState.scissorCount = 1;
321
322 VkPipelineRasterizationStateCreateInfo rasterizer{};
323 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
324 rasterizer.depthClampEnable = VK_FALSE;
325 rasterizer.rasterizerDiscardEnable = VK_FALSE;
326 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
327 rasterizer.lineWidth = 1.0f;
328 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; // same winding as main pass
329 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
330 rasterizer.depthBiasEnable = VK_TRUE;
331 rasterizer.depthBiasConstantFactor = SHADOW_DEPTH_BIAS_CONSTANT;
332 rasterizer.depthBiasSlopeFactor = SHADOW_DEPTH_BIAS_SLOPE;
333 rasterizer.depthBiasClamp = 0.0f;
334
335 VkPipelineMultisampleStateCreateInfo msaa{};
336 msaa.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
337 msaa.sampleShadingEnable = VK_FALSE;
338 msaa.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
339
340 VkPipelineDepthStencilStateCreateInfo depthStencil{};
341 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
342 depthStencil.depthTestEnable = VK_TRUE;
343 depthStencil.depthWriteEnable = VK_TRUE;
344 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
345 depthStencil.depthBoundsTestEnable = VK_FALSE;
346 depthStencil.stencilTestEnable = VK_FALSE;
347
348 // No color blend (depth-only, no color attachment)
349 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
350 colorBlendInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
351 colorBlendInfo.logicOpEnable = VK_FALSE;
352 colorBlendInfo.attachmentCount = 0;
353
354 VkGraphicsPipelineCreateInfo pipelineInfo{};
355 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
356 pipelineInfo.stageCount = 1; // Vertex-only
357 pipelineInfo.pStages = &shaderStage;
358 pipelineInfo.pVertexInputState = &vertexInputInfo;
359 pipelineInfo.pInputAssemblyState = &inputAssembly;
360 pipelineInfo.pViewportState = &viewportState;
361 pipelineInfo.pRasterizationState = &rasterizer;
362 pipelineInfo.pMultisampleState = &msaa;
363 pipelineInfo.pDepthStencilState = &depthStencil;
364 pipelineInfo.pColorBlendState = &colorBlendInfo;
365 pipelineInfo.pDynamicState = &dynamicState;
366 pipelineInfo.layout = pipelineLay;
367 pipelineInfo.renderPass = m_shadowRenderPass;
368 pipelineInfo.subpass = 0;
369 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
370 pipelineInfo.basePipelineIndex = -1;
371
372 VkResult result = vkCreateGraphicsPipelines(
373 device, m_pipelineCache, 1, &pipelineInfo, nullptr, &m_shadowPipeline);
374 if (result != VK_SUCCESS) {
375 SLEAK_ERROR("VulkanRenderer: Failed to create shadow pipeline!");
376 return false;
377 }
378
379 SLEAK_INFO("VulkanRenderer: Shadow pipeline created successfully");
380 return true;
381}
382
383/// Creates the per-frame light and shadow UBO buffers and descriptor sets.
384bool VulkanRenderer::CreateShadowLightUBOResources() {
385 static constexpr VkDeviceSize uboSize = sizeof(ShadowLightUBO);
386
387 // Create per-frame UBO buffers
388 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
389 VkBufferCreateInfo bufferInfo{};
390 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
391 bufferInfo.size = uboSize;
392 bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
393 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
394
395 if (vkCreateBuffer(device, &bufferInfo, nullptr, &m_lightUBOBuffers[i]) != VK_SUCCESS) {
396 SLEAK_ERROR("Failed to create light UBO buffer!");
397 return false;
398 }
399
400 VkMemoryRequirements memReqs;
401 vkGetBufferMemoryRequirements(device, m_lightUBOBuffers[i], &memReqs);
402
403 VkMemoryAllocateInfo allocInfo{};
404 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
405 allocInfo.allocationSize = memReqs.size;
406 allocInfo.memoryTypeIndex = FindMemoryType(memReqs.memoryTypeBits,
407 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
408
409 if (vkAllocateMemory(device, &allocInfo, nullptr, &m_lightUBOMemory[i]) != VK_SUCCESS) {
410 SLEAK_ERROR("Failed to allocate light UBO memory!");
411 return false;
412 }
413
414 vkBindBufferMemory(device, m_lightUBOBuffers[i], m_lightUBOMemory[i], 0);
415 vkMapMemory(device, m_lightUBOMemory[i], 0, uboSize, 0, &m_lightUBOMapped[i]);
416 memset(m_lightUBOMapped[i], 0, uboSize);
417 }
418
419 // Create descriptor pool for light UBO + shadow samplers.
420 // Two shadow samplers per frame now (compare + raw for PCSS blocker
421 // search). Set 3 also carries the scene-read color, depth, sky, and UBO
422 // bindings.
423 std::array<VkDescriptorPoolSize, 2> poolSizes{};
424 poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
425 poolSizes[0].descriptorCount =
426 MAX_FRAMES_IN_FLIGHT * LIGHT_POOL_UBOS_PER_FRAME;
427 poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
428 poolSizes[1].descriptorCount = MAX_FRAMES_IN_FLIGHT * SET3_SAMPLER_COUNT;
429
430 VkDescriptorPoolCreateInfo poolInfo{};
431 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
432 poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
433 poolInfo.pPoolSizes = poolSizes.data();
434 poolInfo.maxSets = MAX_FRAMES_IN_FLIGHT * 2; // UBO sets + sampler sets
435
436 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &m_lightUBODescriptorPool) != VK_SUCCESS) {
437 SLEAK_ERROR("Failed to create light UBO descriptor pool!");
438 return false;
439 }
440
441 // Allocate light UBO descriptor sets (set 2)
442 std::array<VkDescriptorSetLayout, MAX_FRAMES_IN_FLIGHT> uboLayouts;
443 uboLayouts.fill(m_lightUBODescriptorSetLayout);
444
445 VkDescriptorSetAllocateInfo uboAllocInfo{};
446 uboAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
447 uboAllocInfo.descriptorPool = m_lightUBODescriptorPool;
448 uboAllocInfo.descriptorSetCount = MAX_FRAMES_IN_FLIGHT;
449 uboAllocInfo.pSetLayouts = uboLayouts.data();
450
451 if (vkAllocateDescriptorSets(device, &uboAllocInfo, m_lightUBODescriptorSets.data()) != VK_SUCCESS) {
452 SLEAK_ERROR("Failed to allocate light UBO descriptor sets!");
453 return false;
454 }
455
456 // Write UBO descriptors
457 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
458 VkDescriptorBufferInfo bufInfo{};
459 bufInfo.buffer = m_lightUBOBuffers[i];
460 bufInfo.offset = 0;
461 bufInfo.range = uboSize;
462
463 VkWriteDescriptorSet write{};
464 write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
465 write.dstSet = m_lightUBODescriptorSets[i];
466 write.dstBinding = 0;
467 write.dstArrayElement = 0;
468 write.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
469 write.descriptorCount = 1;
470 write.pBufferInfo = &bufInfo;
471
472 vkUpdateDescriptorSets(device, 1, &write, 0, nullptr);
473 }
474
475 // Allocate shadow sampler descriptor sets (set 3)
476 std::array<VkDescriptorSetLayout, MAX_FRAMES_IN_FLIGHT> samplerLayouts;
477 samplerLayouts.fill(m_shadowSamplerDescriptorSetLayout);
478
479 VkDescriptorSetAllocateInfo samplerAllocInfo{};
480 samplerAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
481 samplerAllocInfo.descriptorPool = m_lightUBODescriptorPool;
482 samplerAllocInfo.descriptorSetCount = MAX_FRAMES_IN_FLIGHT;
483 samplerAllocInfo.pSetLayouts = samplerLayouts.data();
484
485 if (vkAllocateDescriptorSets(device, &samplerAllocInfo, m_shadowSamplerDescriptorSets.data()) != VK_SUCCESS) {
486 SLEAK_ERROR("Failed to allocate shadow sampler descriptor sets!");
487 return false;
488 }
489
490 // Write default shadow sampler descriptors (using default texture as placeholder)
491 // These will be overwritten with actual shadow map when shadow resources are created.
492 // Both binding=0 (compare) and binding=1 (raw) must be populated or the layout
493 // is incomplete and first-frame sampling reads undefined memory.
494 if (m_defaultTexture) {
495 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
496 VkDescriptorImageInfo imageInfo{};
497 imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
498 imageInfo.imageView = m_defaultTexture->GetImageView();
499 imageInfo.sampler = m_defaultTexture->GetSampler();
500
501 std::array<VkWriteDescriptorSet, 2> writes{};
502 writes[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
503 writes[0].dstSet = m_shadowSamplerDescriptorSets[i];
504 writes[0].dstBinding = 0;
505 writes[0].dstArrayElement = 0;
506 writes[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
507 writes[0].descriptorCount = 1;
508 writes[0].pImageInfo = &imageInfo;
509
510 writes[1] = writes[0];
511 writes[1].dstBinding = 1;
512
513 vkUpdateDescriptorSets(device, static_cast<uint32_t>(writes.size()),
514 writes.data(), 0, nullptr);
515 }
516 }
517
518 m_lightUBOCreated = true;
519 SLEAK_INFO("VulkanRenderer: Light UBO and shadow sampler resources created");
520 return true;
521}
522
523/// Destroys the shadow map image, pipeline, render pass, and light UBO resources.
524void VulkanRenderer::CleanupShadowResources() {
525 if (m_shadowPipeline) {
526 vkDestroyPipeline(device, m_shadowPipeline, nullptr);
527 m_shadowPipeline = VK_NULL_HANDLE;
528 }
529 delete m_shadowShader;
530 m_shadowShader = nullptr;
531
532 if (m_shadowFramebuffer) {
533 vkDestroyFramebuffer(device, m_shadowFramebuffer, nullptr);
534 m_shadowFramebuffer = VK_NULL_HANDLE;
535 }
536 if (m_shadowRenderPass) {
537 vkDestroyRenderPass(device, m_shadowRenderPass, nullptr);
538 m_shadowRenderPass = VK_NULL_HANDLE;
539 }
540 if (m_shadowSampler) {
541 vkDestroySampler(device, m_shadowSampler, nullptr);
542 m_shadowSampler = VK_NULL_HANDLE;
543 }
544 if (m_shadowRawSampler) {
545 vkDestroySampler(device, m_shadowRawSampler, nullptr);
546 m_shadowRawSampler = VK_NULL_HANDLE;
547 }
548 if (m_shadowImageView) {
549 vkDestroyImageView(device, m_shadowImageView, nullptr);
550 m_shadowImageView = VK_NULL_HANDLE;
551 }
552 if (m_shadowImage) {
553 vkDestroyImage(device, m_shadowImage, nullptr);
554 m_shadowImage = VK_NULL_HANDLE;
555 }
556 if (m_shadowImageMemory) {
557 vkFreeMemory(device, m_shadowImageMemory, nullptr);
558 m_shadowImageMemory = VK_NULL_HANDLE;
559 }
560
561 // Cleanup light UBO resources
562 if (m_lightUBOCreated) {
563 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
564 if (m_lightUBOMapped[i]) {
565 vkUnmapMemory(device, m_lightUBOMemory[i]);
566 m_lightUBOMapped[i] = nullptr;
567 }
568 if (m_lightUBOBuffers[i]) {
569 vkDestroyBuffer(device, m_lightUBOBuffers[i], nullptr);
570 m_lightUBOBuffers[i] = VK_NULL_HANDLE;
571 }
572 if (m_lightUBOMemory[i]) {
573 vkFreeMemory(device, m_lightUBOMemory[i], nullptr);
574 m_lightUBOMemory[i] = VK_NULL_HANDLE;
575 }
576 }
577 m_lightUBOCreated = false;
578 }
579
580 if (m_lightUBODescriptorPool) {
581 vkDestroyDescriptorPool(device, m_lightUBODescriptorPool, nullptr);
582 m_lightUBODescriptorPool = VK_NULL_HANDLE;
583 }
584
586}
587
588/// Marks the shadow pass active and invalidates the push constant cache.
590 m_shadowPassActive = true;
591 m_shadowPCCacheValid = false;
592 m_shadowPCPushedLayout = VK_NULL_HANDLE;
593}
594
595/// Marks the shadow pass inactive.
597 m_shadowPassActive = false;
598}
599
600/// Copies light and shadow data into the current frame's mapped UBO. LightVP
601/// is replaced by the matrix the shadow map was rendered with, since the map
602/// is recorded in BeginRender before the caller stages a newer one.
603void VulkanRenderer::UpdateShadowLightUBO(const void* data, uint32_t size) {
604 if (!m_lightUBOCreated || !data) return;
605 uint32_t copySize = std::min(size, static_cast<uint32_t>(sizeof(ShadowLightUBO)));
606 memcpy(m_lightUBOMapped[currentFrame], data, copySize);
607
608 constexpr size_t kLightVPOffset = offsetof(ShadowLightUBO, LightVP);
609 if (m_shadowMapRendered &&
610 copySize >= kLightVPOffset + sizeof(m_shadowMapLightVP)) {
611 char* dst = static_cast<char*>(m_lightUBOMapped[currentFrame]);
612 memcpy(dst + kLightVPOffset, m_shadowMapLightVP,
613 sizeof(m_shadowMapLightVP));
614 }
615}
616
617/// Stages the light view-projection matrix for commit at the next BeginRender.
618void VulkanRenderer::SetLightVP(const float* lightVP) {
619 // Stage only — commit happens at the next BeginRender. This keeps
620 // m_lightVP frozen for the duration of a frame so the shadow pass and
621 // the main pass agree on the transform (fixes per-frame shadow jitter
622 // caused by LightManager::UpdateAndBind mutating m_lightVP mid-frame,
623 // between the shadow pass and the main pass).
624 if (lightVP) {
625 memcpy(m_pendingLightVP, lightVP, sizeof(m_pendingLightVP));
626 m_hasPendingLightVP = true;
627 }
628}
629
630} // namespace RenderEngine
631} // namespace Sleak
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SHADOW_DEPTH_BIAS_CONSTANT
#define SHADOW_DEPTH_BIAS_SLOPE
void SetLightVP(const float *lightVP) override
Stages the light view-projection matrix for commit at the next BeginRender.
virtual void BeginShadowPass() override
Marks the shadow pass active and invalidates the push constant cache.
virtual void EndShadowPass() override
Marks the shadow pass inactive.
void UpdateShadowLightUBO(const void *data, uint32_t size) override
Copies light and shadow data into the current frame's mapped UBO.
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
Shadow-pass UBO: light/shadow parameters, fog, and extra fill lights (set 2, binding 0).