Rendering Engine 0.2.17
Modular Graphics Rendering Engine | v0.2.17
Loading...
Searching...
No Matches
vulkan_render_resources.cpp
Go to the documentation of this file.
2#include "vulkan_renderer.hpp"
6#include "image_data_gpu.hpp"
7#include "material.hpp"
8#include "mesh_data_gpu.hpp"
9#include "texture_cache.hpp"
10
11#include <stdexcept>
12
13namespace rendering_engine
14{
15
17 :
18 mRenderer(renderer)
19{
20 mRenderer->RegisterObserver(this);
21}
22
27
28void VulkanRenderResources::Initialize(Material* material, MeshDataGpu* meshData, TextureCache* textureCache)
29{
30 mMaterial = material;
31 mMeshData = meshData;
32 mTextureCache = textureCache;
33
35}
36
37void VulkanRenderResources::SubmitResources(Transformations2D& transformations, const PackedMaterialData& materialParameters)
38{
39 UpdateTransformations(transformations);
40 UpdateMaterialParameters(materialParameters);
42}
43
44void VulkanRenderResources::SubmitResources(Transformations3D& transformations, const PackedMaterialData& materialParameters)
45{
46 UpdateTransformations(transformations);
47 UpdateMaterialParameters(materialParameters);
49}
50
52{
53 if (mDescriptorPool != VK_NULL_HANDLE)
54 {
55 DeferredItem descriptorPool;
56 descriptorPool.type = DeferredType::DescriptorPool;
57 descriptorPool.descriptorPool = mDescriptorPool;
58 mRenderer->AddDeferredDestroy(descriptorPool);
59 mDescriptorPool = VK_NULL_HANDLE;
60
61 }
62
63 for (size_t i = 0; i < mTransformationBuffers.size(); i++)
64 {
65 if (mTransformationBuffers[i] != VK_NULL_HANDLE)
66 {
67 DeferredItem tBuffer;
68 tBuffer.type = DeferredType::Buffer;
69 tBuffer.buffer = mTransformationBuffers[i];
70 mRenderer->AddDeferredDestroy(tBuffer);
71 }
72
73 if (i < mTransformationBuffersMemory.size() &&
74 mTransformationBuffersMemory[i] != VK_NULL_HANDLE)
75 {
76
77 DeferredItem tMem;
79 tMem.memory = mTransformationBuffersMemory[i];
80 mRenderer->AddDeferredDestroy(tMem);
81
82 mTransformationBuffers[i] = VK_NULL_HANDLE;
83 mTransformationBuffersMemory[i] = VK_NULL_HANDLE;
84 }
85 }
86
87 for(size_t i = 0; i < mMaterialParametersBuffers.size(); ++i)
88 {
89 if (mMaterialParametersBuffers[i] != VK_NULL_HANDLE)
90 {
91 DeferredItem matBuffer;
92 matBuffer.type = DeferredType::Buffer;
93 matBuffer.buffer = mMaterialParametersBuffers[i];
94 mRenderer->AddDeferredDestroy(matBuffer);
95 }
96
97 if(i < mMaterialParametersMemory.size() &&
98 mMaterialParametersMemory[i] != VK_NULL_HANDLE)
99 {
100 DeferredItem matMem;
101 matMem.type = DeferredType::Memory;
102 matMem.memory = mMaterialParametersMemory[i];
103 mRenderer->AddDeferredDestroy(matMem);
104
105 mMaterialParametersBuffers[i] = VK_NULL_HANDLE;
106 mMaterialParametersMemory[i] = VK_NULL_HANDLE;
107 }
108 }
109
110 mTransformationBuffers.clear();
111 mTransformationBuffersMemory.clear();
112 mMaterialParametersBuffers.clear();
113 mMaterialParametersMemory.clear();
114}
115
120
125
127{
128 if (!mMaterial)
129 {
130 // Log error message, as without initialized material rendering is not possible.
131 return;
132 }
133 VulkanMaterialResources* materialResources = static_cast<VulkanMaterialResources*>(mMaterial->GetMaterialRenderResources());
134 mGraphicsPipeline = materialResources->GetPipeline();
135 mPipelineLayout = materialResources->GetPipelineLayout();
136
137 VulkanMeshResources* meshResources = static_cast<VulkanMeshResources*>(mMeshData->GetMeshRenderResources());
138 mVertexBuffer = meshResources->GetVertexBuffer();
139 mIndexBuffer = meshResources->GetIndexBuffer();
140
144}
145
147{
148 VkDeviceSize transformationBufferSize = 0;
149
150 switch (mMaterial->GetMaterialSettings().materialDomain)
151 {
153 transformationBufferSize = sizeof(Transformations2D);
154 break;
155
157 transformationBufferSize = sizeof(Transformations3D);
158 break;
159
160 default:
161 throw std::runtime_error("Unsupported material domain.");
162 }
163
164 mTransformationBuffers.resize(MAX_FRAMES_IN_FLIGHT);
165 mTransformationBuffersMemory.resize(MAX_FRAMES_IN_FLIGHT);
166
167 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
168 {
169 mRenderer->CreateBuffer(transformationBufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
170 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
171 mTransformationBuffers[i], mTransformationBuffersMemory[i]);
172 }
173
174 auto materialParameters = mMaterial->PackMaterialParameters();
175 if (materialParameters.buffer.empty())
176 {
177 return;
178 }
179
180 VkDeviceSize matVarBufferSize = materialParameters.buffer.size();
181 mMaterialParametersBuffers.resize(MAX_FRAMES_IN_FLIGHT);
182 mMaterialParametersMemory.resize(MAX_FRAMES_IN_FLIGHT);
183
184 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
185 {
186 mRenderer->CreateBuffer(matVarBufferSize, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT,
187 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
188 mMaterialParametersBuffers[i], mMaterialParametersMemory[i]);
189 }
190}
191
193{
194 const uint32_t maxFramesInFlight = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
195 std::vector<VkDescriptorPoolSize> poolSizes;
196
197 VkDescriptorPoolSize tranformationPool;
198 tranformationPool.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
199 tranformationPool.descriptorCount = maxFramesInFlight;
200
201 poolSizes.push_back(tranformationPool);
202
203 auto materialParameters = mMaterial->PackMaterialParameters();
204 if (!materialParameters.buffer.empty())
205 {
206 VkDescriptorPoolSize materialParameterPool;
207 materialParameterPool.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
208 materialParameterPool.descriptorCount = maxFramesInFlight;
209
210 poolSizes.push_back(materialParameterPool);
211 }
212
213 for (const auto& texture : mMaterial->GetTextures())
214 {
215 (void)texture;
216 VkDescriptorPoolSize textureSamplerPool;
217 textureSamplerPool.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
218 textureSamplerPool.descriptorCount = maxFramesInFlight;
219
220 poolSizes.push_back(textureSamplerPool);
221 }
222
223 VkDescriptorPoolCreateInfo poolInfo{};
224 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
225 poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
226 poolInfo.pPoolSizes = poolSizes.data();
227 poolInfo.maxSets = maxFramesInFlight;
228
229 if (vkCreateDescriptorPool(mRenderer->GetLogicalDevice(), &poolInfo, nullptr, &mDescriptorPool) != VK_SUCCESS)
230 {
231 throw std::runtime_error("failed to create descriptor pool!");
232 }
233}
234
236{
237 // By local convention of this engine, bindings will be numbered:
238 // Bindings i = 0, i < n, there n - total number of bindings
239 // Binding i - transformations matrices of types according to material domain (2D or 3D)
240 // Binding i++ - cunstom parameter variable of material, if any. All variables will be
241 // serialized and packed in a single binding
242 // Binding i++ - textures sampler, if any. One texture per binding.
243
244 const uint32_t maxFramesInFlight = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
245
246 VulkanMaterialResources* materialResources = static_cast<VulkanMaterialResources*>(mMaterial->GetMaterialRenderResources());
247 auto descriptorSetLayout = materialResources->GetDescriptorSetLayout();
248 std::vector<VkDescriptorSetLayout> layouts(maxFramesInFlight, descriptorSetLayout);
249 VkDescriptorSetAllocateInfo allocInfo{};
250 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
251 allocInfo.descriptorPool = mDescriptorPool;
252 allocInfo.descriptorSetCount = maxFramesInFlight;
253 allocInfo.pSetLayouts = layouts.data();
254
255 mDescriptorSets.resize(MAX_FRAMES_IN_FLIGHT);
256 VkResult result = vkAllocateDescriptorSets(mRenderer->GetLogicalDevice(), &allocInfo, mDescriptorSets.data());
257 if (result != VK_SUCCESS)
258 {
259 throw std::runtime_error("failed to allocate descriptor sets! Error: " + std::to_string(result));
260 }
261
262 for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
263 {
264 unsigned int dstBinding = 0;
265
266 VkDescriptorBufferInfo matVarBufferInfo{};
267 VkWriteDescriptorSet matVarDescSet;
268
269 std::vector<VkWriteDescriptorSet> descriptorWrites;
270
271 // Transfotmations descriptor set
272 VkDescriptorBufferInfo transformationBufferInfo{};
273 transformationBufferInfo.buffer = mTransformationBuffers[i];
274 transformationBufferInfo.offset = 0;
276 {
277 transformationBufferInfo.range = sizeof(Transformations2D);
278 }
280 {
281 transformationBufferInfo.range = sizeof(Transformations3D);
282 }
283 VkWriteDescriptorSet transformationsDescSet;
284 transformationsDescSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
285 transformationsDescSet.pNext = nullptr;
286 transformationsDescSet.dstSet = mDescriptorSets[i];
287 transformationsDescSet.dstBinding = dstBinding;
288 transformationsDescSet.dstArrayElement = 0;
289 transformationsDescSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
290 transformationsDescSet.descriptorCount = 1;
291 transformationsDescSet.pBufferInfo = &transformationBufferInfo;
292 descriptorWrites.push_back(transformationsDescSet);
293
294 // Custom material parameters descriptor set
295 auto materialParameters = mMaterial->PackMaterialParameters();
296 if (!materialParameters.buffer.empty())
297 {
298 ++dstBinding;
299
300 matVarBufferInfo.buffer = mMaterialParametersBuffers[i];
301 matVarBufferInfo.offset = 0;
302 matVarBufferInfo.range = materialParameters.buffer.size();
303
304 matVarDescSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
305 matVarDescSet.pNext = nullptr;
306 matVarDescSet.dstSet = mDescriptorSets[i];
307 matVarDescSet.dstBinding = dstBinding;
308 matVarDescSet.dstArrayElement = 0;
309 matVarDescSet.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
310 matVarDescSet.descriptorCount = 1;
311 matVarDescSet.pBufferInfo = &matVarBufferInfo;
312 descriptorWrites.push_back(matVarDescSet);
313 }
314
315 // Custom texture image data descriptor set
316 for (const auto& texture : mMaterial->GetTextures())
317 {
318 ++dstBinding;
319 auto imageData = mTextureCache->GetTextureResources(texture);
320 VulkanTextureResources* textureResources = static_cast<VulkanTextureResources*>(imageData->GetTextureRenderResources());
321 VkDescriptorImageInfo imageInfo{};
322 imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
323 imageInfo.imageView = textureResources->GetVkImageView();
324 imageInfo.sampler = textureResources->GetVkSampler();
325
326 VkWriteDescriptorSet imageDescSet;
327 imageDescSet.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
328 imageDescSet.pNext = nullptr;
329 imageDescSet.dstSet = mDescriptorSets[i];
330 imageDescSet.dstBinding = dstBinding;
331 imageDescSet.dstArrayElement = 0;
332 imageDescSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
333 imageDescSet.descriptorCount = 1;
334 imageDescSet.pImageInfo = &imageInfo;
335
336 descriptorWrites.push_back(imageDescSet);
337 }
338
339 vkUpdateDescriptorSets(mRenderer->GetLogicalDevice(), static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
340 }
341}
342
344{
345 auto device = mRenderer->GetLogicalDevice();
346 auto frame = mRenderer->GetCurrentFrame();
347
348 // Update transformations
349 void* dataTransform;
350 vkMapMemory(device, mTransformationBuffersMemory[frame], 0, sizeof(Transformations2D), 0, &dataTransform);
351 memcpy(dataTransform, &transformations, sizeof(transformations));
352 vkUnmapMemory(device, mTransformationBuffersMemory[frame]);
353}
354
356{
357 auto device = mRenderer->GetLogicalDevice();
358 auto frame = mRenderer->GetCurrentFrame();
359
360 // Flip Y-axis for Vulkan clip space
361 transformations.proj[1][1] *= -1;
362 // Update transformations
363 void* dataTransform;
364 vkMapMemory(device, mTransformationBuffersMemory[frame], 0, sizeof(Transformations3D), 0, &dataTransform);
365 memcpy(dataTransform, &transformations, sizeof(transformations));
366 vkUnmapMemory(device, mTransformationBuffersMemory[frame]);
367}
368
370{
371 auto device = mRenderer->GetLogicalDevice();
372 auto frame = mRenderer->GetCurrentFrame();
373
374 // Update custom variables
375 if (!materialParameters.buffer.empty())
376 {
377 void* dataCustom;
378 vkMapMemory(device, mMaterialParametersMemory[frame], 0, materialParameters.buffer.size(), 0, &dataCustom);
379 memcpy(dataCustom, materialParameters.buffer.data(), materialParameters.buffer.size());
380 vkUnmapMemory(device, mMaterialParametersMemory[frame]);
381 }
382}
383
385{
386 auto commandBuffers = mRenderer->GetComandBuffers();
387 auto frame = mRenderer->GetCurrentFrame();
388
389 VkBuffer vertexBuffer[] = { mVertexBuffer };
390 VkDeviceSize offsets[] = { 0 };
391
392 vkCmdBindPipeline(commandBuffers[frame], VK_PIPELINE_BIND_POINT_GRAPHICS, mGraphicsPipeline);
393
394 /*If dynamicState in pipeline is used then vkCmdSetViewport and vkCmdSetScissor per draw call*/
395 //VkViewport viewport{};
396 //viewport.x = 0.0f;
397 //viewport.y = 0.0f;
398 //viewport.width = static_cast<float>(mRenderer->GetSwapChainExtent().width);
399 //viewport.height = static_cast<float>(mRenderer->GetSwapChainExtent().height);
400 //viewport.minDepth = 0.0f;
401 //viewport.maxDepth = 1.0f;
402 //vkCmdSetViewport(commandBuffers[frame], 0, 1, &viewport);
403
404 //VkRect2D scissor{};
405 //scissor.offset = { 0, 0 };
406 //scissor.extent = mRenderer->GetSwapChainExtent();
407 //vkCmdSetScissor(commandBuffers[frame], 0, 1, &scissor);
408
409 vkCmdBindVertexBuffers(commandBuffers[frame], 0, 1, vertexBuffer, offsets);
410 vkCmdBindIndexBuffer(commandBuffers[frame], mIndexBuffer, 0, VK_INDEX_TYPE_UINT32);
411 vkCmdBindDescriptorSets(commandBuffers[frame], VK_PIPELINE_BIND_POINT_GRAPHICS,
412 mPipelineLayout, 0, 1, &mDescriptorSets[frame], 0, nullptr);
413 vkCmdDrawIndexed(commandBuffers[frame], static_cast<uint32_t>(mMeshData->GetIndices().size()), 1, 0, 0, 0);
414}
415
416
417
418} // namespace rendering_engine
Represents a material instance with parameter values, texture bindings, and rendering configuration.
Definition material.hpp:30
std::vector< std::string > GetTextures() const
Returns the list of texture names used by this material.
Definition material.cpp:82
PackedMaterialData PackMaterialParameters()
Packs the current float/vector parameters into a binary buffer and layout metadata.
Definition material.cpp:39
const MaterialSettings GetMaterialSettings() const
Returns the material's static settings (domain, blend mode, shading model, etc.).
Definition material.cpp:22
IMaterialRenderResources * GetMaterialRenderResources() const
Returns the backend-specific GPU handle of the material.
Definition material.cpp:87
Manages mesh data in RAM and GPU, including upload and release operations.
const std::vector< uint32_t > & GetIndices() const
Returns a constant reference to the mesh indices.
IMeshRenderResources * GetMeshRenderResources()
Get the interface for mesh GPU resources (Vulkan or other backend).
Manages texture loading, GPU uploading, and caching for reuse.
std::shared_ptr< ImageDataGpu > GetTextureResources(std::string filename)
Retrieves the full texture resource wrapper from cache.
Vulkan-specific implementation of material render resources.
VkPipeline GetPipeline() const
Gets the Vulkan graphics pipeline used by the material.
VkPipelineLayout GetPipelineLayout() const
Gets the Vulkan pipeline layout used by the material.
VkDescriptorSetLayout GetDescriptorSetLayout() const
Gets the Vulkan descriptor set layout for the material.
Vulkan implementation of the mesh GPU resource interface.
VkBuffer GetIndexBuffer() const
Get the Vulkan index buffer handle.
VkBuffer GetVertexBuffer() const
Get the Vulkan vertex buffer handle.
void AcquireResources()
Allocates and initializes all GPU buffers, descriptor sets, and pipelines for this drawable.
void OnRenderResourcesRebuild() override
Renderer callback: re-upload or recreate all GPU resources (used after device reset/rebuild).
void OnRenderResourcesRelease() override
Renderer callback: release all GPU resources (used during device loss/reset).
void DrawIndexed()
Issues a Vulkan draw command for the currently bound indexed mesh.
VulkanRenderResources(VulkanRenderer *renderer)
Constructor.
void Shutdown() override
Releases all allocated GPU resources for this object.
void UpdateTransformations(Transformations2D &transformations)
void Initialize(Material *material, MeshDataGpu *meshData, TextureCache *textureCache) override
Initializes GPU-side resources using provided material, mesh, and texture cache.
void SubmitResources(Transformations2D &transformations, const PackedMaterialData &materialParameters) override
Updates GPU resources and issues a draw call for a 2D object.
void UpdateMaterialParameters(const PackedMaterialData &materialParameters)
Vulkan-based implementation of the IRenderer interface.
VkDevice & GetLogicalDevice()
Returns reference to the logical Vulkan device.
void CreateBuffer(VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer &buffer, VkDeviceMemory &bufferMemory)
Creates a new Vulkan buffer with the specified usage and memory properties.
void UnregisterObserver(IRendererObserver *notifier) override
Unregisters a previously registered observer.
void AddDeferredDestroy(DeferredItem deferredItem)
size_t GetCurrentFrame() const
Returns the index of the currently active frame in flight.
void RegisterObserver(IRendererObserver *notifier) override
Registers an observer for rendering events.
std::vector< VkCommandBuffer > GetComandBuffers()
Returns the collection of command buffers used for rendering.
Vulkan-specific implementation of ITextureRenderResources.
VkImageView GetVkImageView() const
Returns the Vulkan image view associated with this texture resource.
VkSampler GetVkSampler() const
Returns the Vulkan sampler associated with this texture resource.
const int MAX_FRAMES_IN_FLIGHT
Number of frames that can be processed simultaneously (double buffering).
Contains the raw buffer data and layout metadata of packed material parameters.
Contains transformation matrices for 2D rendering.
Contains model, view, and projection matrices for 3D rendering.
glm::mat4 proj
Projection transformation matrix.