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