blob: 4f2fed7adc0c98214ff52d1332af1d4a2f0cde99 [file] [log] [blame]
Adam Sawickie6e498f2017-06-16 17:21:31 +02001//
2// Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved.
3//
4// Permission is hereby granted, free of charge, to any person obtaining a copy
5// of this software and associated documentation files (the "Software"), to deal
6// in the Software without restriction, including without limitation the rights
7// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8// copies of the Software, and to permit persons to whom the Software is
9// furnished to do so, subject to the following conditions:
10//
11// The above copyright notice and this permission notice shall be included in
12// all copies or substantial portions of the Software.
13//
14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20// THE SOFTWARE.
21//
22
23#define NOMINMAX
24#define WIN32_LEAN_AND_MEAN
25#include <Windows.h>
26
27#define VK_USE_PLATFORM_WIN32_KHR
28#include <vulkan/vulkan.h>
29
30#define VMA_IMPLEMENTATION
31#include "vk_mem_alloc.h"
32
33#define MATHFU_COMPILE_WITHOUT_SIMD_SUPPORT
34#include <mathfu/glsl_mappings.h>
35#include <mathfu/constants.h>
36
37#include <fstream>
38#include <vector>
39#include <string>
40#include <memory>
41#include <algorithm>
42#include <numeric>
43#include <array>
44#include <type_traits>
45#include <utility>
46
47#include <cmath>
48#include <cassert>
49#include <cstdlib>
50#include <cstdio>
51
52#define ERR_GUARD_VULKAN(Expr) do { VkResult res__ = (Expr); if (res__ < 0) assert(0); } while(0)
53
54static const char* const SHADER_PATH1 = "./";
55static const char* const SHADER_PATH2 = "../bin/";
56static const wchar_t* const WINDOW_CLASS_NAME = L"VULKAN_MEMORY_ALLOCATOR_SAMPLE";
57static const char* const VALIDATION_LAYER_NAME = "VK_LAYER_LUNARG_standard_validation";
58static const char* const APP_TITLE_A = "Vulkan Memory Allocator Sample 1.0";
59static const wchar_t* const APP_TITLE_W = L"Vulkan Memory Allocator Sample 1.0";
60
61static const bool VSYNC = true;
62static const uint32_t COMMAND_BUFFER_COUNT = 2;
63
64static bool g_EnableValidationLayer = true;
65
66static HINSTANCE g_hAppInstance;
67static HWND g_hWnd;
68static LONG g_SizeX = 1280, g_SizeY = 720;
69static VkInstance g_hVulkanInstance;
70static VkSurfaceKHR g_hSurface;
71static VkPhysicalDevice g_hPhysicalDevice;
72static VkQueue g_hPresentQueue;
73static VkSurfaceFormatKHR g_SurfaceFormat;
74static VkExtent2D g_Extent;
75static VkSwapchainKHR g_hSwapchain;
76static std::vector<VkImage> g_SwapchainImages;
77static std::vector<VkImageView> g_SwapchainImageViews;
78static std::vector<VkFramebuffer> g_Framebuffers;
79static VkCommandPool g_hCommandPool;
80static VkCommandBuffer g_MainCommandBuffers[COMMAND_BUFFER_COUNT];
81static VkFence g_MainCommandBufferExecutedFances[COMMAND_BUFFER_COUNT];
82static uint32_t g_NextCommandBufferIndex;
83static VkSemaphore g_hImageAvailableSemaphore;
84static VkSemaphore g_hRenderFinishedSemaphore;
85static uint32_t g_GraphicsQueueFamilyIndex = UINT_MAX;
86static uint32_t g_PresentQueueFamilyIndex = UINT_MAX;
87static VkDescriptorSetLayout g_hDescriptorSetLayout;
88static VkDescriptorPool g_hDescriptorPool;
89static VkDescriptorSet g_hDescriptorSet; // Automatically destroyed with m_DescriptorPool.
90static VkSampler g_hSampler;
91static VkFormat g_DepthFormat;
92static VkImage g_hDepthImage;
Adam Sawicki819860e2017-07-04 14:30:38 +020093static VmaAllocation g_hDepthImageAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +020094static VkImageView g_hDepthImageView;
95
96static VkSurfaceCapabilitiesKHR g_SurfaceCapabilities;
97static std::vector<VkSurfaceFormatKHR> g_SurfaceFormats;
98static std::vector<VkPresentModeKHR> g_PresentModes;
99
100static PFN_vkCreateDebugReportCallbackEXT g_pvkCreateDebugReportCallbackEXT;
101static PFN_vkDebugReportMessageEXT g_pvkDebugReportMessageEXT;
102static PFN_vkDestroyDebugReportCallbackEXT g_pvkDestroyDebugReportCallbackEXT;
103static VkDebugReportCallbackEXT g_hCallback;
104
105static VkDevice g_hDevice;
106static VmaAllocator g_hAllocator;
107static VkQueue g_hGraphicsQueue;
108static VkCommandBuffer g_hTemporaryCommandBuffer;
109
110static VkPipelineLayout g_hPipelineLayout;
111static VkRenderPass g_hRenderPass;
112static VkPipeline g_hPipeline;
113
114static VkBuffer g_hVertexBuffer;
Adam Sawicki819860e2017-07-04 14:30:38 +0200115static VmaAllocation g_hVertexBufferAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200116static VkBuffer g_hIndexBuffer;
Adam Sawicki819860e2017-07-04 14:30:38 +0200117static VmaAllocation g_hIndexBufferAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200118static uint32_t g_VertexCount;
119static uint32_t g_IndexCount;
120
121static VkImage g_hTextureImage;
Adam Sawicki819860e2017-07-04 14:30:38 +0200122static VmaAllocation g_hTextureImageAlloc;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200123static VkImageView g_hTextureImageView;
124
125static void BeginSingleTimeCommands()
126{
127 VkCommandBufferBeginInfo cmdBufBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
128 cmdBufBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
129 ERR_GUARD_VULKAN( vkBeginCommandBuffer(g_hTemporaryCommandBuffer, &cmdBufBeginInfo) );
130}
131
132static void EndSingleTimeCommands()
133{
134 ERR_GUARD_VULKAN( vkEndCommandBuffer(g_hTemporaryCommandBuffer) );
135
136 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
137 submitInfo.commandBufferCount = 1;
138 submitInfo.pCommandBuffers = &g_hTemporaryCommandBuffer;
139
140 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, VK_NULL_HANDLE) );
141 ERR_GUARD_VULKAN( vkQueueWaitIdle(g_hGraphicsQueue) );
142}
143
144static void LoadShader(std::vector<char>& out, const char* fileName)
145{
146 std::ifstream file(std::string(SHADER_PATH1) + fileName, std::ios::ate | std::ios::binary);
147 if(file.is_open() == false)
148 file.open(std::string(SHADER_PATH2) + fileName, std::ios::ate | std::ios::binary);
149 assert(file.is_open());
150 size_t fileSize = (size_t)file.tellg();
151 if(fileSize > 0)
152 {
153 out.resize(fileSize);
154 file.seekg(0);
155 file.read(out.data(), fileSize);
156 file.close();
157 }
158 else
159 out.clear();
160}
161
162VKAPI_ATTR VkBool32 VKAPI_CALL MyDebugReportCallback(
163 VkDebugReportFlagsEXT flags,
164 VkDebugReportObjectTypeEXT objectType,
165 uint64_t object,
166 size_t location,
167 int32_t messageCode,
168 const char* pLayerPrefix,
169 const char* pMessage,
170 void* pUserData)
171{
172 printf("%s \xBA %s\n", pLayerPrefix, pMessage);
173
174 if((flags == VK_DEBUG_REPORT_WARNING_BIT_EXT) ||
175 (flags == VK_DEBUG_REPORT_ERROR_BIT_EXT))
176 {
177 OutputDebugStringA(pMessage);
178 OutputDebugStringA("\n");
179 }
180
181 return VK_FALSE;
182}
183
184static VkSurfaceFormatKHR ChooseSurfaceFormat()
185{
186 assert(!g_SurfaceFormats.empty());
187
188 if((g_SurfaceFormats.size() == 1) && (g_SurfaceFormats[0].format == VK_FORMAT_UNDEFINED))
189 {
190 VkSurfaceFormatKHR result = { VK_FORMAT_B8G8R8A8_UNORM, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR };
191 return result;
192 }
193
194 for(const auto& format : g_SurfaceFormats)
195 {
196 if((format.format == VK_FORMAT_B8G8R8A8_UNORM) &&
197 (format.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR))
198 {
199 return format;
200 }
201 }
202
203 return g_SurfaceFormats[0];
204}
205
206VkPresentModeKHR ChooseSwapPresentMode()
207{
208 VkPresentModeKHR preferredMode = VSYNC ? VK_PRESENT_MODE_MAILBOX_KHR : VK_PRESENT_MODE_IMMEDIATE_KHR;
209
210 if(std::find(g_PresentModes.begin(), g_PresentModes.end(), preferredMode) !=
211 g_PresentModes.end())
212 {
213 return preferredMode;
214 }
215
216 return VK_PRESENT_MODE_FIFO_KHR;
217}
218
219static VkExtent2D ChooseSwapExtent()
220{
221 if(g_SurfaceCapabilities.currentExtent.width != UINT_MAX)
222 return g_SurfaceCapabilities.currentExtent;
223
224 VkExtent2D result = {
225 std::max(g_SurfaceCapabilities.minImageExtent.width,
226 std::min(g_SurfaceCapabilities.maxImageExtent.width, (uint32_t)g_SizeX)),
227 std::max(g_SurfaceCapabilities.minImageExtent.height,
228 std::min(g_SurfaceCapabilities.maxImageExtent.height, (uint32_t)g_SizeY)) };
229 return result;
230}
231
232struct Vertex
233{
234 float pos[3];
235 float color[3];
236 float texCoord[2];
237};
238
239static void CreateMesh()
240{
241 assert(g_hAllocator);
242
243 static Vertex vertices[] = {
244 // -X
245 { { -1.f, -1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 0.f} },
246 { { -1.f, -1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 0.f} },
247 { { -1.f, 1.f, -1.f}, {1.0f, 0.0f, 0.0f}, {0.f, 1.f} },
248 { { -1.f, 1.f, 1.f}, {1.0f, 0.0f, 0.0f}, {1.f, 1.f} },
249 // +X
250 { { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 0.f} },
251 { { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 0.f} },
252 { { 1.f, 1.f, 1.f}, {0.0f, 1.0f, 0.0f}, {0.f, 1.f} },
253 { { 1.f, 1.f, -1.f}, {0.0f, 1.0f, 0.0f}, {1.f, 1.f} },
254 // -Z
255 { { 1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 0.f} },
256 { {-1.f, -1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 0.f} },
257 { { 1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {0.f, 1.f} },
258 { {-1.f, 1.f, -1.f}, {0.0f, 0.0f, 1.0f}, {1.f, 1.f} },
259 // +Z
260 { {-1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 0.f} },
261 { { 1.f, -1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 0.f} },
262 { {-1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {0.f, 1.f} },
263 { { 1.f, 1.f, 1.f}, {1.0f, 1.0f, 0.0f}, {1.f, 1.f} },
264 // -Y
265 { {-1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 0.f} },
266 { { 1.f, -1.f, -1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 0.f} },
267 { {-1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {0.f, 1.f} },
268 { { 1.f, -1.f, 1.f}, {0.0f, 1.0f, 1.0f}, {1.f, 1.f} },
269 // +Y
270 { { 1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 0.f} },
271 { {-1.f, 1.f, -1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 0.f} },
272 { { 1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {0.f, 1.f} },
273 { {-1.f, 1.f, 1.f}, {1.0f, 0.0f, 1.0f}, {1.f, 1.f} },
274 };
275 static uint16_t indices[] = {
276 0, 1, 2, 3, USHRT_MAX,
277 4, 5, 6, 7, USHRT_MAX,
278 8, 9, 10, 11, USHRT_MAX,
279 12, 13, 14, 15, USHRT_MAX,
280 16, 17, 18, 19, USHRT_MAX,
281 20, 21, 22, 23, USHRT_MAX,
282 };
283
284 size_t vertexBufferSize = sizeof(Vertex) * _countof(vertices);
285 size_t indexBufferSize = sizeof(uint16_t) * _countof(indices);
286 g_IndexCount = (uint32_t)_countof(indices);
287
288 // Create vertex buffer
289
290 VkBufferCreateInfo vbInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
291 vbInfo.size = vertexBufferSize;
292 vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
293 vbInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200294
Adam Sawicki819860e2017-07-04 14:30:38 +0200295 VmaMemoryRequirements vbMemReq = {};
296 vbMemReq.usage = VMA_MEMORY_USAGE_CPU_ONLY;
297 vbMemReq.flags = VMA_MEMORY_REQUIREMENT_PERSISTENT_MAP_BIT;
298
299 VkBuffer stagingVertexBuffer = VK_NULL_HANDLE;
300 VmaAllocation stagingVertexBufferAlloc = VK_NULL_HANDLE;
301 VmaAllocationInfo stagingVertexBufferAllocInfo = {};
302 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbMemReq, &stagingVertexBuffer, &stagingVertexBufferAlloc, &stagingVertexBufferAllocInfo) );
303
304 memcpy(stagingVertexBufferAllocInfo.pMappedData, vertices, vertexBufferSize);
305
306 // No need to flush stagingVertexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
Adam Sawickie6e498f2017-06-16 17:21:31 +0200307
308 vbInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT;
309 vbMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200310 vbMemReq.flags = 0;
311 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &vbInfo, &vbMemReq, &g_hVertexBuffer, &g_hVertexBufferAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200312
313 // Create index buffer
314
315 VkBufferCreateInfo ibInfo = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO };
316 ibInfo.size = indexBufferSize;
317 ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
318 ibInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200319
Adam Sawickie6e498f2017-06-16 17:21:31 +0200320 VmaMemoryRequirements ibMemReq = {};
Adam Sawicki819860e2017-07-04 14:30:38 +0200321 ibMemReq.usage = VMA_MEMORY_USAGE_CPU_ONLY;
322 ibMemReq.flags = VMA_MEMORY_REQUIREMENT_PERSISTENT_MAP_BIT;
323
Adam Sawickie6e498f2017-06-16 17:21:31 +0200324 VkBuffer stagingIndexBuffer = VK_NULL_HANDLE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200325 VmaAllocation stagingIndexBufferAlloc = VK_NULL_HANDLE;
326 VmaAllocationInfo stagingIndexBufferAllocInfo = {};
327 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibMemReq, &stagingIndexBuffer, &stagingIndexBufferAlloc, &stagingIndexBufferAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200328
Adam Sawicki819860e2017-07-04 14:30:38 +0200329 memcpy(stagingIndexBufferAllocInfo.pMappedData, indices, indexBufferSize);
330
331 // No need to flush stagingIndexBuffer memory because CPU_ONLY memory is always HOST_COHERENT.
Adam Sawickie6e498f2017-06-16 17:21:31 +0200332
333 ibInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT;
334 ibMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200335 ibMemReq.flags = 0;
336 ERR_GUARD_VULKAN( vmaCreateBuffer(g_hAllocator, &ibInfo, &ibMemReq, &g_hIndexBuffer, &g_hIndexBufferAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200337
338 // Copy buffers
339
340 BeginSingleTimeCommands();
341
342 VkBufferCopy vbCopyRegion = {};
343 vbCopyRegion.srcOffset = 0;
344 vbCopyRegion.dstOffset = 0;
345 vbCopyRegion.size = vbInfo.size;
346 vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingVertexBuffer, g_hVertexBuffer, 1, &vbCopyRegion);
347
348 VkBufferCopy ibCopyRegion = {};
349 ibCopyRegion.srcOffset = 0;
350 ibCopyRegion.dstOffset = 0;
351 ibCopyRegion.size = ibInfo.size;
352 vkCmdCopyBuffer(g_hTemporaryCommandBuffer, stagingIndexBuffer, g_hIndexBuffer, 1, &ibCopyRegion);
353
354 EndSingleTimeCommands();
355
Adam Sawicki819860e2017-07-04 14:30:38 +0200356 vmaDestroyBuffer(g_hAllocator, stagingIndexBuffer, stagingIndexBufferAlloc);
357 vmaDestroyBuffer(g_hAllocator, stagingVertexBuffer, stagingVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200358}
359
360static void CopyImage(VkImage srcImage, VkImage dstImage, uint32_t width, uint32_t height, uint32_t mipLevel)
361{
362 BeginSingleTimeCommands();
363
364 VkImageCopy imageCopy = {};
365 imageCopy.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
366 imageCopy.srcSubresource.baseArrayLayer = 0;
367 imageCopy.srcSubresource.mipLevel = mipLevel;
368 imageCopy.srcSubresource.layerCount = 1;
369 imageCopy.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
370 imageCopy.dstSubresource.baseArrayLayer = 0;
371 imageCopy.dstSubresource.mipLevel = mipLevel;
372 imageCopy.dstSubresource.layerCount = 1;
373 imageCopy.srcOffset.x = 0;
374 imageCopy.srcOffset.y = 0;
375 imageCopy.srcOffset.z = 0;
376 imageCopy.dstOffset.x = 0;
377 imageCopy.dstOffset.y = 0;
378 imageCopy.dstOffset.z = 0;
379 imageCopy.extent.width = width;
380 imageCopy.extent.height = height;
381 imageCopy.extent.depth = 1;
382 vkCmdCopyImage(
383 g_hTemporaryCommandBuffer,
384 srcImage, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
385 dstImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
386 1, &imageCopy);
387
388 EndSingleTimeCommands();
389}
390
391static void TransitionImageLayout(VkImage image, VkFormat format, uint32_t mipLevelCount, VkImageLayout oldLayout, VkImageLayout newLayout)
392{
393 BeginSingleTimeCommands();
394
395 VkImageMemoryBarrier imgMemBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER };
396 imgMemBarrier.oldLayout = oldLayout;
397 imgMemBarrier.newLayout = newLayout;
398 imgMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
399 imgMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
400 imgMemBarrier.image = image;
401 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
402 imgMemBarrier.subresourceRange.baseMipLevel = 0;
403 imgMemBarrier.subresourceRange.levelCount = mipLevelCount;
404 imgMemBarrier.subresourceRange.baseArrayLayer = 0;
405 imgMemBarrier.subresourceRange.layerCount = 1;
406
407 if((oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) &&
408 (newLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL))
409 {
410 imgMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
411 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
412 }
413 else if((oldLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) &&
414 (newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
415 {
416 imgMemBarrier.srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
417 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
418 }
419 else if((oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) &&
420 (newLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL))
421 {
422 imgMemBarrier.srcAccessMask = 0;
423 imgMemBarrier.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
424 }
425 else if((oldLayout == VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL) &&
426 (newLayout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL))
427 {
428 imgMemBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
429 imgMemBarrier.dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
430 }
431 else if ((oldLayout == VK_IMAGE_LAYOUT_UNDEFINED) &&
432 (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL))
433 {
434 imgMemBarrier.srcAccessMask = 0;
435 imgMemBarrier.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
436 }
437 else
438 assert(0);
439
440 if (newLayout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL)
441 {
442 imgMemBarrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
443 if ((format == VK_FORMAT_D16_UNORM_S8_UINT) ||
444 (format == VK_FORMAT_D24_UNORM_S8_UINT) ||
445 (format == VK_FORMAT_D32_SFLOAT_S8_UINT))
446 {
447 imgMemBarrier.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
448 }
449 }
450
451 vkCmdPipelineBarrier(
452 g_hTemporaryCommandBuffer,
453 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
454 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
455 0,
456 0, nullptr,
457 0, nullptr,
458 1, &imgMemBarrier);
459
460 EndSingleTimeCommands();
461}
462
463static void CreateTexture(uint32_t sizeX, uint32_t sizeY)
464{
465 // Create Image
466
467 const VkDeviceSize imageSize = sizeX * sizeY * 4;
468
469 VkImageCreateInfo stagingImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
470 stagingImageInfo.imageType = VK_IMAGE_TYPE_2D;
471 stagingImageInfo.extent.width = sizeX;
472 stagingImageInfo.extent.height = sizeY;
473 stagingImageInfo.extent.depth = 1;
474 stagingImageInfo.mipLevels = 1;
475 stagingImageInfo.arrayLayers = 1;
476 stagingImageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
477 stagingImageInfo.tiling = VK_IMAGE_TILING_LINEAR;
478 stagingImageInfo.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED;
479 stagingImageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
480 stagingImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
481 stagingImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
482 stagingImageInfo.flags = 0;
Adam Sawicki819860e2017-07-04 14:30:38 +0200483
Adam Sawickie6e498f2017-06-16 17:21:31 +0200484 VmaMemoryRequirements stagingImageMemReq = {};
Adam Sawicki819860e2017-07-04 14:30:38 +0200485 stagingImageMemReq.usage = VMA_MEMORY_USAGE_CPU_ONLY;
486 stagingImageMemReq.flags = VMA_MEMORY_REQUIREMENT_PERSISTENT_MAP_BIT;
487
Adam Sawickie6e498f2017-06-16 17:21:31 +0200488 VkImage stagingImage = VK_NULL_HANDLE;
Adam Sawicki819860e2017-07-04 14:30:38 +0200489 VmaAllocation stagingImageAlloc = VK_NULL_HANDLE;
490 VmaAllocationInfo stagingImageAllocInfo = {};
491 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &stagingImageInfo, &stagingImageMemReq, &stagingImage, &stagingImageAlloc, &stagingImageAllocInfo) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200492
493 VkImageSubresource imageSubresource = {};
494 imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
495 imageSubresource.mipLevel = 0;
496 imageSubresource.arrayLayer = 0;
497
498 VkSubresourceLayout imageLayout = {};
499 vkGetImageSubresourceLayout(g_hDevice, stagingImage, &imageSubresource, &imageLayout);
500
Adam Sawicki819860e2017-07-04 14:30:38 +0200501 char* const pMipLevelData = (char*)stagingImageAllocInfo.pMappedData + imageLayout.offset;
Adam Sawickie6e498f2017-06-16 17:21:31 +0200502 uint8_t* pRowData = (uint8_t*)pMipLevelData;
503 for(uint32_t y = 0; y < sizeY; ++y)
504 {
505 uint32_t* pPixelData = (uint32_t*)pRowData;
506 for(uint32_t x = 0; x < sizeY; ++x)
507 {
508 *pPixelData =
509 ((x & 0x18) == 0x08 ? 0x000000FF : 0x00000000) |
510 ((x & 0x18) == 0x10 ? 0x0000FFFF : 0x00000000) |
511 ((y & 0x18) == 0x08 ? 0x0000FF00 : 0x00000000) |
512 ((y & 0x18) == 0x10 ? 0x00FF0000 : 0x00000000);
513 ++pPixelData;
514 }
515 pRowData += imageLayout.rowPitch;
516 }
517
Adam Sawicki819860e2017-07-04 14:30:38 +0200518 // No need to flush stagingImage memory because CPU_ONLY memory is always HOST_COHERENT.
Adam Sawickie6e498f2017-06-16 17:21:31 +0200519
520 VkImageCreateInfo imageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
521 imageInfo.imageType = VK_IMAGE_TYPE_2D;
522 imageInfo.extent.width = sizeX;
523 imageInfo.extent.height = sizeY;
524 imageInfo.extent.depth = 1;
525 imageInfo.mipLevels = 1;
526 imageInfo.arrayLayers = 1;
527 imageInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
528 imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
529 imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
530 imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
531 imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
532 imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
533 imageInfo.flags = 0;
534 VmaMemoryRequirements imageMemReq = {};
535 imageMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
Adam Sawicki819860e2017-07-04 14:30:38 +0200536 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &imageInfo, &imageMemReq, &g_hTextureImage, &g_hTextureImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200537
538 TransitionImageLayout(
539 stagingImage,
540 VK_FORMAT_R8G8B8A8_UNORM,
541 1,
542 VK_IMAGE_LAYOUT_PREINITIALIZED,
543 VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
544 TransitionImageLayout(
545 g_hTextureImage,
546 VK_FORMAT_R8G8B8A8_UNORM,
547 1,
548 VK_IMAGE_LAYOUT_UNDEFINED,
549 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
550 CopyImage(stagingImage, g_hTextureImage, sizeX, sizeY, 0);
551 TransitionImageLayout(
552 g_hTextureImage,
553 VK_FORMAT_R8G8B8A8_UNORM,
554 1,
555 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
556 VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
557
Adam Sawicki819860e2017-07-04 14:30:38 +0200558 vmaDestroyImage(g_hAllocator, stagingImage, stagingImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +0200559
560 // Create ImageView
561
562 VkImageViewCreateInfo textureImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
563 textureImageViewInfo.image = g_hTextureImage;
564 textureImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
565 textureImageViewInfo.format = VK_FORMAT_R8G8B8A8_UNORM;
566 textureImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
567 textureImageViewInfo.subresourceRange.baseMipLevel = 0;
568 textureImageViewInfo.subresourceRange.levelCount = 1;
569 textureImageViewInfo.subresourceRange.baseArrayLayer = 0;
570 textureImageViewInfo.subresourceRange.layerCount = 1;
571 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &textureImageViewInfo, nullptr, &g_hTextureImageView) );
572}
573
574struct UniformBufferObject
575{
576 mathfu::vec4_packed ModelViewProj[4];
577};
578
579static void RegisterDebugCallbacks()
580{
581 g_pvkCreateDebugReportCallbackEXT =
582 reinterpret_cast<PFN_vkCreateDebugReportCallbackEXT>
583 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkCreateDebugReportCallbackEXT"));
584 g_pvkDebugReportMessageEXT =
585 reinterpret_cast<PFN_vkDebugReportMessageEXT>
586 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkDebugReportMessageEXT"));
587 g_pvkDestroyDebugReportCallbackEXT =
588 reinterpret_cast<PFN_vkDestroyDebugReportCallbackEXT>
589 (vkGetInstanceProcAddr(g_hVulkanInstance, "vkDestroyDebugReportCallbackEXT"));
590 assert(g_pvkCreateDebugReportCallbackEXT);
591 assert(g_pvkDebugReportMessageEXT);
592 assert(g_pvkDestroyDebugReportCallbackEXT);
593
594 VkDebugReportCallbackCreateInfoEXT callbackCreateInfo;
595 callbackCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
596 callbackCreateInfo.pNext = nullptr;
597 callbackCreateInfo.flags = //VK_DEBUG_REPORT_INFORMATION_BIT_EXT |
598 VK_DEBUG_REPORT_ERROR_BIT_EXT |
599 VK_DEBUG_REPORT_WARNING_BIT_EXT |
600 VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT /*|
601 VK_DEBUG_REPORT_DEBUG_BIT_EXT*/;
602 callbackCreateInfo.pfnCallback = &MyDebugReportCallback;
603 callbackCreateInfo.pUserData = nullptr;
604
605 ERR_GUARD_VULKAN( g_pvkCreateDebugReportCallbackEXT(g_hVulkanInstance, &callbackCreateInfo, nullptr, &g_hCallback) );
606}
607
608static bool IsLayerSupported(const VkLayerProperties* pProps, size_t propCount, const char* pLayerName)
609{
610 const VkLayerProperties* propsEnd = pProps + propCount;
611 return std::find_if(
612 pProps,
613 propsEnd,
614 [pLayerName](const VkLayerProperties& prop) -> bool {
615 return strcmp(pLayerName, prop.layerName) == 0;
616 }) != propsEnd;
617}
618
619static VkFormat FindSupportedFormat(
620 const std::vector<VkFormat>& candidates,
621 VkImageTiling tiling,
622 VkFormatFeatureFlags features)
623{
624 for (VkFormat format : candidates)
625 {
626 VkFormatProperties props;
627 vkGetPhysicalDeviceFormatProperties(g_hPhysicalDevice, format, &props);
628
629 if ((tiling == VK_IMAGE_TILING_LINEAR) &&
630 ((props.linearTilingFeatures & features) == features))
631 {
632 return format;
633 }
634 else if ((tiling == VK_IMAGE_TILING_OPTIMAL) &&
635 ((props.optimalTilingFeatures & features) == features))
636 {
637 return format;
638 }
639 }
640 return VK_FORMAT_UNDEFINED;
641}
642
643static VkFormat FindDepthFormat()
644{
645 std::vector<VkFormat> formats;
646 formats.push_back(VK_FORMAT_D32_SFLOAT);
647 formats.push_back(VK_FORMAT_D32_SFLOAT_S8_UINT);
648 formats.push_back(VK_FORMAT_D24_UNORM_S8_UINT);
649
650 return FindSupportedFormat(
651 formats,
652 VK_IMAGE_TILING_OPTIMAL,
653 VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT);
654}
655
656static void CreateSwapchain()
657{
658 // Query surface formats.
659
660 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceCapabilitiesKHR(g_hPhysicalDevice, g_hSurface, &g_SurfaceCapabilities) );
661
662 uint32_t formatCount = 0;
663 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, nullptr) );
664 g_SurfaceFormats.resize(formatCount);
665 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfaceFormatsKHR(g_hPhysicalDevice, g_hSurface, &formatCount, g_SurfaceFormats.data()) );
666
667 uint32_t presentModeCount = 0;
668 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, nullptr) );
669 g_PresentModes.resize(presentModeCount);
670 ERR_GUARD_VULKAN( vkGetPhysicalDeviceSurfacePresentModesKHR(g_hPhysicalDevice, g_hSurface, &presentModeCount, g_PresentModes.data()) );
671
672 // Create swap chain
673
674 g_SurfaceFormat = ChooseSurfaceFormat();
675 VkPresentModeKHR presentMode = ChooseSwapPresentMode();
676 g_Extent = ChooseSwapExtent();
677
678 uint32_t imageCount = g_SurfaceCapabilities.minImageCount + 1;
679 if((g_SurfaceCapabilities.maxImageCount > 0) &&
680 (imageCount > g_SurfaceCapabilities.maxImageCount))
681 {
682 imageCount = g_SurfaceCapabilities.maxImageCount;
683 }
684
685 VkSwapchainCreateInfoKHR swapChainInfo = { VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
686 swapChainInfo.surface = g_hSurface;
687 swapChainInfo.minImageCount = imageCount;
688 swapChainInfo.imageFormat = g_SurfaceFormat.format;
689 swapChainInfo.imageColorSpace = g_SurfaceFormat.colorSpace;
690 swapChainInfo.imageExtent = g_Extent;
691 swapChainInfo.imageArrayLayers = 1;
692 swapChainInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
693 swapChainInfo.preTransform = g_SurfaceCapabilities.currentTransform;
694 swapChainInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
695 swapChainInfo.presentMode = presentMode;
696 swapChainInfo.clipped = VK_TRUE;
697 swapChainInfo.oldSwapchain = g_hSwapchain;
698
699 uint32_t queueFamilyIndices[] = { g_GraphicsQueueFamilyIndex, g_PresentQueueFamilyIndex };
700 if(g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex)
701 {
702 swapChainInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
703 swapChainInfo.queueFamilyIndexCount = 2;
704 swapChainInfo.pQueueFamilyIndices = queueFamilyIndices;
705 }
706 else
707 {
708 swapChainInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
709 }
710
711 VkSwapchainKHR hNewSwapchain = VK_NULL_HANDLE;
712 ERR_GUARD_VULKAN( vkCreateSwapchainKHR(g_hDevice, &swapChainInfo, nullptr, &hNewSwapchain) );
713 if(g_hSwapchain != VK_NULL_HANDLE)
714 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, nullptr);
715 g_hSwapchain = hNewSwapchain;
716
717 // Retrieve swapchain images.
718
719 uint32_t swapchainImageCount = 0;
720 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, nullptr) );
721 g_SwapchainImages.resize(swapchainImageCount);
722 ERR_GUARD_VULKAN( vkGetSwapchainImagesKHR(g_hDevice, g_hSwapchain, &swapchainImageCount, g_SwapchainImages.data()) );
723
724 // Create swapchain image views.
725
726 for(size_t i = g_SwapchainImageViews.size(); i--; )
727 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], nullptr);
728 g_SwapchainImageViews.clear();
729
730 VkImageViewCreateInfo swapchainImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
731 g_SwapchainImageViews.resize(swapchainImageCount);
732 for(uint32_t i = 0; i < swapchainImageCount; ++i)
733 {
734 swapchainImageViewInfo.image = g_SwapchainImages[i];
735 swapchainImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
736 swapchainImageViewInfo.format = g_SurfaceFormat.format;
737 swapchainImageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
738 swapchainImageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
739 swapchainImageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
740 swapchainImageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
741 swapchainImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
742 swapchainImageViewInfo.subresourceRange.baseMipLevel = 0;
743 swapchainImageViewInfo.subresourceRange.levelCount = 1;
744 swapchainImageViewInfo.subresourceRange.baseArrayLayer = 0;
745 swapchainImageViewInfo.subresourceRange.layerCount = 1;
746 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &swapchainImageViewInfo, nullptr, &g_SwapchainImageViews[i]) );
747 }
748
749 // Create depth buffer
750
751 g_DepthFormat = FindDepthFormat();
752 assert(g_DepthFormat != VK_FORMAT_UNDEFINED);
753
754 VkImageCreateInfo depthImageInfo = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO };
755 depthImageInfo.imageType = VK_IMAGE_TYPE_2D;
756 depthImageInfo.extent.width = g_Extent.width;
757 depthImageInfo.extent.height = g_Extent.height;
758 depthImageInfo.extent.depth = 1;
759 depthImageInfo.mipLevels = 1;
760 depthImageInfo.arrayLayers = 1;
761 depthImageInfo.format = g_DepthFormat;
762 depthImageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
763 depthImageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
764 depthImageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
765 depthImageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
766 depthImageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
767 depthImageInfo.flags = 0;
768
769 VmaMemoryRequirements depthImageMemReq = {};
770 depthImageMemReq.usage = VMA_MEMORY_USAGE_GPU_ONLY;
771
Adam Sawicki819860e2017-07-04 14:30:38 +0200772 ERR_GUARD_VULKAN( vmaCreateImage(g_hAllocator, &depthImageInfo, &depthImageMemReq, &g_hDepthImage, &g_hDepthImageAlloc, nullptr) );
Adam Sawickie6e498f2017-06-16 17:21:31 +0200773
774 VkImageViewCreateInfo depthImageViewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
775 depthImageViewInfo.image = g_hDepthImage;
776 depthImageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
777 depthImageViewInfo.format = g_DepthFormat;
778 depthImageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
779 depthImageViewInfo.subresourceRange.baseMipLevel = 0;
780 depthImageViewInfo.subresourceRange.levelCount = 1;
781 depthImageViewInfo.subresourceRange.baseArrayLayer = 0;
782 depthImageViewInfo.subresourceRange.layerCount = 1;
783
784 ERR_GUARD_VULKAN( vkCreateImageView(g_hDevice, &depthImageViewInfo, nullptr, &g_hDepthImageView) );
785
786 TransitionImageLayout(
787 g_hDepthImage,
788 g_DepthFormat,
789 1,
790 VK_IMAGE_LAYOUT_UNDEFINED,
791 VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
792
793 // Create pipeline layout
794 {
795 if(g_hPipelineLayout != VK_NULL_HANDLE)
796 {
797 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, nullptr);
798 g_hPipelineLayout = VK_NULL_HANDLE;
799 }
800
801 VkPushConstantRange pushConstantRanges[1];
802 ZeroMemory(&pushConstantRanges, sizeof pushConstantRanges);
803 pushConstantRanges[0].offset = 0;
804 pushConstantRanges[0].size = sizeof(UniformBufferObject);
805 pushConstantRanges[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
806
807 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
808 VkPipelineLayoutCreateInfo pipelineLayoutInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO };
809 pipelineLayoutInfo.setLayoutCount = 1;
810 pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts;
811 pipelineLayoutInfo.pushConstantRangeCount = 1;
812 pipelineLayoutInfo.pPushConstantRanges = pushConstantRanges;
813 ERR_GUARD_VULKAN( vkCreatePipelineLayout(g_hDevice, &pipelineLayoutInfo, nullptr, &g_hPipelineLayout) );
814 }
815
816 // Create render pass
817 {
818 if(g_hRenderPass != VK_NULL_HANDLE)
819 {
820 vkDestroyRenderPass(g_hDevice, g_hRenderPass, nullptr);
821 g_hRenderPass = VK_NULL_HANDLE;
822 }
823
824 VkAttachmentDescription attachments[2];
825 ZeroMemory(attachments, sizeof(attachments));
826
827 attachments[0].format = g_SurfaceFormat.format;
828 attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
829 attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
830 attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
831 attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
832 attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
833 attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
834 attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
835
836 attachments[1].format = g_DepthFormat;
837 attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
838 attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
839 attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
840 attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
841 attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
842 attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
843 attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
844
845 VkAttachmentReference colorAttachmentRef = {};
846 colorAttachmentRef.attachment = 0;
847 colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
848
849 VkAttachmentReference depthStencilAttachmentRef = {};
850 depthStencilAttachmentRef.attachment = 1;
851 depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
852
853 VkSubpassDescription subpassDesc = {};
854 subpassDesc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
855 subpassDesc.colorAttachmentCount = 1;
856 subpassDesc.pColorAttachments = &colorAttachmentRef;
857 subpassDesc.pDepthStencilAttachment = &depthStencilAttachmentRef;
858
859 VkSubpassDependency subpassDependency = {};
860 subpassDependency.srcSubpass = VK_SUBPASS_EXTERNAL;
861 subpassDependency.dstSubpass = 0;
862 subpassDependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
863 subpassDependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
864 subpassDependency.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
865 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
866 subpassDependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT |
867 VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT;
868
869 VkRenderPassCreateInfo renderPassInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO };
870 renderPassInfo.attachmentCount = (uint32_t)_countof(attachments);
871 renderPassInfo.pAttachments = attachments;
872 renderPassInfo.subpassCount = 1;
873 renderPassInfo.pSubpasses = &subpassDesc;
874 renderPassInfo.dependencyCount = 1;
875 renderPassInfo.pDependencies = &subpassDependency;
876 ERR_GUARD_VULKAN( vkCreateRenderPass(g_hDevice, &renderPassInfo, nullptr, &g_hRenderPass) );
877 }
878
879 // Create pipeline
880 {
881 std::vector<char> vertShaderCode;
882 LoadShader(vertShaderCode, "Shader.vert.spv");
883 VkShaderModuleCreateInfo shaderModuleInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
884 shaderModuleInfo.codeSize = vertShaderCode.size();
885 shaderModuleInfo.pCode = (const uint32_t*)vertShaderCode.data();
886 VkShaderModule hVertShaderModule = VK_NULL_HANDLE;
887 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, nullptr, &hVertShaderModule) );
888
889 std::vector<char> hFragShaderCode;
890 LoadShader(hFragShaderCode, "Shader.frag.spv");
891 shaderModuleInfo.codeSize = hFragShaderCode.size();
892 shaderModuleInfo.pCode = (const uint32_t*)hFragShaderCode.data();
893 VkShaderModule fragShaderModule = VK_NULL_HANDLE;
894 ERR_GUARD_VULKAN( vkCreateShaderModule(g_hDevice, &shaderModuleInfo, nullptr, &fragShaderModule) );
895
896 VkPipelineShaderStageCreateInfo vertPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
897 vertPipelineShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
898 vertPipelineShaderStageInfo.module = hVertShaderModule;
899 vertPipelineShaderStageInfo.pName = "main";
900
901 VkPipelineShaderStageCreateInfo fragPipelineShaderStageInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
902 fragPipelineShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
903 fragPipelineShaderStageInfo.module = fragShaderModule;
904 fragPipelineShaderStageInfo.pName = "main";
905
906 VkPipelineShaderStageCreateInfo pipelineShaderStageInfos[] = {
907 vertPipelineShaderStageInfo,
908 fragPipelineShaderStageInfo
909 };
910
911 VkVertexInputBindingDescription bindingDescription = {};
912 bindingDescription.binding = 0;
913 bindingDescription.stride = sizeof(Vertex);
914 bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
915
916 VkVertexInputAttributeDescription attributeDescriptions[3];
917 ZeroMemory(attributeDescriptions, sizeof(attributeDescriptions));
918
919 attributeDescriptions[0].binding = 0;
920 attributeDescriptions[0].location = 0;
921 attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT;
922 attributeDescriptions[0].offset = offsetof(Vertex, pos);
923
924 attributeDescriptions[1].binding = 0;
925 attributeDescriptions[1].location = 1;
926 attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
927 attributeDescriptions[1].offset = offsetof(Vertex, color);
928
929 attributeDescriptions[2].binding = 0;
930 attributeDescriptions[2].location = 2;
931 attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
932 attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
933
934 VkPipelineVertexInputStateCreateInfo pipelineVertexInputStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO };
935 pipelineVertexInputStateInfo.vertexBindingDescriptionCount = 1;
936 pipelineVertexInputStateInfo.pVertexBindingDescriptions = &bindingDescription;
937 pipelineVertexInputStateInfo.vertexAttributeDescriptionCount = _countof(attributeDescriptions);
938 pipelineVertexInputStateInfo.pVertexAttributeDescriptions = attributeDescriptions;
939
940 VkPipelineInputAssemblyStateCreateInfo pipelineInputAssemblyStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO };
941 pipelineInputAssemblyStateInfo.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP;
942 pipelineInputAssemblyStateInfo.primitiveRestartEnable = VK_TRUE;
943
944 VkViewport viewport = {};
945 viewport.x = 0.f;
946 viewport.y = 0.f;
947 viewport.width = (float)g_Extent.width;
948 viewport.height = (float)g_Extent.height;
949 viewport.minDepth = 0.f;
950 viewport.maxDepth = 1.f;
951
952 VkRect2D scissor = {};
953 scissor.offset.x = 0;
954 scissor.offset.y = 0;
955 scissor.extent = g_Extent;
956
957 VkPipelineViewportStateCreateInfo pipelineViewportStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO };
958 pipelineViewportStateInfo.viewportCount = 1;
959 pipelineViewportStateInfo.pViewports = &viewport;
960 pipelineViewportStateInfo.scissorCount = 1;
961 pipelineViewportStateInfo.pScissors = &scissor;
962
963 VkPipelineRasterizationStateCreateInfo pipelineRasterizationStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO };
964 pipelineRasterizationStateInfo.depthClampEnable = VK_FALSE;
965 pipelineRasterizationStateInfo.rasterizerDiscardEnable = VK_FALSE;
966 pipelineRasterizationStateInfo.polygonMode = VK_POLYGON_MODE_FILL;
967 pipelineRasterizationStateInfo.lineWidth = 1.f;
968 pipelineRasterizationStateInfo.cullMode = VK_CULL_MODE_BACK_BIT;
969 pipelineRasterizationStateInfo.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
970 pipelineRasterizationStateInfo.depthBiasEnable = VK_FALSE;
971 pipelineRasterizationStateInfo.depthBiasConstantFactor = 0.f;
972 pipelineRasterizationStateInfo.depthBiasClamp = 0.f;
973 pipelineRasterizationStateInfo.depthBiasSlopeFactor = 0.f;
974
975 VkPipelineMultisampleStateCreateInfo pipelineMultisampleStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO };
976 pipelineMultisampleStateInfo.sampleShadingEnable = VK_FALSE;
977 pipelineMultisampleStateInfo.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
978 pipelineMultisampleStateInfo.minSampleShading = 1.f;
979 pipelineMultisampleStateInfo.pSampleMask = nullptr;
980 pipelineMultisampleStateInfo.alphaToCoverageEnable = VK_FALSE;
981 pipelineMultisampleStateInfo.alphaToOneEnable = VK_FALSE;
982
983 VkPipelineColorBlendAttachmentState pipelineColorBlendAttachmentState = {};
984 pipelineColorBlendAttachmentState.colorWriteMask =
985 VK_COLOR_COMPONENT_R_BIT |
986 VK_COLOR_COMPONENT_G_BIT |
987 VK_COLOR_COMPONENT_B_BIT |
988 VK_COLOR_COMPONENT_A_BIT;
989 pipelineColorBlendAttachmentState.blendEnable = VK_FALSE;
990 pipelineColorBlendAttachmentState.srcColorBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
991 pipelineColorBlendAttachmentState.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
992 pipelineColorBlendAttachmentState.colorBlendOp = VK_BLEND_OP_ADD; // Optional
993 pipelineColorBlendAttachmentState.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE; // Optional
994 pipelineColorBlendAttachmentState.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO; // Optional
995 pipelineColorBlendAttachmentState.alphaBlendOp = VK_BLEND_OP_ADD; // Optional
996
997 VkPipelineColorBlendStateCreateInfo pipelineColorBlendStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO };
998 pipelineColorBlendStateInfo.logicOpEnable = VK_FALSE;
999 pipelineColorBlendStateInfo.logicOp = VK_LOGIC_OP_COPY;
1000 pipelineColorBlendStateInfo.attachmentCount = 1;
1001 pipelineColorBlendStateInfo.pAttachments = &pipelineColorBlendAttachmentState;
1002
1003 VkPipelineDepthStencilStateCreateInfo depthStencilStateInfo = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO };
1004 depthStencilStateInfo.depthTestEnable = VK_TRUE;
1005 depthStencilStateInfo.depthWriteEnable = VK_TRUE;
1006 depthStencilStateInfo.depthCompareOp = VK_COMPARE_OP_LESS;
1007 depthStencilStateInfo.depthBoundsTestEnable = VK_FALSE;
1008 depthStencilStateInfo.stencilTestEnable = VK_FALSE;
1009
1010 VkGraphicsPipelineCreateInfo pipelineInfo = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO };
1011 pipelineInfo.stageCount = 2;
1012 pipelineInfo.pStages = pipelineShaderStageInfos;
1013 pipelineInfo.pVertexInputState = &pipelineVertexInputStateInfo;
1014 pipelineInfo.pInputAssemblyState = &pipelineInputAssemblyStateInfo;
1015 pipelineInfo.pViewportState = &pipelineViewportStateInfo;
1016 pipelineInfo.pRasterizationState = &pipelineRasterizationStateInfo;
1017 pipelineInfo.pMultisampleState = &pipelineMultisampleStateInfo;
1018 pipelineInfo.pDepthStencilState = &depthStencilStateInfo;
1019 pipelineInfo.pColorBlendState = &pipelineColorBlendStateInfo;
1020 pipelineInfo.pDynamicState = nullptr;
1021 pipelineInfo.layout = g_hPipelineLayout;
1022 pipelineInfo.renderPass = g_hRenderPass;
1023 pipelineInfo.subpass = 0;
1024 pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
1025 pipelineInfo.basePipelineIndex = -1;
1026 ERR_GUARD_VULKAN( vkCreateGraphicsPipelines(
1027 g_hDevice,
1028 VK_NULL_HANDLE,
1029 1,
1030 &pipelineInfo, nullptr,
1031 &g_hPipeline) );
1032
1033 vkDestroyShaderModule(g_hDevice, fragShaderModule, nullptr);
1034 vkDestroyShaderModule(g_hDevice, hVertShaderModule, nullptr);
1035 }
1036
1037 // Create frambuffers
1038
1039 for(size_t i = g_Framebuffers.size(); i--; )
1040 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], nullptr);
1041 g_Framebuffers.clear();
1042
1043 g_Framebuffers.resize(g_SwapchainImageViews.size());
1044 for(size_t i = 0; i < g_SwapchainImages.size(); ++i)
1045 {
1046 VkImageView attachments[] = { g_SwapchainImageViews[i], g_hDepthImageView };
1047
1048 VkFramebufferCreateInfo framebufferInfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO };
1049 framebufferInfo.renderPass = g_hRenderPass;
1050 framebufferInfo.attachmentCount = (uint32_t)_countof(attachments);
1051 framebufferInfo.pAttachments = attachments;
1052 framebufferInfo.width = g_Extent.width;
1053 framebufferInfo.height = g_Extent.height;
1054 framebufferInfo.layers = 1;
1055 ERR_GUARD_VULKAN( vkCreateFramebuffer(g_hDevice, &framebufferInfo, nullptr, &g_Framebuffers[i]) );
1056 }
1057
1058 // Create semaphores
1059
1060 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1061 {
1062 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, nullptr);
1063 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1064 }
1065 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1066 {
1067 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, nullptr);
1068 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1069 }
1070
1071 VkSemaphoreCreateInfo semaphoreInfo = { VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
1072 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, nullptr, &g_hImageAvailableSemaphore) );
1073 ERR_GUARD_VULKAN( vkCreateSemaphore(g_hDevice, &semaphoreInfo, nullptr, &g_hRenderFinishedSemaphore) );
1074}
1075
1076static void DestroySwapchain(bool destroyActualSwapchain)
1077{
1078 if(g_hImageAvailableSemaphore != VK_NULL_HANDLE)
1079 {
1080 vkDestroySemaphore(g_hDevice, g_hImageAvailableSemaphore, nullptr);
1081 g_hImageAvailableSemaphore = VK_NULL_HANDLE;
1082 }
1083 if(g_hRenderFinishedSemaphore != VK_NULL_HANDLE)
1084 {
1085 vkDestroySemaphore(g_hDevice, g_hRenderFinishedSemaphore, nullptr);
1086 g_hRenderFinishedSemaphore = VK_NULL_HANDLE;
1087 }
1088
1089 for(size_t i = g_Framebuffers.size(); i--; )
1090 vkDestroyFramebuffer(g_hDevice, g_Framebuffers[i], nullptr);
1091 g_Framebuffers.clear();
1092
1093 if(g_hDepthImageView != VK_NULL_HANDLE)
1094 {
1095 vkDestroyImageView(g_hDevice, g_hDepthImageView, nullptr);
1096 g_hDepthImageView = VK_NULL_HANDLE;
1097 }
1098 if(g_hDepthImage != VK_NULL_HANDLE)
1099 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001100 vmaDestroyImage(g_hAllocator, g_hDepthImage, g_hDepthImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001101 g_hDepthImage = VK_NULL_HANDLE;
1102 }
1103
1104 if(g_hPipeline != VK_NULL_HANDLE)
1105 {
1106 vkDestroyPipeline(g_hDevice, g_hPipeline, nullptr);
1107 g_hPipeline = VK_NULL_HANDLE;
1108 }
1109
1110 if(g_hRenderPass != VK_NULL_HANDLE)
1111 {
1112 vkDestroyRenderPass(g_hDevice, g_hRenderPass, nullptr);
1113 g_hRenderPass = VK_NULL_HANDLE;
1114 }
1115
1116 if(g_hPipelineLayout != VK_NULL_HANDLE)
1117 {
1118 vkDestroyPipelineLayout(g_hDevice, g_hPipelineLayout, nullptr);
1119 g_hPipelineLayout = VK_NULL_HANDLE;
1120 }
1121
1122 for(size_t i = g_SwapchainImageViews.size(); i--; )
1123 vkDestroyImageView(g_hDevice, g_SwapchainImageViews[i], nullptr);
1124 g_SwapchainImageViews.clear();
1125
1126 if(destroyActualSwapchain && (g_hSwapchain != VK_NULL_HANDLE))
1127 {
1128 vkDestroySwapchainKHR(g_hDevice, g_hSwapchain, nullptr);
1129 g_hSwapchain = VK_NULL_HANDLE;
1130 }
1131}
1132
1133static void InitializeApplication()
1134{
1135 uint32_t instanceLayerPropCount = 0;
1136 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, nullptr) );
1137 std::vector<VkLayerProperties> instanceLayerProps(instanceLayerPropCount);
1138 if(instanceLayerPropCount > 0)
1139 {
1140 ERR_GUARD_VULKAN( vkEnumerateInstanceLayerProperties(&instanceLayerPropCount, instanceLayerProps.data()) );
1141 }
1142
1143 if(g_EnableValidationLayer == true)
1144 {
1145 if(IsLayerSupported(instanceLayerProps.data(), instanceLayerProps.size(), VALIDATION_LAYER_NAME) == false)
1146 {
1147 printf("Layer \"%s\" not supported.", VALIDATION_LAYER_NAME);
1148 g_EnableValidationLayer = false;
1149 }
1150 }
1151
1152 std::vector<const char*> instanceExtensions;
1153 instanceExtensions.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
1154 instanceExtensions.push_back(VK_KHR_WIN32_SURFACE_EXTENSION_NAME);
1155
1156 std::vector<const char*> instanceLayers;
1157 if(g_EnableValidationLayer == true)
1158 {
1159 instanceLayers.push_back(VALIDATION_LAYER_NAME);
1160 instanceExtensions.push_back("VK_EXT_debug_report");
1161 }
1162
1163 VkApplicationInfo appInfo = { VK_STRUCTURE_TYPE_APPLICATION_INFO };
1164 appInfo.pApplicationName = APP_TITLE_A;
1165 appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
1166 appInfo.pEngineName = "Adam Sawicki Engine";
1167 appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
1168 appInfo.apiVersion = VK_API_VERSION_1_0;
1169
1170 VkInstanceCreateInfo instInfo = { VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
1171 instInfo.pApplicationInfo = &appInfo;
1172 instInfo.enabledExtensionCount = static_cast<uint32_t>(instanceExtensions.size());
1173 instInfo.ppEnabledExtensionNames = instanceExtensions.data();
1174 instInfo.enabledLayerCount = static_cast<uint32_t>(instanceLayers.size());
1175 instInfo.ppEnabledLayerNames = instanceLayers.data();
1176
1177 ERR_GUARD_VULKAN( vkCreateInstance(&instInfo, NULL, &g_hVulkanInstance) );
1178
1179 // Create VkSurfaceKHR.
1180 VkWin32SurfaceCreateInfoKHR surfaceInfo = { VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR };
1181 surfaceInfo.hinstance = g_hAppInstance;
1182 surfaceInfo.hwnd = g_hWnd;
1183 VkResult result = vkCreateWin32SurfaceKHR(g_hVulkanInstance, &surfaceInfo, NULL, &g_hSurface);
1184 assert(result == VK_SUCCESS);
1185
1186 if(g_EnableValidationLayer == true)
1187 RegisterDebugCallbacks();
1188
1189 // Find physical device
1190
1191 uint32_t deviceCount = 0;
1192 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, nullptr) );
1193 assert(deviceCount > 0);
1194
1195 std::vector<VkPhysicalDevice> physicalDevices(deviceCount);
1196 ERR_GUARD_VULKAN( vkEnumeratePhysicalDevices(g_hVulkanInstance, &deviceCount, physicalDevices.data()) );
1197
1198 g_hPhysicalDevice = physicalDevices[0];
1199
1200 // Query for features
1201
1202 VkPhysicalDeviceProperties physicalDeviceProperties = {};
1203 vkGetPhysicalDeviceProperties(g_hPhysicalDevice, &physicalDeviceProperties);
1204
1205 //VkPhysicalDeviceFeatures physicalDeviceFreatures = {};
1206 //vkGetPhysicalDeviceFeatures(g_PhysicalDevice, &physicalDeviceFreatures);
1207
1208 // Find queue family index
1209
1210 uint32_t queueFamilyCount = 0;
1211 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, nullptr);
1212 assert(queueFamilyCount > 0);
1213 std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
1214 vkGetPhysicalDeviceQueueFamilyProperties(g_hPhysicalDevice, &queueFamilyCount, queueFamilies.data());
1215 for(uint32_t i = 0;
1216 (i < queueFamilyCount) &&
1217 (g_GraphicsQueueFamilyIndex == UINT_MAX || g_PresentQueueFamilyIndex == UINT_MAX);
1218 ++i)
1219 {
1220 if(queueFamilies[i].queueCount > 0)
1221 {
1222 if((g_GraphicsQueueFamilyIndex != 0) &&
1223 ((queueFamilies[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0))
1224 {
1225 g_GraphicsQueueFamilyIndex = i;
1226 }
1227
1228 VkBool32 surfaceSupported = 0;
1229 VkResult res = vkGetPhysicalDeviceSurfaceSupportKHR(g_hPhysicalDevice, i, g_hSurface, &surfaceSupported);
1230 if((res >= 0) && (surfaceSupported == VK_TRUE))
1231 {
1232 g_PresentQueueFamilyIndex = i;
1233 }
1234 }
1235 }
1236 assert(g_GraphicsQueueFamilyIndex != UINT_MAX);
1237
1238 // Create logical device
1239
1240 const float queuePriority = 1.f;
1241
1242 VkDeviceQueueCreateInfo deviceQueueCreateInfo[2] = { VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
1243 deviceQueueCreateInfo[0].queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1244 deviceQueueCreateInfo[0].queueCount = 1;
1245 deviceQueueCreateInfo[0].pQueuePriorities = &queuePriority;
1246 deviceQueueCreateInfo[1].sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
1247 deviceQueueCreateInfo[1].queueFamilyIndex = g_PresentQueueFamilyIndex;
1248 deviceQueueCreateInfo[1].queueCount = 1;
1249 deviceQueueCreateInfo[1].pQueuePriorities = &queuePriority;
1250
1251 VkPhysicalDeviceFeatures deviceFeatures = {};
1252 deviceFeatures.fillModeNonSolid = VK_TRUE;
1253 deviceFeatures.samplerAnisotropy = VK_TRUE;
1254
1255 std::vector<const char*> enabledDeviceExtensions;
1256 enabledDeviceExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
1257
1258 VkDeviceCreateInfo deviceCreateInfo = { VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
1259 deviceCreateInfo.enabledLayerCount = 0;
1260 deviceCreateInfo.ppEnabledLayerNames = nullptr;
1261 deviceCreateInfo.enabledExtensionCount = (uint32_t)enabledDeviceExtensions.size();
1262 deviceCreateInfo.ppEnabledExtensionNames = enabledDeviceExtensions.data();
1263 deviceCreateInfo.queueCreateInfoCount = g_PresentQueueFamilyIndex != g_GraphicsQueueFamilyIndex ? 2 : 1;
1264 deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfo;
1265 deviceCreateInfo.pEnabledFeatures = &deviceFeatures;
1266
1267 ERR_GUARD_VULKAN( vkCreateDevice(g_hPhysicalDevice, &deviceCreateInfo, nullptr, &g_hDevice) );
1268
1269 // Create memory allocator
1270
1271 VmaAllocatorCreateInfo allocatorInfo = {};
1272 allocatorInfo.physicalDevice = g_hPhysicalDevice;
1273 allocatorInfo.device = g_hDevice;
1274 ERR_GUARD_VULKAN( vmaCreateAllocator(&allocatorInfo, &g_hAllocator) );
1275
1276 // Retrieve queue (doesn't need to be destroyed)
1277
1278 vkGetDeviceQueue(g_hDevice, g_GraphicsQueueFamilyIndex, 0, &g_hGraphicsQueue);
1279 vkGetDeviceQueue(g_hDevice, g_PresentQueueFamilyIndex, 0, &g_hPresentQueue);
1280 assert(g_hGraphicsQueue);
1281 assert(g_hPresentQueue);
1282
1283 // Create command pool
1284
1285 VkCommandPoolCreateInfo commandPoolInfo = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO };
1286 commandPoolInfo.queueFamilyIndex = g_GraphicsQueueFamilyIndex;
1287 commandPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1288 ERR_GUARD_VULKAN( vkCreateCommandPool(g_hDevice, &commandPoolInfo, nullptr, &g_hCommandPool) );
1289
1290 VkCommandBufferAllocateInfo commandBufferInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
1291 commandBufferInfo.commandPool = g_hCommandPool;
1292 commandBufferInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1293 commandBufferInfo.commandBufferCount = COMMAND_BUFFER_COUNT;
1294 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, g_MainCommandBuffers) );
1295
1296 VkFenceCreateInfo fenceInfo = { VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
1297 fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1298 for(size_t i = 0; i < COMMAND_BUFFER_COUNT; ++i)
1299 {
1300 ERR_GUARD_VULKAN( vkCreateFence(g_hDevice, &fenceInfo, nullptr, &g_MainCommandBufferExecutedFances[i]) );
1301 }
1302
1303 commandBufferInfo.commandBufferCount = 1;
1304 ERR_GUARD_VULKAN( vkAllocateCommandBuffers(g_hDevice, &commandBufferInfo, &g_hTemporaryCommandBuffer) );
1305
1306 // Create texture sampler
1307
1308 VkSamplerCreateInfo samplerInfo = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO };
1309 samplerInfo.magFilter = VK_FILTER_LINEAR;
1310 samplerInfo.minFilter = VK_FILTER_LINEAR;
1311 samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1312 samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1313 samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1314 samplerInfo.anisotropyEnable = VK_TRUE;
1315 samplerInfo.maxAnisotropy = 16;
1316 samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK;
1317 samplerInfo.unnormalizedCoordinates = VK_FALSE;
1318 samplerInfo.compareEnable = VK_FALSE;
1319 samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
1320 samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1321 samplerInfo.mipLodBias = 0.f;
1322 samplerInfo.minLod = 0.f;
1323 samplerInfo.maxLod = FLT_MAX;
1324 ERR_GUARD_VULKAN( vkCreateSampler(g_hDevice, &samplerInfo, nullptr, &g_hSampler) );
1325
1326 CreateTexture(128, 128);
1327 CreateMesh();
1328
1329 VkDescriptorSetLayoutBinding samplerLayoutBinding = {};
1330 samplerLayoutBinding.binding = 1;
1331 samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1332 samplerLayoutBinding.descriptorCount = 1;
1333 samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1334
1335 VkDescriptorSetLayoutCreateInfo descriptorSetLayoutInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO };
1336 descriptorSetLayoutInfo.bindingCount = 1;
1337 descriptorSetLayoutInfo.pBindings = &samplerLayoutBinding;
1338 ERR_GUARD_VULKAN( vkCreateDescriptorSetLayout(g_hDevice, &descriptorSetLayoutInfo, nullptr, &g_hDescriptorSetLayout) );
1339
1340 // Create descriptor pool
1341
1342 VkDescriptorPoolSize descriptorPoolSizes[2];
1343 ZeroMemory(descriptorPoolSizes, sizeof(descriptorPoolSizes));
1344 descriptorPoolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
1345 descriptorPoolSizes[0].descriptorCount = 1;
1346 descriptorPoolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1347 descriptorPoolSizes[1].descriptorCount = 1;
1348
1349 VkDescriptorPoolCreateInfo descriptorPoolInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO };
1350 descriptorPoolInfo.poolSizeCount = (uint32_t)_countof(descriptorPoolSizes);
1351 descriptorPoolInfo.pPoolSizes = descriptorPoolSizes;
1352 descriptorPoolInfo.maxSets = 1;
1353 ERR_GUARD_VULKAN( vkCreateDescriptorPool(g_hDevice, &descriptorPoolInfo, nullptr, &g_hDescriptorPool) );
1354
1355 // Create descriptor set layout
1356
1357 VkDescriptorSetLayout descriptorSetLayouts[] = { g_hDescriptorSetLayout };
1358 VkDescriptorSetAllocateInfo descriptorSetInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO };
1359 descriptorSetInfo.descriptorPool = g_hDescriptorPool;
1360 descriptorSetInfo.descriptorSetCount = 1;
1361 descriptorSetInfo.pSetLayouts = descriptorSetLayouts;
1362 ERR_GUARD_VULKAN( vkAllocateDescriptorSets(g_hDevice, &descriptorSetInfo, &g_hDescriptorSet) );
1363
1364 VkDescriptorImageInfo descriptorImageInfo = {};
1365 descriptorImageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1366 descriptorImageInfo.imageView = g_hTextureImageView;
1367 descriptorImageInfo.sampler = g_hSampler;
1368
1369 VkWriteDescriptorSet writeDescriptorSet = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET };
1370 writeDescriptorSet.dstSet = g_hDescriptorSet;
1371 writeDescriptorSet.dstBinding = 1;
1372 writeDescriptorSet.dstArrayElement = 0;
1373 writeDescriptorSet.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1374 writeDescriptorSet.descriptorCount = 1;
1375 writeDescriptorSet.pImageInfo = &descriptorImageInfo;
1376
1377 vkUpdateDescriptorSets(g_hDevice, 1, &writeDescriptorSet, 0, nullptr);
1378
1379 CreateSwapchain();
1380}
1381
1382static void FinalizeApplication()
1383{
1384 vkDeviceWaitIdle(g_hDevice);
1385
1386 DestroySwapchain(true);
1387
1388 if(g_hDescriptorPool != VK_NULL_HANDLE)
1389 {
1390 vkDestroyDescriptorPool(g_hDevice, g_hDescriptorPool, nullptr);
1391 g_hDescriptorPool = VK_NULL_HANDLE;
1392 }
1393
1394 if(g_hDescriptorSetLayout != VK_NULL_HANDLE)
1395 {
1396 vkDestroyDescriptorSetLayout(g_hDevice, g_hDescriptorSetLayout, nullptr);
1397 g_hDescriptorSetLayout = VK_NULL_HANDLE;
1398 }
1399
1400 if(g_hTextureImageView != VK_NULL_HANDLE)
1401 {
1402 vkDestroyImageView(g_hDevice, g_hTextureImageView, nullptr);
1403 g_hTextureImageView = VK_NULL_HANDLE;
1404 }
1405 if(g_hTextureImage != VK_NULL_HANDLE)
1406 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001407 vmaDestroyImage(g_hAllocator, g_hTextureImage, g_hTextureImageAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001408 g_hTextureImage = VK_NULL_HANDLE;
1409 }
1410
1411 if(g_hIndexBuffer != VK_NULL_HANDLE)
1412 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001413 vmaDestroyBuffer(g_hAllocator, g_hIndexBuffer, g_hIndexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001414 g_hIndexBuffer = VK_NULL_HANDLE;
1415 }
1416 if(g_hVertexBuffer != VK_NULL_HANDLE)
1417 {
Adam Sawicki819860e2017-07-04 14:30:38 +02001418 vmaDestroyBuffer(g_hAllocator, g_hVertexBuffer, g_hVertexBufferAlloc);
Adam Sawickie6e498f2017-06-16 17:21:31 +02001419 g_hVertexBuffer = VK_NULL_HANDLE;
1420 }
1421
1422 if(g_hSampler != VK_NULL_HANDLE)
1423 {
1424 vkDestroySampler(g_hDevice, g_hSampler, nullptr);
1425 g_hSampler = VK_NULL_HANDLE;
1426 }
1427
1428 for(size_t i = COMMAND_BUFFER_COUNT; i--; )
1429 {
1430 if(g_MainCommandBufferExecutedFances[i] != VK_NULL_HANDLE)
1431 {
1432 vkDestroyFence(g_hDevice, g_MainCommandBufferExecutedFances[i], nullptr);
1433 g_MainCommandBufferExecutedFances[i] = VK_NULL_HANDLE;
1434 }
1435 }
1436 if(g_MainCommandBuffers[0] != VK_NULL_HANDLE)
1437 {
1438 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, COMMAND_BUFFER_COUNT, g_MainCommandBuffers);
1439 ZeroMemory(g_MainCommandBuffers, sizeof(g_MainCommandBuffers));
1440 }
1441 if(g_hTemporaryCommandBuffer != VK_NULL_HANDLE)
1442 {
1443 vkFreeCommandBuffers(g_hDevice, g_hCommandPool, 1, &g_hTemporaryCommandBuffer);
1444 g_hTemporaryCommandBuffer = VK_NULL_HANDLE;
1445 }
1446
1447 if(g_hCommandPool != VK_NULL_HANDLE)
1448 {
1449 vkDestroyCommandPool(g_hDevice, g_hCommandPool, nullptr);
1450 g_hCommandPool = VK_NULL_HANDLE;
1451 }
1452
1453 if(g_hAllocator != VK_NULL_HANDLE)
1454 {
1455 vmaDestroyAllocator(g_hAllocator);
1456 g_hAllocator = nullptr;
1457 }
1458
1459 if(g_hDevice != VK_NULL_HANDLE)
1460 {
1461 vkDestroyDevice(g_hDevice, nullptr);
1462 g_hDevice = nullptr;
1463 }
1464
1465 if(g_pvkDestroyDebugReportCallbackEXT && g_hCallback != VK_NULL_HANDLE)
1466 {
1467 g_pvkDestroyDebugReportCallbackEXT(g_hVulkanInstance, g_hCallback, nullptr);
1468 g_hCallback = VK_NULL_HANDLE;
1469 }
1470
1471 if(g_hSurface != VK_NULL_HANDLE)
1472 {
1473 vkDestroySurfaceKHR(g_hVulkanInstance, g_hSurface, NULL);
1474 g_hSurface = VK_NULL_HANDLE;
1475 }
1476
1477 if(g_hVulkanInstance != VK_NULL_HANDLE)
1478 {
1479 vkDestroyInstance(g_hVulkanInstance, NULL);
1480 g_hVulkanInstance = VK_NULL_HANDLE;
1481 }
1482}
1483
1484static void PrintAllocatorStats()
1485{
1486#if VMA_STATS_STRING_ENABLED
1487 char* statsString = nullptr;
1488 vmaBuildStatsString(g_hAllocator, &statsString, true);
1489 printf("%s\n", statsString);
1490 vmaFreeStatsString(g_hAllocator, statsString);
1491#endif
1492}
1493
1494static void RecreateSwapChain()
1495{
1496 vkDeviceWaitIdle(g_hDevice);
1497 DestroySwapchain(false);
1498 CreateSwapchain();
1499}
1500
1501static void DrawFrame()
1502{
1503 // Begin main command buffer
1504 size_t cmdBufIndex = (g_NextCommandBufferIndex++) % COMMAND_BUFFER_COUNT;
1505 VkCommandBuffer hCommandBuffer = g_MainCommandBuffers[cmdBufIndex];
1506 VkFence hCommandBufferExecutedFence = g_MainCommandBufferExecutedFances[cmdBufIndex];
1507
1508 ERR_GUARD_VULKAN( vkWaitForFences(g_hDevice, 1, &hCommandBufferExecutedFence, VK_TRUE, UINT64_MAX) );
1509 ERR_GUARD_VULKAN( vkResetFences(g_hDevice, 1, &hCommandBufferExecutedFence) );
1510
1511 VkCommandBufferBeginInfo commandBufferBeginInfo = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO };
1512 commandBufferBeginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
1513 ERR_GUARD_VULKAN( vkBeginCommandBuffer(hCommandBuffer, &commandBufferBeginInfo) );
1514
1515 // Acquire swapchain image
1516 uint32_t imageIndex = 0;
1517 VkResult res = vkAcquireNextImageKHR(g_hDevice, g_hSwapchain, UINT64_MAX, g_hImageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
1518 if(res == VK_ERROR_OUT_OF_DATE_KHR)
1519 {
1520 RecreateSwapChain();
1521 return;
1522 }
1523 else if(res < 0)
1524 {
1525 ERR_GUARD_VULKAN(res);
1526 }
1527
1528 // Record geometry pass
1529
1530 VkClearValue clearValues[2];
1531 ZeroMemory(clearValues, sizeof(clearValues));
1532 clearValues[0].color.float32[0] = 0.25f;
1533 clearValues[0].color.float32[1] = 0.25f;
1534 clearValues[0].color.float32[2] = 0.5f;
1535 clearValues[0].color.float32[3] = 1.0f;
1536 clearValues[1].depthStencil.depth = 1.0f;
1537
1538 VkRenderPassBeginInfo renderPassBeginInfo = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO };
1539 renderPassBeginInfo.renderPass = g_hRenderPass;
1540 renderPassBeginInfo.framebuffer = g_Framebuffers[imageIndex];
1541 renderPassBeginInfo.renderArea.offset.x = 0;
1542 renderPassBeginInfo.renderArea.offset.y = 0;
1543 renderPassBeginInfo.renderArea.extent = g_Extent;
1544 renderPassBeginInfo.clearValueCount = (uint32_t)_countof(clearValues);
1545 renderPassBeginInfo.pClearValues = clearValues;
1546 vkCmdBeginRenderPass(hCommandBuffer, &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE);
1547
1548 vkCmdBindPipeline(
1549 hCommandBuffer,
1550 VK_PIPELINE_BIND_POINT_GRAPHICS,
1551 g_hPipeline);
1552
1553 mathfu::mat4 view = mathfu::mat4::LookAt(
1554 mathfu::kZeros3f,
1555 mathfu::vec3(0.f, -2.f, 4.f),
1556 mathfu::kAxisY3f);
1557 mathfu::mat4 proj = mathfu::mat4::Perspective(
1558 1.0471975511966f, // 60 degrees
1559 (float)g_Extent.width / (float)g_Extent.height,
1560 0.1f,
1561 1000.f,
1562 -1.f);
1563 //proj[1][1] *= -1.f;
1564 mathfu::mat4 viewProj = proj * view;
1565
1566 vkCmdBindDescriptorSets(
1567 hCommandBuffer,
1568 VK_PIPELINE_BIND_POINT_GRAPHICS,
1569 g_hPipelineLayout,
1570 0,
1571 1,
1572 &g_hDescriptorSet,
1573 0,
1574 nullptr);
1575
1576 float rotationAngle = (float)GetTickCount() * 0.001f * (float)M_PI * 0.2f;
1577 mathfu::mat3 model_3 = mathfu::mat3::RotationY(rotationAngle);
1578 mathfu::mat4 model_4 = mathfu::mat4(
1579 model_3(0, 0), model_3(0, 1), model_3(0, 2), 0.f,
1580 model_3(1, 0), model_3(1, 1), model_3(1, 2), 0.f,
1581 model_3(2, 0), model_3(2, 1), model_3(2, 2), 0.f,
1582 0.f, 0.f, 0.f, 1.f);
1583 mathfu::mat4 modelViewProj = viewProj * model_4;
1584
1585 UniformBufferObject ubo = {};
1586 modelViewProj.Pack(ubo.ModelViewProj);
1587 vkCmdPushConstants(hCommandBuffer, g_hPipelineLayout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(UniformBufferObject), &ubo);
1588
1589 VkBuffer vertexBuffers[] = { g_hVertexBuffer };
1590 VkDeviceSize offsets[] = { 0 };
1591 vkCmdBindVertexBuffers(hCommandBuffer, 0, 1, vertexBuffers, offsets);
1592
1593 vkCmdBindIndexBuffer(hCommandBuffer, g_hIndexBuffer, 0, VK_INDEX_TYPE_UINT16);
1594
1595 vkCmdDrawIndexed(hCommandBuffer, g_IndexCount, 1, 0, 0, 0);
1596
1597 vkCmdEndRenderPass(hCommandBuffer);
1598
1599 vkEndCommandBuffer(hCommandBuffer);
1600
1601 // Submit command buffer
1602
1603 VkSemaphore submitWaitSemaphores[] = { g_hImageAvailableSemaphore };
1604 VkPipelineStageFlags submitWaitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
1605 VkSemaphore submitSignalSemaphores[] = { g_hRenderFinishedSemaphore };
1606 VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO };
1607 submitInfo.waitSemaphoreCount = 1;
1608 submitInfo.pWaitSemaphores = submitWaitSemaphores;
1609 submitInfo.pWaitDstStageMask = submitWaitStages;
1610 submitInfo.commandBufferCount = 1;
1611 submitInfo.pCommandBuffers = &hCommandBuffer;
1612 submitInfo.signalSemaphoreCount = _countof(submitSignalSemaphores);
1613 submitInfo.pSignalSemaphores = submitSignalSemaphores;
1614 ERR_GUARD_VULKAN( vkQueueSubmit(g_hGraphicsQueue, 1, &submitInfo, hCommandBufferExecutedFence) );
1615
1616 VkSemaphore presentWaitSemaphores[] = { g_hRenderFinishedSemaphore };
1617
1618 VkSwapchainKHR swapchains[] = { g_hSwapchain };
1619 VkPresentInfoKHR presentInfo = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR };
1620 presentInfo.waitSemaphoreCount = _countof(presentWaitSemaphores);
1621 presentInfo.pWaitSemaphores = presentWaitSemaphores;
1622 presentInfo.swapchainCount = 1;
1623 presentInfo.pSwapchains = swapchains;
1624 presentInfo.pImageIndices = &imageIndex;
1625 presentInfo.pResults = nullptr;
1626 res = vkQueuePresentKHR(g_hPresentQueue, &presentInfo);
1627 if(res == VK_ERROR_OUT_OF_DATE_KHR)
1628 {
1629 RecreateSwapChain();
1630 }
1631 else
1632 ERR_GUARD_VULKAN(res);
1633}
1634
1635static void HandlePossibleSizeChange()
1636{
1637 RECT clientRect;
1638 GetClientRect(g_hWnd, &clientRect);
1639 LONG newSizeX = clientRect.right - clientRect.left;
1640 LONG newSizeY = clientRect.bottom - clientRect.top;
1641 if((newSizeX > 0) &&
1642 (newSizeY > 0) &&
1643 ((newSizeX != g_SizeX) || (newSizeY != g_SizeY)))
1644 {
1645 g_SizeX = newSizeX;
1646 g_SizeY = newSizeY;
1647
1648 RecreateSwapChain();
1649 }
1650}
1651
1652static LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
1653{
1654 switch(msg)
1655 {
1656 case WM_CREATE:
1657 // This is intentionally assigned here because we are now inside CreateWindow, before it returns.
1658 g_hWnd = hWnd;
1659 InitializeApplication();
1660 PrintAllocatorStats();
1661 return 0;
1662
1663 case WM_DESTROY:
1664 FinalizeApplication();
1665 PostQuitMessage(0);
1666 return 0;
1667
1668 // This prevents app from freezing when left Alt is pressed
1669 // (which normally enters modal menu loop).
1670 case WM_SYSKEYDOWN:
1671 case WM_SYSKEYUP:
1672 return 0;
1673
1674 case WM_SIZE:
1675 if((wParam == SIZE_MAXIMIZED) || (wParam == SIZE_RESTORED))
1676 HandlePossibleSizeChange();
1677 return 0;
1678
1679 case WM_EXITSIZEMOVE:
1680 HandlePossibleSizeChange();
1681 return 0;
1682
1683 case WM_KEYDOWN:
1684 if(wParam == VK_ESCAPE)
1685 PostMessage(hWnd, WM_CLOSE, 0, 0);
1686 return 0;
1687
1688 default:
1689 break;
1690 }
1691
1692 return DefWindowProc(hWnd, msg, wParam, lParam);
1693}
1694
1695int main()
1696{
1697 g_hAppInstance = (HINSTANCE)GetModuleHandle(NULL);
1698
1699 WNDCLASSEX wndClassDesc = { sizeof(WNDCLASSEX) };
1700 wndClassDesc.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS;
1701 wndClassDesc.hbrBackground = NULL;
1702 wndClassDesc.hCursor = LoadCursor(NULL, IDC_CROSS);
1703 wndClassDesc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
1704 wndClassDesc.hInstance = g_hAppInstance;
1705 wndClassDesc.lpfnWndProc = WndProc;
1706 wndClassDesc.lpszClassName = WINDOW_CLASS_NAME;
1707
1708 const ATOM hWndClass = RegisterClassEx(&wndClassDesc);
1709 assert(hWndClass);
1710
1711 const DWORD style = WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_THICKFRAME;
1712 const DWORD exStyle = 0;
1713
1714 RECT rect = { 0, 0, g_SizeX, g_SizeY };
1715 AdjustWindowRectEx(&rect, style, FALSE, exStyle);
1716
1717 HWND hWnd = CreateWindowEx(
1718 exStyle, WINDOW_CLASS_NAME, APP_TITLE_W, style,
1719 CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
1720 NULL, NULL, g_hAppInstance, NULL);
1721
1722 MSG msg;
1723 for(;;)
1724 {
1725 if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1726 {
1727 if(msg.message == WM_QUIT)
1728 break;
1729 TranslateMessage(&msg);
1730 DispatchMessage(&msg);
1731 }
1732 if(g_hDevice != VK_NULL_HANDLE)
1733 DrawFrame();
1734 }
1735
1736 return 0;
1737}