SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanDescriptors.cpp
Go to the documentation of this file.
1#include <Core/Window.hpp>
2#include <algorithm>
3#include <array>
4#include <cstring>
5#include <vector>
6
9#include "Core/Logger.hpp"
10
11namespace Sleak {
12 namespace RenderEngine {
13
14/// Creates the texture, bone UBO, light UBO, and shadow sampler descriptor set layouts.
15bool VulkanRenderer::CreateDescriptorSetLayout() {
16 // Set 0: texture sampler
17 VkDescriptorSetLayoutBinding samplerBinding{};
18 samplerBinding.binding = 0;
19 samplerBinding.descriptorType =
20 VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
21 samplerBinding.descriptorCount = 1;
22 samplerBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
23 samplerBinding.pImmutableSamplers = nullptr;
24
25 VkDescriptorSetLayoutCreateInfo layoutInfo{};
26 layoutInfo.sType =
27 VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
28 layoutInfo.bindingCount = 1;
29 layoutInfo.pBindings = &samplerBinding;
30
31 if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr,
32 &descriptorSetLayout) != VK_SUCCESS)
33 SLEAK_RETURN_ERR("Failed to create descriptor set layout!");
34
35 // Set 1: bone UBO (for skeletal animation)
36 VkDescriptorSetLayoutBinding boneUBOBinding{};
37 boneUBOBinding.binding = 0;
38 boneUBOBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
39 boneUBOBinding.descriptorCount = 1;
40 boneUBOBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
41 boneUBOBinding.pImmutableSamplers = nullptr;
42
43 VkDescriptorSetLayoutCreateInfo boneLayoutInfo{};
44 boneLayoutInfo.sType =
45 VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
46 boneLayoutInfo.bindingCount = 1;
47 boneLayoutInfo.pBindings = &boneUBOBinding;
48
49 if (vkCreateDescriptorSetLayout(device, &boneLayoutInfo, nullptr,
50 &boneDescriptorSetLayout) != VK_SUCCESS)
51 SLEAK_RETURN_ERR("Failed to create bone descriptor set layout!");
52
53 // Set 2: light/shadow UBO
54 VkDescriptorSetLayoutBinding lightUBOBinding{};
55 lightUBOBinding.binding = 0;
56 lightUBOBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
57 lightUBOBinding.descriptorCount = 1;
58 lightUBOBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
59 lightUBOBinding.pImmutableSamplers = nullptr;
60
61 VkDescriptorSetLayoutCreateInfo lightUBOLayoutInfo{};
62 lightUBOLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
63 lightUBOLayoutInfo.bindingCount = 1;
64 lightUBOLayoutInfo.pBindings = &lightUBOBinding;
65
66 if (vkCreateDescriptorSetLayout(device, &lightUBOLayoutInfo, nullptr,
67 &m_lightUBODescriptorSetLayout) != VK_SUCCESS)
68 SLEAK_RETURN_ERR("Failed to create light UBO descriptor set layout!");
69
70 // Set 3: shadow map samplers — binding 0 = compare sampler (PCF),
71 // binding 1 = raw sampler (PCSS blocker
72 // search)
73 // Bindings 2-5: scene color, depth, sky, SceneReadUBO (scene-read formats)
74 std::array<VkDescriptorSetLayoutBinding, SET3_BINDING_COUNT>
75 shadowSamplerBindings{};
76 for (uint32_t b = 0; b < shadowSamplerBindings.size(); ++b) {
77 shadowSamplerBindings[b].binding = b;
78 shadowSamplerBindings[b].descriptorType =
79 VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
80 shadowSamplerBindings[b].descriptorCount = 1;
81 shadowSamplerBindings[b].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
82 shadowSamplerBindings[b].pImmutableSamplers = nullptr;
83 }
84 shadowSamplerBindings[SCENE_UBO_BINDING].descriptorType =
85 VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
86 shadowSamplerBindings[SCENE_UBO_BINDING].stageFlags =
87 VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
88
89 VkDescriptorSetLayoutCreateInfo shadowSamplerLayoutInfo{};
90 shadowSamplerLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
91 shadowSamplerLayoutInfo.bindingCount = static_cast<uint32_t>(shadowSamplerBindings.size());
92 shadowSamplerLayoutInfo.pBindings = shadowSamplerBindings.data();
93
94 if (vkCreateDescriptorSetLayout(device, &shadowSamplerLayoutInfo, nullptr,
95 &m_shadowSamplerDescriptorSetLayout) != VK_SUCCESS)
96 SLEAK_RETURN_ERR("Failed to create shadow sampler descriptor set layout!");
97
98 return true;
99}
100
101
102/// Creates the descriptor pool backing the per-texture descriptor sets.
103bool VulkanRenderer::CreateDescriptorPool() {
104 uint32_t imageCount =
105 static_cast<uint32_t>(swapChainImages.size());
106
107 // Allow up to 128 textures, each needing imageCount descriptor sets
108 static constexpr uint32_t MAX_TEXTURES = 1024;
109 uint32_t totalSets = imageCount * MAX_TEXTURES;
110
111 VkDescriptorPoolSize poolSize{};
112 poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
113 poolSize.descriptorCount = totalSets;
114
115 VkDescriptorPoolCreateInfo poolInfo{};
116 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
117 poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
118 poolInfo.poolSizeCount = 1;
119 poolInfo.pPoolSizes = &poolSize;
120 poolInfo.maxSets = totalSets;
121
122 if (vkCreateDescriptorPool(device, &poolInfo, nullptr,
123 &descriptorPool) != VK_SUCCESS)
124 SLEAK_RETURN_ERR("Failed to create descriptor pool!");
125
126 return true;
127}
128
129
130/// Allocates one texture descriptor set per swapchain image.
131bool VulkanRenderer::AllocateDescriptorSets() {
132 uint32_t imageCount =
133 static_cast<uint32_t>(swapChainImages.size());
134
135 std::vector<VkDescriptorSetLayout> layouts(imageCount,
136 descriptorSetLayout);
137
138 VkDescriptorSetAllocateInfo allocInfo{};
139 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
140 allocInfo.descriptorPool = descriptorPool;
141 allocInfo.descriptorSetCount = imageCount;
142 allocInfo.pSetLayouts = layouts.data();
143
144 descriptorSets.resize(imageCount);
145 if (vkAllocateDescriptorSets(device, &allocInfo,
146 descriptorSets.data()) != VK_SUCCESS)
147 SLEAK_RETURN_ERR("Failed to allocate descriptor sets!");
148
149 return true;
150}
151
152
153/// Creates the fallback 1x1 white texture and writes it into the global descriptor sets.
154bool VulkanRenderer::CreateDefaultTexture() {
155 // Create a 1x1 white pixel texture as fallback so descriptor sets
156 // are always valid, even when no user texture is loaded.
157 uint32_t whitePixel = 0xFFFFFFFF; // RGBA(255,255,255,255)
158 m_defaultTexture = new VulkanTexture(device, physicalDevice, commands,
159 graphicsQueue);
160 if (!m_defaultTexture->LoadFromMemory(&whitePixel, 1, 1,
162 delete m_defaultTexture;
163 m_defaultTexture = nullptr;
164 return false;
165 }
166
167 // Allocate per-texture descriptor sets for the default texture
168 WriteTextureDescriptors(m_defaultTexture);
169
170 // Also write the default texture to the global descriptor sets
171 // (used as initial binding in BeginRender)
172 for (size_t i = 0; i < descriptorSets.size(); i++) {
173 VkDescriptorImageInfo imageInfo{};
174 imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
175 imageInfo.imageView = m_defaultTexture->GetImageView();
176 imageInfo.sampler = m_defaultTexture->GetSampler();
177
178 VkWriteDescriptorSet descriptorWrite{};
179 descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
180 descriptorWrite.dstSet = descriptorSets[i];
181 descriptorWrite.dstBinding = 0;
182 descriptorWrite.dstArrayElement = 0;
183 descriptorWrite.descriptorType =
184 VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
185 descriptorWrite.descriptorCount = 1;
186 descriptorWrite.pImageInfo = &imageInfo;
187
188 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
189 }
190 m_textureDescriptorsWritten = true;
191
192 return true;
193}
194
195
196/// Allocates and writes a per-texture descriptor set for the given texture.
197void VulkanRenderer::WriteTextureDescriptors(VulkanTexture* texture) {
198 if (!texture || texture->GetImageView() == VK_NULL_HANDLE ||
199 texture->GetSampler() == VK_NULL_HANDLE)
200 return;
201
202 uint32_t imageCount = static_cast<uint32_t>(swapChainImages.size());
203
204 // Allocate per-texture descriptor sets (one per swapchain image)
205 std::vector<VkDescriptorSetLayout> layouts(imageCount, descriptorSetLayout);
206
207 VkDescriptorSetAllocateInfo allocInfo{};
208 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
209 allocInfo.descriptorPool = descriptorPool;
210 allocInfo.descriptorSetCount = imageCount;
211 allocInfo.pSetLayouts = layouts.data();
212
213 std::vector<VkDescriptorSet> sets(imageCount);
214 if (vkAllocateDescriptorSets(device, &allocInfo, sets.data()) != VK_SUCCESS) {
215 SLEAK_ERROR("VulkanRenderer: Failed to allocate descriptor sets for texture");
216 return;
217 }
218
219 // Write the texture's imageView/sampler to each descriptor set
220 for (size_t i = 0; i < sets.size(); i++) {
221 VkDescriptorImageInfo imageInfo{};
222 imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
223 imageInfo.imageView = texture->GetImageView();
224 imageInfo.sampler = texture->GetSampler();
225
226 VkWriteDescriptorSet descriptorWrite{};
227 descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
228 descriptorWrite.dstSet = sets[i];
229 descriptorWrite.dstBinding = 0;
230 descriptorWrite.dstArrayElement = 0;
231 descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
232 descriptorWrite.descriptorCount = 1;
233 descriptorWrite.pImageInfo = &imageInfo;
234
235 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
236 }
237
238 texture->SetDescriptorSets(std::move(sets), descriptorPool);
239}
240
241/// Initializes ImGui and its Vulkan backend against the active render pass.
243 if (!device || !instance || !graphicsQueue)
244 return false;
245
246 // In deferred mode, ImGui renders inside the bloom COMPOSITE pass (swapchain
247 // target, post-tonemap). Forward pass can't host ImGui because its output
248 // is linear HDR and it ends in SHADER_READ_ONLY_OPTIMAL for bloom sampling.
249 VkRenderPass imguiRenderPass = VK_NULL_HANDLE;
250 if (m_gbufferResourcesCreated && m_deferredEnabled && m_bloomCompositeRenderPass != VK_NULL_HANDLE) {
251 imguiRenderPass = m_bloomCompositeRenderPass;
252 } else if (m_gbufferResourcesCreated && m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE) {
253 imguiRenderPass = m_forwardRenderPass;
254 } else {
255 imguiRenderPass = renderPass;
256 }
257
258 if (!imguiRenderPass)
259 return false;
260
261 // ImGui backend allocates split SAMPLED_IMAGE + SAMPLER sets, not COMBINED_IMAGE_SAMPLER
262 VkDescriptorPoolSize poolSizes[] = {
263 {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 64},
264 {VK_DESCRIPTOR_TYPE_SAMPLER, IMGUI_IMPL_VULKAN_MINIMUM_SAMPLER_POOL_SIZE},
265 };
266
267 VkDescriptorPoolCreateInfo poolInfo{};
268 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
269 poolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
270 poolInfo.maxSets = 64 + IMGUI_IMPL_VULKAN_MINIMUM_SAMPLER_POOL_SIZE;
271 poolInfo.poolSizeCount = 2;
272 poolInfo.pPoolSizes = poolSizes;
273
274 if (vkCreateDescriptorPool(device, &poolInfo, nullptr,
275 &imguiDescriptorPool) != VK_SUCCESS) {
276 SLEAK_ERROR("Failed to create ImGUI descriptor pool!");
277 return false;
278 }
279
280 IMGUI_CHECKVERSION();
281 ImGui::CreateContext();
282 ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
283 ImGui::StyleColorsDark();
284
285 if (!ImGui_ImplSDL3_InitForVulkan(sdlWindow->GetSDLWindow()))
286 return false;
287
288 ImGui_ImplVulkan_InitInfo initInfo{};
289 initInfo.Instance = instance;
290 initInfo.PhysicalDevice = physicalDevice;
291 initInfo.Device = device;
292 initInfo.QueueFamily = QueueIDs.GraphicsIndex;
293 initInfo.Queue = graphicsQueue;
294 initInfo.PipelineCache = m_pipelineCache;
295 initInfo.DescriptorPool = imguiDescriptorPool;
296 initInfo.MinImageCount = 2;
297 initInfo.ImageCount =
298 static_cast<uint32_t>(swapChainImages.size());
299 initInfo.PipelineInfoMain.MSAASamples = (m_gbufferResourcesCreated && m_deferredEnabled)
300 ? VK_SAMPLE_COUNT_1_BIT : m_msaaSamples;
301 initInfo.PipelineInfoMain.RenderPass = imguiRenderPass;
302 initInfo.PipelineInfoMain.Subpass = 0;
303
304 if (!ImGui_ImplVulkan_Init(&initInfo))
305 return false;
306
307 bImInitialized = true;
308 return true;
309}
310
311/// Creates each frame's first bone ring chunk; slot 0 holds identity.
312bool VulkanRenderer::CreateBoneUBOResources() {
313 if (m_boneUBOCreated) return true;
314
315 VkPhysicalDeviceProperties props{};
316 vkGetPhysicalDeviceProperties(physicalDevice, &props);
317 const VkDeviceSize align = props.limits.minUniformBufferOffsetAlignment;
318 m_boneSlotStride = BONE_PALETTE_BYTES;
319 if (align > 0)
320 m_boneSlotStride = (m_boneSlotStride + align - 1) / align * align;
321
322 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
323 if (!AddBoneUBOChunk(i)) {
324 CleanupBoneUBOResources();
325 return false;
326 }
327
328 // Identity palette in slot 0
329 auto* matrices = static_cast<float*>(m_boneChunks[i][0].mapped);
330 for (uint32_t b = 0; b < BONE_PALETTE_BYTES / BONE_MATRIX_BYTES; ++b) {
331 for (int c = 0; c < 16; ++c)
332 matrices[b * 16 + c] = (c % 5 == 0) ? 1.0f : 0.0f;
333 }
334 m_boneSlot[i] = 1;
335 }
336
337 m_boneUBOCreated = true;
339 "VulkanRenderer: Bone UBO ring created ({} x {} bytes per frame)",
340 BONE_SLOTS_PER_CHUNK, m_boneSlotStride);
341 return true;
342}
343
344/// Appends BONE_SLOTS_PER_CHUNK palette slots to one frame's bone ring: its
345/// own buffer and dynamic-UBO set, so sets bound earlier stay valid.
346bool VulkanRenderer::AddBoneUBOChunk(uint32_t frame) {
347 BoneUBOChunk chunk{};
348
349 VkDescriptorPoolSize poolSize{};
350 poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
351 poolSize.descriptorCount = 1;
352
353 VkDescriptorPoolCreateInfo poolInfo{};
354 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
355 poolInfo.poolSizeCount = 1;
356 poolInfo.pPoolSizes = &poolSize;
357 poolInfo.maxSets = 1;
358 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &chunk.pool) !=
359 VK_SUCCESS) {
360 SLEAK_ERROR("Failed to create bone descriptor pool!");
361 return false;
362 }
363
364 VkDescriptorSetAllocateInfo dsAllocInfo{};
365 dsAllocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
366 dsAllocInfo.descriptorPool = chunk.pool;
367 dsAllocInfo.descriptorSetCount = 1;
368 dsAllocInfo.pSetLayouts = &boneDescriptorSetLayout;
369 if (vkAllocateDescriptorSets(device, &dsAllocInfo, &chunk.set) !=
370 VK_SUCCESS) {
371 SLEAK_ERROR("Failed to allocate bone descriptor set!");
372 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
373 return false;
374 }
375
376 // Host-visible, coherent for fast CPU writes
377 const VkDeviceSize size = m_boneSlotStride * BONE_SLOTS_PER_CHUNK;
378 VkBufferCreateInfo bufferInfo{};
379 bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
380 bufferInfo.size = size;
381 bufferInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
382 bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
383 if (vkCreateBuffer(device, &bufferInfo, nullptr, &chunk.buffer) !=
384 VK_SUCCESS) {
385 SLEAK_ERROR("Failed to create bone UBO buffer!");
386 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
387 return false;
388 }
389
390 VkMemoryRequirements memReqs;
391 vkGetBufferMemoryRequirements(device, chunk.buffer, &memReqs);
392 VkMemoryAllocateInfo allocInfo{};
393 allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
394 allocInfo.allocationSize = memReqs.size;
395 allocInfo.memoryTypeIndex = FindMemoryType(
396 memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
397 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
398 if (vkAllocateMemory(device, &allocInfo, nullptr, &chunk.memory) !=
399 VK_SUCCESS) {
400 SLEAK_ERROR("Failed to allocate bone UBO memory!");
401 vkDestroyBuffer(device, chunk.buffer, nullptr);
402 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
403 return false;
404 }
405 vkBindBufferMemory(device, chunk.buffer, chunk.memory, 0);
406 vkMapMemory(device, chunk.memory, 0, size, 0, &chunk.mapped);
407
408 // One palette range; binds select the slot by dynamic offset
409 VkDescriptorBufferInfo bufInfo{};
410 bufInfo.buffer = chunk.buffer;
411 bufInfo.offset = 0;
412 bufInfo.range = BONE_PALETTE_BYTES;
413
414 VkWriteDescriptorSet descriptorWrite{};
415 descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
416 descriptorWrite.dstSet = chunk.set;
417 descriptorWrite.dstBinding = 0;
418 descriptorWrite.dstArrayElement = 0;
419 descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
420 descriptorWrite.descriptorCount = 1;
421 descriptorWrite.pBufferInfo = &bufInfo;
422 vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr);
423
424 m_boneChunks[frame].push_back(chunk);
425 if (m_boneChunks[frame].size() > 1)
426 SLEAK_INFO("VulkanRenderer: frame {} bone ring grew to {} slots", frame,
427 m_boneChunks[frame].size() * BONE_SLOTS_PER_CHUNK);
428 return true;
429}
430
431/// Destroys every bone ring chunk of every frame.
432void VulkanRenderer::CleanupBoneUBOResources() {
433 for (auto& chunks : m_boneChunks) {
434 for (BoneUBOChunk& chunk : chunks) {
435 if (chunk.mapped) vkUnmapMemory(device, chunk.memory);
436 if (chunk.buffer) vkDestroyBuffer(device, chunk.buffer, nullptr);
437 if (chunk.memory) vkFreeMemory(device, chunk.memory, nullptr);
438 if (chunk.pool)
439 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
440 }
441 chunks.clear();
442 }
443 m_boneUBOCreated = false;
444}
445
446/// Binds the identity palette (ring slot 0) at set 1.
447void VulkanRenderer::BindIdentityBonePalette(VkPipelineLayout layout) {
448 if (!m_boneUBOCreated || m_boneChunks[currentFrame].empty()) return;
449 const uint32_t offset = 0;
450 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 1,
451 1, &m_boneChunks[currentFrame][0].set, 1, &offset);
452}
453
454/// Copies bone matrices into this bind's own slot of the frame's bone ring
455/// and binds set 1 at that slot, so every skinned draw keeps its palette.
457 if (!bFrameStarted) return;
458 if (!buffer) return;
459
460 // Lazily create bone UBO resources on first use
461 if (!m_boneUBOCreated) {
462 if (!CreateBoneUBOResources()) return;
463 }
464
465 auto* vkBuf = static_cast<VulkanBuffer*>(buffer.get());
466 if (!vkBuf) return;
467
468 void* data = vkBuf->GetData();
469 if (!data) return;
470
471 uint32_t size = static_cast<uint32_t>(vkBuf->GetSize());
472 if (size > BONE_PALETTE_BYTES) size = BONE_PALETTE_BYTES;
473
474 // Claim the next ring slot (use currentFrame, not CurrentFrameIndex
475 // which is the swapchain image index and can exceed MAX_FRAMES_IN_FLIGHT)
476 const uint32_t slot = m_boneSlot[currentFrame];
477 auto& chunks = m_boneChunks[currentFrame];
478 const uint32_t chunkIdx = slot / BONE_SLOTS_PER_CHUNK;
479 if (chunkIdx >= chunks.size() && !AddBoneUBOChunk(currentFrame)) return;
480 const BoneUBOChunk& chunk = chunks[chunkIdx];
481 const uint32_t offset =
482 static_cast<uint32_t>((slot % BONE_SLOTS_PER_CHUNK) * m_boneSlotStride);
483 memcpy(static_cast<char*>(chunk.mapped) + offset, data, size);
484 m_boneSlot[currentFrame] = slot + 1;
485
486 // Bind bone descriptor set at set index 1.
487 // In the GBuffer geometry pass the active layout is m_gbufferGeomLayout;
488 // outside it pipelineLay is active. The layout used here must match the
489 // pipeline that will draw, because Vulkan invalidates sets when layouts
490 // are incompatible at lower-numbered sets (set 0 differs between the two).
491 VkPipelineLayout boneBindLayout = (m_inGeometryPass && m_gbufferGeomLayout != VK_NULL_HANDLE)
492 ? m_gbufferGeomLayout : pipelineLay;
493 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
494 boneBindLayout, 1, 1, &chunk.set, 1, &offset);
495}
496
497/// Creates the per-frame PBR material descriptor set (set 0 in GBuffer pass):
498/// bindings 0-5 are combined image samplers, binding 6 is the params UBO.
499/// Also creates m_gbufferGeomLayout used by the GBuffer pipeline.
500bool VulkanRenderer::CreatePBRMaterialResources() {
501 if (m_pbrMaterialResourcesCreated) return true;
502
503 // --- Descriptor Set Layout ---
504 std::array<VkDescriptorSetLayoutBinding, 7> bindings{};
505 for (uint32_t i = 0; i < 6; ++i) {
506 bindings[i].binding = i;
507 bindings[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
508 bindings[i].descriptorCount = 1;
509 bindings[i].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
510 }
511 bindings[6].binding = 6;
512 bindings[6].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
513 bindings[6].descriptorCount = 1;
514 bindings[6].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
515
516 VkDescriptorSetLayoutCreateInfo dslInfo{};
517 dslInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
518 dslInfo.bindingCount = 7;
519 dslInfo.pBindings = bindings.data();
520 if (vkCreateDescriptorSetLayout(device, &dslInfo, nullptr, &m_pbrMaterialDSL) != VK_SUCCESS) {
521 SLEAK_ERROR("PBR: Failed to create PBR material DSL!");
522 return false;
523 }
524
525 // --- Material params UBO stride, then one starting chunk per frame ---
526 VkPhysicalDeviceProperties props{};
527 vkGetPhysicalDeviceProperties(physicalDevice, &props);
528 VkDeviceSize minAlign = props.limits.minUniformBufferOffsetAlignment;
529 VkDeviceSize stride = sizeof(PBRMaterialParams);
530 if (minAlign > 0)
531 stride = ((stride + minAlign - 1) / minAlign) * minAlign;
532 m_pbrMaterialUBOStride = stride;
533 for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; ++i) {
534 if (!AddPBRMaterialChunk(i)) return false;
535 }
536
537 // --- GBuffer geometry pipeline layout ---
538 // Set 0: PBR material DSL, Set 1: bone DSL, Set 2: lightUBO DSL, Set 3: shadow sampler DSL
539 // Push constants: VK_SHADER_STAGE_VERTEX_BIT, offset=0, size=128 (WVP + World)
540 std::array<VkDescriptorSetLayout, 4> geomSetLayouts = {
541 m_pbrMaterialDSL,
542 boneDescriptorSetLayout,
543 m_lightUBODescriptorSetLayout,
544 m_shadowSamplerDescriptorSetLayout
545 };
546 VkPushConstantRange pcRange{};
547 pcRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
548 pcRange.offset = 0;
549 pcRange.size = 128;
550
551 VkPipelineLayoutCreateInfo layoutInfo{};
552 layoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
553 layoutInfo.setLayoutCount = static_cast<uint32_t>(geomSetLayouts.size());
554 layoutInfo.pSetLayouts = geomSetLayouts.data();
555 layoutInfo.pushConstantRangeCount = 1;
556 layoutInfo.pPushConstantRanges = &pcRange;
557 if (vkCreatePipelineLayout(device, &layoutInfo, nullptr, &m_gbufferGeomLayout) != VK_SUCCESS) {
558 SLEAK_ERROR("PBR: Failed to create GBuffer geometry pipeline layout!");
559 return false;
560 }
561
562 m_pbrMaterialResourcesCreated = true;
563 SLEAK_INFO("VulkanRenderer: PBR material resources created");
564 return true;
565}
566
567/// Allocates a descriptor pool, PBR_SETS_PER_FRAME sets and a mapped UBO for
568/// one frame.
569bool VulkanRenderer::AddPBRMaterialChunk(uint32_t frame) {
570 PBRMaterialChunk chunk{};
571
572 std::array<VkDescriptorPoolSize, 2> poolSizes{};
573 poolSizes[0].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
574 poolSizes[0].descriptorCount = 6 * PBR_SETS_PER_FRAME;
575 poolSizes[1].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
576 poolSizes[1].descriptorCount = 1 * PBR_SETS_PER_FRAME;
577
578 VkDescriptorPoolCreateInfo poolInfo{};
579 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
580 poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
581 poolInfo.pPoolSizes = poolSizes.data();
582 poolInfo.maxSets = PBR_SETS_PER_FRAME;
583 if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &chunk.pool) !=
584 VK_SUCCESS) {
585 SLEAK_ERROR("PBR: Failed to create PBR material pool!");
586 return false;
587 }
588
589 std::array<VkDescriptorSetLayout, PBR_SETS_PER_FRAME> layouts;
590 layouts.fill(m_pbrMaterialDSL);
591 VkDescriptorSetAllocateInfo allocInfo{};
592 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
593 allocInfo.descriptorPool = chunk.pool;
594 allocInfo.descriptorSetCount = PBR_SETS_PER_FRAME;
595 allocInfo.pSetLayouts = layouts.data();
596 if (vkAllocateDescriptorSets(device, &allocInfo, chunk.sets.data()) !=
597 VK_SUCCESS) {
598 SLEAK_ERROR("PBR: Failed to allocate PBR material descriptor sets!");
599 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
600 return false;
601 }
602
603 const VkDeviceSize uboSize = m_pbrMaterialUBOStride * PBR_SETS_PER_FRAME;
604 VkBufferCreateInfo bufInfo{};
605 bufInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
606 bufInfo.size = uboSize;
607 bufInfo.usage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT;
608 bufInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
609 if (vkCreateBuffer(device, &bufInfo, nullptr, &chunk.ubo) != VK_SUCCESS) {
610 SLEAK_ERROR("PBR: Failed to create material UBO buffer for frame {}!",
611 frame);
612 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
613 return false;
614 }
615
616 VkMemoryRequirements memReqs;
617 vkGetBufferMemoryRequirements(device, chunk.ubo, &memReqs);
618 VkMemoryAllocateInfo memInfo{};
619 memInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
620 memInfo.allocationSize = memReqs.size;
621 memInfo.memoryTypeIndex = FindMemoryType(
622 memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
623 VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
624 if (vkAllocateMemory(device, &memInfo, nullptr, &chunk.memory) !=
625 VK_SUCCESS) {
626 SLEAK_ERROR("PBR: Failed to allocate material UBO memory for frame {}!",
627 frame);
628 vkDestroyBuffer(device, chunk.ubo, nullptr);
629 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
630 return false;
631 }
632 vkBindBufferMemory(device, chunk.ubo, chunk.memory, 0);
633 vkMapMemory(device, chunk.memory, 0, uboSize, 0, &chunk.mapped);
634
635 m_pbrMaterialChunks[frame].push_back(chunk);
636 if (m_pbrMaterialChunks[frame].size() > 1)
637 SLEAK_INFO("PBR: frame {} material ring grew to {} sets", frame,
638 m_pbrMaterialChunks[frame].size() * PBR_SETS_PER_FRAME);
639 return true;
640}
641
642/// Frees every chunk's UBO, memory and descriptor pool for all frames.
643void VulkanRenderer::DestroyPBRMaterialChunks() {
644 for (auto& chunks : m_pbrMaterialChunks) {
645 for (auto& chunk : chunks) {
646 if (chunk.mapped) vkUnmapMemory(device, chunk.memory);
647 if (chunk.ubo) vkDestroyBuffer(device, chunk.ubo, nullptr);
648 if (chunk.memory) vkFreeMemory(device, chunk.memory, nullptr);
649 if (chunk.pool)
650 vkDestroyDescriptorPool(device, chunk.pool, nullptr);
651 }
652 chunks.clear();
653 }
654}
655
656/// Writes a material's textures and params into its ring slot and binds it at set 0.
658 if (!bFrameStarted || !m_pbrMaterialResourcesCreated || !material) return;
659
660 // Switch to the default GBuffer pipeline and drop the active custom format
661 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_gbufferPipeline);
662 m_activeCustomFormat = 0;
663
664 // Build PBRMaterialParams from Material properties
665 PBRMaterialParams params{};
666 auto dc = material->GetDiffuseColor();
667 params.albedoFactorR = dc.GetR() / 255.0f;
668 params.albedoFactorG = dc.GetG() / 255.0f;
669 params.albedoFactorB = dc.GetB() / 255.0f;
670 params.albedoFactorA = material->GetOpacity();
671 params.metallicFactor = material->GetMetallic();
672 params.roughnessFactor = material->GetRoughness();
673 params.aoFactor = material->GetAO();
674 params.normalIntensity = material->GetNormalIntensity();
675 auto ec = material->GetEmissiveColor();
676 params.emissiveR = ec.GetR() / 255.0f;
677 params.emissiveG = ec.GetG() / 255.0f;
678 params.emissiveB = ec.GetB() / 255.0f;
679 params.emissiveIntensity = material->GetEmissiveIntensity();
680 auto tiling = material->GetTiling();
681 params.tilingX = tiling.GetX();
682 params.tilingY = tiling.GetY();
683 auto offset = material->GetOffset();
684 params.offsetX = offset.GetX();
685 params.offsetY = offset.GetY();
686 params.hasNormalMap = material->HasNormalTexture() ? 1u : 0u;
687 params.hasMetallicMap = material->HasMetallicTexture() ? 1u : 0u;
688 params.hasRoughnessMap = material->HasRoughnessTexture() ? 1u : 0u;
689 params.hasAOMap = material->HasAOTexture() ? 1u : 0u;
690 params.hasEmissiveMap = material->HasEmissiveTexture() ? 1u : 0u;
691
692 // Resolve textures — fall back to the default white 1×1 texture if absent
693 auto resolveView = [&](Texture* tex) -> VkImageView {
694 auto* vt = tex ? static_cast<VulkanTexture*>(tex) : nullptr;
695 if (!vt && m_defaultTexture) vt = m_defaultTexture;
696 return vt ? vt->GetImageView() : VK_NULL_HANDLE;
697 };
698 auto resolveSampler = [&](Texture* tex) -> VkSampler {
699 auto* vt = tex ? static_cast<VulkanTexture*>(tex) : nullptr;
700 if (!vt && m_defaultTexture) vt = m_defaultTexture;
701 return vt ? vt->GetSampler() : VK_NULL_HANDLE;
702 };
703
704 Texture* textures[PBR_TEXTURE_COUNT] = {
705 material->GetDiffuseTexture(),
706 material->HasNormalTexture() ? material->GetNormalTexture() : nullptr,
707 material->HasMetallicTexture() ? material->GetMetallicTexture()
708 : nullptr,
709 material->HasRoughnessTexture() ? material->GetRoughnessTexture()
710 : nullptr,
711 material->HasAOTexture() ? material->GetAOTexture() : nullptr,
712 material->HasEmissiveTexture() ? material->GetEmissiveTexture()
713 : nullptr,
714 };
715
716 std::array<VkDescriptorImageInfo, PBR_TEXTURE_COUNT> imageInfos{};
717 for (uint32_t i = 0; i < PBR_TEXTURE_COUNT; ++i) {
718 imageInfos[i].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
719 imageInfos[i].imageView = resolveView(textures[i]);
720 imageInfos[i].sampler = resolveSampler(textures[i]);
721 }
722
723 // Same material with unchanged contents this frame: rebind its set
724 auto& bindings = m_pbrMaterialBindings[currentFrame];
725 auto cached = bindings.find(material);
726 if (cached != bindings.end() &&
727 memcmp(&cached->second.params, &params, sizeof(params)) == 0 &&
728 std::equal(
729 imageInfos.begin(), imageInfos.end(), cached->second.images.begin(),
730 [](const VkDescriptorImageInfo& a, const VkDescriptorImageInfo& b) {
731 return a.sampler == b.sampler && a.imageView == b.imageView &&
732 a.imageLayout == b.imageLayout;
733 })) {
734 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
735 m_gbufferGeomLayout, 0, 1, &cached->second.set,
736 0, nullptr);
737 return;
738 }
739
740 // Claim this material's own ring slot (own set + own UBO region) so the
741 // set is never rewritten while already bound by a prior draw this frame.
742 const uint32_t slot = m_pbrMaterialSlot[currentFrame];
743 auto& chunks = m_pbrMaterialChunks[currentFrame];
744 const uint32_t chunkIdx = slot / PBR_SETS_PER_FRAME;
745 if (chunkIdx >= chunks.size() && !AddPBRMaterialChunk(currentFrame)) return;
746 PBRMaterialChunk& chunk = chunks[chunkIdx];
747 const uint32_t local = slot % PBR_SETS_PER_FRAME;
748 const VkDescriptorSet set = chunk.sets[local];
749 const VkDeviceSize uboOffset = local * m_pbrMaterialUBOStride;
750
751 if (chunk.mapped)
752 memcpy(static_cast<char*>(chunk.mapped) + uboOffset, &params,
753 sizeof(params));
754
755 VkDescriptorBufferInfo bufInfo{};
756 bufInfo.buffer = chunk.ubo;
757 bufInfo.offset = uboOffset;
758 bufInfo.range = sizeof(PBRMaterialParams);
759
760 std::array<VkWriteDescriptorSet, PBR_TEXTURE_COUNT + 1> writes{};
761 for (uint32_t i = 0; i < PBR_TEXTURE_COUNT; ++i) {
762 writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
763 writes[i].dstSet = set;
764 writes[i].dstBinding = i;
765 writes[i].dstArrayElement = 0;
766 writes[i].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
767 writes[i].descriptorCount = 1;
768 writes[i].pImageInfo = &imageInfos[i];
769 }
770 writes[PBR_TEXTURE_COUNT].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
771 writes[PBR_TEXTURE_COUNT].dstSet = set;
772 writes[PBR_TEXTURE_COUNT].dstBinding = PBR_TEXTURE_COUNT;
773 writes[PBR_TEXTURE_COUNT].dstArrayElement = 0;
774 writes[PBR_TEXTURE_COUNT].descriptorType =
775 VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
776 writes[PBR_TEXTURE_COUNT].descriptorCount = 1;
777 writes[PBR_TEXTURE_COUNT].pBufferInfo = &bufInfo;
778
779 vkUpdateDescriptorSets(device, static_cast<uint32_t>(writes.size()),
780 writes.data(), 0, nullptr);
781
782 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
783 m_gbufferGeomLayout, 0, 1, &set, 0, nullptr);
784
785 bindings[material] = {params, imageInfos, set};
786
787 // Advance the ring for the next material this frame.
788 m_pbrMaterialSlot[currentFrame] = slot + 1;
789}
790
791}
792}
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_RETURN_ERR(...)
Definition Logger.hpp:25
#define SLEAK_INFO(...)
Definition Logger.hpp:20
Math::Color GetEmissiveColor() const
Definition Material.cpp:338
Texture * GetRoughnessTexture() const
Definition Material.cpp:222
Texture * GetMetallicTexture() const
Definition Material.cpp:243
bool HasNormalTexture() const
Definition Material.cpp:184
Texture * GetNormalTexture() const
Definition Material.cpp:180
Texture * GetDiffuseTexture() const
Definition Material.cpp:159
bool HasEmissiveTexture() const
Definition Material.cpp:287
bool HasAOTexture() const
Definition Material.cpp:266
float GetOpacity() const
Definition Material.cpp:380
Texture * GetEmissiveTexture() const
Definition Material.cpp:283
float GetAO() const
Definition Material.cpp:362
bool HasRoughnessTexture() const
Definition Material.cpp:226
Math::Vector2D GetTiling() const
Definition Material.cpp:398
Math::Color GetDiffuseColor() const
Definition Material.cpp:308
Math::Vector2D GetOffset() const
Definition Material.cpp:412
Texture * GetAOTexture() const
Definition Material.cpp:264
float GetNormalIntensity() const
Definition Material.cpp:368
float GetRoughness() const
Definition Material.cpp:358
float GetMetallic() const
Definition Material.cpp:352
float GetEmissiveIntensity() const
Definition Material.cpp:374
bool HasMetallicTexture() const
Definition Material.cpp:247
T * get() const
Definition RefPtr.hpp:170
VMA-backed Vulkan buffer with staging uploads, batched copies, and a size-bucketed recycling pool.
virtual bool CreateImGUI() override
Initializes ImGui and its Vulkan backend against the active render pass.
virtual void BindPBRMaterial(Sleak::Material *material) override
Writes a material's textures and params into its ring slot and binds it at set 0.
virtual void BindBoneBuffer(RefPtr< BufferBase > buffer) override
Copies bone matrices into their own bone ring slot and binds it.
Vulkan 2D texture: image + view + sampler, with per-swapchain-image descriptor sets.
VulkanTexture(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue)
Backend-facing rendering layer shared by the four graphics backends.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10