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