source: opengl-game/graphics-pipeline_vulkan.cpp@ e3bef3a

feature/imgui-sdl points-test
Last change on this file since e3bef3a was e3bef3a, checked in by Dmitry Portnoy <dmp1488@…>, 5 years ago

Finish the rewrite of the original vulkangame project

  • Property mode set to 100644
File size: 16.3 KB
Line 
1#include "graphics-pipeline_vulkan.hpp"
2
3#include <fstream>
4#include <stdexcept>
5#include <iostream>
6
7using namespace std;
8
9// TODO: Remove any instances of cout and instead throw exceptions
10
11GraphicsPipeline_Vulkan::GraphicsPipeline_Vulkan(VkPhysicalDevice physicalDevice, VkDevice device,
12 VkRenderPass renderPass, Viewport viewport, int vertexSize) {
13 this->physicalDevice = physicalDevice;
14 this->device = device;
15 this->renderPass = renderPass;
16 this->viewport = viewport;
17
18 // Since there is only one array of vertex data, we use binding = 0
19 // I'll probably do that for the foreseeable future
20 // I can calculate the stride myself given info about all the varying attributes
21 this->bindingDescription.binding = 0;
22 this->bindingDescription.stride = vertexSize;
23 this->bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
24}
25
26GraphicsPipeline_Vulkan::~GraphicsPipeline_Vulkan() {
27}
28
29void GraphicsPipeline_Vulkan::updateRenderPass(VkRenderPass renderPass) {
30 this->renderPass = renderPass;
31}
32
33void GraphicsPipeline_Vulkan::createVertexBuffer(const void* bufferData, int vertexSize,
34 VkCommandPool commandPool, VkQueue graphicsQueue) {
35 VkDeviceSize bufferSize = numVertices * vertexSize;
36 VkDeviceSize bufferCapacity = vertexCapacity * vertexSize;
37
38 VkBuffer stagingBuffer;
39 VkDeviceMemory stagingBufferMemory;
40 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
41 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
42 stagingBuffer, stagingBufferMemory);
43
44 void* data;
45 vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
46 memcpy(data, bufferData, (size_t) bufferSize);
47 vkUnmapMemory(device, stagingBufferMemory);
48
49 VulkanUtils::createBuffer(device, physicalDevice, bufferCapacity,
50 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT,
51 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory);
52
53 VulkanUtils::copyBuffer(device, commandPool, stagingBuffer, vertexBuffer, 0, 0, bufferSize, graphicsQueue);
54
55 vkDestroyBuffer(device, stagingBuffer, nullptr);
56 vkFreeMemory(device, stagingBufferMemory, nullptr);
57}
58
59void GraphicsPipeline_Vulkan::createIndexBuffer(const void* bufferData, int indexSize,
60 VkCommandPool commandPool, VkQueue graphicsQueue) {
61 VkDeviceSize bufferSize = numIndices * indexSize;
62 VkDeviceSize bufferCapacity = indexCapacity * indexSize;
63
64 VkBuffer stagingBuffer;
65 VkDeviceMemory stagingBufferMemory;
66 VulkanUtils::createBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT,
67 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
68 stagingBuffer, stagingBufferMemory);
69
70 void* data;
71 vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data);
72 memcpy(data, bufferData, (size_t) bufferSize);
73 vkUnmapMemory(device, stagingBufferMemory);
74
75 VulkanUtils::createBuffer(device, physicalDevice, bufferCapacity,
76 VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT,
77 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory);
78
79 VulkanUtils::copyBuffer(device, commandPool, stagingBuffer, indexBuffer, 0, 0, bufferSize, graphicsQueue);
80
81 vkDestroyBuffer(device, stagingBuffer, nullptr);
82 vkFreeMemory(device, stagingBufferMemory, nullptr);
83}
84
85void GraphicsPipeline_Vulkan::addAttribute(VkFormat format, size_t offset) {
86 VkVertexInputAttributeDescription attributeDesc = {};
87
88 attributeDesc.binding = 0;
89 attributeDesc.location = this->attributeDescriptions.size();
90 attributeDesc.format = format;
91 attributeDesc.offset = offset;
92
93 this->attributeDescriptions.push_back(attributeDesc);
94}
95
96void GraphicsPipeline_Vulkan::addDescriptorInfo(VkDescriptorType type, VkShaderStageFlags stageFlags, vector<VkDescriptorBufferInfo>* bufferData) {
97 this->descriptorInfoList.push_back({ type, stageFlags, bufferData, nullptr });
98}
99
100void GraphicsPipeline_Vulkan::addDescriptorInfo(VkDescriptorType type, VkShaderStageFlags stageFlags, VkDescriptorImageInfo* imageData) {
101 this->descriptorInfoList.push_back({ type, stageFlags, nullptr, imageData });
102}
103
104void GraphicsPipeline_Vulkan::createPipeline(string vertShaderFile, string fragShaderFile) {
105 vector<char> vertShaderCode = readFile(vertShaderFile);
106 vector<char> fragShaderCode = readFile(fragShaderFile);
107
108 VkShaderModule vertShaderModule = createShaderModule(vertShaderCode);
109 VkShaderModule fragShaderModule = createShaderModule(fragShaderCode);
110
111 VkPipelineShaderStageCreateInfo vertShaderStageInfo = {};
112 vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
113 vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
114 vertShaderStageInfo.module = vertShaderModule;
115 vertShaderStageInfo.pName = "main";
116
117 VkPipelineShaderStageCreateInfo fragShaderStageInfo = {};
118 fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
119 fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
120 fragShaderStageInfo.module = fragShaderModule;
121 fragShaderStageInfo.pName = "main";
122
123 VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
124
125 VkPipelineVertexInputStateCreateInfo vertexInputInfo = {};
126 vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
127
128 vertexInputInfo.vertexBindingDescriptionCount = 1;
129 vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(this->attributeDescriptions.size());
130 vertexInputInfo.pVertexBindingDescriptions = &this->bindingDescription;
131 vertexInputInfo.pVertexAttributeDescriptions = this->attributeDescriptions.data();
132
133 VkPipelineInputAssemblyStateCreateInfo inputAssembly = {};
134 inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
135 inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
136 inputAssembly.primitiveRestartEnable = VK_FALSE;
137
138 VkViewport viewport = {};
139 viewport.x = (float)this->viewport.x;
140 viewport.y = (float)this->viewport.y;
141 viewport.width = (float)this->viewport.width;
142 viewport.height = (float)this->viewport.height;
143 viewport.minDepth = 0.0f;
144 viewport.maxDepth = 1.0f;
145
146 VkRect2D scissor = {};
147 scissor.offset = { 0, 0 };
148 scissor.extent = { (uint32_t)this->viewport.width, (uint32_t)this->viewport.height };
149
150 VkPipelineViewportStateCreateInfo viewportState = {};
151 viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
152 viewportState.viewportCount = 1;
153 viewportState.pViewports = &viewport;
154 viewportState.scissorCount = 1;
155 viewportState.pScissors = &scissor;
156
157 VkPipelineRasterizationStateCreateInfo rasterizer = {};
158 rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
159 rasterizer.depthClampEnable = VK_FALSE;
160 rasterizer.rasterizerDiscardEnable = VK_FALSE;
161 rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
162 rasterizer.lineWidth = 1.0f;
163 rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
164 rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
165 rasterizer.depthBiasEnable = VK_FALSE;
166
167 VkPipelineMultisampleStateCreateInfo multisampling = {};
168 multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
169 multisampling.sampleShadingEnable = VK_FALSE;
170 multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
171
172 VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
173 colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
174 colorBlendAttachment.blendEnable = VK_TRUE;
175 colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
176 colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
177 colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
178 colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
179 colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
180 colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
181
182 VkPipelineColorBlendStateCreateInfo colorBlending = {};
183 colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
184 colorBlending.logicOpEnable = VK_FALSE;
185 colorBlending.logicOp = VK_LOGIC_OP_COPY;
186 colorBlending.attachmentCount = 1;
187 colorBlending.pAttachments = &colorBlendAttachment;
188 colorBlending.blendConstants[0] = 0.0f;
189 colorBlending.blendConstants[1] = 0.0f;
190 colorBlending.blendConstants[2] = 0.0f;
191 colorBlending.blendConstants[3] = 0.0f;
192
193 VkPipelineDepthStencilStateCreateInfo depthStencil = {};
194 depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
195 depthStencil.depthTestEnable = VK_TRUE;
196 depthStencil.depthWriteEnable = VK_TRUE;
197 depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
198 depthStencil.depthBoundsTestEnable = VK_FALSE;
199 depthStencil.minDepthBounds = 0.0f;
200 depthStencil.maxDepthBounds = 1.0f;
201 depthStencil.stencilTestEnable = VK_FALSE;
202 depthStencil.front = {};
203 depthStencil.back = {};
204
205 VkPipelineLayoutCreateInfo pipelineLayoutInfo = {};
206 pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
207 pipelineLayoutInfo.setLayoutCount = 1;
208 pipelineLayoutInfo.pSetLayouts = &this->descriptorSetLayout;
209 pipelineLayoutInfo.pushConstantRangeCount = 0;
210
211 if (vkCreatePipelineLayout(this->device, &pipelineLayoutInfo, nullptr, &this->pipelineLayout) != VK_SUCCESS) {
212 throw runtime_error("failed to create pipeline layout!");
213 }
214
215 VkGraphicsPipelineCreateInfo pipelineInfo = {};
216 pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
217 pipelineInfo.stageCount = 2;
218 pipelineInfo.pStages = shaderStages;
219 pipelineInfo.pVertexInputState = &vertexInputInfo;
220 pipelineInfo.pInputAssemblyState = &inputAssembly;
221 pipelineInfo.pViewportState = &viewportState;
222 pipelineInfo.pRasterizationState = &rasterizer;
223 pipelineInfo.pMultisampleState = &multisampling;
224 pipelineInfo.pDepthStencilState = &depthStencil;
225 pipelineInfo.pColorBlendState = &colorBlending;
226 pipelineInfo.pDynamicState = nullptr;
227 pipelineInfo.layout = this->pipelineLayout;
228 pipelineInfo.renderPass = this->renderPass;
229 pipelineInfo.subpass = 0;
230 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
231 pipelineInfo.basePipelineIndex = -1;
232
233 if (vkCreateGraphicsPipelines(this->device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &this->pipeline) != VK_SUCCESS) {
234 throw runtime_error("failed to create graphics pipeline!");
235 }
236
237 vkDestroyShaderModule(this->device, vertShaderModule, nullptr);
238 vkDestroyShaderModule(this->device, fragShaderModule, nullptr);
239}
240
241void GraphicsPipeline_Vulkan::createDescriptorSetLayout() {
242 vector<VkDescriptorSetLayoutBinding> bindings(this->descriptorInfoList.size());
243
244 for (size_t i = 0; i < bindings.size(); i++) {
245 bindings[i].binding = i;
246 bindings[i].descriptorCount = 1;
247 bindings[i].descriptorType = this->descriptorInfoList[i].type;
248 bindings[i].stageFlags = this->descriptorInfoList[i].stageFlags;
249 bindings[i].pImmutableSamplers = nullptr;
250 }
251
252 VkDescriptorSetLayoutCreateInfo layoutInfo = {};
253 layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
254 layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
255 layoutInfo.pBindings = bindings.data();
256
257 if (vkCreateDescriptorSetLayout(this->device, &layoutInfo, nullptr, &this->descriptorSetLayout) != VK_SUCCESS) {
258 throw runtime_error("failed to create descriptor set layout!");
259 }
260}
261
262void GraphicsPipeline_Vulkan::createDescriptorPool(vector<VkImage>& swapChainImages) {
263 vector<VkDescriptorPoolSize> poolSizes(this->descriptorInfoList.size());
264
265 for (size_t i = 0; i < poolSizes.size(); i++) {
266 poolSizes[i].type = this->descriptorInfoList[i].type;
267 poolSizes[i].descriptorCount = static_cast<uint32_t>(swapChainImages.size());
268 }
269
270 VkDescriptorPoolCreateInfo poolInfo = {};
271 poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
272 poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
273 poolInfo.pPoolSizes = poolSizes.data();
274 poolInfo.maxSets = static_cast<uint32_t>(swapChainImages.size());
275
276 if (vkCreateDescriptorPool(this->device, &poolInfo, nullptr, &this->descriptorPool) != VK_SUCCESS) {
277 throw runtime_error("failed to create descriptor pool!");
278 }
279}
280
281void GraphicsPipeline_Vulkan::createDescriptorSets(vector<VkImage>& swapChainImages) {
282 vector<VkDescriptorSetLayout> layouts(swapChainImages.size(), this->descriptorSetLayout);
283
284 VkDescriptorSetAllocateInfo allocInfo = {};
285 allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
286 allocInfo.descriptorPool = this->descriptorPool;
287 allocInfo.descriptorSetCount = static_cast<uint32_t>(swapChainImages.size());
288 allocInfo.pSetLayouts = layouts.data();
289
290 this->descriptorSets.resize(swapChainImages.size());
291 if (vkAllocateDescriptorSets(device, &allocInfo, this->descriptorSets.data()) != VK_SUCCESS) {
292 throw runtime_error("failed to allocate descriptor sets!");
293 }
294
295 for (size_t i = 0; i < swapChainImages.size(); i++) {
296 vector<VkWriteDescriptorSet> descriptorWrites(this->descriptorInfoList.size());
297
298 for (size_t j = 0; j < descriptorWrites.size(); j++) {
299 descriptorWrites[j].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
300 descriptorWrites[j].dstSet = this->descriptorSets[i];
301 descriptorWrites[j].dstBinding = j;
302 descriptorWrites[j].dstArrayElement = 0;
303 descriptorWrites[j].descriptorType = this->descriptorInfoList[j].type;
304 descriptorWrites[j].descriptorCount = 1;
305 descriptorWrites[j].pBufferInfo = nullptr;
306 descriptorWrites[j].pImageInfo = nullptr;
307 descriptorWrites[j].pTexelBufferView = nullptr;
308
309 switch (descriptorWrites[j].descriptorType) {
310 case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
311 descriptorWrites[j].pBufferInfo = &(*this->descriptorInfoList[j].bufferDataList)[i];
312 break;
313 case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
314 descriptorWrites[j].pImageInfo = this->descriptorInfoList[j].imageData;
315 break;
316 default:
317 cout << "Unknown descriptor type: " << descriptorWrites[j].descriptorType << endl;
318 }
319 }
320
321 vkUpdateDescriptorSets(this->device, static_cast<uint32_t>(descriptorWrites.size()), descriptorWrites.data(), 0, nullptr);
322 }
323}
324
325void GraphicsPipeline_Vulkan::createRenderCommands(VkCommandBuffer& commandBuffer, uint32_t currentImage) {
326 vkCmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
327 vkCmdBindDescriptorSets(commandBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1,
328 &descriptorSets[currentImage], 0, nullptr);
329
330 VkBuffer vertexBuffers[] = { vertexBuffer };
331 VkDeviceSize offsets[] = { 0 };
332 vkCmdBindVertexBuffers(commandBuffer, 0, 1, vertexBuffers, offsets);
333
334 vkCmdBindIndexBuffer(commandBuffer, indexBuffer, 0, VK_INDEX_TYPE_UINT16);
335
336 vkCmdDrawIndexed(commandBuffer, static_cast<uint32_t>(numIndices), 1, 0, 0, 0);
337}
338
339VkShaderModule GraphicsPipeline_Vulkan::createShaderModule(const vector<char>& code) {
340 VkShaderModuleCreateInfo createInfo = {};
341 createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
342 createInfo.codeSize = code.size();
343 createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
344
345 VkShaderModule shaderModule;
346 if (vkCreateShaderModule(this->device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
347 throw runtime_error("failed to create shader module!");
348 }
349
350 return shaderModule;
351}
352
353vector<char> GraphicsPipeline_Vulkan::readFile(const string& filename) {
354 ifstream file(filename, ios::ate | ios::binary);
355
356 if (!file.is_open()) {
357 throw runtime_error("failed to open file!");
358 }
359
360 size_t fileSize = (size_t)file.tellg();
361 vector<char> buffer(fileSize);
362
363 file.seekg(0);
364 file.read(buffer.data(), fileSize);
365
366 file.close();
367
368 return buffer;
369}
370
371void GraphicsPipeline_Vulkan::cleanup() {
372 vkDestroyPipeline(device, pipeline, nullptr);
373 vkDestroyDescriptorPool(device, descriptorPool, nullptr);
374 vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
375}
376
377void GraphicsPipeline_Vulkan::cleanupBuffers() {
378 vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
379
380 vkDestroyBuffer(device, vertexBuffer, nullptr);
381 vkFreeMemory(device, vertexBufferMemory, nullptr);
382 vkDestroyBuffer(device, indexBuffer, nullptr);
383 vkFreeMemory(device, indexBufferMemory, nullptr);
384}
Note: See TracBrowser for help on using the repository browser.