SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
VulkanPipelines.cpp
Go to the documentation of this file.
2#include <array>
3#include <cstddef>
4#include <cstdint>
5#include <cstring>
6#include <filesystem>
7#include <fstream>
8#include <string>
9#include <system_error>
10#include <utility>
11#include <vector>
12
14#include "Core/Logger.hpp"
15
16namespace Sleak {
17 namespace RenderEngine {
18
19 namespace {
20
21 // Relative to the working directory, which is the executable's directory
22 constexpr const char* kPipelineCacheDir = "cache";
23 constexpr const char* kPipelineCachePath = "cache/vulkan_pipelines.bin";
24 constexpr const char* kPipelineCacheTempPath =
25 "cache/vulkan_pipelines.bin.tmp";
26 constexpr size_t kPipelineCacheHeaderSize =
27 sizeof(VkPipelineCacheHeaderVersionOne);
28#define FNV1A_OFFSET_BASIS 14695981039346656037ull
29#define FNV1A_PRIME 1099511628211ull
30
31 /// FNV-1a hash, used to skip rewriting an unchanged pipeline cache.
32 uint64_t HashBytes(const std::vector<char>& data) {
33 uint64_t hash = FNV1A_OFFSET_BASIS;
34 for (char c : data) {
35 hash ^= static_cast<uint8_t>(c);
36 hash *= FNV1A_PRIME;
37 }
38 return hash;
39 }
40
41 /// Reads one little-endian field of a pipeline cache header.
42 uint32_t ReadLE32(const char* bytes) {
43 const auto* b = reinterpret_cast<const uint8_t*>(bytes);
44 return static_cast<uint32_t>(b[0]) | static_cast<uint32_t>(b[1]) << 8 |
45 static_cast<uint32_t>(b[2]) << 16 |
46 static_cast<uint32_t>(b[3]) << 24;
47 }
48
49 } // namespace
50
51 /// Creates the pipeline cache, seeded from disk when the saved blob was
52 /// written by this device and driver.
53 void VulkanRenderer::CreatePipelineCache() {
54 std::vector<char> blob;
55 std::ifstream file(kPipelineCachePath,
56 std::ios::binary | std::ios::ate);
57 if (file) {
58 const std::streamoff size = file.tellg();
59 if (size > 0) {
60 blob.resize(static_cast<size_t>(size));
61 file.seekg(0);
62 if (!file.read(blob.data(), size)) blob.clear();
63 }
64 }
65 file.close();
66
67 // Header check
68 if (!blob.empty()) {
69 VkPhysicalDeviceProperties props{};
70 vkGetPhysicalDeviceProperties(physicalDevice, &props);
71 const bool valid =
72 blob.size() >= kPipelineCacheHeaderSize &&
73 ReadLE32(blob.data()) >= kPipelineCacheHeaderSize &&
74 ReadLE32(blob.data()) <= blob.size() &&
75 ReadLE32(blob.data() + offsetof(VkPipelineCacheHeaderVersionOne,
76 headerVersion)) ==
77 static_cast<uint32_t>(
78 VK_PIPELINE_CACHE_HEADER_VERSION_ONE) &&
79 ReadLE32(blob.data() + offsetof(VkPipelineCacheHeaderVersionOne,
80 vendorID)) == props.vendorID &&
81 ReadLE32(blob.data() + offsetof(VkPipelineCacheHeaderVersionOne,
82 deviceID)) == props.deviceID &&
83 std::memcmp(
84 blob.data() + offsetof(VkPipelineCacheHeaderVersionOne,
85 pipelineCacheUUID),
86 props.pipelineCacheUUID, VK_UUID_SIZE) == 0;
87 if (!valid) {
89 "Pipeline cache: ignoring blob from another device or "
90 "driver");
91 blob.clear();
92 }
93 }
94
95 VkPipelineCacheCreateInfo info{};
96 info.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
97 info.initialDataSize = blob.size();
98 info.pInitialData = blob.empty() ? nullptr : blob.data();
99 VkResult result =
100 vkCreatePipelineCache(device, &info, nullptr, &m_pipelineCache);
101 if (result != VK_SUCCESS && !blob.empty()) {
102 blob.clear();
103 info.initialDataSize = 0;
104 info.pInitialData = nullptr;
105 result =
106 vkCreatePipelineCache(device, &info, nullptr, &m_pipelineCache);
107 }
108 if (result != VK_SUCCESS) {
109 m_pipelineCache = VK_NULL_HANDLE;
111 "Pipeline cache: creation failed, pipelines compile uncached");
112 return;
113 }
114
115 m_pipelineCacheLoadedSize = blob.size();
116 m_pipelineCacheLoadedHash = blob.empty() ? 0 : HashBytes(blob);
117 SLEAK_INFO("Pipeline cache: {} ({} bytes)",
118 blob.empty() ? "empty" : "loaded", blob.size());
119 }
120
121 /// Saves the pipeline cache to disk when it changed, then destroys it.
122 /// Writes a temp file and renames it so a failed write never leaves a torn
123 /// cache.
124 void VulkanRenderer::DestroyPipelineCache() {
125 if (m_pipelineCache == VK_NULL_HANDLE) return;
126
127 std::vector<char> data;
128 size_t size = 0;
129 if (vkGetPipelineCacheData(device, m_pipelineCache, &size, nullptr) ==
130 VK_SUCCESS &&
131 size > 0) {
132 data.resize(size);
133 if (vkGetPipelineCacheData(device, m_pipelineCache, &size,
134 data.data()) == VK_SUCCESS)
135 data.resize(size);
136 else
137 data.clear();
138 }
139 vkDestroyPipelineCache(device, m_pipelineCache, nullptr);
140 m_pipelineCache = VK_NULL_HANDLE;
141
142 if (data.empty()) return;
143 if (data.size() == m_pipelineCacheLoadedSize &&
144 HashBytes(data) == m_pipelineCacheLoadedHash)
145 return;
146
147 std::error_code ec;
148 std::filesystem::create_directories(kPipelineCacheDir, ec);
149 std::ofstream out(kPipelineCacheTempPath,
150 std::ios::binary | std::ios::trunc);
151 out.write(data.data(), static_cast<std::streamsize>(data.size()));
152 out.close();
153 if (!out) {
154 SLEAK_WARN("Pipeline cache: could not write {}",
155 kPipelineCacheTempPath);
156 std::filesystem::remove(kPipelineCacheTempPath, ec);
157 return;
158 }
159 std::filesystem::rename(kPipelineCacheTempPath, kPipelineCachePath, ec);
160 if (ec) {
161 SLEAK_WARN("Pipeline cache: could not replace {}: {}",
162 kPipelineCachePath, ec.message());
163 std::filesystem::remove(kPipelineCacheTempPath, ec);
164 return;
165 }
166 SLEAK_INFO("Pipeline cache: saved {} bytes", data.size());
167 }
168
169/// Binds the skybox pipeline and its descriptor set for the current frame.
171 if (!bFrameStarted) return;
172 // Skybox only makes sense in forward context — not inside the GBuffer geometry pass
173 // where set 0 is a PBR material descriptor set incompatible with pipelineLay.
174 if (m_inGeometryPass) return;
175 if (skyboxPipeline == VK_NULL_HANDLE || !m_skyboxDescriptorsWritten)
176 return;
177
178 m_activeCustomFormat = 0; // prevent BindVertexBuffer from overriding this pipeline
179 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
180 skyboxPipeline);
181
182 if (CurrentFrameIndex < skyboxDescriptorSets.size()) {
183 vkCmdBindDescriptorSets(
184 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
185 &skyboxDescriptorSets[CurrentFrameIndex], 0, nullptr);
186 }
187}
188
189
190/// Restores the previous pipeline and descriptor set after the skybox draw.
192 if (!bFrameStarted) return;
193
194 // Restore pipeline: inside geometry pass restore to the GBuffer pipeline;
195 // otherwise the main forward pipeline.
196 VkPipeline restoreTo =
197 (m_inGeometryPass && m_gbufferPipeline != VK_NULL_HANDLE)
198 ? m_gbufferPipeline : pipeline;
199 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, restoreTo);
200
201 // Rebind main texture descriptor sets.
202 // In the GBuffer geometry pass set 0 belongs to m_gbufferGeomLayout and is
203 // managed by BindPBRMaterial — do NOT overwrite it with the forward
204 // single-sampler descriptor set or use pipelineLay here.
205 if (!m_inGeometryPass && m_textureDescriptorsWritten &&
206 CurrentFrameIndex < descriptorSets.size()) {
207 vkCmdBindDescriptorSets(
208 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
209 &descriptorSets[CurrentFrameIndex], 0, nullptr);
210 }
211}
212
213/// Creates the layout shared by the forward, skybox, debug line, skinned, and
214/// shadow pipelines.
215bool VulkanRenderer::CreateMainPipelineLayout() {
216 if (pipelineLay != VK_NULL_HANDLE) return true;
217
218 // Push constants
219 VkPushConstantRange pushConstantRange{};
220 pushConstantRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
221 pushConstantRange.offset = 0;
222 pushConstantRange.size = PUSH_CONSTANT_BYTES;
223
224 // Descriptor set layouts
225 std::array<VkDescriptorSetLayout, 4> setLayouts = {
226 descriptorSetLayout, boneDescriptorSetLayout,
227 m_lightUBODescriptorSetLayout, m_shadowSamplerDescriptorSetLayout};
228
229 VkPipelineLayoutCreateInfo layoutInfo{};
230 layoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
231 layoutInfo.setLayoutCount = static_cast<uint32_t>(setLayouts.size());
232 layoutInfo.pSetLayouts = setLayouts.data();
233 layoutInfo.pushConstantRangeCount = 1;
234 layoutInfo.pPushConstantRanges = &pushConstantRange;
235
236 if (vkCreatePipelineLayout(device, &layoutInfo, nullptr, &pipelineLay) !=
237 VK_SUCCESS)
238 SLEAK_RETURN_ERR("Failed to create graphics pipeline layout!");
239
240 return true;
241}
242
243/// Creates the main forward graphics pipeline, plus its layout and shader on
244/// first use.
245bool VulkanRenderer::CreateGraphicsPipeline() {
246 if (pipeline != VK_NULL_HANDLE) return true;
247 if (!CreateMainPipelineLayout()) return false;
248
249 if (!simpleShader) {
250 simpleShader = new VulkanShader(device);
251 if (!simpleShader->compile("assets/shaders/default_shader")) {
252 delete simpleShader;
253 simpleShader = nullptr;
254 SLEAK_RETURN_ERR("Cannot compile shaders!")
255 }
256 }
257
258 VkPipelineShaderStageCreateInfo shaderStages[] = {
259 simpleShader->GetVertexInfo(), simpleShader->GetFragInfo()};
260
261 // Dynamic states
262 std::vector<VkDynamicState> dynamicStates = {
263 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
264
265 VkPipelineDynamicStateCreateInfo dynamicState{};
266 dynamicState.sType =
267 VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
268 dynamicState.dynamicStateCount =
269 static_cast<uint32_t>(dynamicStates.size());
270 dynamicState.pDynamicStates = dynamicStates.data();
271
272 // Vertex input (locations 0-4)
273 VkVertexInputBindingDescription bindingDescription{};
274 bindingDescription.binding = 0;
275 bindingDescription.stride = sizeof(Vertex);
276 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
277
278 std::array<VkVertexInputAttributeDescription, 5> attributeDescs{};
279
280 // Position: float3 at offset 0
281 attributeDescs[0].binding = 0;
282 attributeDescs[0].location = 0;
283 attributeDescs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
284 attributeDescs[0].offset = offsetof(Vertex, px);
285
286 // Normal: float3 at offset 12
287 attributeDescs[1].binding = 0;
288 attributeDescs[1].location = 1;
289 attributeDescs[1].format = VK_FORMAT_R32G32B32_SFLOAT;
290 attributeDescs[1].offset = offsetof(Vertex, nx);
291
292 // Tangent: float4 at offset 24
293 attributeDescs[2].binding = 0;
294 attributeDescs[2].location = 2;
295 attributeDescs[2].format = VK_FORMAT_R32G32B32A32_SFLOAT;
296 attributeDescs[2].offset = offsetof(Vertex, tx);
297
298 // Color: float4 at offset 40
299 attributeDescs[3].binding = 0;
300 attributeDescs[3].location = 3;
301 attributeDescs[3].format = VK_FORMAT_R32G32B32A32_SFLOAT;
302 attributeDescs[3].offset = offsetof(Vertex, r);
303
304 // UV: float2 at offset 56
305 attributeDescs[4].binding = 0;
306 attributeDescs[4].location = 4;
307 attributeDescs[4].format = VK_FORMAT_R32G32_SFLOAT;
308 attributeDescs[4].offset = offsetof(Vertex, u);
309
310 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
311 vertexInputInfo.sType =
312 VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
313 vertexInputInfo.vertexBindingDescriptionCount = 1;
314 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
315 vertexInputInfo.vertexAttributeDescriptionCount =
316 static_cast<uint32_t>(attributeDescs.size());
317 vertexInputInfo.pVertexAttributeDescriptions = attributeDescs.data();
318
319 // Input assembly
320 VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};
321 inputAssemblyInfo.sType =
322 VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
323 inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
324 inputAssemblyInfo.primitiveRestartEnable = VK_FALSE;
325
326 // Viewport state (dynamic)
327 VkPipelineViewportStateCreateInfo viewportInfo{};
328 viewportInfo.sType =
329 VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
330 viewportInfo.viewportCount = 1;
331 viewportInfo.scissorCount = 1;
332
333 // Rasterization
334 VkPipelineRasterizationStateCreateInfo rasterizer{};
335 rasterizer.sType =
336 VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
337 rasterizer.depthClampEnable = VK_FALSE;
338 rasterizer.rasterizerDiscardEnable = VK_FALSE;
339 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
340 rasterizer.lineWidth = 1.0f;
341 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
342 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
343 rasterizer.depthBiasEnable = VK_FALSE;
344
345 // Multisampling
346 VkPipelineMultisampleStateCreateInfo msaa{};
347 msaa.sType =
348 VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
349 msaa.sampleShadingEnable = VK_FALSE;
350 msaa.rasterizationSamples = m_msaaSamples;
351
352 // Depth stencil
353 VkPipelineDepthStencilStateCreateInfo depthStencil{};
354 depthStencil.sType =
355 VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
356 depthStencil.depthTestEnable = VK_TRUE;
357 depthStencil.depthWriteEnable = VK_TRUE;
358 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
359 depthStencil.depthBoundsTestEnable = VK_FALSE;
360 depthStencil.stencilTestEnable = VK_FALSE;
361
362 // Color blending (fixed: R | G | B | A, not R | G | R | A)
363 VkPipelineColorBlendAttachmentState colorBlendAttachment{};
364 colorBlendAttachment.blendEnable = VK_TRUE;
365 colorBlendAttachment.colorWriteMask =
366 VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
367 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
368 colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
369 colorBlendAttachment.dstColorBlendFactor =
370 VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
371 colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
372 colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
373 colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
374 colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
375
376 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
377 colorBlendInfo.sType =
378 VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
379 colorBlendInfo.logicOpEnable = VK_FALSE;
380 colorBlendInfo.attachmentCount = 1;
381 colorBlendInfo.pAttachments = &colorBlendAttachment;
382
383 // Create pipeline
384 VkGraphicsPipelineCreateInfo pipelineInfo{};
385 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
386 pipelineInfo.stageCount = 2;
387 pipelineInfo.pStages = shaderStages;
388 pipelineInfo.pVertexInputState = &vertexInputInfo;
389 pipelineInfo.pInputAssemblyState = &inputAssemblyInfo;
390 pipelineInfo.pViewportState = &viewportInfo;
391 pipelineInfo.pRasterizationState = &rasterizer;
392 pipelineInfo.pMultisampleState = &msaa;
393 pipelineInfo.pDepthStencilState = &depthStencil;
394 pipelineInfo.pColorBlendState = &colorBlendInfo;
395 pipelineInfo.pDynamicState = &dynamicState;
396 pipelineInfo.layout = pipelineLay;
397 pipelineInfo.subpass = 0;
398 pipelineInfo.renderPass = (m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE)
399 ? m_forwardRenderPass : renderPass;
400 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
401 pipelineInfo.basePipelineIndex = -1;
402
403 VkResult result = vkCreateGraphicsPipelines(
404 device, m_pipelineCache, 1, &pipelineInfo, nullptr, &pipeline);
405 if (result != VK_SUCCESS)
406 SLEAK_ERROR("Failed to create graphics pipeline!!");
407
408 return true;
409}
410
411/// Creates the main forward render pass with optional MSAA color and resolve attachments.
412bool VulkanRenderer::CreateRenderPass() {
413 const bool msaaEnabled = (m_msaaSamples != VK_SAMPLE_COUNT_1_BIT);
414
415 // Color attachment (multisampled when MSAA on)
416 VkAttachmentDescription colorAttachment{};
417 colorAttachment.format = scImageFormat;
418 colorAttachment.samples = m_msaaSamples;
419 colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
420 colorAttachment.storeOp = msaaEnabled ? VK_ATTACHMENT_STORE_OP_DONT_CARE : VK_ATTACHMENT_STORE_OP_STORE;
421 colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
422 colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
423 colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
424 colorAttachment.finalLayout = msaaEnabled ? VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL : VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
425
426 VkAttachmentReference colorRef{};
427 colorRef.attachment = 0;
428 colorRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
429
430 // Depth attachment (multisampled when MSAA on)
431 VkAttachmentDescription depthAttachment{};
432 depthAttachment.format = depthFormat;
433 depthAttachment.samples = m_msaaSamples;
434 depthAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
435 depthAttachment.storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
436 depthAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
437 depthAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
438 depthAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
439 depthAttachment.finalLayout =
440 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
441
442 VkAttachmentReference depthRef{};
443 depthRef.attachment = 1;
444 depthRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
445
446 // Resolve attachment (swapchain image, only when MSAA on)
447 VkAttachmentDescription resolveAttachment{};
448 VkAttachmentReference resolveRef{};
449 if (msaaEnabled) {
450 resolveAttachment.format = scImageFormat;
451 resolveAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
452 resolveAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
453 resolveAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
454 resolveAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
455 resolveAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
456 resolveAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
457 resolveAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
458
459 resolveRef.attachment = 2;
460 resolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
461 }
462
463 // Subpass
464 VkSubpassDescription subpass{};
465 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
466 subpass.colorAttachmentCount = 1;
467 subpass.pColorAttachments = &colorRef;
468 subpass.pDepthStencilAttachment = &depthRef;
469 subpass.pResolveAttachments = msaaEnabled ? &resolveRef : nullptr;
470
471 // Subpass dependency
472 VkSubpassDependency dependency{};
473 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
474 dependency.dstSubpass = 0;
475 dependency.srcStageMask =
476 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
477 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
478 dependency.srcAccessMask = 0;
479 dependency.dstStageMask =
480 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT |
481 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
482 dependency.dstAccessMask =
483 VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT |
484 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
485
486 // Create render pass
487 std::vector<VkAttachmentDescription> attachments = {
488 colorAttachment, depthAttachment};
489 if (msaaEnabled)
490 attachments.push_back(resolveAttachment);
491
492 VkRenderPassCreateInfo renderInfo{};
493 renderInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
494 renderInfo.attachmentCount =
495 static_cast<uint32_t>(attachments.size());
496 renderInfo.pAttachments = attachments.data();
497 renderInfo.subpassCount = 1;
498 renderInfo.pSubpasses = &subpass;
499 renderInfo.dependencyCount = 1;
500 renderInfo.pDependencies = &dependency;
501
502 if (vkCreateRenderPass(device, &renderInfo, nullptr, &renderPass) !=
503 VK_SUCCESS)
504 SLEAK_RETURN_ERR("Failed to create render pass!");
505
506 return true;
507}
508
509
510/// Creates one framebuffer per swapchain image for the main render pass.
511bool VulkanRenderer::CreateFrameBuffer() {
512 swapChainFramebuffers.resize(swapChainImageViews.size());
513 const bool msaaEnabled = (m_msaaSamples != VK_SAMPLE_COUNT_1_BIT);
514
515 for (size_t i = 0; i < swapChainImageViews.size(); i++) {
516 std::vector<VkImageView> attachments;
517 if (msaaEnabled) {
518 // MSAA color, depth, resolve (swapchain)
519 attachments = {m_msaaColorImageView, depthImageView, swapChainImageViews[i]};
520 } else {
521 // No MSAA: swapchain color, depth
522 attachments = {swapChainImageViews[i], depthImageView};
523 }
524
525 VkFramebufferCreateInfo info{};
526 info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
527 info.renderPass = renderPass;
528 info.attachmentCount =
529 static_cast<uint32_t>(attachments.size());
530 info.pAttachments = attachments.data();
531 info.layers = 1;
532 info.width = scExtent.width;
533 info.height = scExtent.height;
534
535 if (vkCreateFramebuffer(device, &info, nullptr,
536 &swapChainFramebuffers[i]) != VK_SUCCESS)
537 SLEAK_RETURN_ERR("Failed to create frame buffer!");
538 }
539 return true;
540}
541
542/// Compiles the skybox shaders on first use, sizes the skybox descriptor sets
543/// to the swapchain image count, and creates the skybox pipeline.
544bool VulkanRenderer::CreateSkyboxPipeline() {
545 // 1. Compile skybox shaders
546 if (!skyboxShader) {
547 skyboxShader = new VulkanShader(device);
548 if (!skyboxShader->compile("assets/shaders/skybox")) {
549 SLEAK_ERROR("VulkanRenderer: Failed to compile skybox shaders");
550 delete skyboxShader;
551 skyboxShader = nullptr;
552 return false;
553 }
554 }
555
556 // 2. Create skybox descriptor pool and sets (same layout as main)
557 uint32_t imageCount =
558 static_cast<uint32_t>(swapChainImages.size());
559
560 if (skyboxDescriptorSets.size() != imageCount) {
561 if (skyboxDescriptorPool) {
562 vkDestroyDescriptorPool(device, skyboxDescriptorPool, nullptr);
563 skyboxDescriptorPool = VK_NULL_HANDLE;
564 }
565 skyboxDescriptorSets.clear();
566
567 VkDescriptorPoolSize poolSize{};
568 poolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
569 poolSize.descriptorCount = imageCount;
570
571 VkDescriptorPoolCreateInfo poolInfo{};
572 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
573 poolInfo.poolSizeCount = 1;
574 poolInfo.pPoolSizes = &poolSize;
575 poolInfo.maxSets = imageCount;
576
577 if (vkCreateDescriptorPool(device, &poolInfo, nullptr,
578 &skyboxDescriptorPool) != VK_SUCCESS) {
580 "VulkanRenderer: Failed to create skybox descriptor pool");
581 return false;
582 }
583
584 std::vector<VkDescriptorSetLayout> layouts(imageCount,
585 descriptorSetLayout);
586
587 VkDescriptorSetAllocateInfo allocInfo{};
588 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
589 allocInfo.descriptorPool = skyboxDescriptorPool;
590 allocInfo.descriptorSetCount = imageCount;
591 allocInfo.pSetLayouts = layouts.data();
592
593 std::vector<VkDescriptorSet> sets(imageCount);
594 if (vkAllocateDescriptorSets(device, &allocInfo, sets.data()) !=
595 VK_SUCCESS) {
597 "VulkanRenderer: Failed to allocate skybox descriptor sets");
598 return false;
599 }
600 skyboxDescriptorSets = std::move(sets);
601 }
602
603 // 3. Create skybox pipeline (same as main but with skybox shaders
604 // and depth write disabled)
605 VkPipelineShaderStageCreateInfo shaderStages[] = {
606 skyboxShader->GetVertexInfo(), skyboxShader->GetFragInfo()};
607
608 std::vector<VkDynamicState> dynamicStates = {
609 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
610
611 VkPipelineDynamicStateCreateInfo dynamicState{};
612 dynamicState.sType =
613 VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
614 dynamicState.dynamicStateCount =
615 static_cast<uint32_t>(dynamicStates.size());
616 dynamicState.pDynamicStates = dynamicStates.data();
617
618 // Same vertex layout as main pipeline (locations 0-4)
619 VkVertexInputBindingDescription bindingDescription{};
620 bindingDescription.binding = 0;
621 bindingDescription.stride = sizeof(Vertex);
622 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
623
624 std::array<VkVertexInputAttributeDescription, 5> attributeDescs{};
625 attributeDescs[0].binding = 0;
626 attributeDescs[0].location = 0;
627 attributeDescs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
628 attributeDescs[0].offset = offsetof(Vertex, px);
629
630 attributeDescs[1].binding = 0;
631 attributeDescs[1].location = 1;
632 attributeDescs[1].format = VK_FORMAT_R32G32B32_SFLOAT;
633 attributeDescs[1].offset = offsetof(Vertex, nx);
634
635 attributeDescs[2].binding = 0;
636 attributeDescs[2].location = 2;
637 attributeDescs[2].format = VK_FORMAT_R32G32B32A32_SFLOAT;
638 attributeDescs[2].offset = offsetof(Vertex, tx);
639
640 attributeDescs[3].binding = 0;
641 attributeDescs[3].location = 3;
642 attributeDescs[3].format = VK_FORMAT_R32G32B32A32_SFLOAT;
643 attributeDescs[3].offset = offsetof(Vertex, r);
644
645 attributeDescs[4].binding = 0;
646 attributeDescs[4].location = 4;
647 attributeDescs[4].format = VK_FORMAT_R32G32_SFLOAT;
648 attributeDescs[4].offset = offsetof(Vertex, u);
649
650 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
651 vertexInputInfo.sType =
652 VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
653 vertexInputInfo.vertexBindingDescriptionCount = 1;
654 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
655 vertexInputInfo.vertexAttributeDescriptionCount =
656 static_cast<uint32_t>(attributeDescs.size());
657 vertexInputInfo.pVertexAttributeDescriptions = attributeDescs.data();
658
659 VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};
660 inputAssemblyInfo.sType =
661 VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
662 inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
663 inputAssemblyInfo.primitiveRestartEnable = VK_FALSE;
664
665 VkPipelineViewportStateCreateInfo viewportInfo{};
666 viewportInfo.sType =
667 VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
668 viewportInfo.viewportCount = 1;
669 viewportInfo.scissorCount = 1;
670
671 VkPipelineRasterizationStateCreateInfo rasterizer{};
672 rasterizer.sType =
673 VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
674 rasterizer.depthClampEnable = VK_FALSE;
675 rasterizer.rasterizerDiscardEnable = VK_FALSE;
676 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
677 rasterizer.lineWidth = 1.0f;
678 rasterizer.cullMode = VK_CULL_MODE_NONE;
679 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
680 rasterizer.depthBiasEnable = VK_FALSE;
681
682 VkPipelineMultisampleStateCreateInfo msaa{};
683 msaa.sType =
684 VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
685 msaa.sampleShadingEnable = VK_FALSE;
686 msaa.rasterizationSamples = m_msaaSamples;
687
688 // Skybox: depth test enabled (LEQUAL), depth write DISABLED
689 VkPipelineDepthStencilStateCreateInfo depthStencil{};
690 depthStencil.sType =
691 VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
692 depthStencil.depthTestEnable = VK_TRUE;
693 depthStencil.depthWriteEnable = VK_FALSE;
694 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
695 depthStencil.depthBoundsTestEnable = VK_FALSE;
696 depthStencil.stencilTestEnable = VK_FALSE;
697
698 VkPipelineColorBlendAttachmentState colorBlendAttachment{};
699 colorBlendAttachment.blendEnable = VK_FALSE;
700 colorBlendAttachment.colorWriteMask =
701 VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
702 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
703
704 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
705 colorBlendInfo.sType =
706 VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
707 colorBlendInfo.logicOpEnable = VK_FALSE;
708 colorBlendInfo.attachmentCount = 1;
709 colorBlendInfo.pAttachments = &colorBlendAttachment;
710
711 VkGraphicsPipelineCreateInfo pipelineInfo{};
712 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
713 pipelineInfo.stageCount = 2;
714 pipelineInfo.pStages = shaderStages;
715 pipelineInfo.pVertexInputState = &vertexInputInfo;
716 pipelineInfo.pInputAssemblyState = &inputAssemblyInfo;
717 pipelineInfo.pViewportState = &viewportInfo;
718 pipelineInfo.pRasterizationState = &rasterizer;
719 pipelineInfo.pMultisampleState = &msaa;
720 pipelineInfo.pDepthStencilState = &depthStencil;
721 pipelineInfo.pColorBlendState = &colorBlendInfo;
722 pipelineInfo.pDynamicState = &dynamicState;
723 pipelineInfo.layout = pipelineLay; // Reuse same pipeline layout
724 pipelineInfo.subpass = 0;
725 pipelineInfo.renderPass = (m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE)
726 ? m_forwardRenderPass : renderPass;
727 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
728 pipelineInfo.basePipelineIndex = -1;
729
730 VkResult result = vkCreateGraphicsPipelines(
731 device, m_pipelineCache, 1, &pipelineInfo, nullptr, &skyboxPipeline);
732 if (result != VK_SUCCESS) {
733 SLEAK_ERROR("VulkanRenderer: Failed to create skybox pipeline!");
734 return false;
735 }
736
737 SLEAK_INFO("VulkanRenderer: Skybox pipeline created successfully");
738 return true;
739}
740
741
742/// Compiles the debug line shaders and creates the line-list pipeline.
743bool VulkanRenderer::CreateDebugLinePipeline() {
744 if (debugLinePipeline != VK_NULL_HANDLE) return true;
745
746 if (!debugLineShader) {
747 debugLineShader = new VulkanShader(device);
748 if (!debugLineShader->compile("assets/shaders/debug_line")) {
749 SLEAK_ERROR("VulkanRenderer: Failed to compile debug line shaders");
750 delete debugLineShader;
751 debugLineShader = nullptr;
752 return false;
753 }
754 }
755
756 VkPipelineShaderStageCreateInfo shaderStages[] = {
757 debugLineShader->GetVertexInfo(), debugLineShader->GetFragInfo()};
758
759 std::vector<VkDynamicState> dynamicStates = {
760 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
761
762 VkPipelineDynamicStateCreateInfo dynamicState{};
763 dynamicState.sType =
764 VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
765 dynamicState.dynamicStateCount =
766 static_cast<uint32_t>(dynamicStates.size());
767 dynamicState.pDynamicStates = dynamicStates.data();
768
769 VkVertexInputBindingDescription bindingDescription{};
770 bindingDescription.binding = 0;
771 bindingDescription.stride = sizeof(Vertex);
772 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
773
774 std::array<VkVertexInputAttributeDescription, 5> attributeDescs{};
775 attributeDescs[0] = {0, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, px)};
776 attributeDescs[1] = {1, 0, VK_FORMAT_R32G32B32_SFLOAT, offsetof(Vertex, nx)};
777 attributeDescs[2] = {2, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, tx)};
778 attributeDescs[3] = {3, 0, VK_FORMAT_R32G32B32A32_SFLOAT, offsetof(Vertex, r)};
779 attributeDescs[4] = {4, 0, VK_FORMAT_R32G32_SFLOAT, offsetof(Vertex, u)};
780
781 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
782 vertexInputInfo.sType =
783 VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
784 vertexInputInfo.vertexBindingDescriptionCount = 1;
785 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
786 vertexInputInfo.vertexAttributeDescriptionCount =
787 static_cast<uint32_t>(attributeDescs.size());
788 vertexInputInfo.pVertexAttributeDescriptions = attributeDescs.data();
789
790 VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};
791 inputAssemblyInfo.sType =
792 VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
793 inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST;
794 inputAssemblyInfo.primitiveRestartEnable = VK_FALSE;
795
796 VkPipelineViewportStateCreateInfo viewportInfo{};
797 viewportInfo.sType =
798 VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
799 viewportInfo.viewportCount = 1;
800 viewportInfo.scissorCount = 1;
801
802 VkPipelineRasterizationStateCreateInfo rasterizer{};
803 rasterizer.sType =
804 VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
805 rasterizer.depthClampEnable = VK_FALSE;
806 rasterizer.rasterizerDiscardEnable = VK_FALSE;
807 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
808 rasterizer.lineWidth = 1.0f;
809 rasterizer.cullMode = VK_CULL_MODE_NONE;
810 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
811 rasterizer.depthBiasEnable = VK_FALSE;
812
813 VkPipelineMultisampleStateCreateInfo msaa{};
814 msaa.sType =
815 VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
816 msaa.sampleShadingEnable = VK_FALSE;
817 msaa.rasterizationSamples = m_msaaSamples;
818
819 VkPipelineDepthStencilStateCreateInfo depthStencil{};
820 depthStencil.sType =
821 VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
822 depthStencil.depthTestEnable = VK_TRUE;
823 depthStencil.depthWriteEnable = VK_TRUE;
824 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
825 depthStencil.depthBoundsTestEnable = VK_FALSE;
826 depthStencil.stencilTestEnable = VK_FALSE;
827
828 VkPipelineColorBlendAttachmentState colorBlendAttachment{};
829 colorBlendAttachment.blendEnable = VK_FALSE;
830 colorBlendAttachment.colorWriteMask =
831 VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
832 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
833
834 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
835 colorBlendInfo.sType =
836 VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
837 colorBlendInfo.logicOpEnable = VK_FALSE;
838 colorBlendInfo.attachmentCount = 1;
839 colorBlendInfo.pAttachments = &colorBlendAttachment;
840
841 VkGraphicsPipelineCreateInfo pipelineInfo{};
842 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
843 pipelineInfo.stageCount = 2;
844 pipelineInfo.pStages = shaderStages;
845 pipelineInfo.pVertexInputState = &vertexInputInfo;
846 pipelineInfo.pInputAssemblyState = &inputAssemblyInfo;
847 pipelineInfo.pViewportState = &viewportInfo;
848 pipelineInfo.pRasterizationState = &rasterizer;
849 pipelineInfo.pMultisampleState = &msaa;
850 pipelineInfo.pDepthStencilState = &depthStencil;
851 pipelineInfo.pColorBlendState = &colorBlendInfo;
852 pipelineInfo.pDynamicState = &dynamicState;
853 pipelineInfo.layout = pipelineLay;
854 pipelineInfo.subpass = 0;
855 pipelineInfo.renderPass = (m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE)
856 ? m_forwardRenderPass : renderPass;
857 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
858 pipelineInfo.basePipelineIndex = -1;
859
860 VkResult result = vkCreateGraphicsPipelines(
861 device, m_pipelineCache, 1, &pipelineInfo, nullptr, &debugLinePipeline);
862 if (result != VK_SUCCESS) {
863 SLEAK_ERROR("VulkanRenderer: Failed to create debug line pipeline!");
864 return false;
865 }
866
867 SLEAK_INFO("VulkanRenderer: Debug line pipeline created successfully");
868 return true;
869}
870
871
872// ============================================================
873// Custom vertex format pipelines — vertex input and shader stems
874// come from VertexFormatRegistry, so no layout is hard-coded in the backend.
875// ============================================================
876
877/// Translates a registry attribute format into its Vulkan vertex format.
878static VkFormat ToVkVertexFormat(VertexAttribFormat format) {
879 switch (format) {
880 case VertexAttribFormat::Float1: return VK_FORMAT_R32_SFLOAT;
881 case VertexAttribFormat::Float2: return VK_FORMAT_R32G32_SFLOAT;
882 case VertexAttribFormat::Float3: return VK_FORMAT_R32G32B32_SFLOAT;
883 case VertexAttribFormat::Float4: return VK_FORMAT_R32G32B32A32_SFLOAT;
884 case VertexAttribFormat::UInt1: return VK_FORMAT_R32_UINT;
885 case VertexAttribFormat::Int1: return VK_FORMAT_R32_SINT;
886 }
887 return VK_FORMAT_R32G32B32_SFLOAT;
888}
889
890/// True when the render pass a custom-format variant targets exists.
891bool VulkanRenderer::CustomPassAvailable(CustomPass pass) const {
892 switch (pass) {
893 case CustomPass::Shadow:
894 return m_shadowRenderPass != VK_NULL_HANDLE &&
895 m_shadowShader != nullptr;
896 case CustomPass::GBuffer:
897 return m_gbufferResourcesCreated &&
898 m_gbufferRenderPass != VK_NULL_HANDLE;
899 default:
900 return true;
901 }
902}
903
904/// Returns a format's pipeline for a pass, compiling it on first request.
905/// A variant that failed once stays absent instead of recompiling per frame.
906VkPipeline VulkanRenderer::GetCustomFormatPipeline(VertexFormatHandle format,
907 CustomPass pass) {
908 if (format == 0) return VK_NULL_HANDLE;
909 if (format > m_customFormatPipelines.size()) {
910 if (!VertexFormatRegistry::Get(format)) return VK_NULL_HANDLE;
911 m_customFormatPipelines.resize(format);
912 }
913 CustomFormatPipelines& pipes = m_customFormatPipelines[format - 1];
914 const size_t slot = static_cast<size_t>(pass);
915 if (pipes.pipelines[slot] != VK_NULL_HANDLE || pipes.failed[slot])
916 return pipes.pipelines[slot];
917
918 // Lazy fallback
919 if (!CustomPassAvailable(pass)) return VK_NULL_HANDLE;
920 const VertexLayoutDesc* desc = VertexFormatRegistry::Get(format);
921 if (!desc) return VK_NULL_HANDLE;
922 pipes.pipelines[slot] = BuildCustomFormatPipeline(format, *desc, pass);
923 pipes.failed[slot] = pipes.pipelines[slot] == VK_NULL_HANDLE;
924 return pipes.pipelines[slot];
925}
926
927/// Compiles one pipeline variant of a registered layout; returns
928/// VK_NULL_HANDLE when its stem is empty or compilation fails.
929VkPipeline VulkanRenderer::BuildCustomFormatPipeline(
930 VertexFormatHandle format, const VertexLayoutDesc& desc, CustomPass pass) {
931 static constexpr const char* kPassNames[CUSTOM_PASS_COUNT] = {
932 "main", "shadow", "GBuffer", "transparent"};
933 const char* passName = kPassNames[static_cast<size_t>(pass)];
934
935 if (desc.stride == 0 || desc.attributes.empty()) {
936 SLEAK_ERROR("VulkanRenderer: Vertex format {} has an empty layout",
937 format);
938 return VK_NULL_HANDLE;
939 }
940
941 const std::string* stem = &desc.shaderStem;
942 if (pass == CustomPass::Shadow) stem = &desc.shadowShaderStem;
943 if (pass == CustomPass::GBuffer) stem = &desc.gbufferShaderStem;
944 if (pass == CustomPass::Transparent) stem = &desc.transparentShaderStem;
945 if (stem->empty()) {
946 if (pass == CustomPass::Main)
948 "VulkanRenderer: Vertex format {} has no main shader stem",
949 format);
950 return VK_NULL_HANDLE;
951 }
952
953 // Shader stages
954 const std::string base = "assets/shaders/" + *stem;
955 std::string shaderPath = base;
956 VulkanShader shader(device);
957 bool compiled = false;
958 if (pass == CustomPass::Shadow) {
959 shaderPath = base + ".vert.spv";
960 compiled = shader.compileVertexOnly(shaderPath);
961 } else if (pass == CustomPass::GBuffer) {
962 shaderPath = base + ".vert.spv";
963 compiled =
964 shader.compile(shaderPath, "assets/shaders/gbuffer.frag.spv");
965 } else {
966 compiled = shader.compile(base);
967 }
968 if (!compiled) {
970 "VulkanRenderer: Failed to compile '{}' for vertex format {}",
971 shaderPath, format);
972 return VK_NULL_HANDLE;
973 }
974 VkPipelineShaderStageCreateInfo stages[] = {shader.GetVertexInfo(),
975 shader.GetFragInfo()};
976
977 // Vertex input
978 VkVertexInputBindingDescription binding{};
979 binding.binding = 0;
980 binding.stride = desc.stride;
981 binding.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
982
983 std::vector<VkVertexInputAttributeDescription> attributes;
984 attributes.reserve(desc.attributes.size());
985 for (const auto& attr : desc.attributes) {
986 attributes.push_back(
987 {attr.location, 0, ToVkVertexFormat(attr.format), attr.offset});
988 }
989
990 VkPipelineVertexInputStateCreateInfo vertexInput{};
991 vertexInput.sType =
992 VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
993 vertexInput.vertexBindingDescriptionCount = 1;
994 vertexInput.pVertexBindingDescriptions = &binding;
995 vertexInput.vertexAttributeDescriptionCount =
996 static_cast<uint32_t>(attributes.size());
997 vertexInput.pVertexAttributeDescriptions = attributes.data();
998
999 VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
1000 inputAssembly.sType =
1001 VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1002 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1003 inputAssembly.primitiveRestartEnable = VK_FALSE;
1004
1005 VkPipelineViewportStateCreateInfo viewportState{};
1006 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1007 viewportState.viewportCount = 1;
1008 viewportState.scissorCount = 1;
1009
1010 const VkDynamicState dynamicStates[] = {VK_DYNAMIC_STATE_VIEWPORT,
1011 VK_DYNAMIC_STATE_SCISSOR};
1012 VkPipelineDynamicStateCreateInfo dynamicState{};
1013 dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1014 dynamicState.dynamicStateCount = 2;
1015 dynamicState.pDynamicStates = dynamicStates;
1016
1017 // Rasterization
1018 VkPipelineRasterizationStateCreateInfo rasterizer{};
1019 rasterizer.sType =
1020 VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1021 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
1022 rasterizer.lineWidth = 1.0f;
1023 rasterizer.cullMode = pass == CustomPass::Transparent
1024 ? VK_CULL_MODE_NONE
1025 : VK_CULL_MODE_BACK_BIT;
1026 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1027 if (pass == CustomPass::Shadow) {
1028 rasterizer.depthBiasEnable = VK_TRUE;
1029 rasterizer.depthBiasConstantFactor = SHADOW_DEPTH_BIAS_CONSTANT;
1030 rasterizer.depthBiasSlopeFactor = SHADOW_DEPTH_BIAS_SLOPE;
1031 }
1032
1033 // Multisampling
1034 const bool forwardTarget =
1035 m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE;
1036 VkPipelineMultisampleStateCreateInfo multisample{};
1037 multisample.sType =
1038 VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1039 multisample.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
1040 if (pass == CustomPass::Main ||
1041 (pass == CustomPass::Transparent && !forwardTarget))
1042 multisample.rasterizationSamples = m_msaaSamples;
1043
1044 VkPipelineDepthStencilStateCreateInfo depthStencil{};
1045 depthStencil.sType =
1046 VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1047 depthStencil.depthTestEnable = VK_TRUE;
1048 depthStencil.depthWriteEnable = VK_TRUE;
1049 depthStencil.depthCompareOp = pass == CustomPass::Shadow
1050 ? VK_COMPARE_OP_LESS_OR_EQUAL
1051 : VK_COMPARE_OP_LESS;
1052
1053 // Color blending
1054 VkPipelineColorBlendAttachmentState blend{};
1055 blend.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
1056 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1057 if (pass == CustomPass::Main || pass == CustomPass::Transparent) {
1058 blend.blendEnable = VK_TRUE;
1059 blend.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
1060 blend.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1061 blend.colorBlendOp = VK_BLEND_OP_ADD;
1062 // Transparent draws zero the HDR scene alpha: TAA's reactive mask
1063 const bool transparent = pass == CustomPass::Transparent;
1064 blend.srcAlphaBlendFactor =
1065 transparent ? VK_BLEND_FACTOR_ZERO : VK_BLEND_FACTOR_ONE;
1066 blend.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
1067 blend.alphaBlendOp = VK_BLEND_OP_ADD;
1068 }
1069 std::array<VkPipelineColorBlendAttachmentState, GBUFFER_COUNT> blends;
1070 blends.fill(blend);
1071
1072 VkPipelineColorBlendStateCreateInfo colorBlend{};
1073 colorBlend.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1074 colorBlend.attachmentCount = 1;
1075 if (pass == CustomPass::Shadow) colorBlend.attachmentCount = 0;
1076 if (pass == CustomPass::GBuffer) colorBlend.attachmentCount = GBUFFER_COUNT;
1077 colorBlend.pAttachments =
1078 colorBlend.attachmentCount > 0 ? blends.data() : nullptr;
1079
1080 // Pipeline
1081 VkGraphicsPipelineCreateInfo pipelineInfo{};
1082 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1083 pipelineInfo.stageCount = pass == CustomPass::Shadow ? 1 : 2;
1084 pipelineInfo.pStages = stages;
1085 pipelineInfo.pVertexInputState = &vertexInput;
1086 pipelineInfo.pInputAssemblyState = &inputAssembly;
1087 pipelineInfo.pViewportState = &viewportState;
1088 pipelineInfo.pRasterizationState = &rasterizer;
1089 pipelineInfo.pMultisampleState = &multisample;
1090 pipelineInfo.pDepthStencilState = &depthStencil;
1091 pipelineInfo.pColorBlendState = &colorBlend;
1092 pipelineInfo.pDynamicState = &dynamicState;
1093 pipelineInfo.layout =
1094 pass == CustomPass::GBuffer ? m_gbufferGeomLayout : pipelineLay;
1095 pipelineInfo.renderPass = forwardTarget ? m_forwardRenderPass : renderPass;
1096 if (pass == CustomPass::Shadow)
1097 pipelineInfo.renderPass = m_shadowRenderPass;
1098 if (pass == CustomPass::GBuffer)
1099 pipelineInfo.renderPass = m_gbufferRenderPass;
1100 pipelineInfo.subpass = 0;
1101 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
1102 pipelineInfo.basePipelineIndex = -1;
1103
1104 VkPipeline created = VK_NULL_HANDLE;
1105 if (vkCreateGraphicsPipelines(device, m_pipelineCache, 1, &pipelineInfo,
1106 nullptr, &created) != VK_SUCCESS) {
1108 "VulkanRenderer: Failed to create {} pipeline for vertex format {}",
1109 passName, format);
1110 return VK_NULL_HANDLE;
1111 }
1112 SLEAK_INFO("VulkanRenderer: Custom format {} {} pipeline created", format,
1113 passName);
1114 return created;
1115}
1116
1117/// Compiles the variants the active render path draws with for every
1118/// registered format not prebuilt yet; the forward main variant is skipped
1119/// while deferred is active and only built if a draw asks for it.
1120void VulkanRenderer::PrebuildCustomFormatPipelines() {
1121 while (VertexFormatRegistry::Get(m_customFormatsPrebuilt + 1)) {
1122 const VertexFormatHandle format = ++m_customFormatsPrebuilt;
1123 GetCustomFormatPipeline(format, CustomPass::Shadow);
1124 GetCustomFormatPipeline(format, IsDeferredEnabled()
1125 ? CustomPass::GBuffer
1126 : CustomPass::Main);
1127 GetCustomFormatPipeline(format, CustomPass::Transparent);
1128 }
1129}
1130
1131/// Binds the custom-format pipeline matching the currently active render pass.
1133 if (!bFrameStarted) return;
1134 if (format == 0) return;
1135 if (m_activeCustomFormat == format) return;
1136 m_activeCustomFormat = format;
1137
1138 CustomPass pass = CustomPass::Main;
1139 if (m_shadowPassActive) {
1140 pass = CustomPass::Shadow;
1141 } else if (m_inGeometryPass) {
1142 pass = CustomPass::GBuffer;
1143 } else if (m_inForwardTransparentPass) {
1144 pass = CustomPass::Transparent;
1145 }
1146
1147 // No variant for this pass: drop the draws rather than rasterize this
1148 // layout's vertices through a pipeline built for another one.
1149 const VkPipeline target = GetCustomFormatPipeline(format, pass);
1150 m_customFormatUnbound = target == VK_NULL_HANDLE;
1151 if (m_customFormatUnbound) return;
1152
1153 // Scene-reading shaders need set 3 bindings 2-5 written
1154 if (pass == CustomPass::Transparent) {
1155 const VertexLayoutDesc* desc = VertexFormatRegistry::Get(format);
1156 if (desc && desc->transparentReadsScene) {
1157 m_customFormatUnbound = !m_sceneReadCreated;
1158 if (m_customFormatUnbound) return;
1159 PrepareSceneRead();
1160 }
1161 }
1162
1163 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, target);
1164}
1165
1166
1167/// Restores the previous pipeline and descriptor set after custom-format draws.
1169 if (!bFrameStarted) return;
1170 if (m_activeCustomFormat == 0) return;
1171 m_activeCustomFormat = 0;
1172 m_customFormatUnbound = false;
1173
1174 if (m_shadowPassActive) {
1175 if (m_shadowPipeline != VK_NULL_HANDLE) {
1176 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1177 m_shadowPipeline);
1178 }
1179 } else if (m_inGeometryPass && m_gbufferPipeline != VK_NULL_HANDLE) {
1180 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1181 m_gbufferPipeline);
1182 } else {
1183 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
1184 }
1185
1186 // Re-bind descriptors after pipeline change; set 0 inside the GBuffer
1187 // geometry pass belongs to m_gbufferGeomLayout and is owned by BindPBRMaterial.
1188 if (!m_inGeometryPass && m_textureDescriptorsWritten &&
1189 CurrentFrameIndex < descriptorSets.size()) {
1190 vkCmdBindDescriptorSets(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1191 pipelineLay, 0, 1,
1192 &descriptorSets[CurrentFrameIndex], 0, nullptr);
1193 }
1194}
1195
1196/// Destroys every cached custom-format pipeline and clears the table.
1197void VulkanRenderer::DestroyCustomFormatPipelines() {
1198 for (const CustomFormatPipelines& pipes : m_customFormatPipelines) {
1199 for (VkPipeline pipe : pipes.pipelines) {
1200 if (pipe) vkDestroyPipeline(device, pipe, nullptr);
1201 }
1202 }
1203 m_customFormatPipelines.clear();
1204 m_customFormatsPrebuilt = 0;
1205 m_activeCustomFormat = 0;
1206}
1207
1208
1209
1210/// Binds the debug line pipeline for the current frame.
1212 if (!bFrameStarted) return;
1213 if (debugLinePipeline == VK_NULL_HANDLE) {
1214 if (!CreateDebugLinePipeline()) return;
1215 }
1216 m_activeCustomFormat = 0; // prevent BindVertexBuffer from overriding this pipeline
1217 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1218 debugLinePipeline);
1219}
1220
1221
1222/// Restores the previous pipeline and descriptor set after debug line draws.
1224 if (!bFrameStarted) return;
1225
1226 // Restore pipeline: inside geometry pass restore to the GBuffer pipeline;
1227 // otherwise the main forward pipeline.
1228 VkPipeline restoreTo =
1229 (m_inGeometryPass && m_gbufferPipeline != VK_NULL_HANDLE)
1230 ? m_gbufferPipeline : pipeline;
1231 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, restoreTo);
1232
1233 // Rebind main texture descriptor sets.
1234 // In the GBuffer geometry pass set 0 belongs to m_gbufferGeomLayout and is
1235 // managed by BindPBRMaterial — do NOT overwrite it with the forward
1236 // single-sampler descriptor set or use pipelineLay here.
1237 if (!m_inGeometryPass && m_textureDescriptorsWritten &&
1238 CurrentFrameIndex < descriptorSets.size()) {
1239 vkCmdBindDescriptorSets(
1240 command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLay, 0, 1,
1241 &descriptorSets[CurrentFrameIndex], 0, nullptr);
1242 }
1243}
1244
1245/// Compiles the skinned shaders on first use and creates the forward skinned
1246/// pipeline.
1247bool VulkanRenderer::CreateSkinnedPipeline() {
1248 if (skinnedPipeline != VK_NULL_HANDLE) return true;
1249
1250 // 1. Compile skinned shaders
1251 if (!skinnedShader) {
1252 skinnedShader = new VulkanShader(device);
1253 if (!skinnedShader->compile("assets/shaders/skinned_shader")) {
1254 SLEAK_ERROR("VulkanRenderer: Failed to compile skinned shaders");
1255 delete skinnedShader;
1256 skinnedShader = nullptr;
1257 return false;
1258 }
1259 }
1260
1261 // 2. Create pipeline (same as main but with skinned shaders)
1262 VkPipelineShaderStageCreateInfo shaderStages[] = {
1263 skinnedShader->GetVertexInfo(), skinnedShader->GetFragInfo()};
1264
1265 std::vector<VkDynamicState> dynamicStates = {
1266 VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
1267
1268 VkPipelineDynamicStateCreateInfo dynamicState{};
1269 dynamicState.sType =
1270 VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1271 dynamicState.dynamicStateCount =
1272 static_cast<uint32_t>(dynamicStates.size());
1273 dynamicState.pDynamicStates = dynamicStates.data();
1274
1275 // Same vertex layout as main pipeline (7 attributes including bone data)
1276 VkVertexInputBindingDescription bindingDescription{};
1277 bindingDescription.binding = 0;
1278 bindingDescription.stride = sizeof(Vertex);
1279 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1280
1281 std::array<VkVertexInputAttributeDescription, 7> attributeDescs{};
1282 attributeDescs[0].binding = 0;
1283 attributeDescs[0].location = 0;
1284 attributeDescs[0].format = VK_FORMAT_R32G32B32_SFLOAT;
1285 attributeDescs[0].offset = offsetof(Vertex, px);
1286
1287 attributeDescs[1].binding = 0;
1288 attributeDescs[1].location = 1;
1289 attributeDescs[1].format = VK_FORMAT_R32G32B32_SFLOAT;
1290 attributeDescs[1].offset = offsetof(Vertex, nx);
1291
1292 attributeDescs[2].binding = 0;
1293 attributeDescs[2].location = 2;
1294 attributeDescs[2].format = VK_FORMAT_R32G32B32A32_SFLOAT;
1295 attributeDescs[2].offset = offsetof(Vertex, tx);
1296
1297 attributeDescs[3].binding = 0;
1298 attributeDescs[3].location = 3;
1299 attributeDescs[3].format = VK_FORMAT_R32G32B32A32_SFLOAT;
1300 attributeDescs[3].offset = offsetof(Vertex, r);
1301
1302 attributeDescs[4].binding = 0;
1303 attributeDescs[4].location = 4;
1304 attributeDescs[4].format = VK_FORMAT_R32G32_SFLOAT;
1305 attributeDescs[4].offset = offsetof(Vertex, u);
1306
1307 attributeDescs[5].binding = 0;
1308 attributeDescs[5].location = 5;
1309 attributeDescs[5].format = VK_FORMAT_R32G32B32A32_SINT;
1310 attributeDescs[5].offset = offsetof(Vertex, boneIDs);
1311
1312 attributeDescs[6].binding = 0;
1313 attributeDescs[6].location = 6;
1314 attributeDescs[6].format = VK_FORMAT_R32G32B32A32_SFLOAT;
1315 attributeDescs[6].offset = offsetof(Vertex, boneWeights);
1316
1317 VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
1318 vertexInputInfo.sType =
1319 VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1320 vertexInputInfo.vertexBindingDescriptionCount = 1;
1321 vertexInputInfo.pVertexBindingDescriptions = &bindingDescription;
1322 vertexInputInfo.vertexAttributeDescriptionCount =
1323 static_cast<uint32_t>(attributeDescs.size());
1324 vertexInputInfo.pVertexAttributeDescriptions = attributeDescs.data();
1325
1326 VkPipelineInputAssemblyStateCreateInfo inputAssemblyInfo{};
1327 inputAssemblyInfo.sType =
1328 VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1329 inputAssemblyInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1330 inputAssemblyInfo.primitiveRestartEnable = VK_FALSE;
1331
1332 VkPipelineViewportStateCreateInfo viewportInfo{};
1333 viewportInfo.sType =
1334 VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1335 viewportInfo.viewportCount = 1;
1336 viewportInfo.scissorCount = 1;
1337
1338 VkPipelineRasterizationStateCreateInfo rasterizer{};
1339 rasterizer.sType =
1340 VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1341 rasterizer.depthClampEnable = VK_FALSE;
1342 rasterizer.rasterizerDiscardEnable = VK_FALSE;
1343 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
1344 rasterizer.lineWidth = 1.0f;
1345 rasterizer.cullMode = VK_CULL_MODE_NONE;
1346 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1347 rasterizer.depthBiasEnable = VK_FALSE;
1348
1349 VkPipelineMultisampleStateCreateInfo msaa{};
1350 msaa.sType =
1351 VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1352 msaa.sampleShadingEnable = VK_FALSE;
1353 // When deferred is enabled the skinned pipeline runs inside m_forwardRenderPass
1354 // which is always 1-sample (GBuffer outputs are resolved separately).
1355 // When forward-only, match the main render pass sample count.
1356 msaa.rasterizationSamples = (m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE)
1357 ? VK_SAMPLE_COUNT_1_BIT : m_msaaSamples;
1358
1359 // Skinned: depth test + depth write enabled (same as main pipeline)
1360 VkPipelineDepthStencilStateCreateInfo depthStencil{};
1361 depthStencil.sType =
1362 VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1363 depthStencil.depthTestEnable = VK_TRUE;
1364 depthStencil.depthWriteEnable = VK_TRUE;
1365 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
1366 depthStencil.depthBoundsTestEnable = VK_FALSE;
1367 depthStencil.stencilTestEnable = VK_FALSE;
1368
1369 VkPipelineColorBlendAttachmentState colorBlendAttachment{};
1370 colorBlendAttachment.blendEnable = VK_FALSE;
1371 colorBlendAttachment.colorWriteMask =
1372 VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
1373 VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1374
1375 VkPipelineColorBlendStateCreateInfo colorBlendInfo{};
1376 colorBlendInfo.sType =
1377 VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1378 colorBlendInfo.logicOpEnable = VK_FALSE;
1379 colorBlendInfo.attachmentCount = 1;
1380 colorBlendInfo.pAttachments = &colorBlendAttachment;
1381
1382 VkGraphicsPipelineCreateInfo pipelineInfo{};
1383 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1384 pipelineInfo.stageCount = 2;
1385 pipelineInfo.pStages = shaderStages;
1386 pipelineInfo.pVertexInputState = &vertexInputInfo;
1387 pipelineInfo.pInputAssemblyState = &inputAssemblyInfo;
1388 pipelineInfo.pViewportState = &viewportInfo;
1389 pipelineInfo.pRasterizationState = &rasterizer;
1390 pipelineInfo.pMultisampleState = &msaa;
1391 pipelineInfo.pDepthStencilState = &depthStencil;
1392 pipelineInfo.pColorBlendState = &colorBlendInfo;
1393 pipelineInfo.pDynamicState = &dynamicState;
1394 pipelineInfo.layout = pipelineLay; // Reuse same pipeline layout (set 0 + set 1)
1395 pipelineInfo.subpass = 0;
1396 pipelineInfo.renderPass = (m_deferredEnabled && m_forwardRenderPass != VK_NULL_HANDLE)
1397 ? m_forwardRenderPass : renderPass;
1398 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
1399 pipelineInfo.basePipelineIndex = -1;
1400
1401 VkResult result = vkCreateGraphicsPipelines(
1402 device, m_pipelineCache, 1, &pipelineInfo, nullptr, &skinnedPipeline);
1403 if (result != VK_SUCCESS) {
1404 SLEAK_ERROR("VulkanRenderer: Failed to create skinned pipeline!");
1405 return false;
1406 }
1407
1408 SLEAK_INFO("VulkanRenderer: Skinned pipeline created successfully");
1409 return true;
1410}
1411
1412
1413/// Binds the skinned pipeline matching the currently active render pass.
1415 if (!bFrameStarted) return;
1416
1417 if (m_inGeometryPass) {
1418 // GBuffer pass — use the GBuffer-compatible skinned pipeline
1419 if (m_skinnedGbufferPipeline == VK_NULL_HANDLE)
1420 CreateSkinnedGbufferPipeline();
1421 if (m_skinnedGbufferPipeline != VK_NULL_HANDLE)
1422 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS,
1423 m_skinnedGbufferPipeline);
1424 return;
1425 }
1426
1427 // Forward pass — use the forward skinned pipeline
1428 if (skinnedPipeline == VK_NULL_HANDLE) {
1429 if (!CreateSkinnedPipeline()) return;
1430 }
1431 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, skinnedPipeline);
1432}
1433
1434
1435/// Restores the previous pipeline after skinned draws.
1437 if (!bFrameStarted) return;
1438
1439 if (m_inGeometryPass) {
1440 // Restore static GBuffer pipeline
1441 if (m_gbufferPipeline != VK_NULL_HANDLE)
1442 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, m_gbufferPipeline);
1443 return;
1444 }
1445
1446 vkCmdBindPipeline(command, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
1447}
1448
1449#ifdef SLEAK_HOT_RELOAD
1450/// Rebuilds every pipeline from the SPIR-V on disk; this version ignores the
1451/// stems and rebuilds them all.
1452bool VulkanRenderer::ReloadShaders(const std::vector<std::string>& stems) {
1453 (void)stems;
1454 vkDeviceWaitIdle(device);
1455
1456 const PipelineGroup groups[] = {
1457 {"default_shader",
1458 {&pipeline},
1459 {},
1460 {&simpleShader},
1461 &VulkanRenderer::CreateGraphicsPipeline},
1462 {"skybox",
1463 {&skyboxPipeline},
1464 {},
1465 {&skyboxShader},
1466 &VulkanRenderer::CreateSkyboxPipeline},
1467 {"debug_line",
1468 {&debugLinePipeline},
1469 {},
1470 {&debugLineShader},
1471 &VulkanRenderer::CreateDebugLinePipeline},
1472 {"skinned_shader",
1473 {&skinnedPipeline},
1474 {},
1475 {&skinnedShader},
1476 &VulkanRenderer::CreateSkinnedPipeline},
1477 {"shadow_depth",
1478 {&m_shadowPipeline},
1479 {},
1480 {&m_shadowShader},
1481 &VulkanRenderer::CreateShadowPipeline},
1482 {"gbuffer",
1483 {&m_gbufferPipeline},
1484 {},
1485 {&m_gbufferShader},
1486 &VulkanRenderer::CreateGBufferPipeline},
1487 {"skinned gbuffer",
1488 {&m_skinnedGbufferPipeline},
1489 {},
1490 {},
1491 &VulkanRenderer::CreateSkinnedGbufferPipeline},
1492 {"lighting_pass",
1493 {&m_lightingPipeline},
1494 {&m_lightingPipelineLayout},
1495 {&m_lightingShader},
1496 &VulkanRenderer::CreateLightingPipeline},
1497 {"ssao",
1498 {&m_ssaoPipeline, &m_ssaoBlurPipeline},
1499 {&m_ssaoPipelineLayout, &m_ssaoBlurPipelineLayout},
1500 {&m_ssaoShader, &m_ssaoBlurShader},
1501 &VulkanRenderer::CreateSSAOPipelines},
1502 {"ssr",
1503 {&m_ssrPipeline},
1504 {},
1505 {&m_ssrShader},
1506 &VulkanRenderer::CreateSSRPipeline},
1507 {"taa",
1508 {&m_taaPipeline},
1509 {},
1510 {&m_taaShader},
1511 &VulkanRenderer::CreateTAAPipeline},
1512 {"bloom",
1513 {&m_bloomThresholdPipeline, &m_bloomDownsamplePipeline,
1514 &m_bloomUpsamplePipeline, &m_bloomCompositePipeline},
1515 {&m_bloomFilterPipelineLayout, &m_bloomCompositePipelineLayout},
1516 {&m_bloomThresholdShader, &m_bloomDownsampleShader,
1517 &m_bloomUpsampleShader, &m_bloomCompositeShader},
1518 &VulkanRenderer::CreateBloomPipelines},
1519 };
1520 for (const PipelineGroup& group : groups) ReloadPipelineGroup(group);
1521 ReloadCustomFormatPipelines();
1522 return true;
1523}
1524
1525/// Rebuilds a live group through its create function, keeping the old
1526/// objects when the rebuild fails.
1527void VulkanRenderer::ReloadPipelineGroup(const PipelineGroup& group) {
1528 // Pass is off or still builds lazily from disk
1529 if (*group.pipelines.front() == VK_NULL_HANDLE) return;
1530
1531 // Detach the live objects so the create function builds new ones
1532 std::vector<VkPipeline> pipelines;
1533 std::vector<VkPipelineLayout> layouts;
1534 std::vector<VulkanShader*> shaders;
1535 for (VkPipeline* pipe : group.pipelines)
1536 pipelines.push_back(std::exchange(*pipe, VK_NULL_HANDLE));
1537 for (VkPipelineLayout* layout : group.layouts)
1538 layouts.push_back(std::exchange(*layout, VK_NULL_HANDLE));
1539 for (VulkanShader** shader : group.shaders)
1540 shaders.push_back(std::exchange(*shader, nullptr));
1541
1542 bool built = (this->*group.create)();
1543 for (VkPipeline* pipe : group.pipelines)
1544 built = built && *pipe != VK_NULL_HANDLE;
1545 if (!built)
1546 SLEAK_ERROR("Hot reload: {} rebuild failed, keeping the previous one",
1547 group.name);
1548
1549 // Destroy the losing generation
1550 for (size_t i = 0; i < pipelines.size(); ++i) {
1551 if (!built) std::swap(*group.pipelines[i], pipelines[i]);
1552 if (pipelines[i]) vkDestroyPipeline(device, pipelines[i], nullptr);
1553 }
1554 for (size_t i = 0; i < layouts.size(); ++i) {
1555 if (!built) std::swap(*group.layouts[i], layouts[i]);
1556 if (layouts[i]) vkDestroyPipelineLayout(device, layouts[i], nullptr);
1557 }
1558 for (size_t i = 0; i < shaders.size(); ++i) {
1559 if (!built) std::swap(*group.shaders[i], shaders[i]);
1560 delete shaders[i];
1561 }
1562}
1563
1564/// Rebuilds every cached custom-format variant, keeping the old pipeline of
1565/// a variant that fails.
1566void VulkanRenderer::ReloadCustomFormatPipelines() {
1567 for (size_t i = 0; i < m_customFormatPipelines.size(); ++i) {
1568 const auto format = static_cast<VertexFormatHandle>(i + 1);
1569 CustomFormatPipelines& pipes = m_customFormatPipelines[i];
1570 // Variants that failed before retry on next use
1571 pipes.failed.fill(false);
1572 const VertexLayoutDesc* desc = VertexFormatRegistry::Get(format);
1573 if (!desc) continue;
1574 for (size_t slot = 0; slot < CUSTOM_PASS_COUNT; ++slot) {
1575 VkPipeline& live = pipes.pipelines[slot];
1576 if (live == VK_NULL_HANDLE) continue;
1577 const VkPipeline rebuilt = BuildCustomFormatPipeline(
1578 format, *desc, static_cast<CustomPass>(slot));
1579 if (rebuilt == VK_NULL_HANDLE) {
1581 "Hot reload: vertex format {} keeps its previous pipeline",
1582 format);
1583 continue;
1584 }
1585 vkDestroyPipeline(device, live, nullptr);
1586 live = rebuilt;
1587 }
1588 }
1589}
1590#endif
1591}
1592}
#define SLEAK_ERROR(...)
Definition Logger.hpp:22
#define SLEAK_RETURN_ERR(...)
Definition Logger.hpp:25
#define SLEAK_INFO(...)
Definition Logger.hpp:20
#define SLEAK_WARN(...)
Definition Logger.hpp:21
#define FNV1A_PRIME
#define FNV1A_OFFSET_BASIS
#define SHADOW_DEPTH_BIAS_CONSTANT
#define PUSH_CONSTANT_BYTES
#define SHADOW_DEPTH_BIAS_SLOPE
virtual bool ReloadShaders(const std::vector< std::string > &stems)
Definition Renderer.hpp:56
virtual void EndDebugLinePass() override
Restores the previous pipeline and descriptor set after debug line draws.
virtual bool IsDeferredEnabled() const override
virtual void EndSkinnedPass() override
Restores the previous pipeline after skinned draws.
virtual void EndCustomFormatPass() override
Restores the previous pipeline and descriptor set after custom-format draws.
virtual void EndSkyboxPass() override
Restores the previous pipeline and descriptor set after the skybox draw.
virtual void BeginDebugLinePass() override
Binds the debug line pipeline for the current frame.
virtual void BeginSkinnedPass() override
Binds the skinned pipeline matching the currently active render pass.
virtual void BeginSkyboxPass() override
Binds the skybox pipeline and its descriptor set for the current frame.
virtual void BeginCustomFormatPass(VertexFormatHandle format) override
Binds the custom-format pipeline matching the currently active render pass.
VkPipelineShaderStageCreateInfo GetFragInfo()
VkPipelineShaderStageCreateInfo GetVertexInfo()
virtual bool compile(const std::string &shaderPath) override
Loads the combined-path convention's .vert.spv/.frag.spv pair.
static const VertexLayoutDesc * Get(VertexFormatHandle handle)
Backend-facing rendering layer shared by the four graphics backends.
static VkFormat ToVkVertexFormat(VertexAttribFormat format)
Translates a registry attribute format into its Vulkan vertex format.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10
uint32_t VertexFormatHandle