1 #include <gmath/gmath.h>
2 #include <vulkan/vulkan.h>
10 #include "allocator.h"
13 /* global variables */
14 VkPhysicalDevice vk_physical;
16 VkInstance vk_instance;
19 VkCommandPool vk_pool;
20 VkSurfaceKHR vk_surface;
21 VkSwapchainKHR vk_swapchain;
22 VkRenderPass vk_renderpass;
23 VkDescriptorPool vk_dpool;
25 /* static functions */
26 static const char *get_device_name_str(VkPhysicalDeviceType type);
27 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags);
28 static const char *get_queue_flags_str(VkQueueFlags flags);
29 static const char *get_mem_size_str(long sz);
30 static int ver_major(uint32_t ver);
31 static int ver_minor(uint32_t ver);
32 static int ver_patch(uint32_t ver);
34 /* static variables */
35 static VkPhysicalDevice *phys_devices;
38 static int sel_qfamily;
40 static VkExtensionProperties *vkext, *vkdevext;
41 static uint32_t vkext_count, vkdevext_count;
43 bool vku_have_extension(const char *name)
47 vkEnumerateInstanceExtensionProperties(0, &vkext_count, 0);
49 vkext = new VkExtensionProperties[vkext_count];
50 vkEnumerateInstanceExtensionProperties(0, &vkext_count, vkext);
52 printf("instance extensions:\n");
53 for(int i=0; i<(int)vkext_count; i++) {
54 printf(" %s (ver: %u)\n", vkext[i].extensionName, (unsigned int)vkext[i].specVersion);
59 for(int i=0; i<(int)vkext_count; i++) {
60 if(strcmp(vkext[i].extensionName, name) == 0) {
67 bool vku_have_device_extension(const char *name)
69 if(sel_dev < 0) return false;
73 vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, 0);
75 vkdevext = new VkExtensionProperties[vkdevext_count];
76 vkEnumerateDeviceExtensionProperties(phys_devices[sel_dev], 0, &vkdevext_count, vkdevext);
78 printf("selected device extensions:\n");
79 for(int i=0; i<(int)vkdevext_count; i++) {
80 printf(" %s (ver: %u)\n", vkdevext[i].extensionName, (unsigned int)vkdevext[i].specVersion);
85 for(int i=0; i<(int)vkdevext_count; i++) {
86 if(strcmp(vkdevext[i].extensionName, name) == 0) {
93 bool vku_create_device()
95 VkInstanceCreateInfo inst_info;
96 VkDeviceCreateInfo dev_info;
97 VkDeviceQueueCreateInfo queue_info;
98 VkCommandPoolCreateInfo cmdpool_info;
102 static const char *ext_names[] = {
103 "VK_KHR_xcb_surface",
107 static const char *devext_names[] = {
114 for(unsigned int i=0; i<sizeof ext_names / sizeof *ext_names; i++) {
115 if(!vku_have_extension(ext_names[i])) {
116 fprintf(stderr, "required extension (%s) not found\n", ext_names[i]);
120 memset(&inst_info, 0, sizeof inst_info);
121 inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
122 inst_info.ppEnabledExtensionNames = ext_names;
123 inst_info.enabledExtensionCount = sizeof ext_names / sizeof *ext_names;
125 if(vkCreateInstance(&inst_info, 0, &vk_instance) != 0) {
126 fprintf(stderr, "failed to create vulkan instance\n");
129 printf("created vulkan instance\n");
130 if(vkEnumeratePhysicalDevices(vk_instance, &num_devices, 0) != 0) {
131 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
134 phys_devices = new VkPhysicalDevice[num_devices];
135 if(vkEnumeratePhysicalDevices(vk_instance, &num_devices, phys_devices) != 0) {
136 fprintf(stderr, "failed to enumerate vulkan physical devices\n");
139 printf("found %u physical device(s)\n", (unsigned int)num_devices);
141 for(int i=0; i<(int)num_devices; i++) {
142 VkPhysicalDeviceProperties dev_prop;
143 VkPhysicalDeviceMemoryProperties mem_prop;
144 VkQueueFamilyProperties *qprop;
145 uint32_t qprop_count;
147 vkGetPhysicalDeviceProperties(phys_devices[i], &dev_prop);
149 printf("Device %d: %s\n", i, dev_prop.deviceName);
150 printf(" type: %s\n", get_device_name_str(dev_prop.deviceType));
151 printf(" API version: %d.%d.%d\n", ver_major(dev_prop.apiVersion), ver_minor(dev_prop.apiVersion),
152 ver_patch(dev_prop.apiVersion));
153 printf(" driver version: %d.%d.%d\n", ver_major(dev_prop.driverVersion), ver_minor(dev_prop.driverVersion),
154 ver_patch(dev_prop.driverVersion));
155 printf(" vendor id: %x device id: %x\n", dev_prop.vendorID, dev_prop.deviceID);
158 vkGetPhysicalDeviceMemoryProperties(phys_devices[i], &mem_prop);
159 printf(" %d memory heaps:\n", mem_prop.memoryHeapCount);
160 for(unsigned int j=0; j<mem_prop.memoryHeapCount; j++) {
161 VkMemoryHeap heap = mem_prop.memoryHeaps[j];
162 printf(" Heap %d - size: %s, flags: %s\n", j, get_mem_size_str(heap.size),
163 heap.flags & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT ? "device-local" : "-");
165 printf(" %d memory types:\n", mem_prop.memoryTypeCount);
166 for(unsigned int j=0; j<mem_prop.memoryTypeCount; j++) {
167 VkMemoryType type = mem_prop.memoryTypes[j];
168 printf(" Type %d - heap: %d, flags: %s\n", j, type.heapIndex,
169 get_memtype_flags_str(type.propertyFlags));
172 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, 0);
173 if(qprop_count <= 0) {
176 qprop = new VkQueueFamilyProperties[qprop_count];
177 vkGetPhysicalDeviceQueueFamilyProperties(phys_devices[i], &qprop_count, qprop);
179 for(unsigned int j=0; j<qprop_count; j++) {
180 printf(" Queue family %d:\n", j);
181 printf(" flags: %s\n", get_queue_flags_str(qprop[j].queueFlags));
182 printf(" num queues: %u\n", qprop[j].queueCount);
184 if(qprop[j].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
192 if(sel_dev < 0 || sel_qfamily < 0) {
193 fprintf(stderr, "failed to find any device with a graphics-capable command queue\n");
194 vkDestroyDevice(vk_device, 0);
198 for(unsigned int i=0; i<sizeof devext_names / sizeof *devext_names; i++) {
199 if(!vku_have_device_extension(devext_names[i])) {
200 fprintf(stderr, "required extension (%s) not found on the selected device (%d)\n",
201 ext_names[i], sel_dev);
206 /* create device & command queue */
207 memset(&queue_info, 0, sizeof queue_info);
208 queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
209 queue_info.queueFamilyIndex = sel_qfamily;
210 queue_info.queueCount = 1;
211 queue_info.pQueuePriorities = &qprio;
213 memset(&dev_info, 0, sizeof dev_info);
214 dev_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
215 dev_info.queueCreateInfoCount = 1;
216 dev_info.pQueueCreateInfos = &queue_info;
217 dev_info.enabledExtensionCount = sizeof devext_names / sizeof *devext_names;
218 dev_info.ppEnabledExtensionNames = devext_names;
220 if(vkCreateDevice(phys_devices[sel_dev], &dev_info, 0, &vk_device) != 0) {
221 fprintf(stderr, "failed to create device %d\n", sel_dev);
224 printf("created device %d\n", sel_dev);
226 vk_physical = phys_devices[sel_dev];
227 vk_qfamily = sel_qfamily;
229 vkGetDeviceQueue(vk_device, sel_qfamily, 0, &vk_queue);
231 /* create command buffer pool */
232 memset(&cmdpool_info, 0, sizeof cmdpool_info);
233 cmdpool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
234 cmdpool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
235 cmdpool_info.queueFamilyIndex = sel_qfamily;
237 if(vkCreateCommandPool(vk_device, &cmdpool_info, 0, &vk_pool) != 0) {
238 fprintf(stderr, "failed to get command queue!\n");
242 /* if(!(vkcmdbuf = vku_alloc_cmdbuf(vk_pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY))) {
243 fprintf(stderr, "failed to create primary command buffer\n");
253 vkDeviceWaitIdle(vk_device);
254 vkDestroyCommandPool(vk_device, vk_pool, 0);
256 vkDestroyDevice(vk_device, 0);
257 vkDestroyInstance(vk_instance, 0);
261 delete [] phys_devices;
265 VkCommandBuffer vku_alloc_cmdbuf(VkCommandPool pool, VkCommandBufferLevel level)
267 VkCommandBuffer cmdbuf;
268 VkCommandBufferAllocateInfo inf;
270 memset(&inf, 0, sizeof inf);
271 inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
272 inf.commandPool = pool;
274 inf.commandBufferCount = 1;
276 if(vkAllocateCommandBuffers(vk_device, &inf, &cmdbuf) != 0) {
282 bool vku_alloc_cmdbufs(VkCommandPool pool, VkCommandBufferLevel level, unsigned int count, VkCommandBuffer *buf_array)
284 VkCommandBufferAllocateInfo cinf;
285 memset(&cinf, 0, sizeof cinf);
287 cinf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
288 cinf.commandPool = vk_pool;
290 cinf.commandBufferCount = count;
292 if(vkAllocateCommandBuffers(vk_device, &cinf, buf_array) != VK_SUCCESS) {
293 fprintf(stderr, "Failed to allocate command buffer\n");
300 void vku_free_cmdbuf(VkCommandPool pool, VkCommandBuffer buf)
302 vkFreeCommandBuffers(vk_device, pool, 1, &buf);
305 void vku_begin_cmdbuf(VkCommandBuffer buf, unsigned int flags)
307 VkCommandBufferBeginInfo inf;
309 memset(&inf, 0, sizeof inf);
310 inf.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
313 vkBeginCommandBuffer(buf, &inf);
317 void vku_end_cmdbuf(VkCommandBuffer buf)
319 vkEndCommandBuffer(buf);
322 void vku_reset_cmdbuf(VkCommandBuffer buf)
324 vkResetCommandBuffer(buf, 0);
327 void vku_submit_cmdbuf(VkQueue q, VkCommandBuffer buf, VkFence done_fence)
331 memset(&info, 0, sizeof info);
332 info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
333 info.commandBufferCount = 1;
334 info.pCommandBuffers = &buf;
336 vkQueueSubmit(q, 1, &info, done_fence);
339 bool vku_get_surface_format(VkPhysicalDevice gpu, VkSurfaceKHR surface, VkSurfaceFormatKHR *sformat)
343 if(vkGetPhysicalDeviceSurfaceFormatsKHR(vk_physical,
344 vk_surface, &fcount, 0) != VK_SUCCESS) {
345 fprintf(stderr, "Failed to get format count for physical device.\n");
349 fprintf(stderr, "No color formats were found.\n");
353 VkSurfaceFormatKHR *formats = new VkSurfaceFormatKHR[fcount];
354 if(vkGetPhysicalDeviceSurfaceFormatsKHR(vk_physical, vk_surface,
355 &fcount, formats) != VK_SUCCESS) {
357 fprintf(stderr, "Failed to get surface formats.\n");
361 *sformat = formats[0];
363 if((fcount == 1) && (formats[0].format == VK_FORMAT_UNDEFINED)) {
364 sformat->format = VK_FORMAT_B8G8R8_UNORM;
372 int vku_get_next_image(VkSwapchainKHR sc)
376 if(vkAcquireNextImageKHR(vk_device, sc, UINT64_MAX, 0, 0, &next) != 0) {
382 void vku_present(VkSwapchainKHR sc, int img_idx)
384 VkPresentInfoKHR inf;
386 uint32_t index = img_idx;
388 memset(&inf, 0, sizeof inf);
389 inf.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
390 inf.swapchainCount = 1;
391 inf.pSwapchains = ≻
392 inf.pImageIndices = &index;
395 vkQueuePresentKHR(vk_queue, &inf);
398 struct vku_buffer *vku_create_buffer(int sz, unsigned int usage)
400 struct vku_buffer *buf;
401 VkBufferCreateInfo binfo;
403 buf = new vku_buffer;
405 memset(&binfo, 0, sizeof binfo);
406 binfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
409 binfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
411 if(vkCreateBuffer(vk_device, &binfo, 0, &buf->buf) != 0) {
412 fprintf(stderr, "failed to create %d byte buffer (usage: %x)\n", sz, usage);
416 VkMemoryRequirements mr;
417 vkGetBufferMemoryRequirements(vk_device, buf->buf, &mr);
420 if(!vku_allocate(mr.size, &block))
423 buf->mem_pool = block.dev_mem;
428 void vku_destroy_buffer(struct vku_buffer *buf)
432 bool vku_update_buffer(vku_buffer *buf, int size, void *data)
435 if(vkMapMemory(vk_device, buf->mem_pool, 0, size, 0, (void **)&pdata) != VK_SUCCESS) {
436 fprintf(stderr, "Failed to map memory.\n");
439 memcpy(pdata, data, size);
440 vkUnmapMemory(vk_device, buf->mem_pool);
445 void vku_cmd_copybuf(VkCommandBuffer cmdbuf, VkBuffer dest, int doffs,
446 VkBuffer src, int soffs, int size)
450 copy.srcOffset = soffs;
451 copy.dstOffset = doffs;
453 vkCmdCopyBuffer(cmdbuf, src, dest, 1, ©);
456 const char *vku_get_vulkan_error_str(VkResult error)
461 errmsg = std::string("VK_SUCCESS");
464 errmsg = std::string("VK_NOT_READY");
467 errmsg = std::string("VK_TIMEOUT");
470 errmsg = std::string("VK_EVENT_SET");
473 errmsg = std::string("VK_EVENT_RESET");
476 errmsg = std::string("VK_EVENT");
478 case VK_ERROR_OUT_OF_HOST_MEMORY:
479 errmsg = std::string("VK_ERROR_OUT_OF_HOST_MEMORY");
481 case VK_ERROR_OUT_OF_DEVICE_MEMORY:
482 errmsg = std::string("VK_ERROR_OUT_OF_DEVICE_MEMORY");
484 case VK_ERROR_INITIALIZATION_FAILED:
485 errmsg = std::string("VK_ERROR_INITIALIZATION_FAILED");
487 case VK_ERROR_DEVICE_LOST:
488 errmsg = std::string("VK_ERROR_DEVICE_LOST");
490 case VK_ERROR_MEMORY_MAP_FAILED:
491 errmsg = std::string("VK_ERROR_MEMORY_MAP_FAILED");
493 case VK_ERROR_LAYER_NOT_PRESENT:
494 errmsg = std::string("VK_ERROR_LAYER_NOT_PRESENT");
496 case VK_ERROR_EXTENSION_NOT_PRESENT:
497 errmsg = std::string("VK_ERROR_EXTENSION_NOT_PRESENT");
499 case VK_ERROR_FEATURE_NOT_PRESENT:
500 errmsg = std::string("VK_ERROR_FEATURE_NOT_PRESENT");
501 case VK_ERROR_INCOMPATIBLE_DRIVER:
502 errmsg = std::string("VK_ERROR_INCOMPATIBLE_DRIVER");
504 case VK_ERROR_TOO_MANY_OBJECTS:
505 errmsg = std::string("VK_ERROR_TOO_MANY_OBJECTS");
507 case VK_ERROR_FORMAT_NOT_SUPPORTED:
508 errmsg = std::string("VK_ERROR_FORMAT_NOT_SUPPORTED");
510 case VK_ERROR_FRAGMENTED_POOL:
511 errmsg = std::string("VK_ERROR_FRAGMENTED_POOL");
514 errmsg = std::string("UNKNOWN");
518 return errmsg.c_str();
522 static const char *get_device_name_str(VkPhysicalDeviceType type)
525 case VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU:
526 return "integrated GPU";
527 case VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU:
528 return "discrete GPU";
529 case VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU:
530 return "virtual GPU";
531 case VK_PHYSICAL_DEVICE_TYPE_CPU:
539 static const char *get_memtype_flags_str(VkMemoryPropertyFlags flags)
541 static char str[128];
544 if(flags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) {
545 strcat(str, "device-local ");
547 if(flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) {
548 strcat(str, "host-visible ");
550 if(flags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) {
551 strcat(str, "host-coherent ");
553 if(flags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) {
554 strcat(str, "host-cached ");
556 if(flags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) {
557 strcat(str, "lazily-allocated ");
566 static const char *get_queue_flags_str(VkQueueFlags flags)
568 static char str[128];
571 if(flags & VK_QUEUE_GRAPHICS_BIT) {
572 strcat(str, "graphics ");
574 if(flags & VK_QUEUE_COMPUTE_BIT) {
575 strcat(str, "compute ");
577 if(flags & VK_QUEUE_TRANSFER_BIT) {
578 strcat(str, "transfer ");
580 if(flags & VK_QUEUE_SPARSE_BINDING_BIT) {
581 strcat(str, "sparse-binding ");
589 static int ver_major(uint32_t ver)
591 return (ver >> 22) & 0x3ff;
594 static int ver_minor(uint32_t ver)
596 return (ver >> 12) & 0x3ff;
599 static int ver_patch(uint32_t ver)
604 static const char *get_mem_size_str(long sz)
607 static const char *unitstr[] = { "bytes", "KB", "MB", "GB", "TB", "PB", 0 };
611 while(sz >= 10240 && unitstr[uidx + 1]) {
615 sprintf(str, "%ld.%ld %s", sz / 10, sz % 10, unitstr[uidx]);
619 vku_descriptor *vku_create_descriptor(VkDescriptorType type,
620 VkFlags stage, int binding_point,
621 int size, int num_desc)
623 vku_descriptor *desc = new vku_descriptor;
627 desc->stage_flags = stage;
628 desc->binding_point = binding_point;
630 VkDescriptorSetLayoutBinding dslb;
631 memset(&dslb, 0, sizeof dslb);
633 dslb.binding = binding_point;
634 dslb.descriptorType = type;
635 dslb.descriptorCount = num_desc;
636 dslb.stageFlags = stage;
638 VkDescriptorSetLayoutCreateInfo dslinf;
639 memset(&dslinf, 0, sizeof dslinf);
641 dslinf.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
642 dslinf.bindingCount = 1;
643 dslinf.pBindings = &dslb;
645 if(vkCreateDescriptorSetLayout(vk_device, &dslinf, 0, &desc->layout) != VK_SUCCESS) {
646 fprintf(stderr, "Failed to create vku_descriptor.\n");
653 void vku_destroy_descriptor(vku_descriptor *desc)
655 vkDestroyDescriptorSetLayout(vk_device, desc->layout, 0);
659 bool vku_create_descriptor_pool(vku_descriptor **descriptors, int num_desc)
662 vkDestroyDescriptorPool(vk_device, vk_dpool, 0);
664 VkDescriptorPoolCreateInfo dpinf;
665 memset(&dpinf, 0, sizeof dpinf);
666 dpinf.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
669 dpinf.poolSizeCount = num_desc;
671 std::vector<VkDescriptorPoolSize> sizes;
672 for(int i=0; i<num_desc; i++) {
673 VkDescriptorPoolSize psz;
674 psz.type = descriptors[i]->type;
675 psz.descriptorCount = 1;
676 sizes.push_back(psz);
679 dpinf.pPoolSizes = sizes.data();
681 if(vkCreateDescriptorPool(vk_device, &dpinf, 0, &vk_dpool) != VK_SUCCESS) {
682 fprintf(stderr, "Failed to create descriptor pool.\n");
689 void vku_destroy_descriptor_pool()
691 vkDestroyDescriptorPool(vk_device, vk_dpool, 0);
694 bool vku_allocate_descriptor_sets(vku_descriptor **desc, int num_desc, VkDescriptorSet set)
696 VkDescriptorSetAllocateInfo dainf;
697 memset(&dainf, 0, sizeof dainf);
699 dainf.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
700 dainf.descriptorPool = vk_dpool;
701 dainf.descriptorSetCount = num_desc;
703 std::vector<VkDescriptorSetLayout> layouts;
704 for(int i=0; i<num_desc; i++) {
705 layouts.push_back(desc[i]->layout);
708 dainf.pSetLayouts = layouts.data();
710 if(vkAllocateDescriptorSets(vk_device, &dainf, &set) != VK_SUCCESS) {
711 fprintf(stderr, "Failed to allocate descriptor sets.\n");
717 void vku_free_descriptor_sets(VkDescriptorSet *sets, int num)
719 vkFreeDescriptorSets(vk_device, vk_dpool, num, sets);
722 bool vku_update_descriptor_sets(VkDescriptorSet *sets, int num_sets)