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