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