Line data Source code
1 : /* Copyright (C) 2026 Wildfire Games.
2 : * This file is part of 0 A.D.
3 : *
4 : * 0 A.D. is free software: you can redistribute it and/or modify
5 : * it under the terms of the GNU General Public License as published by
6 : * the Free Software Foundation, either version 2 of the License, or
7 : * (at your option) any later version.
8 : *
9 : * 0 A.D. is distributed in the hope that it will be useful,
10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 : * GNU General Public License for more details.
13 : *
14 : * You should have received a copy of the GNU General Public License
15 : * along with 0 A.D. If not, see <http://www.gnu.org/licenses/>.
16 : */
17 :
18 : #include "precompiled.h"
19 :
20 : #include "ShaderProgram.h"
21 :
22 : #include "graphics/ShaderDefines.h"
23 : #include "lib/path.h"
24 : #include "lib/utf8.h"
25 : #include "ps/CLogger.h"
26 : #include "ps/CStr.h"
27 : #include "ps/CStrInternStatic.h"
28 : #include "ps/Errors.h"
29 : #include "ps/Filesystem.h"
30 : #include "ps/XMB/XMBData.h"
31 : #include "ps/XMB/XMBStorage.h"
32 : #include "ps/XML/Xeromyces.h"
33 : #include "ps/containers/StaticVector.h"
34 : #include "renderer/backend/ITexture.h"
35 : #include "renderer/backend/vulkan/Buffer.h"
36 : #include "renderer/backend/vulkan/DescriptorManager.h"
37 : #include "renderer/backend/vulkan/Device.h"
38 : #include "renderer/backend/vulkan/DeviceSelection.h"
39 : #include "renderer/backend/vulkan/RingCommandContext.h"
40 : #include "renderer/backend/vulkan/Texture.h"
41 : #include "renderer/backend/vulkan/Utilities.h"
42 :
43 : #include <algorithm>
44 : #include <cstring>
45 : #include <iterator>
46 : #include <limits>
47 : #include <map>
48 : #include <string>
49 : #include <tuple>
50 :
51 : namespace Renderer
52 : {
53 :
54 : namespace Backend
55 : {
56 :
57 : namespace Vulkan
58 : {
59 :
60 : namespace
61 : {
62 :
63 : enum class BindingSlotType
64 : {
65 : PUSH_CONSTANT,
66 : UNIFORM,
67 : TEXTURE,
68 : STORAGE_IMAGE,
69 : STORAGE_BUFFER
70 : };
71 :
72 : constexpr uint32_t BINDING_SLOT_TYPE_SHIFT{16u};
73 : constexpr uint32_t BINDING_SLOT_VALUE_MASK{(1u << BINDING_SLOT_TYPE_SHIFT) - 1u};
74 :
75 0 : VkShaderModule CreateShaderModule(CDevice* device, const VfsPath& path)
76 : {
77 0 : CVFSFile file;
78 0 : if (file.Load(g_VFS, path) != PSRETURN_OK)
79 : {
80 0 : LOGERROR("Failed to load shader file: '{}'", path.string8());
81 0 : return VK_NULL_HANDLE;
82 : }
83 :
84 0 : VkShaderModuleCreateInfo createInfo{};
85 0 : createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
86 : // Casting to uint32_t requires to fit alignment and size.
87 0 : ENSURE(file.GetBufferSize() % 4 == 0);
88 0 : ENSURE(reinterpret_cast<uintptr_t>(file.GetBuffer()) % alignof(uint32_t) == 0u);
89 0 : createInfo.codeSize = file.GetBufferSize();
90 0 : createInfo.pCode = reinterpret_cast<const uint32_t*>(file.GetBuffer());
91 :
92 0 : VkShaderModule shaderModule;
93 0 : const VkResult result = vkCreateShaderModule(device->GetVkDevice(), &createInfo, nullptr, &shaderModule);
94 0 : if (result != VK_SUCCESS)
95 : {
96 0 : LOGERROR("Failed to create shader module from file: '{}' {} ({})",
97 : path.string8(), static_cast<int>(result), Utilities::GetVkResultName(result));
98 0 : return VK_NULL_HANDLE;
99 : }
100 0 : device->SetObjectName(VK_OBJECT_TYPE_SHADER_MODULE, shaderModule, path.string8().c_str());
101 0 : return shaderModule;
102 0 : }
103 :
104 0 : VfsPath FindProgramMatchingDefines(const VfsPath& xmlFilename, const CShaderDefines& defines)
105 : {
106 0 : CXeromyces xeroFile;
107 0 : PSRETURN ret = xeroFile.Load(g_VFS, xmlFilename);
108 0 : if (ret != PSRETURN_OK)
109 0 : return {};
110 :
111 : // TODO: add XML validation.
112 :
113 : #define EL(x) const int el_##x = xeroFile.GetElementID(#x)
114 : #define AT(x) const int at_##x = xeroFile.GetAttributeID(#x)
115 0 : EL(define);
116 0 : EL(defines);
117 0 : EL(program);
118 0 : AT(file);
119 0 : AT(name);
120 0 : AT(value);
121 : #undef AT
122 : #undef EL
123 :
124 0 : const CStrIntern strUndefined("UNDEFINED");
125 0 : VfsPath programFilename;
126 0 : XMBElement root = xeroFile.GetRoot();
127 0 : for (XMBElement rootChild : root.GetChildNodes())
128 : {
129 0 : if (rootChild.GetNodeName() == el_program)
130 : {
131 0 : CShaderDefines programDefines;
132 0 : for (XMBElement programChild : rootChild.GetChildNodes())
133 : {
134 0 : if (programChild.GetNodeName() == el_defines)
135 : {
136 0 : for (XMBElement definesChild : programChild.GetChildNodes())
137 : {
138 0 : XMBAttributeList attributes = definesChild.GetAttributes();
139 0 : if (definesChild.GetNodeName() == el_define)
140 : {
141 0 : const CStrIntern value(attributes.GetNamedItem(at_value));
142 0 : if (value == strUndefined)
143 0 : continue;
144 0 : programDefines.Add(
145 0 : CStrIntern(attributes.GetNamedItem(at_name)), value);
146 : }
147 : }
148 : }
149 : }
150 :
151 0 : if (programDefines == defines)
152 0 : return L"shaders/" + rootChild.GetAttributes().GetNamedItem(at_file).FromUTF8();
153 : }
154 : }
155 :
156 0 : return {};
157 0 : }
158 :
159 : } // anonymous namespace
160 :
161 0 : IDevice* CVertexInputLayout::GetDevice()
162 : {
163 0 : return m_Device;
164 : }
165 :
166 : // static
167 0 : std::unique_ptr<CShaderProgram> CShaderProgram::Create(
168 : CDevice* device, const CStr& name, const CShaderDefines& baseDefines)
169 : {
170 0 : const VfsPath xmlFilename = L"shaders/" + wstring_from_utf8(name) + L".xml";
171 :
172 0 : std::unique_ptr<CShaderProgram> shaderProgram(new CShaderProgram());
173 0 : shaderProgram->m_Device = device;
174 0 : shaderProgram->m_FileDependencies = {xmlFilename};
175 :
176 0 : CShaderDefines defines = baseDefines;
177 0 : if (device->GetDescriptorManager().UseDescriptorIndexing())
178 0 : defines.Add(str_USE_DESCRIPTOR_INDEXING, str_1);
179 :
180 0 : const VfsPath programFilename = FindProgramMatchingDefines(xmlFilename, defines);
181 0 : if (programFilename.empty())
182 : {
183 0 : LOGERROR("Program '{}' with required defines not found.", name);
184 0 : for (const auto& pair : defines.GetMap())
185 0 : LOGERROR(" \"{}\": \"{}\"", pair.first.string(), pair.second.string());
186 0 : return nullptr;
187 : }
188 0 : shaderProgram->m_FileDependencies.emplace_back(programFilename);
189 :
190 0 : CXeromyces programXeroFile;
191 0 : if (programXeroFile.Load(g_VFS, programFilename) != PSRETURN_OK)
192 0 : return nullptr;
193 0 : XMBElement programRoot = programXeroFile.GetRoot();
194 :
195 : #define EL(x) const int el_##x = programXeroFile.GetElementID(#x)
196 : #define AT(x) const int at_##x = programXeroFile.GetAttributeID(#x)
197 0 : EL(binding);
198 0 : EL(compute);
199 0 : EL(descriptor_set);
200 0 : EL(descriptor_sets);
201 0 : EL(fragment);
202 0 : EL(member);
203 0 : EL(push_constant);
204 0 : EL(stream);
205 0 : EL(vertex);
206 0 : AT(binding);
207 0 : AT(file);
208 0 : AT(location);
209 0 : AT(name);
210 0 : AT(offset);
211 0 : AT(set);
212 0 : AT(size);
213 0 : AT(type);
214 : #undef AT
215 : #undef EL
216 :
217 0 : auto addPushConstant =
218 0 : [&pushConstants=shaderProgram->m_PushConstants, &pushConstantDataFlags=shaderProgram->m_PushConstantDataFlags, &at_name, &at_offset, &at_size](
219 0 : const XMBElement& element, VkShaderStageFlags stageFlags) -> bool
220 : {
221 0 : const XMBAttributeList attributes = element.GetAttributes();
222 0 : const CStrIntern name = CStrIntern(attributes.GetNamedItem(at_name));
223 0 : const uint32_t size = attributes.GetNamedItem(at_size).ToUInt();
224 0 : const uint32_t offset = attributes.GetNamedItem(at_offset).ToUInt();
225 0 : if (offset % 4 != 0 || size % 4 != 0)
226 : {
227 0 : LOGERROR("Push constant should have offset and size be multiple of 4.");
228 0 : return false;
229 : }
230 0 : for (PushConstant& pushConstant : pushConstants)
231 : {
232 0 : if (pushConstant.name == name)
233 : {
234 0 : if (size != pushConstant.size || offset != pushConstant.offset)
235 : {
236 0 : LOGERROR("All shared push constants must have the same size and offset.");
237 0 : return false;
238 : }
239 : // We found the same constant so we don't need to add it again.
240 0 : pushConstant.stageFlags |= stageFlags;
241 0 : for (uint32_t index = 0; index < (size >> 2); ++index)
242 0 : pushConstantDataFlags[(offset >> 2) + index] |= stageFlags;
243 : return true;
244 : }
245 0 : if (offset + size < pushConstant.offset || offset >= pushConstant.offset + pushConstant.size)
246 0 : continue;
247 0 : LOGERROR("All push constant must not intersect each other in memory.");
248 0 : return false;
249 : }
250 0 : pushConstants.push_back({name, offset, size, stageFlags});
251 0 : for (uint32_t index = 0; index < (size >> 2); ++index)
252 0 : pushConstantDataFlags[(offset >> 2) + index] = stageFlags;
253 : return true;
254 0 : };
255 :
256 0 : uint32_t texturesDescriptorSetSize = 0;
257 0 : std::unordered_map<CStrIntern, uint32_t> textureMapping;
258 :
259 0 : VkDescriptorType storageImageDescriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM;
260 0 : uint32_t storageImageDescriptorSetSize = 0;
261 0 : std::unordered_map<CStrIntern, uint32_t> storageImageMapping;
262 :
263 0 : VkDescriptorType storageBufferDescriptorType = VK_DESCRIPTOR_TYPE_MAX_ENUM;
264 0 : uint32_t storageBufferDescriptorSetSize = 0;
265 0 : std::unordered_map<CStrIntern, uint32_t> storageBufferMapping;
266 :
267 0 : auto addDescriptorSets = [&](const XMBElement& element) -> bool
268 : {
269 0 : const bool useDescriptorIndexing =
270 0 : device->GetDescriptorManager().UseDescriptorIndexing();
271 : // TODO: reduce the indentation.
272 0 : for (XMBElement descriporSetsChild : element.GetChildNodes())
273 : {
274 0 : if (descriporSetsChild.GetNodeName() == el_descriptor_set)
275 : {
276 0 : const uint32_t set = descriporSetsChild.GetAttributes().GetNamedItem(at_set).ToUInt();
277 0 : if (useDescriptorIndexing && set == 0 && !descriporSetsChild.GetChildNodes().empty())
278 : {
279 0 : LOGERROR("Descriptor set for descriptor indexing shouldn't contain bindings.");
280 0 : return false;
281 : }
282 0 : for (XMBElement descriporSetChild : descriporSetsChild.GetChildNodes())
283 : {
284 0 : if (descriporSetChild.GetNodeName() == el_binding)
285 : {
286 0 : const XMBAttributeList attributes = descriporSetChild.GetAttributes();
287 0 : const uint32_t binding = attributes.GetNamedItem(at_binding).ToUInt();
288 0 : const uint32_t size = attributes.GetNamedItem(at_size).ToUInt();
289 0 : const CStr type = attributes.GetNamedItem(at_type);
290 0 : if (type == "uniform")
291 : {
292 0 : const uint32_t expectedSet =
293 0 : device->GetDescriptorManager().GetUniformSet();
294 0 : if (set != expectedSet || binding != 0)
295 : {
296 0 : LOGERROR("We support only a single uniform block per shader program.");
297 0 : return false;
298 : }
299 0 : shaderProgram->m_MaterialConstantsDataSize = size;
300 0 : for (XMBElement bindingChild : descriporSetChild.GetChildNodes())
301 : {
302 0 : if (bindingChild.GetNodeName() == el_member)
303 : {
304 0 : const XMBAttributeList memberAttributes = bindingChild.GetAttributes();
305 0 : const uint32_t offset = memberAttributes.GetNamedItem(at_offset).ToUInt();
306 0 : const uint32_t size = memberAttributes.GetNamedItem(at_size).ToUInt();
307 0 : const CStrIntern name{memberAttributes.GetNamedItem(at_name)};
308 0 : bool found = false;
309 0 : for (const Uniform& uniform : shaderProgram->m_Uniforms)
310 : {
311 0 : if (uniform.name == name)
312 : {
313 0 : if (offset != uniform.offset || size != uniform.size)
314 : {
315 0 : LOGERROR("All uniforms across all stage should match.");
316 0 : return false;
317 : }
318 : found = true;
319 : }
320 : else
321 : {
322 0 : if (offset + size <= uniform.offset || uniform.offset + uniform.size <= offset)
323 0 : continue;
324 0 : LOGERROR("Uniforms must not overlap each other.");
325 0 : return false;
326 : }
327 : }
328 0 : if (!found)
329 0 : shaderProgram->m_Uniforms.push_back({name, offset, size});
330 : }
331 : }
332 : }
333 0 : else if (type == "sampler1D" || type == "sampler2D" || type == "sampler2DShadow" || type == "sampler3D" || type == "samplerCube")
334 : {
335 0 : if (useDescriptorIndexing)
336 : {
337 0 : LOGERROR("We support only uniform descriptor sets with enabled descriptor indexing.");
338 0 : return false;
339 : }
340 0 : const CStrIntern name{attributes.GetNamedItem(at_name)};
341 0 : textureMapping[name] = binding;
342 0 : texturesDescriptorSetSize =
343 0 : std::max(texturesDescriptorSetSize, binding + 1);
344 : }
345 0 : else if (type == "storageImage")
346 : {
347 0 : const CStrIntern name{attributes.GetNamedItem(at_name)};
348 0 : storageImageMapping[name] = binding;
349 0 : storageImageDescriptorSetSize =
350 0 : std::max(storageImageDescriptorSetSize, binding + 1);
351 0 : const VkDescriptorType descriptorType{VK_DESCRIPTOR_TYPE_STORAGE_IMAGE};
352 0 : if (storageImageDescriptorType == VK_DESCRIPTOR_TYPE_MAX_ENUM)
353 0 : storageImageDescriptorType = descriptorType;
354 0 : else if (storageImageDescriptorType != descriptorType)
355 : {
356 0 : LOGERROR("Shader should have storages of the same type.");
357 0 : return false;
358 : }
359 : }
360 0 : else if (type == "storageBuffer")
361 : {
362 0 : const CStrIntern name{attributes.GetNamedItem(at_name)};
363 0 : storageBufferMapping[name] = binding;
364 0 : storageBufferDescriptorSetSize =
365 0 : std::max(storageBufferDescriptorSetSize, binding + 1);
366 0 : const VkDescriptorType descriptorType{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER};
367 0 : if (storageBufferDescriptorType == VK_DESCRIPTOR_TYPE_MAX_ENUM)
368 0 : storageBufferDescriptorType = descriptorType;
369 0 : else if (storageBufferDescriptorType != descriptorType)
370 : {
371 0 : LOGERROR("Shader should have storages of the same type.");
372 0 : return false;
373 : }
374 : }
375 : else
376 : {
377 0 : LOGERROR("Unsupported binding: '{}'", type);
378 0 : return false;
379 : }
380 0 : }
381 : }
382 : }
383 : }
384 0 : return true;
385 0 : };
386 :
387 0 : for (XMBElement programChild : programRoot.GetChildNodes())
388 : {
389 0 : if (programChild.GetNodeName() == el_vertex)
390 : {
391 0 : if (shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_MAX_ENUM &&
392 0 : shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_GRAPHICS)
393 : {
394 0 : LOGERROR("Shader program can't mix different pipelines: '{}'.", name);
395 0 : return nullptr;
396 : }
397 0 : shaderProgram->m_PipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
398 0 : const VfsPath shaderModulePath =
399 0 : L"shaders/" + programChild.GetAttributes().GetNamedItem(at_file).FromUTF8();
400 0 : shaderProgram->m_FileDependencies.emplace_back(shaderModulePath);
401 0 : shaderProgram->m_ShaderModules.emplace_back(
402 0 : CreateShaderModule(device, shaderModulePath));
403 0 : if (shaderProgram->m_ShaderModules.back() == VK_NULL_HANDLE)
404 0 : return nullptr;
405 0 : VkPipelineShaderStageCreateInfo vertexShaderStageInfo{};
406 0 : vertexShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
407 0 : vertexShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
408 0 : vertexShaderStageInfo.module = shaderProgram->m_ShaderModules.back();
409 0 : vertexShaderStageInfo.pName = "main";
410 0 : shaderProgram->m_Stages.emplace_back(std::move(vertexShaderStageInfo));
411 0 : for (XMBElement stageChild : programChild.GetChildNodes())
412 : {
413 0 : if (stageChild.GetNodeName() == el_stream)
414 : {
415 0 : XMBAttributeList attributes = stageChild.GetAttributes();
416 0 : const uint32_t location = attributes.GetNamedItem(at_location).ToUInt();
417 0 : const CStr streamName = attributes.GetNamedItem(at_name);
418 0 : VertexAttributeStream stream = VertexAttributeStream::UV7;
419 0 : if (streamName == "pos")
420 0 : stream = VertexAttributeStream::POSITION;
421 0 : else if (streamName == "normal")
422 0 : stream = VertexAttributeStream::NORMAL;
423 0 : else if (streamName == "color")
424 0 : stream = VertexAttributeStream::COLOR;
425 0 : else if (streamName == "uv0")
426 0 : stream = VertexAttributeStream::UV0;
427 0 : else if (streamName == "uv1")
428 0 : stream = VertexAttributeStream::UV1;
429 0 : else if (streamName == "uv2")
430 0 : stream = VertexAttributeStream::UV2;
431 0 : else if (streamName == "uv3")
432 0 : stream = VertexAttributeStream::UV3;
433 0 : else if (streamName == "uv4")
434 0 : stream = VertexAttributeStream::UV4;
435 0 : else if (streamName == "uv5")
436 0 : stream = VertexAttributeStream::UV5;
437 0 : else if (streamName == "uv6")
438 0 : stream = VertexAttributeStream::UV6;
439 0 : else if (streamName == "uv7")
440 : stream = VertexAttributeStream::UV7;
441 : else
442 0 : debug_warn("Unknown stream");
443 0 : shaderProgram->m_StreamLocations[stream] = location;
444 0 : }
445 0 : else if (stageChild.GetNodeName() == el_push_constant)
446 : {
447 0 : if (!addPushConstant(stageChild, VK_SHADER_STAGE_VERTEX_BIT))
448 0 : return nullptr;
449 : }
450 0 : else if (stageChild.GetNodeName() == el_descriptor_sets)
451 : {
452 0 : if (!addDescriptorSets(stageChild))
453 0 : return nullptr;
454 : }
455 : }
456 0 : }
457 0 : else if (programChild.GetNodeName() == el_fragment)
458 : {
459 0 : if (shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_MAX_ENUM &&
460 0 : shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_GRAPHICS)
461 : {
462 0 : LOGERROR("Shader program can't mix different pipelines: '{}'.", name);
463 0 : return nullptr;
464 : }
465 0 : shaderProgram->m_PipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
466 0 : const VfsPath shaderModulePath =
467 0 : L"shaders/" + programChild.GetAttributes().GetNamedItem(at_file).FromUTF8();
468 0 : shaderProgram->m_FileDependencies.emplace_back(shaderModulePath);
469 0 : shaderProgram->m_ShaderModules.emplace_back(
470 0 : CreateShaderModule(device, shaderModulePath));
471 0 : if (shaderProgram->m_ShaderModules.back() == VK_NULL_HANDLE)
472 0 : return nullptr;
473 0 : VkPipelineShaderStageCreateInfo fragmentShaderStageInfo{};
474 0 : fragmentShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
475 0 : fragmentShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
476 0 : fragmentShaderStageInfo.module = shaderProgram->m_ShaderModules.back();
477 0 : fragmentShaderStageInfo.pName = "main";
478 0 : shaderProgram->m_Stages.emplace_back(std::move(fragmentShaderStageInfo));
479 0 : for (XMBElement stageChild : programChild.GetChildNodes())
480 : {
481 0 : if (stageChild.GetNodeName() == el_push_constant)
482 : {
483 0 : if (!addPushConstant(stageChild, VK_SHADER_STAGE_FRAGMENT_BIT))
484 0 : return nullptr;
485 : }
486 0 : else if (stageChild.GetNodeName() == el_descriptor_sets)
487 : {
488 0 : if (!addDescriptorSets(stageChild))
489 0 : return nullptr;
490 : }
491 : }
492 0 : }
493 0 : else if (programChild.GetNodeName() == el_compute)
494 : {
495 0 : if (shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_MAX_ENUM &&
496 0 : shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_COMPUTE)
497 : {
498 0 : LOGERROR("Shader program can't mix different pipelines: '{}'.", name);
499 0 : return nullptr;
500 : }
501 0 : shaderProgram->m_PipelineBindPoint = VK_PIPELINE_BIND_POINT_COMPUTE;
502 0 : const VfsPath shaderModulePath =
503 0 : L"shaders/" + programChild.GetAttributes().GetNamedItem(at_file).FromUTF8();
504 0 : shaderProgram->m_FileDependencies.emplace_back(shaderModulePath);
505 0 : shaderProgram->m_ShaderModules.emplace_back(
506 0 : CreateShaderModule(device, shaderModulePath));
507 0 : if (shaderProgram->m_ShaderModules.back() == VK_NULL_HANDLE)
508 0 : return nullptr;
509 0 : VkPipelineShaderStageCreateInfo computeShaderStageInfo{};
510 0 : computeShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
511 0 : computeShaderStageInfo.stage = VK_SHADER_STAGE_COMPUTE_BIT;
512 0 : computeShaderStageInfo.module = shaderProgram->m_ShaderModules.back();
513 0 : computeShaderStageInfo.pName = "main";
514 0 : shaderProgram->m_Stages.emplace_back(std::move(computeShaderStageInfo));
515 0 : for (XMBElement stageChild : programChild.GetChildNodes())
516 : {
517 0 : if (stageChild.GetNodeName() == el_push_constant)
518 : {
519 0 : if (!addPushConstant(stageChild, VK_SHADER_STAGE_COMPUTE_BIT))
520 0 : return nullptr;
521 : }
522 0 : else if (stageChild.GetNodeName() == el_descriptor_sets)
523 : {
524 0 : if (!addDescriptorSets(stageChild))
525 0 : return nullptr;
526 : }
527 : }
528 0 : }
529 : }
530 :
531 0 : if (shaderProgram->m_Stages.empty())
532 : {
533 0 : LOGERROR("Program should contain at least one stage.");
534 0 : return nullptr;
535 : }
536 :
537 0 : ENSURE(shaderProgram->m_PipelineBindPoint != VK_PIPELINE_BIND_POINT_MAX_ENUM);
538 :
539 0 : for (size_t index = 0; index < shaderProgram->m_PushConstants.size(); ++index)
540 0 : shaderProgram->m_PushConstantMapping[shaderProgram->m_PushConstants[index].name] = index;
541 0 : std::vector<VkPushConstantRange> pushConstantRanges;
542 0 : pushConstantRanges.reserve(shaderProgram->m_PushConstants.size());
543 0 : std::transform(
544 0 : shaderProgram->m_PushConstants.begin(), shaderProgram->m_PushConstants.end(),
545 0 : std::back_insert_iterator(pushConstantRanges), [](const PushConstant& pushConstant)
546 : {
547 0 : return VkPushConstantRange{pushConstant.stageFlags, pushConstant.offset, pushConstant.size};
548 : });
549 0 : if (!pushConstantRanges.empty())
550 : {
551 0 : std::sort(pushConstantRanges.begin(), pushConstantRanges.end(),
552 0 : [](const VkPushConstantRange& lhs, const VkPushConstantRange& rhs)
553 : {
554 0 : return lhs.offset < rhs.offset;
555 : });
556 : // Merge subsequent constants.
557 0 : auto it = pushConstantRanges.begin();
558 0 : while (std::next(it) != pushConstantRanges.end())
559 : {
560 0 : auto next = std::next(it);
561 0 : if (it->stageFlags == next->stageFlags)
562 : {
563 0 : it->size = next->offset - it->offset + next->size;
564 0 : pushConstantRanges.erase(next);
565 : }
566 : else
567 : it = next;
568 : }
569 0 : for (const VkPushConstantRange& range : pushConstantRanges)
570 0 : if (std::count_if(pushConstantRanges.begin(), pushConstantRanges.end(),
571 0 : [stageFlags=range.stageFlags](const VkPushConstantRange& range) { return range.stageFlags & stageFlags; }) != 1)
572 : {
573 0 : LOGERROR("Any two range must not include the same stage in stageFlags.");
574 0 : return nullptr;
575 : }
576 : }
577 :
578 0 : for (size_t index = 0; index < shaderProgram->m_Uniforms.size(); ++index)
579 0 : shaderProgram->m_UniformMapping[shaderProgram->m_Uniforms[index].name] = index;
580 0 : if (!shaderProgram->m_Uniforms.empty())
581 : {
582 0 : if (shaderProgram->m_MaterialConstantsDataSize > device->GetChoosenPhysicalDevice().properties.limits.maxUniformBufferRange)
583 : {
584 0 : LOGERROR("Uniform buffer size is too big for the device.");
585 0 : return nullptr;
586 : }
587 0 : shaderProgram->m_MaterialConstantsData =
588 0 : std::make_unique<std::byte[]>(shaderProgram->m_MaterialConstantsDataSize);
589 : }
590 :
591 0 : std::vector<VkDescriptorSetLayout> layouts =
592 0 : device->GetDescriptorManager().GetDescriptorSetLayouts();
593 0 : if (texturesDescriptorSetSize > 0)
594 : {
595 0 : ENSURE(!device->GetDescriptorManager().UseDescriptorIndexing());
596 0 : shaderProgram->m_TextureBinding.emplace(
597 0 : device, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, texturesDescriptorSetSize, std::move(textureMapping));
598 0 : layouts.emplace_back(shaderProgram->m_TextureBinding->GetDescriptorSetLayout());
599 : }
600 0 : if (storageImageDescriptorSetSize > 0)
601 : {
602 0 : shaderProgram->m_StorageImageBinding.emplace(
603 : device, storageImageDescriptorType, storageImageDescriptorSetSize, std::move(storageImageMapping));
604 0 : layouts.emplace_back(shaderProgram->m_StorageImageBinding->GetDescriptorSetLayout());
605 : }
606 0 : if (storageBufferDescriptorSetSize > 0)
607 : {
608 0 : shaderProgram->m_StorageBufferBinding.emplace(
609 : device, storageBufferDescriptorType, storageBufferDescriptorSetSize, std::move(storageBufferMapping));
610 0 : layouts.emplace_back(shaderProgram->m_StorageBufferBinding->GetDescriptorSetLayout());
611 : }
612 :
613 0 : VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{};
614 0 : pipelineLayoutCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
615 0 : pipelineLayoutCreateInfo.setLayoutCount = layouts.size();
616 0 : pipelineLayoutCreateInfo.pSetLayouts = layouts.data();
617 0 : pipelineLayoutCreateInfo.pushConstantRangeCount = pushConstantRanges.size();
618 0 : pipelineLayoutCreateInfo.pPushConstantRanges = pushConstantRanges.data();
619 :
620 0 : const VkResult result = vkCreatePipelineLayout(
621 : device->GetVkDevice(), &pipelineLayoutCreateInfo, nullptr,
622 0 : &shaderProgram->m_PipelineLayout);
623 0 : if (result != VK_SUCCESS)
624 : {
625 0 : LOGERROR("Failed to create a pipeline layout: {} ({})",
626 : static_cast<int>(result), Utilities::GetVkResultName(result));
627 0 : return nullptr;
628 : }
629 :
630 0 : return shaderProgram;
631 0 : }
632 :
633 0 : CShaderProgram::CShaderProgram() = default;
634 :
635 0 : CShaderProgram::~CShaderProgram()
636 : {
637 0 : if (m_PipelineLayout != VK_NULL_HANDLE)
638 0 : m_Device->ScheduleObjectToDestroy(VK_OBJECT_TYPE_PIPELINE_LAYOUT, m_PipelineLayout, VK_NULL_HANDLE);
639 0 : for (VkShaderModule shaderModule : m_ShaderModules)
640 0 : if (shaderModule != VK_NULL_HANDLE)
641 0 : m_Device->ScheduleObjectToDestroy(VK_OBJECT_TYPE_SHADER_MODULE, shaderModule, VK_NULL_HANDLE);
642 0 : }
643 :
644 0 : IDevice* CShaderProgram::GetDevice()
645 : {
646 0 : return m_Device;
647 : }
648 :
649 0 : int32_t CShaderProgram::GetBindingSlot(const CStrIntern name) const
650 : {
651 0 : if (auto it = m_PushConstantMapping.find(name); it != m_PushConstantMapping.end())
652 0 : return (static_cast<uint32_t>(BindingSlotType::PUSH_CONSTANT) << BINDING_SLOT_TYPE_SHIFT) | it->second;
653 0 : if (auto it = m_UniformMapping.find(name); it != m_UniformMapping.end())
654 0 : return (static_cast<uint32_t>(BindingSlotType::UNIFORM) << BINDING_SLOT_TYPE_SHIFT) | it->second;
655 0 : if (const int32_t bindingSlot = m_TextureBinding.has_value() ? m_TextureBinding->GetBindingSlot(name) : -1; bindingSlot != -1)
656 0 : return (static_cast<uint32_t>(BindingSlotType::TEXTURE) << BINDING_SLOT_TYPE_SHIFT) | bindingSlot;
657 0 : if (const int32_t bindingSlot = m_StorageImageBinding.has_value() ? m_StorageImageBinding->GetBindingSlot(name) : -1; bindingSlot != -1)
658 0 : return (static_cast<uint32_t>(BindingSlotType::STORAGE_IMAGE) << BINDING_SLOT_TYPE_SHIFT) | bindingSlot;
659 0 : if (const int32_t bindingSlot = m_StorageBufferBinding.has_value() ? m_StorageBufferBinding->GetBindingSlot(name) : -1; bindingSlot != -1)
660 0 : return (static_cast<uint32_t>(BindingSlotType::STORAGE_BUFFER) << BINDING_SLOT_TYPE_SHIFT) | bindingSlot;
661 : return -1;
662 : }
663 :
664 0 : std::vector<VfsPath> CShaderProgram::GetFileDependencies() const
665 : {
666 0 : return m_FileDependencies;
667 : }
668 :
669 0 : uint32_t CShaderProgram::GetStreamLocation(const VertexAttributeStream stream) const
670 : {
671 0 : auto it = m_StreamLocations.find(stream);
672 0 : return it != m_StreamLocations.end() ? it->second : std::numeric_limits<uint32_t>::max();
673 : }
674 :
675 0 : void CShaderProgram::Bind()
676 : {
677 0 : if (m_MaterialConstantsData)
678 0 : m_MaterialConstantsDataOutdated = true;
679 0 : }
680 :
681 0 : void CShaderProgram::Unbind()
682 : {
683 0 : if (m_TextureBinding.has_value())
684 0 : m_TextureBinding->Unbind();
685 0 : if (m_StorageImageBinding.has_value())
686 0 : m_StorageImageBinding->Unbind();
687 0 : if (m_StorageBufferBinding.has_value())
688 0 : m_StorageBufferBinding->Unbind();
689 0 : }
690 :
691 0 : void CShaderProgram::PreDraw(CRingCommandContext& commandContext)
692 : {
693 0 : BindOutdatedDescriptorSets(commandContext);
694 0 : if (m_PushConstantDataMask)
695 : {
696 0 : for (uint32_t index = 0; index < 32;)
697 : {
698 0 : if (!(m_PushConstantDataMask & (1 << index)))
699 : {
700 0 : ++index;
701 0 : continue;
702 : }
703 0 : uint32_t indexEnd = index + 1;
704 0 : while (indexEnd < 32 && (m_PushConstantDataMask & (1 << indexEnd)) && m_PushConstantDataFlags[index] == m_PushConstantDataFlags[indexEnd])
705 0 : ++indexEnd;
706 0 : vkCmdPushConstants(
707 : commandContext.GetCommandBuffer(), GetPipelineLayout(),
708 0 : m_PushConstantDataFlags[index],
709 0 : index * 4, (indexEnd - index) * 4, m_PushConstantData.data() + index * 4);
710 0 : index = indexEnd;
711 : }
712 0 : m_PushConstantDataMask = 0;
713 : }
714 0 : }
715 :
716 0 : void CShaderProgram::PreDispatch(
717 : CRingCommandContext& commandContext)
718 : {
719 0 : PreDraw(commandContext);
720 :
721 0 : if (m_StorageImageBinding.has_value())
722 0 : for (CTexture* texture : m_StorageImageBinding->GetBoundDeviceObjects())
723 0 : if (texture)
724 : {
725 0 : if (!(texture->GetUsage() & ITexture::Usage::SAMPLED) && texture->IsInitialized())
726 0 : continue;
727 0 : VkImageLayout oldLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
728 0 : if (!texture->IsInitialized())
729 0 : oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
730 0 : Utilities::SetTextureLayout(
731 : commandContext.GetCommandBuffer(), texture,
732 : oldLayout,
733 : VK_IMAGE_LAYOUT_GENERAL,
734 : VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT,
735 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
736 : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
737 : }
738 0 : }
739 :
740 0 : void CShaderProgram::PostDispatch(CRingCommandContext& commandContext)
741 : {
742 0 : if (m_StorageImageBinding.has_value())
743 0 : for (CTexture* texture : m_StorageImageBinding->GetBoundDeviceObjects())
744 0 : if (texture)
745 : {
746 0 : if (!(texture->GetUsage() & ITexture::Usage::SAMPLED) && texture->IsInitialized())
747 0 : continue;
748 0 : Utilities::SetTextureLayout(
749 : commandContext.GetCommandBuffer(), texture,
750 : VK_IMAGE_LAYOUT_GENERAL,
751 : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL,
752 : VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
753 : VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT,
754 : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
755 : }
756 0 : }
757 :
758 0 : void CShaderProgram::BindOutdatedDescriptorSets(
759 : CRingCommandContext& commandContext)
760 : {
761 : // TODO: combine calls after more sets to bind.
762 0 : PS::StaticVector<std::tuple<uint32_t, VkDescriptorSet>, 2> descriptortSets;
763 0 : if (m_TextureBinding.has_value() && m_TextureBinding->IsOutdated())
764 : {
765 0 : constexpr uint32_t TEXTURE_BINDING_SET = 1u;
766 0 : descriptortSets.emplace_back(TEXTURE_BINDING_SET, m_TextureBinding->UpdateAndReturnDescriptorSet());
767 : }
768 0 : if (m_StorageImageBinding.has_value() && m_StorageImageBinding->IsOutdated())
769 : {
770 0 : constexpr uint32_t STORAGE_IMAGE_BINDING_SET = 2u;
771 0 : descriptortSets.emplace_back(STORAGE_IMAGE_BINDING_SET, m_StorageImageBinding->UpdateAndReturnDescriptorSet());
772 : }
773 0 : if (m_StorageBufferBinding.has_value() && m_StorageBufferBinding->IsOutdated())
774 : {
775 : // Currently we assume that in computer shaders we use either textures
776 : // or buffers but not together.
777 0 : const uint32_t STORAGE_BUFFER_BINDING_SET{
778 0 : m_Device->GetDescriptorManager().UseDescriptorIndexing() ? 2u : 1u};
779 0 : descriptortSets.emplace_back(
780 0 : STORAGE_BUFFER_BINDING_SET, m_StorageBufferBinding->UpdateAndReturnDescriptorSet());
781 : }
782 :
783 0 : for (const auto& [firstSet, descriptorSet] : descriptortSets)
784 : {
785 0 : vkCmdBindDescriptorSets(
786 : commandContext.GetCommandBuffer(), GetPipelineBindPoint(), GetPipelineLayout(),
787 : firstSet, 1, &descriptorSet, 0, nullptr);
788 : }
789 0 : }
790 :
791 0 : void CShaderProgram::SetUniform(
792 : const int32_t bindingSlot,
793 : const float value)
794 : {
795 0 : const float values[1] = {value};
796 0 : SetUniform(bindingSlot, std::span<const float>(values, values + 1));
797 0 : }
798 :
799 0 : void CShaderProgram::SetUniform(
800 : const int32_t bindingSlot,
801 : const float valueX, const float valueY)
802 : {
803 0 : const float values[2] = {valueX, valueY};
804 0 : SetUniform(bindingSlot, std::span<const float>(values, values + 2));
805 0 : }
806 :
807 0 : void CShaderProgram::SetUniform(
808 : const int32_t bindingSlot,
809 : const float valueX, const float valueY,
810 : const float valueZ)
811 : {
812 0 : const float values[3] = {valueX, valueY, valueZ};
813 0 : SetUniform(bindingSlot, std::span<const float>(values, values + 3));
814 0 : }
815 :
816 0 : void CShaderProgram::SetUniform(
817 : const int32_t bindingSlot,
818 : const float valueX, const float valueY,
819 : const float valueZ, const float valueW)
820 : {
821 0 : const float values[4] = {valueX, valueY, valueZ, valueW};
822 0 : SetUniform(bindingSlot, std::span<const float>(values, values + 4));
823 0 : }
824 :
825 0 : void CShaderProgram::SetUniform(const int32_t bindingSlot, std::span<const float> values)
826 : {
827 0 : if (bindingSlot < 0)
828 0 : return;
829 0 : const auto data = GetUniformData(bindingSlot, values.size() * sizeof(float));
830 0 : std::memcpy(data.first, values.data(), data.second);
831 : }
832 :
833 0 : std::pair<std::byte*, uint32_t> CShaderProgram::GetUniformData(
834 : const int32_t bindingSlot, const uint32_t dataSize)
835 : {
836 0 : const BindingSlotType bindingSlotType{static_cast<BindingSlotType>(bindingSlot >> BINDING_SLOT_TYPE_SHIFT)};
837 0 : const uint32_t index{bindingSlot & BINDING_SLOT_VALUE_MASK};
838 0 : if (bindingSlotType == BindingSlotType::PUSH_CONSTANT)
839 : {
840 0 : const uint32_t size = m_PushConstants[index].size;
841 0 : const uint32_t offset = m_PushConstants[index].offset;
842 0 : ENSURE(size <= dataSize);
843 0 : m_PushConstantDataMask |= ((1 << (size >> 2)) - 1) << (offset >> 2);
844 0 : return {m_PushConstantData.data() + offset, size};
845 : }
846 : else
847 : {
848 0 : ENSURE(bindingSlotType == BindingSlotType::UNIFORM);
849 0 : const Uniform& uniform = m_Uniforms[index];
850 0 : m_MaterialConstantsDataOutdated = true;
851 0 : const uint32_t size = uniform.size;
852 0 : const uint32_t offset = uniform.offset;
853 0 : return {m_MaterialConstantsData.get() + offset, std::min(dataSize, size)};
854 : }
855 : }
856 :
857 0 : void CShaderProgram::SetTexture(const int32_t bindingSlot, CTexture* texture)
858 : {
859 0 : if (bindingSlot < 0)
860 : return;
861 0 : const BindingSlotType bindingSlotType{static_cast<BindingSlotType>(bindingSlot >> BINDING_SLOT_TYPE_SHIFT)};
862 0 : const uint32_t index{bindingSlot & BINDING_SLOT_VALUE_MASK};
863 0 : CDescriptorManager& descriptorManager = m_Device->GetDescriptorManager();
864 0 : if (descriptorManager.UseDescriptorIndexing())
865 : {
866 0 : ENSURE(bindingSlotType == BindingSlotType::PUSH_CONSTANT);
867 0 : const uint32_t descriptorIndex = descriptorManager.GetTextureDescriptor(texture->As<CTexture>());
868 0 : const uint32_t size = m_PushConstants[index].size;
869 0 : const uint32_t offset = m_PushConstants[index].offset;
870 0 : ENSURE(size == sizeof(descriptorIndex));
871 0 : std::memcpy(m_PushConstantData.data() + offset, &descriptorIndex, size);
872 0 : m_PushConstantDataMask |= ((1 << (size >> 2)) - 1) << (offset >> 2);
873 : }
874 : else
875 : {
876 0 : ENSURE(bindingSlotType == BindingSlotType::TEXTURE);
877 0 : ENSURE(m_TextureBinding.has_value());
878 0 : m_TextureBinding->SetObject(index, texture);
879 : }
880 : }
881 :
882 0 : void CShaderProgram::SetStorageTexture(const int32_t bindingSlot, CTexture* texture)
883 : {
884 0 : if (bindingSlot < 0)
885 : return;
886 0 : ENSURE(static_cast<BindingSlotType>(bindingSlot >> BINDING_SLOT_TYPE_SHIFT) == BindingSlotType::STORAGE_IMAGE);
887 0 : const uint32_t index{bindingSlot & BINDING_SLOT_VALUE_MASK};
888 0 : ENSURE(m_StorageImageBinding.has_value());
889 0 : m_StorageImageBinding->SetObject(index, texture);
890 : }
891 :
892 0 : void CShaderProgram::SetStorageBuffer(const int32_t bindingSlot, CBuffer* buffer)
893 : {
894 0 : if (bindingSlot < 0)
895 : return;
896 0 : ENSURE(static_cast<BindingSlotType>(bindingSlot >> BINDING_SLOT_TYPE_SHIFT) == BindingSlotType::STORAGE_BUFFER);
897 0 : const uint32_t index{bindingSlot & BINDING_SLOT_VALUE_MASK};
898 0 : ENSURE(m_StorageBufferBinding.has_value());
899 0 : m_StorageBufferBinding->SetObject(index, buffer);
900 : }
901 :
902 : } // namespace Vulkan
903 :
904 : } // namespace Backend
905 :
906 : } // namespace Renderer
|