rewriting swapchain/image/allocation parts
[demo] / src / vulkan / vkutil.cc
1 #include <gmath/gmath.h>
2 #include <vulkan/vulkan.h>
3 #include <stdio.h>
4 #include <stdint.h>
5 #include <stdlib.h>
6 #include <string.h>
7 #include <string>
8 #include <vector>
9
10 #include "vkutil.h"
11
12 /* global variables */
13 VkPhysicalDevice vk_physical;
14 VkDevice vk_device;
15 VkCommandPool vk_pool;
16 VkQueue vk_queue;
17 VkSurfaceKHR vk_surface;
18 VkSwapchainKHR vk_swapchain;
19
20 VkPipeline *vkgparent_pipeline;
21 VkFramebuffer *vkfbufs;
22 VkRenderPass vkrpass;
23 VkInstance vkinst;
24 VkCommandBuffer vkcmdbuf;       /* primary command buffer */
25 int vkqfamily;
26
27 VkSemaphore vk_img_avail_sema;
28 VkSemaphore vk_rend_done_sema;
29 VkImage *vkswapchain_images;
30 VkImageView *vkswapchain_views;
31 int vknum_swapchain_images;
32 int vk_curr_swapchain_image;
33
34 /* static functions */
35 static const char *get_device_name_str(VkPhysicalDeviceType type);
36 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags);
37 static const char *get_queue_flags_str(VkQueueFlags flags);
38 static const char *get_mem_size_str(long sz);
39 static int ver_major(uint32_t ver);
40 static int ver_minor(uint32_t ver);
41 static int ver_patch(uint32_t ver);
42
43 /* static variables */
44 static VkPhysicalDevice *phys_devices;
45
46 static int sel_dev;
47 static int sel_qfamily;
48
49 static VkExtensionProperties *vkext, *vkdevext;
50 static uint32_t vkext_count, vkdevext_count;
51
52 bool vku_have_extension(const char *name)
53 {
54         if(!vkext) {
55                 vkext_count = 0;
56                 vkEnumerateInstanceExtensionProperties(0, &vkext_count, 0);
57                 if(vkext_count) {
58                         vkext = new VkExtensionProperties[vkext_count];
59                         vkEnumerateInstanceExtensionProperties(0, &vkext_count, vkext);
60
61                         printf("instance extensions:\n");
62                         for(int i=0; i<(int)vkext_count; i++) {
63                                 printf(" %s (ver: %u)\n", vkext[i].extensionName, (unsigned int)vkext[i].specVersion);
64                         }
65                 }
66         }
67
68         for(int i=0; i<(int)vkext_count; i++) {
69                 if(strcmp(vkext[i].extensionName, name) == 0) {
70                         return true;
71                 }
72         }
73         return false;
74 }
75
76 bool vku_have_device_extension(const char *name)
77 {
78         if(sel_dev < 0) return false;
79
80         if(!vkdevext) {
81                 vkdevext_count = 0;
82                 vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, 0);
83                 if(vkdevext_count) {
84                         vkdevext = new VkExtensionProperties[vkdevext_count];
85                         vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, vkdevext);
86
87                         printf("selected device extensions:\n");
88                         for(int i=0; i<(int)vkdevext_count; i++) {
89                                 printf(" %s (ver: %u)\n", vkdevext[i].extensionName, (unsigned int)vkdevext[i].specVersion);
90                         }
91                 }
92         }
93
94         for(int i=0; i<(int)vkdevext_count; i++) {
95                 if(strcmp(vkdevext[i].extensionName, name) == 0) {
96                         return true;
97                 }
98         }
99         return false;
100 }
101
102 bool vku_create_device()
103 {
104         VkInstanceCreateInfo inst_info;
105         VkDeviceCreateInfo dev_info;
106         VkDeviceQueueCreateInfo queue_info;
107         VkCommandPoolCreateInfo cmdpool_info;
108         uint32_t num_devices;
109         float qprio = 0.0f;
110
111         static const char *ext_names[] = {
112                 "VK_KHR_xcb_surface",
113                 "VK_KHR_surface"
114         };
115
116         static const char *devext_names[] = {
117                 "VK_KHR_swapchain"
118         };
119
120         sel_dev = -1;
121         sel_qfamily = -1;
122
123         for(unsigned int i=0; i<sizeof ext_names / sizeof *ext_names; i++) {
124                 if(!vku_have_extension(ext_names[i])) {
125                         fprintf(stderr, "required extension (%s) not found\n", ext_names[i]);
126                         return false;
127                 }
128         }
129         memset(&inst_info, 0, sizeof inst_info);
130         inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
131         inst_info.ppEnabledExtensionNames = ext_names;
132         inst_info.enabledExtensionCount = sizeof ext_names / sizeof *ext_names;
133
134         if(vkCreateInstance(&inst_info, 0, &vkinst) != 0) {
135                 fprintf(stderr, "failed to create vulkan instance\n");
136                 return false;
137         }
138         printf("created vulkan instance\n");
139         if(vkEnumeratePhysicalDevices(vkinst, &num_devices, 0) != 0) {
140                 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
141                 return false;
142         }
143         phys_devices = new VkPhysicalDevice[num_devices];
144         if(vkEnumeratePhysicalDevices(vkinst, &num_devices, phys_devices) != 0) {
145                 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
146                 return false;
147         }
148         printf("found %u physical device(s)\n", (unsigned int)num_devices);
149
150         for(int i=0; i<(int)num_devices; i++) {
151                 VkPhysicalDeviceProperties dev_prop;
152                 VkPhysicalDeviceMemoryProperties mem_prop;
153                 VkQueueFamilyProperties *qprop;
154                 uint32_t qprop_count;
155
156                 vkGetPhysicalDeviceProperties(phys_devices[i], &dev_prop);
157
158                 printf("Device %d: %s\n", i, dev_prop.deviceName);
159                 printf("  type: %s\n", get_device_name_str(dev_prop.deviceType));
160                 printf("  API version: %d.%d.%d\n", ver_major(dev_prop.apiVersion), ver_minor(dev_prop.apiVersion),
161                        ver_patch(dev_prop.apiVersion));
162                 printf("  driver version: %d.%d.%d\n", ver_major(dev_prop.driverVersion), ver_minor(dev_prop.driverVersion),
163                        ver_patch(dev_prop.driverVersion));
164                 printf("  vendor id: %x  device id: %x\n", dev_prop.vendorID, dev_prop.deviceID);
165
166
167                 vkGetPhysicalDeviceMemoryProperties(phys_devices[i], &mem_prop);
168                 printf("  %d memory heaps:\n", mem_prop.memoryHeapCount);
169                 for(unsigned int j=0; j<mem_prop.memoryHeapCount; j++) {
170                         VkMemoryHeap heap = mem_prop.memoryHeaps[j];
171                         printf("    Heap %d - size: %s, flags: %s\n", j, get_mem_size_str(heap.size),
172                                heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT ? "device-local" : "-");
173                 }
174                 printf("  %d memory types:\n", mem_prop.memoryTypeCount);
175                 for(unsigned int j=0; j<mem_prop.memoryTypeCount; j++) {
176                         VkMemoryType type = mem_prop.memoryTypes[j];
177                         printf("    Type %d - heap: %d, flags: %s\n", j, type.heapIndex,
178                                get_memtype_flags_str(type.propertyFlags));
179                 }
180
181                 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, 0);
182                 if(qprop_count <= 0) {
183                         continue;
184                 }
185                 qprop = new VkQueueFamilyProperties[qprop_count];
186                 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, qprop);
187
188                 for(unsigned int j=0; j<qprop_count; j++) {
189                         printf("  Queue family %d:\n", j);
190                         printf("    flags: %s\n", get_queue_flags_str(qprop[j].queueFlags));
191                         printf("    num queues: %u\n", qprop[j].queueCount);
192
193                         if(qprop[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
194                                 sel_dev = i;
195                                 sel_qfamily = j;
196                         }
197                 }
198                 delete [] qprop;
199         }
200
201         if(sel_dev < 0 || sel_qfamily < 0) {
202                 fprintf(stderr, "failed to find any device with a graphics-capable command queue\n");
203                 vkDestroyDevice(vk_device, 0);
204                 return false;
205         }
206
207         for(unsigned int i=0; i<sizeof devext_names / sizeof *devext_names; i++) {
208                 if(!vku_have_device_extension(devext_names[i])) {
209                         fprintf(stderr, "required extension (%s) not found on the selected device (%d)\n",
210                                 ext_names[i], sel_dev);
211                         return false;
212                 }
213         }
214
215         /* create device & command queue */
216         memset(&queue_info, 0, sizeof queue_info);
217         queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
218         queue_info.queueFamilyIndex = sel_qfamily;
219         queue_info.queueCount = 1;
220         queue_info.pQueuePriorities = &qprio;
221
222         memset(&dev_info, 0, sizeof dev_info);
223         dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
224         dev_info.queueCreateInfoCount = 1;
225         dev_info.pQueueCreateInfos = &queue_info;
226         dev_info.enabledExtensionCount = sizeof devext_names / sizeof *devext_names;
227         dev_info.ppEnabledExtensionNames = devext_names;
228
229         if(vkCreateDevice(phys_devices[sel_dev], &dev_info, 0, &vk_device) != 0) {
230                 fprintf(stderr, "failed to create device %d\n", sel_dev);
231                 return false;
232         }
233         printf("created device %d\n", sel_dev);
234
235         vk_physical = phys_devices[sel_dev];
236         vkqfamily = sel_qfamily;
237
238         vkGetDeviceQueue(vk_device, sel_qfamily, 0, &vk_queue);
239
240         /* create command buffer pool */
241         memset(&cmdpool_info, 0, sizeof cmdpool_info);
242         cmdpool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
243         cmdpool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
244         cmdpool_info.queueFamilyIndex = sel_qfamily;
245
246         if(vkCreateCommandPool(vk_device, &cmdpool_info, 0, &vk_pool) != 0) {
247                 fprintf(stderr, "failed to get command queue!\n");
248                 return false;
249         }
250
251 /*      if(!(vkcmdbuf = vku_alloc_cmdbuf(vk_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY))) {
252                 fprintf(stderr, "failed to create primary command buffer\n");
253                 return false;
254         } */
255
256         return true;
257 }
258
259 void vku_cleanup()
260 {
261         if(vkinst) {
262                 vkDeviceWaitIdle(vk_device);
263                 vkDestroyCommandPool(vk_device, vk_pool, 0);
264
265                 vkDestroySemaphore(vk_device, vk_img_avail_sema, 0);
266                 vkDestroySemaphore(vk_device, vk_rend_done_sema, 0);
267
268                 vkDestroyDevice(vk_device, 0);
269                 vkDestroyInstance(vkinst, 0);
270                 vkinst = 0;
271         }
272
273         delete [] phys_devices;
274         phys_devices = 0;
275 }
276
277 bool vku_create_semaphores()
278 {
279         VkSemaphoreCreateInfo sinf;
280         memset(&sinf, 0, sizeof sinf);
281
282         sinf.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
283         if(vkCreateSemaphore(vk_device, &sinf, 0, &vk_img_avail_sema) != VK_SUCCESS) {
284                 fprintf(stderr, "Failed to create semaphore\n");
285                 return false;
286         }
287
288         if(vkCreateSemaphore(vk_device, &sinf, 0, &vk_rend_done_sema) != VK_SUCCESS) {
289                 fprintf(stderr, "Failed to create semaphore\n");
290                 return false;
291         }
292
293         return true;
294 }
295
296 VkCommandBuffer vku_alloc_cmdbuf(VkCommandPool pool, VkCommandBufferLevel level)
297 {
298         VkCommandBuffer cmdbuf;
299         VkCommandBufferAllocateInfo inf;
300
301         memset(&inf, 0, sizeof inf);
302         inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
303         inf.commandPool = pool;
304         inf.level = level;
305         inf.commandBufferCount = 1;
306
307         if(vkAllocateCommandBuffers(vk_device, &inf, &cmdbuf) != 0) {
308                 return 0;
309         }
310         return cmdbuf;
311 }
312
313 void vku_free_cmdbuf(VkCommandPool pool, VkCommandBuffer buf)
314 {
315         vkFreeCommandBuffers(vk_device, pool, 1, &buf);
316 }
317
318 void vku_begin_cmdbuf(VkCommandBuffer buf, unsigned int flags)
319 {
320         VkCommandBufferBeginInfo inf;
321
322         memset(&inf, 0, sizeof inf);
323         inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
324         inf.flags = flags;
325
326         vkBeginCommandBuffer(buf, &inf);
327 }
328
329
330 void vku_end_cmdbuf(VkCommandBuffer buf)
331 {
332         vkEndCommandBuffer(buf);
333 }
334
335 void vku_reset_cmdbuf(VkCommandBuffer buf)
336 {
337         vkResetCommandBuffer(buf, 0);
338 }
339
340 void vku_submit_cmdbuf(VkQueue q, VkCommandBuffer buf, VkFence done_fence)
341 {
342         VkSubmitInfo info;
343
344         memset(&info, 0, sizeof info);
345         info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
346         info.commandBufferCount = 1;
347         info.pCommandBuffers = &buf;
348
349         vkQueueSubmit(q, 1, &info, done_fence);
350 }
351
352 VkSwapchainKHR vku_create_swapchain(VkSurfaceKHR surf, int xsz, int ysz, int n,
353                                     VkPresentModeKHR pmode, VkSwapchainKHR prev)
354 {
355         VkSurfaceCapabilitiesKHR scap;
356         vkGetPhysicalDeviceSurfaceCapabilitiesKHR(vk_physical, surf, &scap);
357
358         VkPhysicalDeviceMemoryProperties mprops;
359         vkGetPhysicalDeviceMemoryProperties(vk_physical, &mprops);
360
361         uint32_t pmcnt;
362         vkGetPhysicalDeviceSurfacePresentModesKHR(vk_physical, surf, &pmcnt, 0);
363         VkPresentModeKHR scpm = VK_PRESENT_MODE_IMMEDIATE_KHR;
364         VkExtent2D scext;
365         scext.width = xsz;
366         scext.height = ysz;
367
368 //      VkSurfaceTransformFlagBitsKHR pretransf;
369 //      if(scap.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR) {
370 //              pretransf = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
371 //      } else {
372 //              pretransf = scap.currentTransform;
373 //      }
374
375         VkSwapchainKHR sc;
376         VkSwapchainCreateInfoKHR inf;
377
378         VkSurfaceFormatKHR sformat;
379         sformat.format = VK_FORMAT_B8G8R8A8_UNORM;
380
381         memset(&inf, 0, sizeof inf);
382         inf.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
383         inf.surface = surf;
384         inf.minImageCount = n;
385         inf.imageFormat = sformat.format;       /* TODO enumerate and choose */
386         inf.imageColorSpace = sformat.colorSpace;
387         inf.imageExtent = scext;
388         inf.imageArrayLayers = 1;
389         inf.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
390         inf.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;       /* XXX make this an option? */
391         inf.preTransform = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
392         inf.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
393         inf.presentMode = pmode;
394         inf.oldSwapchain = VK_NULL_HANDLE;
395         inf.clipped = VK_TRUE;
396
397         if(vkCreateSwapchainKHR(vk_device, &inf, 0, &sc) != 0) {
398                 return 0;
399         }
400         return sc;
401 }
402
403 VkImage *vku_get_swapchain_images(VkSwapchainKHR sc, int *count)
404 {
405         uint32_t nimg;
406         VkImage *images;
407
408         if(vkGetSwapchainImagesKHR(vk_device, sc, &nimg, 0) != 0) {
409                 return 0;
410         }
411         images = new VkImage[nimg];
412         vkGetSwapchainImagesKHR(vk_device, sc, &nimg, images);
413
414         if(count) *count = (int)nimg;
415         return images;
416 }
417
418 VkImageView *vku_create_image_views(VkImage *images, int count)
419 {
420         VkImageView *iviews;
421
422         iviews = new VkImageView[count];
423         for(int i=0; i<count; i++) {
424                 VkImageViewCreateInfo inf;
425                 memset(&inf, 0, sizeof inf);
426
427                 inf.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
428                 inf.image = images[i];
429                 inf.viewType = VK_IMAGE_VIEW_TYPE_2D;
430                 inf.format = VK_FORMAT_B8G8R8A8_UNORM; //TODO
431                 inf.components.r = inf.components.g = inf.components.b =
432                         inf.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
433                 inf.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
434                 inf.subresourceRange.levelCount = 1;
435                 inf.subresourceRange.layerCount = 1;
436
437                 if(vkCreateImageView(vk_device, &inf, 0, iviews) != 0) {
438                         fprintf(stderr, "Failed to create image views.\n");
439                         delete iviews;
440                         return 0;
441                 }
442         }
443
444         return iviews;
445 }
446
447 int vku_get_next_image(VkSwapchainKHR sc)
448 {
449         uint32_t next;
450
451         if(vkAcquireNextImageKHR(vk_device, sc, UINT64_MAX, 0, 0, &next) != 0) {
452                 return -1;
453         }
454         return (int)next;
455 }
456
457 void vku_present(VkSwapchainKHR sc, int img_idx)
458 {
459         VkPresentInfoKHR inf;
460         VkResult res;
461         uint32_t index = img_idx;
462
463         memset(&inf, 0, sizeof inf);
464         inf.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
465         inf.swapchainCount = 1;
466         inf.pSwapchains = &sc;
467         inf.pImageIndices = &index;
468         inf.pResults = &res;
469
470         vkQueuePresentKHR(vk_queue, &inf);
471 }
472
473 bool vku_create_renderpass()
474 {
475         VkAttachmentDescription attachments[2];
476         memset(&attachments, 0, 2 * sizeof *attachments);
477
478         /* color */
479         attachments[0].format = VK_FORMAT_B8G8R8A8_UNORM;
480         attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
481         attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
482         attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
483         attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
484         attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
485         attachments[0].initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
486         attachments[0].finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
487
488         /* depth */
489         attachments[1].format = VK_FORMAT_D32_SFLOAT_S8_UINT; //TODO
490         attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
491         attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
492         attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
493         attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
494         attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
495         attachments[1].initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
496         attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
497
498         VkAttachmentReference color_ref;
499         color_ref.attachment = 0;
500         color_ref.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
501
502         VkAttachmentReference depth_ref;
503         depth_ref.attachment = 1;
504         depth_ref.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
505
506         VkSubpassDescription subpass_desc;
507         memset(&subpass_desc, 0, sizeof subpass_desc);
508
509         subpass_desc.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
510         subpass_desc.colorAttachmentCount = 1;
511         subpass_desc.pColorAttachments = &color_ref;
512         subpass_desc.pDepthStencilAttachment = &depth_ref;
513
514         VkRenderPassCreateInfo inf;
515         memset(&inf, 0, sizeof inf);
516
517         inf.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
518         inf.attachmentCount = 2;
519         inf.pAttachments = attachments;
520         inf.subpassCount = 1;
521         inf.pSubpasses = &subpass_desc;
522
523         if(vkCreateRenderPass(vk_device, &inf, 0, &vkrpass) != VK_SUCCESS) {
524                 return false;
525         }
526
527         return true;
528 }
529
530 bool vku_create_framebuffers(VkImageView *image_views, int count, int w, int h)
531 {
532         delete vkfbufs;
533         vkfbufs = new VkFramebuffer[count];
534
535         VkFramebufferCreateInfo inf;
536         memset(&inf, 0, sizeof inf);
537
538         inf.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
539         inf.renderPass = vkrpass;
540         inf.attachmentCount = count;
541         inf.pAttachments = image_views;
542         inf.width = w;
543         inf.height = h;
544         inf.layers = 1;
545
546         for(int i=0; i<count; i++) {
547                 if(vkCreateFramebuffer(vk_device, &inf, 0, &vkfbufs[i]) != VK_SUCCESS) {
548                         fprintf(stderr, "Failed to create framebuffer for image view: %d\n", i);
549                         delete vkfbufs;
550                         return false;
551                 }
552         }
553         return true;
554 }
555
556 struct vku_buffer *vku_create_buffer(int sz, unsigned int usage)
557 {
558         struct vku_buffer *buf;
559         VkBufferCreateInfo binfo;
560
561         buf = new vku_buffer;
562
563         memset(&binfo, 0, sizeof binfo);
564         binfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
565         binfo.size = sz;
566         binfo.usage = usage;
567         binfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
568
569         if(vkCreateBuffer(vk_device, &binfo, 0, &buf->buf) != 0) {
570                 fprintf(stderr, "failed to create %d byte buffer (usage: %x)\n", sz, usage);
571                 return 0;
572         }
573         // TODO back with memory
574         return buf;
575 }
576
577 void vku_destroy_buffer(struct vku_buffer *buf)
578 {
579         if(buf) {
580                 vkDestroyBuffer(vk_device, buf->buf, 0);
581                 delete buf;
582         }
583 }
584
585 void vku_cmd_copybuf(VkCommandBuffer cmdbuf, VkBuffer dest, int doffs,
586                      VkBuffer src, int soffs, int size)
587 {
588         VkBufferCopy copy;
589         copy.size = size;
590         copy.srcOffset = soffs;
591         copy.dstOffset = doffs;
592
593         vkCmdCopyBuffer(cmdbuf, src, dest, 1, &copy);
594 }
595
596 const char *vku_get_vulkan_error_str(VkResult error)
597 {
598         std::string errmsg;
599         switch(error) {
600         case VK_SUCCESS:
601                 errmsg = std::string("VK_SUCCESS");
602                 break;
603         case VK_NOT_READY:
604                 errmsg = std::string("VK_NOT_READY");
605                 break;
606         case VK_TIMEOUT:
607                 errmsg = std::string("VK_TIMEOUT");
608                 break;
609         case VK_EVENT_SET:
610                 errmsg = std::string("VK_EVENT_SET");
611                 break;
612         case VK_EVENT_RESET:
613                 errmsg = std::string("VK_EVENT_RESET");
614                 break;
615         case VK_INCOMPLETE:
616                 errmsg = std::string("VK_EVENT");
617                 break;
618         case VK_ERROR_OUT_OF_HOST_MEMORY:
619                 errmsg = std::string("VK_ERROR_OUT_OF_HOST_MEMORY");
620                 break;
621         case VK_ERROR_OUT_OF_DEVICE_MEMORY:
622                 errmsg = std::string("VK_ERROR_OUT_OF_DEVICE_MEMORY");
623                 break;
624         case VK_ERROR_INITIALIZATION_FAILED:
625                 errmsg = std::string("VK_ERROR_INITIALIZATION_FAILED");
626                 break;
627         case VK_ERROR_DEVICE_LOST:
628                 errmsg = std::string("VK_ERROR_DEVICE_LOST");
629                 break;
630         case VK_ERROR_MEMORY_MAP_FAILED:
631                 errmsg = std::string("VK_ERROR_MEMORY_MAP_FAILED");
632                 break;
633         case VK_ERROR_LAYER_NOT_PRESENT:
634                 errmsg = std::string("VK_ERROR_LAYER_NOT_PRESENT");
635                 break;
636         case VK_ERROR_EXTENSION_NOT_PRESENT:
637                 errmsg = std::string("VK_ERROR_EXTENSION_NOT_PRESENT");
638                 break;
639         case VK_ERROR_FEATURE_NOT_PRESENT:
640                 errmsg = std::string("VK_ERROR_FEATURE_NOT_PRESENT");
641         case VK_ERROR_INCOMPATIBLE_DRIVER:
642                 errmsg = std::string("VK_ERROR_INCOMPATIBLE_DRIVER");
643                 break;
644         case VK_ERROR_TOO_MANY_OBJECTS:
645                 errmsg = std::string("VK_ERROR_TOO_MANY_OBJECTS");
646                 break;
647         case VK_ERROR_FORMAT_NOT_SUPPORTED:
648                 errmsg = std::string("VK_ERROR_FORMAT_NOT_SUPPORTED");
649                 break;
650         case VK_ERROR_FRAGMENTED_POOL:
651                 errmsg = std::string("VK_ERROR_FRAGMENTED_POOL");
652                 break;
653         default:
654                 errmsg = std::string("UNKNOWN");
655                 break;
656         }
657
658         return errmsg.c_str();
659 }
660
661 bool vku_create_graphics_pipeline(VkPipelineLayout *layout)
662 {
663         VkGraphicsPipelineCreateInfo inf;
664         memset(&inf, 0, sizeof inf);
665
666         inf.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
667         inf.layout = *layout;
668         inf.renderPass = vkrpass;
669
670         /* states */
671
672         /* how primitives are assembled */
673         VkPipelineInputAssemblyStateCreateInfo ias;
674         memset(&ias, 0, sizeof ias);
675         ias.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
676         ias.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
677
678         /* rasterisation */
679         VkPipelineRasterizationStateCreateInfo rsi;
680         memset(&rsi, 0, sizeof rsi);
681         rsi.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
682         rsi.polygonMode = VK_POLYGON_MODE_FILL;
683         rsi.cullMode = VK_CULL_MODE_BACK_BIT;
684         rsi.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
685         rsi.lineWidth = 1.0f;
686
687         /* blend factors */
688         VkPipelineColorBlendAttachmentState bas[1];
689         memset(&bas[0], 0, sizeof bas[0]);
690
691         VkPipelineColorBlendStateCreateInfo cbs;
692         memset(&cbs, 0, sizeof cbs);
693         cbs.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
694         cbs.attachmentCount = 1;
695         cbs.pAttachments = bas;
696
697         /* number of viewport and scissors in this pipeline */
698         VkPipelineViewportStateCreateInfo vs;
699         memset(&vs, 0, sizeof vs);
700         vs.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
701         vs.viewportCount = 1;
702         vs.scissorCount = 1;
703
704         /* dynamic states: that can be changed later */
705 //      std::vector<VkDynamicState> ds_enabled;
706 //      ds_enabled.push_back(VK_DYNAMIC_STATE_VIEWPORT);
707         //ds_enabled.push_back(VK_DYNAMIC_STATE_SCISSOR);
708 //      VkPipelineDynamicStateCreateInfo ds;
709 //      ds.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
710 //      ds.pDynamicStates = ds_enabled.data();
711 //      ds.dynamicStateCount = static_cast<uint32_t>(ds_enabled.size());
712
713         /* depth tests */
714         VkPipelineDepthStencilStateCreateInfo dsi;
715         memset(&dsi, 0, sizeof dsi);
716         dsi.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
717         dsi.depthTestEnable = VK_TRUE;
718         dsi.depthWriteEnable = VK_TRUE;
719         dsi.depthCompareOp = VK_COMPARE_OP_LESS_OR_EQUAL;
720         dsi.back.failOp = VK_STENCIL_OP_KEEP;
721         dsi.back.passOp = VK_STENCIL_OP_KEEP;
722         dsi.back.compareOp = VK_COMPARE_OP_ALWAYS;
723         dsi.front = dsi.back;
724
725         /* multisampling - must be set even if not used */
726         VkPipelineMultisampleStateCreateInfo msi;
727         memset(&msi, 0, sizeof msi);
728         msi.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
729         msi.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
730
731         /* vertex input descriptions */
732         VkVertexInputBindingDescription vib;
733         memset(&vib, 0, sizeof vib);
734         vib.stride = sizeof(Vec3);
735         vib.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
736
737         /* input attr bindings */
738         VkVertexInputAttributeDescription via[2];
739         memset(&via, 0, sizeof via);
740         via[0].format = VK_FORMAT_R32G32B32A32_SFLOAT;
741
742         return true;
743 }
744
745 static const char *get_device_name_str(VkPhysicalDeviceType type)
746 {
747         switch(type) {
748         case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
749                 return "integrated GPU";
750         case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
751                 return "discrete GPU";
752         case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
753                 return "virtual GPU";
754         case VK_PHYSICAL_DEVICE_TYPE_CPU:
755                 return "CPU";
756         default:
757                 break;
758         }
759         return "unknown";
760 }
761
762 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags)
763 {
764         static char str[128];
765
766         str[0] = 0;
767         if(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
768                 strcat(str, "device-local ");
769         }
770         if(flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
771                 strcat(str, "host-visible ");
772         }
773         if(flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
774                 strcat(str, "host-coherent ");
775         }
776         if(flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) {
777                 strcat(str, "host-cached ");
778         }
779         if(flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
780                 strcat(str, "lazily-allocated ");
781         }
782
783         if(!*str) {
784                 strcat(str, "-");
785         }
786         return str;
787 }
788
789 static const char *get_queue_flags_str(VkQueueFlags flags)
790 {
791         static char str[128];
792
793         str[0] = 0;
794         if(flags & VK_QUEUE_GRAPHICS_BIT) {
795                 strcat(str, "graphics ");
796         }
797         if(flags & VK_QUEUE_COMPUTE_BIT) {
798                 strcat(str, "compute ");
799         }
800         if(flags & VK_QUEUE_TRANSFER_BIT) {
801                 strcat(str, "transfer ");
802         }
803         if(flags & VK_QUEUE_SPARSE_BINDING_BIT) {
804                 strcat(str, "sparse-binding ");
805         }
806         if(!*str) {
807                 strcat(str, "-");
808         }
809         return str;
810 }
811
812 static int ver_major(uint32_t ver)
813 {
814         return (ver >> 22) & 0x3ff;
815 }
816
817 static int ver_minor(uint32_t ver)
818 {
819         return (ver >> 12) & 0x3ff;
820 }
821
822 static int ver_patch(uint32_t ver)
823 {
824         return ver & 0xfff;
825 }
826
827 static const char *get_mem_size_str(long sz)
828 {
829         static char str[64];
830         static const char *unitstr[] = { "bytes", "KB", "MB", "GB", "TB", "PB", 0 };
831         int uidx = 0;
832         sz *= 10;
833
834         while(sz >= 10240 && unitstr[uidx + 1]) {
835                 sz /= 1024;
836                 ++uidx;
837         }
838         sprintf(str, "%ld.%ld %s", sz / 10, sz % 10, unitstr[uidx]);
839         return str;
840 }