565f5884bb690488dd1fcdf7818a15199862a4cc
[mesa.git] / src / vulkan / overlay-layer / overlay.cpp
1 /*
2 * Copyright © 2019 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 */
23
24 #include <string.h>
25 #include <stdlib.h>
26 #include <assert.h>
27
28 #include <vulkan/vulkan.h>
29 #include <vulkan/vk_layer.h>
30
31 #include "git_sha1.h"
32
33 #include "imgui.h"
34
35 #include "overlay_params.h"
36
37 #include "util/debug.h"
38 #include "util/hash_table.h"
39 #include "util/list.h"
40 #include "util/ralloc.h"
41 #include "util/os_time.h"
42 #include "util/os_socket.h"
43 #include "util/simple_mtx.h"
44
45 #include "vk_enum_to_str.h"
46 #include "vk_util.h"
47
48 /* Mapped from VkInstace/VkPhysicalDevice */
49 struct instance_data {
50 struct vk_instance_dispatch_table vtable;
51 VkInstance instance;
52
53 struct overlay_params params;
54 bool pipeline_statistics_enabled;
55
56 bool first_line_printed;
57
58 int control_client;
59
60 /* Dumping of frame stats to a file has been enabled. */
61 bool capture_enabled;
62
63 /* Dumping of frame stats to a file has been enabled and started. */
64 bool capture_started;
65 };
66
67 struct frame_stat {
68 uint64_t stats[OVERLAY_PARAM_ENABLED_MAX];
69 };
70
71 /* Mapped from VkDevice */
72 struct queue_data;
73 struct device_data {
74 struct instance_data *instance;
75
76 PFN_vkSetDeviceLoaderData set_device_loader_data;
77
78 struct vk_device_dispatch_table vtable;
79 VkPhysicalDevice physical_device;
80 VkDevice device;
81
82 VkPhysicalDeviceProperties properties;
83
84 struct queue_data *graphic_queue;
85
86 struct queue_data **queues;
87 uint32_t n_queues;
88
89 /* For a single frame */
90 struct frame_stat frame_stats;
91 };
92
93 /* Mapped from VkCommandBuffer */
94 struct command_buffer_data {
95 struct device_data *device;
96
97 VkCommandBufferLevel level;
98
99 VkCommandBuffer cmd_buffer;
100 VkQueryPool pipeline_query_pool;
101 VkQueryPool timestamp_query_pool;
102 uint32_t query_index;
103
104 struct frame_stat stats;
105
106 struct list_head link; /* link into queue_data::running_command_buffer */
107 };
108
109 /* Mapped from VkQueue */
110 struct queue_data {
111 struct device_data *device;
112
113 VkQueue queue;
114 VkQueueFlags flags;
115 uint32_t family_index;
116 uint64_t timestamp_mask;
117
118 VkFence queries_fence;
119
120 struct list_head running_command_buffer;
121 };
122
123 struct overlay_draw {
124 struct list_head link;
125
126 VkCommandBuffer command_buffer;
127
128 VkSemaphore semaphore;
129 VkFence fence;
130
131 VkBuffer vertex_buffer;
132 VkDeviceMemory vertex_buffer_mem;
133 VkDeviceSize vertex_buffer_size;
134
135 VkBuffer index_buffer;
136 VkDeviceMemory index_buffer_mem;
137 VkDeviceSize index_buffer_size;
138 };
139
140 /* Mapped from VkSwapchainKHR */
141 struct swapchain_data {
142 struct device_data *device;
143
144 VkSwapchainKHR swapchain;
145 unsigned width, height;
146 VkFormat format;
147
148 uint32_t n_images;
149 VkImage *images;
150 VkImageView *image_views;
151 VkFramebuffer *framebuffers;
152
153 VkRenderPass render_pass;
154
155 VkDescriptorPool descriptor_pool;
156 VkDescriptorSetLayout descriptor_layout;
157 VkDescriptorSet descriptor_set;
158
159 VkSampler font_sampler;
160
161 VkPipelineLayout pipeline_layout;
162 VkPipeline pipeline;
163
164 VkCommandPool command_pool;
165
166 struct list_head draws; /* List of struct overlay_draw */
167
168 bool font_uploaded;
169 VkImage font_image;
170 VkImageView font_image_view;
171 VkDeviceMemory font_mem;
172 VkBuffer upload_font_buffer;
173 VkDeviceMemory upload_font_buffer_mem;
174
175 /**/
176 ImGuiContext* imgui_context;
177 ImVec2 window_size;
178
179 /**/
180 uint64_t n_frames;
181 uint64_t last_present_time;
182
183 unsigned n_frames_since_update;
184 uint64_t last_fps_update;
185 double fps;
186
187 enum overlay_param_enabled stat_selector;
188 double time_dividor;
189 struct frame_stat stats_min, stats_max;
190 struct frame_stat frames_stats[200];
191
192 /* Over a single frame */
193 struct frame_stat frame_stats;
194
195 /* Over fps_sampling_period */
196 struct frame_stat accumulated_stats;
197 };
198
199 static const VkQueryPipelineStatisticFlags overlay_query_flags =
200 VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT |
201 VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT |
202 VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT |
203 VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT |
204 VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT |
205 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT |
206 VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT |
207 VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT |
208 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT |
209 VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT |
210 VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT;
211 #define OVERLAY_QUERY_COUNT (11)
212
213 static struct hash_table_u64 *vk_object_to_data = NULL;
214 static simple_mtx_t vk_object_to_data_mutex = _SIMPLE_MTX_INITIALIZER_NP;
215
216 thread_local ImGuiContext* __MesaImGui;
217
218 static inline void ensure_vk_object_map(void)
219 {
220 if (!vk_object_to_data)
221 vk_object_to_data = _mesa_hash_table_u64_create(NULL);
222 }
223
224 #define HKEY(obj) ((uint64_t)(obj))
225 #define FIND(type, obj) ((type *)find_object_data(HKEY(obj)))
226
227 static void *find_object_data(uint64_t obj)
228 {
229 simple_mtx_lock(&vk_object_to_data_mutex);
230 ensure_vk_object_map();
231 void *data = _mesa_hash_table_u64_search(vk_object_to_data, obj);
232 simple_mtx_unlock(&vk_object_to_data_mutex);
233 return data;
234 }
235
236 static void map_object(uint64_t obj, void *data)
237 {
238 simple_mtx_lock(&vk_object_to_data_mutex);
239 ensure_vk_object_map();
240 _mesa_hash_table_u64_insert(vk_object_to_data, obj, data);
241 simple_mtx_unlock(&vk_object_to_data_mutex);
242 }
243
244 static void unmap_object(uint64_t obj)
245 {
246 simple_mtx_lock(&vk_object_to_data_mutex);
247 _mesa_hash_table_u64_remove(vk_object_to_data, obj);
248 simple_mtx_unlock(&vk_object_to_data_mutex);
249 }
250
251 /**/
252
253 #define VK_CHECK(expr) \
254 do { \
255 VkResult __result = (expr); \
256 if (__result != VK_SUCCESS) { \
257 fprintf(stderr, "'%s' line %i failed with %s\n", \
258 #expr, __LINE__, vk_Result_to_str(__result)); \
259 } \
260 } while (0)
261
262 /**/
263
264 static VkLayerInstanceCreateInfo *get_instance_chain_info(const VkInstanceCreateInfo *pCreateInfo,
265 VkLayerFunction func)
266 {
267 vk_foreach_struct(item, pCreateInfo->pNext) {
268 if (item->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO &&
269 ((VkLayerInstanceCreateInfo *) item)->function == func)
270 return (VkLayerInstanceCreateInfo *) item;
271 }
272 unreachable("instance chain info not found");
273 return NULL;
274 }
275
276 static VkLayerDeviceCreateInfo *get_device_chain_info(const VkDeviceCreateInfo *pCreateInfo,
277 VkLayerFunction func)
278 {
279 vk_foreach_struct(item, pCreateInfo->pNext) {
280 if (item->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO &&
281 ((VkLayerDeviceCreateInfo *) item)->function == func)
282 return (VkLayerDeviceCreateInfo *)item;
283 }
284 unreachable("device chain info not found");
285 return NULL;
286 }
287
288 static struct VkBaseOutStructure *
289 clone_chain(const struct VkBaseInStructure *chain)
290 {
291 struct VkBaseOutStructure *head = NULL, *tail = NULL;
292
293 vk_foreach_struct_const(item, chain) {
294 size_t item_size = vk_structure_type_size(item);
295 struct VkBaseOutStructure *new_item =
296 (struct VkBaseOutStructure *)malloc(item_size);;
297
298 memcpy(new_item, item, item_size);
299
300 if (!head)
301 head = new_item;
302 if (tail)
303 tail->pNext = new_item;
304 tail = new_item;
305 }
306
307 return head;
308 }
309
310 static void
311 free_chain(struct VkBaseOutStructure *chain)
312 {
313 while (chain) {
314 void *node = chain;
315 chain = chain->pNext;
316 free(node);
317 }
318 }
319
320 /**/
321
322 static struct instance_data *new_instance_data(VkInstance instance)
323 {
324 struct instance_data *data = rzalloc(NULL, struct instance_data);
325 data->instance = instance;
326 data->control_client = -1;
327 map_object(HKEY(data->instance), data);
328 return data;
329 }
330
331 static void destroy_instance_data(struct instance_data *data)
332 {
333 if (data->params.output_file)
334 fclose(data->params.output_file);
335 if (data->params.control >= 0)
336 os_socket_close(data->params.control);
337 unmap_object(HKEY(data->instance));
338 ralloc_free(data);
339 }
340
341 static void instance_data_map_physical_devices(struct instance_data *instance_data,
342 bool map)
343 {
344 uint32_t physicalDeviceCount = 0;
345 instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
346 &physicalDeviceCount,
347 NULL);
348
349 VkPhysicalDevice *physicalDevices = (VkPhysicalDevice *) malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
350 instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
351 &physicalDeviceCount,
352 physicalDevices);
353
354 for (uint32_t i = 0; i < physicalDeviceCount; i++) {
355 if (map)
356 map_object(HKEY(physicalDevices[i]), instance_data);
357 else
358 unmap_object(HKEY(physicalDevices[i]));
359 }
360
361 free(physicalDevices);
362 }
363
364 /**/
365 static struct device_data *new_device_data(VkDevice device, struct instance_data *instance)
366 {
367 struct device_data *data = rzalloc(NULL, struct device_data);
368 data->instance = instance;
369 data->device = device;
370 map_object(HKEY(data->device), data);
371 return data;
372 }
373
374 static struct queue_data *new_queue_data(VkQueue queue,
375 const VkQueueFamilyProperties *family_props,
376 uint32_t family_index,
377 struct device_data *device_data)
378 {
379 struct queue_data *data = rzalloc(device_data, struct queue_data);
380 data->device = device_data;
381 data->queue = queue;
382 data->flags = family_props->queueFlags;
383 data->timestamp_mask = (1ull << family_props->timestampValidBits) - 1;
384 data->family_index = family_index;
385 list_inithead(&data->running_command_buffer);
386 map_object(HKEY(data->queue), data);
387
388 /* Fence synchronizing access to queries on that queue. */
389 VkFenceCreateInfo fence_info = {};
390 fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
391 fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
392 VK_CHECK(device_data->vtable.CreateFence(device_data->device,
393 &fence_info,
394 NULL,
395 &data->queries_fence));
396
397 if (data->flags & VK_QUEUE_GRAPHICS_BIT)
398 device_data->graphic_queue = data;
399
400 return data;
401 }
402
403 static void destroy_queue(struct queue_data *data)
404 {
405 struct device_data *device_data = data->device;
406 device_data->vtable.DestroyFence(device_data->device, data->queries_fence, NULL);
407 unmap_object(HKEY(data->queue));
408 ralloc_free(data);
409 }
410
411 static void device_map_queues(struct device_data *data,
412 const VkDeviceCreateInfo *pCreateInfo)
413 {
414 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++)
415 data->n_queues += pCreateInfo->pQueueCreateInfos[i].queueCount;
416 data->queues = ralloc_array(data, struct queue_data *, data->n_queues);
417
418 struct instance_data *instance_data = data->instance;
419 uint32_t n_family_props;
420 instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
421 &n_family_props,
422 NULL);
423 VkQueueFamilyProperties *family_props =
424 (VkQueueFamilyProperties *)malloc(sizeof(VkQueueFamilyProperties) * n_family_props);
425 instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
426 &n_family_props,
427 family_props);
428
429 uint32_t queue_index = 0;
430 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
431 for (uint32_t j = 0; j < pCreateInfo->pQueueCreateInfos[i].queueCount; j++) {
432 VkQueue queue;
433 data->vtable.GetDeviceQueue(data->device,
434 pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex,
435 j, &queue);
436
437 VK_CHECK(data->set_device_loader_data(data->device, queue));
438
439 data->queues[queue_index++] =
440 new_queue_data(queue, &family_props[pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex],
441 pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, data);
442 }
443 }
444
445 free(family_props);
446 }
447
448 static void device_unmap_queues(struct device_data *data)
449 {
450 for (uint32_t i = 0; i < data->n_queues; i++)
451 destroy_queue(data->queues[i]);
452 }
453
454 static void destroy_device_data(struct device_data *data)
455 {
456 unmap_object(HKEY(data->device));
457 ralloc_free(data);
458 }
459
460 /**/
461 static struct command_buffer_data *new_command_buffer_data(VkCommandBuffer cmd_buffer,
462 VkCommandBufferLevel level,
463 VkQueryPool pipeline_query_pool,
464 VkQueryPool timestamp_query_pool,
465 uint32_t query_index,
466 struct device_data *device_data)
467 {
468 struct command_buffer_data *data = rzalloc(NULL, struct command_buffer_data);
469 data->device = device_data;
470 data->cmd_buffer = cmd_buffer;
471 data->level = level;
472 data->pipeline_query_pool = pipeline_query_pool;
473 data->timestamp_query_pool = timestamp_query_pool;
474 data->query_index = query_index;
475 list_inithead(&data->link);
476 map_object(HKEY(data->cmd_buffer), data);
477 return data;
478 }
479
480 static void destroy_command_buffer_data(struct command_buffer_data *data)
481 {
482 unmap_object(HKEY(data->cmd_buffer));
483 list_delinit(&data->link);
484 ralloc_free(data);
485 }
486
487 /**/
488 static struct swapchain_data *new_swapchain_data(VkSwapchainKHR swapchain,
489 struct device_data *device_data)
490 {
491 struct instance_data *instance_data = device_data->instance;
492 struct swapchain_data *data = rzalloc(NULL, struct swapchain_data);
493 data->device = device_data;
494 data->swapchain = swapchain;
495 data->window_size = ImVec2(instance_data->params.width, instance_data->params.height);
496 list_inithead(&data->draws);
497 map_object(HKEY(data->swapchain), data);
498 return data;
499 }
500
501 static void destroy_swapchain_data(struct swapchain_data *data)
502 {
503 unmap_object(HKEY(data->swapchain));
504 ralloc_free(data);
505 }
506
507 struct overlay_draw *get_overlay_draw(struct swapchain_data *data)
508 {
509 struct device_data *device_data = data->device;
510 struct overlay_draw *draw = list_is_empty(&data->draws) ?
511 NULL : list_first_entry(&data->draws, struct overlay_draw, link);
512
513 VkSemaphoreCreateInfo sem_info = {};
514 sem_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
515
516 if (draw && device_data->vtable.GetFenceStatus(device_data->device, draw->fence) == VK_SUCCESS) {
517 list_del(&draw->link);
518 VK_CHECK(device_data->vtable.ResetFences(device_data->device,
519 1, &draw->fence));
520 list_addtail(&draw->link, &data->draws);
521 return draw;
522 }
523
524 draw = rzalloc(data, struct overlay_draw);
525
526 VkCommandBufferAllocateInfo cmd_buffer_info = {};
527 cmd_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
528 cmd_buffer_info.commandPool = data->command_pool;
529 cmd_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
530 cmd_buffer_info.commandBufferCount = 1;
531 VK_CHECK(device_data->vtable.AllocateCommandBuffers(device_data->device,
532 &cmd_buffer_info,
533 &draw->command_buffer));
534 VK_CHECK(device_data->set_device_loader_data(device_data->device,
535 draw->command_buffer));
536
537
538 VkFenceCreateInfo fence_info = {};
539 fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
540 VK_CHECK(device_data->vtable.CreateFence(device_data->device,
541 &fence_info,
542 NULL,
543 &draw->fence));
544
545 VK_CHECK(device_data->vtable.CreateSemaphore(device_data->device, &sem_info,
546 NULL, &draw->semaphore));
547
548 list_addtail(&draw->link, &data->draws);
549
550 return draw;
551 }
552
553 static const char *param_unit(enum overlay_param_enabled param)
554 {
555 switch (param) {
556 case OVERLAY_PARAM_ENABLED_frame_timing:
557 case OVERLAY_PARAM_ENABLED_acquire_timing:
558 case OVERLAY_PARAM_ENABLED_present_timing:
559 return "(us)";
560 case OVERLAY_PARAM_ENABLED_gpu_timing:
561 return "(ns)";
562 default:
563 return "";
564 }
565 }
566
567 static void parse_command(struct instance_data *instance_data,
568 const char *cmd, unsigned cmdlen,
569 const char *param, unsigned paramlen)
570 {
571 if (!strncmp(cmd, "capture", cmdlen)) {
572 int value = atoi(param);
573 bool enabled = value > 0;
574
575 if (enabled) {
576 instance_data->capture_enabled = true;
577 } else {
578 instance_data->capture_enabled = false;
579 instance_data->capture_started = false;
580 }
581 }
582 }
583
584 #define BUFSIZE 4096
585
586 /**
587 * This function will process commands through the control file.
588 *
589 * A command starts with a colon, followed by the command, and followed by an
590 * option '=' and a parameter. It has to end with a semi-colon. A full command
591 * + parameter looks like:
592 *
593 * :cmd=param;
594 */
595 static void process_char(struct instance_data *instance_data, char c)
596 {
597 static char cmd[BUFSIZE];
598 static char param[BUFSIZE];
599
600 static unsigned cmdpos = 0;
601 static unsigned parampos = 0;
602 static bool reading_cmd = false;
603 static bool reading_param = false;
604
605 switch (c) {
606 case ':':
607 cmdpos = 0;
608 parampos = 0;
609 reading_cmd = true;
610 reading_param = false;
611 break;
612 case ';':
613 if (!reading_cmd)
614 break;
615 cmd[cmdpos++] = '\0';
616 param[parampos++] = '\0';
617 parse_command(instance_data, cmd, cmdpos, param, parampos);
618 reading_cmd = false;
619 reading_param = false;
620 break;
621 case '=':
622 if (!reading_cmd)
623 break;
624 reading_param = true;
625 break;
626 default:
627 if (!reading_cmd)
628 break;
629
630 if (reading_param) {
631 /* overflow means an invalid parameter */
632 if (parampos >= BUFSIZE - 1) {
633 reading_cmd = false;
634 reading_param = false;
635 break;
636 }
637
638 param[parampos++] = c;
639 } else {
640 /* overflow means an invalid command */
641 if (cmdpos >= BUFSIZE - 1) {
642 reading_cmd = false;
643 break;
644 }
645
646 cmd[cmdpos++] = c;
647 }
648 }
649 }
650
651 static void control_send(struct instance_data *instance_data,
652 const char *cmd, unsigned cmdlen,
653 const char *param, unsigned paramlen)
654 {
655 unsigned msglen = 0;
656 char buffer[BUFSIZE];
657
658 assert(cmdlen + paramlen + 3 < BUFSIZE);
659
660 buffer[msglen++] = ':';
661
662 memcpy(&buffer[msglen], cmd, cmdlen);
663 msglen += cmdlen;
664
665 if (paramlen > 0) {
666 buffer[msglen++] = '=';
667 memcpy(&buffer[msglen], param, paramlen);
668 msglen += paramlen;
669 buffer[msglen++] = ';';
670 }
671
672 os_socket_send(instance_data->control_client, buffer, msglen, 0);
673 }
674
675 static void control_send_connection_string(struct device_data *device_data)
676 {
677 struct instance_data *instance_data = device_data->instance;
678
679 const char *controlVersionCmd = "MesaOverlayControlVersion";
680 const char *controlVersionString = "1";
681
682 control_send(instance_data, controlVersionCmd, strlen(controlVersionCmd),
683 controlVersionString, strlen(controlVersionString));
684
685 const char *deviceCmd = "DeviceName";
686 const char *deviceName = device_data->properties.deviceName;
687
688 control_send(instance_data, deviceCmd, strlen(deviceCmd),
689 deviceName, strlen(deviceName));
690
691 const char *mesaVersionCmd = "MesaVersion";
692 const char *mesaVersionString = "Mesa " PACKAGE_VERSION MESA_GIT_SHA1;
693
694 control_send(instance_data, mesaVersionCmd, strlen(mesaVersionCmd),
695 mesaVersionString, strlen(mesaVersionString));
696 }
697
698 static void control_client_check(struct device_data *device_data)
699 {
700 struct instance_data *instance_data = device_data->instance;
701
702 /* Already connected, just return. */
703 if (instance_data->control_client >= 0)
704 return;
705
706 int socket = os_socket_accept(instance_data->params.control);
707 if (socket == -1) {
708 if (errno != EAGAIN && errno != EWOULDBLOCK && errno != ECONNABORTED)
709 fprintf(stderr, "ERROR on socket: %s\n", strerror(errno));
710 return;
711 }
712
713 if (socket >= 0) {
714 os_socket_block(socket, false);
715 instance_data->control_client = socket;
716 control_send_connection_string(device_data);
717 }
718 }
719
720 static void control_client_disconnected(struct instance_data *instance_data)
721 {
722 os_socket_close(instance_data->control_client);
723 instance_data->control_client = -1;
724 }
725
726 static void process_control_socket(struct instance_data *instance_data)
727 {
728 const int client = instance_data->control_client;
729 if (client >= 0) {
730 char buf[BUFSIZE];
731
732 while (true) {
733 ssize_t n = os_socket_recv(client, buf, BUFSIZE, 0);
734
735 if (n == -1) {
736 if (errno == EAGAIN || errno == EWOULDBLOCK) {
737 /* nothing to read, try again later */
738 break;
739 }
740
741 if (errno != ECONNRESET)
742 fprintf(stderr, "ERROR on connection: %s\n", strerror(errno));
743
744 control_client_disconnected(instance_data);
745 } else if (n == 0) {
746 /* recv() returns 0 when the client disconnects */
747 control_client_disconnected(instance_data);
748 }
749
750 for (ssize_t i = 0; i < n; i++) {
751 process_char(instance_data, buf[i]);
752 }
753
754 /* If we try to read BUFSIZE and receive BUFSIZE bytes from the
755 * socket, there's a good chance that there's still more data to be
756 * read, so we will try again. Otherwise, simply be done for this
757 * iteration and try again on the next frame.
758 */
759 if (n < BUFSIZE)
760 break;
761 }
762 }
763 }
764
765 static void snapshot_swapchain_frame(struct swapchain_data *data)
766 {
767 struct device_data *device_data = data->device;
768 struct instance_data *instance_data = device_data->instance;
769 uint32_t f_idx = data->n_frames % ARRAY_SIZE(data->frames_stats);
770 uint64_t now = os_time_get(); /* us */
771
772 if (instance_data->params.control >= 0) {
773 control_client_check(device_data);
774 process_control_socket(instance_data);
775 }
776
777 if (data->last_present_time) {
778 data->frame_stats.stats[OVERLAY_PARAM_ENABLED_frame_timing] =
779 now - data->last_present_time;
780 }
781
782 memset(&data->frames_stats[f_idx], 0, sizeof(data->frames_stats[f_idx]));
783 for (int s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
784 data->frames_stats[f_idx].stats[s] += device_data->frame_stats.stats[s] + data->frame_stats.stats[s];
785 data->accumulated_stats.stats[s] += device_data->frame_stats.stats[s] + data->frame_stats.stats[s];
786 }
787
788 /* If capture has been enabled but it hasn't started yet, it means we are on
789 * the first snapshot after it has been enabled. At this point we want to
790 * use the stats captured so far to update the display, but we don't want
791 * this data to cause noise to the stats that we want to capture from now
792 * on.
793 *
794 * capture_begin == true will trigger an update of the fps on display, and a
795 * flush of the data, but no stats will be written to the output file. This
796 * way, we will have only stats from after the capture has been enabled
797 * written to the output_file.
798 */
799 const bool capture_begin =
800 instance_data->capture_enabled && !instance_data->capture_started;
801
802 if (data->last_fps_update) {
803 double elapsed = (double)(now - data->last_fps_update); /* us */
804 if (capture_begin ||
805 elapsed >= instance_data->params.fps_sampling_period) {
806 data->fps = 1000000.0f * data->n_frames_since_update / elapsed;
807 if (instance_data->capture_started) {
808 if (!instance_data->first_line_printed) {
809 bool first_column = true;
810
811 instance_data->first_line_printed = true;
812
813 #define OVERLAY_PARAM_BOOL(name) \
814 if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_##name]) { \
815 fprintf(instance_data->params.output_file, \
816 "%s%s%s", first_column ? "" : ", ", #name, \
817 param_unit(OVERLAY_PARAM_ENABLED_##name)); \
818 first_column = false; \
819 }
820 #define OVERLAY_PARAM_CUSTOM(name)
821 OVERLAY_PARAMS
822 #undef OVERLAY_PARAM_BOOL
823 #undef OVERLAY_PARAM_CUSTOM
824 fprintf(instance_data->params.output_file, "\n");
825 }
826
827 for (int s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
828 if (!instance_data->params.enabled[s])
829 continue;
830 if (s == OVERLAY_PARAM_ENABLED_fps) {
831 fprintf(instance_data->params.output_file,
832 "%s%.2f", s == 0 ? "" : ", ", data->fps);
833 } else {
834 fprintf(instance_data->params.output_file,
835 "%s%" PRIu64, s == 0 ? "" : ", ",
836 data->accumulated_stats.stats[s]);
837 }
838 }
839 fprintf(instance_data->params.output_file, "\n");
840 fflush(instance_data->params.output_file);
841 }
842
843 memset(&data->accumulated_stats, 0, sizeof(data->accumulated_stats));
844 data->n_frames_since_update = 0;
845 data->last_fps_update = now;
846
847 if (capture_begin)
848 instance_data->capture_started = true;
849 }
850 } else {
851 data->last_fps_update = now;
852 }
853
854 memset(&device_data->frame_stats, 0, sizeof(device_data->frame_stats));
855 memset(&data->frame_stats, 0, sizeof(device_data->frame_stats));
856
857 data->last_present_time = now;
858 data->n_frames++;
859 data->n_frames_since_update++;
860 }
861
862 static float get_time_stat(void *_data, int _idx)
863 {
864 struct swapchain_data *data = (struct swapchain_data *) _data;
865 if ((ARRAY_SIZE(data->frames_stats) - _idx) > data->n_frames)
866 return 0.0f;
867 int idx = ARRAY_SIZE(data->frames_stats) +
868 data->n_frames < ARRAY_SIZE(data->frames_stats) ?
869 _idx - data->n_frames :
870 _idx + data->n_frames;
871 idx %= ARRAY_SIZE(data->frames_stats);
872 /* Time stats are in us. */
873 return data->frames_stats[idx].stats[data->stat_selector] / data->time_dividor;
874 }
875
876 static float get_stat(void *_data, int _idx)
877 {
878 struct swapchain_data *data = (struct swapchain_data *) _data;
879 if ((ARRAY_SIZE(data->frames_stats) - _idx) > data->n_frames)
880 return 0.0f;
881 int idx = ARRAY_SIZE(data->frames_stats) +
882 data->n_frames < ARRAY_SIZE(data->frames_stats) ?
883 _idx - data->n_frames :
884 _idx + data->n_frames;
885 idx %= ARRAY_SIZE(data->frames_stats);
886 return data->frames_stats[idx].stats[data->stat_selector];
887 }
888
889 static void position_layer(struct swapchain_data *data)
890
891 {
892 struct device_data *device_data = data->device;
893 struct instance_data *instance_data = device_data->instance;
894 const float margin = 10.0f;
895
896 ImGui::SetNextWindowBgAlpha(0.5);
897 ImGui::SetNextWindowSize(data->window_size, ImGuiCond_Always);
898 switch (instance_data->params.position) {
899 case LAYER_POSITION_TOP_LEFT:
900 ImGui::SetNextWindowPos(ImVec2(margin, margin), ImGuiCond_Always);
901 break;
902 case LAYER_POSITION_TOP_RIGHT:
903 ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x - margin, margin),
904 ImGuiCond_Always);
905 break;
906 case LAYER_POSITION_BOTTOM_LEFT:
907 ImGui::SetNextWindowPos(ImVec2(margin, data->height - data->window_size.y - margin),
908 ImGuiCond_Always);
909 break;
910 case LAYER_POSITION_BOTTOM_RIGHT:
911 ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x - margin,
912 data->height - data->window_size.y - margin),
913 ImGuiCond_Always);
914 break;
915 }
916 }
917
918 static void compute_swapchain_display(struct swapchain_data *data)
919 {
920 struct device_data *device_data = data->device;
921 struct instance_data *instance_data = device_data->instance;
922
923 ImGui::SetCurrentContext(data->imgui_context);
924 ImGui::NewFrame();
925 position_layer(data);
926 ImGui::Begin("Mesa overlay");
927 ImGui::Text("Device: %s", device_data->properties.deviceName);
928
929 const char *format_name = vk_Format_to_str(data->format);
930 format_name = format_name ? (format_name + strlen("VK_FORMAT_")) : "unknown";
931 ImGui::Text("Swapchain format: %s", format_name);
932 ImGui::Text("Frames: %" PRIu64, data->n_frames);
933 if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_fps])
934 ImGui::Text("FPS: %.2f" , data->fps);
935
936 /* Recompute min/max */
937 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
938 data->stats_min.stats[s] = UINT64_MAX;
939 data->stats_max.stats[s] = 0;
940 }
941 for (uint32_t f = 0; f < MIN2(data->n_frames, ARRAY_SIZE(data->frames_stats)); f++) {
942 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
943 data->stats_min.stats[s] = MIN2(data->frames_stats[f].stats[s],
944 data->stats_min.stats[s]);
945 data->stats_max.stats[s] = MAX2(data->frames_stats[f].stats[s],
946 data->stats_max.stats[s]);
947 }
948 }
949 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
950 assert(data->stats_min.stats[s] != UINT64_MAX);
951 }
952
953 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++) {
954 if (!instance_data->params.enabled[s] ||
955 s == OVERLAY_PARAM_ENABLED_fps ||
956 s == OVERLAY_PARAM_ENABLED_frame)
957 continue;
958
959 char hash[40];
960 snprintf(hash, sizeof(hash), "##%s", overlay_param_names[s]);
961 data->stat_selector = (enum overlay_param_enabled) s;
962 data->time_dividor = 1000.0f;
963 if (s == OVERLAY_PARAM_ENABLED_gpu_timing)
964 data->time_dividor = 1000000.0f;
965
966 if (s == OVERLAY_PARAM_ENABLED_frame_timing ||
967 s == OVERLAY_PARAM_ENABLED_acquire_timing ||
968 s == OVERLAY_PARAM_ENABLED_present_timing ||
969 s == OVERLAY_PARAM_ENABLED_gpu_timing) {
970 double min_time = data->stats_min.stats[s] / data->time_dividor;
971 double max_time = data->stats_max.stats[s] / data->time_dividor;
972 ImGui::PlotHistogram(hash, get_time_stat, data,
973 ARRAY_SIZE(data->frames_stats), 0,
974 NULL, min_time, max_time,
975 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
976 ImGui::Text("%s: %.3fms [%.3f, %.3f]", overlay_param_names[s],
977 get_time_stat(data, ARRAY_SIZE(data->frames_stats) - 1),
978 min_time, max_time);
979 } else {
980 ImGui::PlotHistogram(hash, get_stat, data,
981 ARRAY_SIZE(data->frames_stats), 0,
982 NULL,
983 data->stats_min.stats[s],
984 data->stats_max.stats[s],
985 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
986 ImGui::Text("%s: %.0f [%" PRIu64 ", %" PRIu64 "]", overlay_param_names[s],
987 get_stat(data, ARRAY_SIZE(data->frames_stats) - 1),
988 data->stats_min.stats[s], data->stats_max.stats[s]);
989 }
990 }
991 data->window_size = ImVec2(data->window_size.x, ImGui::GetCursorPosY() + 10.0f);
992 ImGui::End();
993 ImGui::EndFrame();
994 ImGui::Render();
995 }
996
997 static uint32_t vk_memory_type(struct device_data *data,
998 VkMemoryPropertyFlags properties,
999 uint32_t type_bits)
1000 {
1001 VkPhysicalDeviceMemoryProperties prop;
1002 data->instance->vtable.GetPhysicalDeviceMemoryProperties(data->physical_device, &prop);
1003 for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
1004 if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
1005 return i;
1006 return 0xFFFFFFFF; // Unable to find memoryType
1007 }
1008
1009 static void ensure_swapchain_fonts(struct swapchain_data *data,
1010 VkCommandBuffer command_buffer)
1011 {
1012 if (data->font_uploaded)
1013 return;
1014
1015 data->font_uploaded = true;
1016
1017 struct device_data *device_data = data->device;
1018 ImGuiIO& io = ImGui::GetIO();
1019 unsigned char* pixels;
1020 int width, height;
1021 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1022 size_t upload_size = width * height * 4 * sizeof(char);
1023
1024 /* Upload buffer */
1025 VkBufferCreateInfo buffer_info = {};
1026 buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1027 buffer_info.size = upload_size;
1028 buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
1029 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1030 VK_CHECK(device_data->vtable.CreateBuffer(device_data->device, &buffer_info,
1031 NULL, &data->upload_font_buffer));
1032 VkMemoryRequirements upload_buffer_req;
1033 device_data->vtable.GetBufferMemoryRequirements(device_data->device,
1034 data->upload_font_buffer,
1035 &upload_buffer_req);
1036 VkMemoryAllocateInfo upload_alloc_info = {};
1037 upload_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1038 upload_alloc_info.allocationSize = upload_buffer_req.size;
1039 upload_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1040 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
1041 upload_buffer_req.memoryTypeBits);
1042 VK_CHECK(device_data->vtable.AllocateMemory(device_data->device,
1043 &upload_alloc_info,
1044 NULL,
1045 &data->upload_font_buffer_mem));
1046 VK_CHECK(device_data->vtable.BindBufferMemory(device_data->device,
1047 data->upload_font_buffer,
1048 data->upload_font_buffer_mem, 0));
1049
1050 /* Upload to Buffer */
1051 char* map = NULL;
1052 VK_CHECK(device_data->vtable.MapMemory(device_data->device,
1053 data->upload_font_buffer_mem,
1054 0, upload_size, 0, (void**)(&map)));
1055 memcpy(map, pixels, upload_size);
1056 VkMappedMemoryRange range[1] = {};
1057 range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1058 range[0].memory = data->upload_font_buffer_mem;
1059 range[0].size = upload_size;
1060 VK_CHECK(device_data->vtable.FlushMappedMemoryRanges(device_data->device, 1, range));
1061 device_data->vtable.UnmapMemory(device_data->device,
1062 data->upload_font_buffer_mem);
1063
1064 /* Copy buffer to image */
1065 VkImageMemoryBarrier copy_barrier[1] = {};
1066 copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1067 copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1068 copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1069 copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1070 copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1071 copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1072 copy_barrier[0].image = data->font_image;
1073 copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1074 copy_barrier[0].subresourceRange.levelCount = 1;
1075 copy_barrier[0].subresourceRange.layerCount = 1;
1076 device_data->vtable.CmdPipelineBarrier(command_buffer,
1077 VK_PIPELINE_STAGE_HOST_BIT,
1078 VK_PIPELINE_STAGE_TRANSFER_BIT,
1079 0, 0, NULL, 0, NULL,
1080 1, copy_barrier);
1081
1082 VkBufferImageCopy region = {};
1083 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1084 region.imageSubresource.layerCount = 1;
1085 region.imageExtent.width = width;
1086 region.imageExtent.height = height;
1087 region.imageExtent.depth = 1;
1088 device_data->vtable.CmdCopyBufferToImage(command_buffer,
1089 data->upload_font_buffer,
1090 data->font_image,
1091 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
1092 1, &region);
1093
1094 VkImageMemoryBarrier use_barrier[1] = {};
1095 use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1096 use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
1097 use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
1098 use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
1099 use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1100 use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1101 use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
1102 use_barrier[0].image = data->font_image;
1103 use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1104 use_barrier[0].subresourceRange.levelCount = 1;
1105 use_barrier[0].subresourceRange.layerCount = 1;
1106 device_data->vtable.CmdPipelineBarrier(command_buffer,
1107 VK_PIPELINE_STAGE_TRANSFER_BIT,
1108 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
1109 0,
1110 0, NULL,
1111 0, NULL,
1112 1, use_barrier);
1113
1114 /* Store our identifier */
1115 io.Fonts->TexID = (ImTextureID)(intptr_t)data->font_image;
1116 }
1117
1118 static void CreateOrResizeBuffer(struct device_data *data,
1119 VkBuffer *buffer,
1120 VkDeviceMemory *buffer_memory,
1121 VkDeviceSize *buffer_size,
1122 size_t new_size, VkBufferUsageFlagBits usage)
1123 {
1124 if (*buffer != VK_NULL_HANDLE)
1125 data->vtable.DestroyBuffer(data->device, *buffer, NULL);
1126 if (*buffer_memory)
1127 data->vtable.FreeMemory(data->device, *buffer_memory, NULL);
1128
1129 VkBufferCreateInfo buffer_info = {};
1130 buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
1131 buffer_info.size = new_size;
1132 buffer_info.usage = usage;
1133 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1134 VK_CHECK(data->vtable.CreateBuffer(data->device, &buffer_info, NULL, buffer));
1135
1136 VkMemoryRequirements req;
1137 data->vtable.GetBufferMemoryRequirements(data->device, *buffer, &req);
1138 VkMemoryAllocateInfo alloc_info = {};
1139 alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1140 alloc_info.allocationSize = req.size;
1141 alloc_info.memoryTypeIndex =
1142 vk_memory_type(data, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
1143 VK_CHECK(data->vtable.AllocateMemory(data->device, &alloc_info, NULL, buffer_memory));
1144
1145 VK_CHECK(data->vtable.BindBufferMemory(data->device, *buffer, *buffer_memory, 0));
1146 *buffer_size = new_size;
1147 }
1148
1149 static struct overlay_draw *render_swapchain_display(struct swapchain_data *data,
1150 struct queue_data *present_queue,
1151 const VkSemaphore *wait_semaphores,
1152 unsigned n_wait_semaphores,
1153 unsigned image_index)
1154 {
1155 ImDrawData* draw_data = ImGui::GetDrawData();
1156 if (draw_data->TotalVtxCount == 0)
1157 return NULL;
1158
1159 struct device_data *device_data = data->device;
1160 struct overlay_draw *draw = get_overlay_draw(data);
1161
1162 device_data->vtable.ResetCommandBuffer(draw->command_buffer, 0);
1163
1164 VkRenderPassBeginInfo render_pass_info = {};
1165 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
1166 render_pass_info.renderPass = data->render_pass;
1167 render_pass_info.framebuffer = data->framebuffers[image_index];
1168 render_pass_info.renderArea.extent.width = data->width;
1169 render_pass_info.renderArea.extent.height = data->height;
1170
1171 VkCommandBufferBeginInfo buffer_begin_info = {};
1172 buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
1173
1174 device_data->vtable.BeginCommandBuffer(draw->command_buffer, &buffer_begin_info);
1175
1176 ensure_swapchain_fonts(data, draw->command_buffer);
1177
1178 /* Bounce the image to display back to color attachment layout for
1179 * rendering on top of it.
1180 */
1181 VkImageMemoryBarrier imb;
1182 imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1183 imb.pNext = nullptr;
1184 imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1185 imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1186 imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1187 imb.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1188 imb.image = data->images[image_index];
1189 imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1190 imb.subresourceRange.baseMipLevel = 0;
1191 imb.subresourceRange.levelCount = 1;
1192 imb.subresourceRange.baseArrayLayer = 0;
1193 imb.subresourceRange.layerCount = 1;
1194 imb.srcQueueFamilyIndex = present_queue->family_index;
1195 imb.dstQueueFamilyIndex = device_data->graphic_queue->family_index;
1196 device_data->vtable.CmdPipelineBarrier(draw->command_buffer,
1197 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1198 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1199 0, /* dependency flags */
1200 0, nullptr, /* memory barriers */
1201 0, nullptr, /* buffer memory barriers */
1202 1, &imb); /* image memory barriers */
1203
1204 device_data->vtable.CmdBeginRenderPass(draw->command_buffer, &render_pass_info,
1205 VK_SUBPASS_CONTENTS_INLINE);
1206
1207 /* Create/Resize vertex & index buffers */
1208 size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
1209 size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
1210 if (draw->vertex_buffer_size < vertex_size) {
1211 CreateOrResizeBuffer(device_data,
1212 &draw->vertex_buffer,
1213 &draw->vertex_buffer_mem,
1214 &draw->vertex_buffer_size,
1215 vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
1216 }
1217 if (draw->index_buffer_size < index_size) {
1218 CreateOrResizeBuffer(device_data,
1219 &draw->index_buffer,
1220 &draw->index_buffer_mem,
1221 &draw->index_buffer_size,
1222 index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
1223 }
1224
1225 /* Upload vertex & index data */
1226 ImDrawVert* vtx_dst = NULL;
1227 ImDrawIdx* idx_dst = NULL;
1228 VK_CHECK(device_data->vtable.MapMemory(device_data->device, draw->vertex_buffer_mem,
1229 0, vertex_size, 0, (void**)(&vtx_dst)));
1230 VK_CHECK(device_data->vtable.MapMemory(device_data->device, draw->index_buffer_mem,
1231 0, index_size, 0, (void**)(&idx_dst)));
1232 for (int n = 0; n < draw_data->CmdListsCount; n++)
1233 {
1234 const ImDrawList* cmd_list = draw_data->CmdLists[n];
1235 memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
1236 memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
1237 vtx_dst += cmd_list->VtxBuffer.Size;
1238 idx_dst += cmd_list->IdxBuffer.Size;
1239 }
1240 VkMappedMemoryRange range[2] = {};
1241 range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1242 range[0].memory = draw->vertex_buffer_mem;
1243 range[0].size = VK_WHOLE_SIZE;
1244 range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
1245 range[1].memory = draw->index_buffer_mem;
1246 range[1].size = VK_WHOLE_SIZE;
1247 VK_CHECK(device_data->vtable.FlushMappedMemoryRanges(device_data->device, 2, range));
1248 device_data->vtable.UnmapMemory(device_data->device, draw->vertex_buffer_mem);
1249 device_data->vtable.UnmapMemory(device_data->device, draw->index_buffer_mem);
1250
1251 /* Bind pipeline and descriptor sets */
1252 device_data->vtable.CmdBindPipeline(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, data->pipeline);
1253 VkDescriptorSet desc_set[1] = { data->descriptor_set };
1254 device_data->vtable.CmdBindDescriptorSets(draw->command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
1255 data->pipeline_layout, 0, 1, desc_set, 0, NULL);
1256
1257 /* Bind vertex & index buffers */
1258 VkBuffer vertex_buffers[1] = { draw->vertex_buffer };
1259 VkDeviceSize vertex_offset[1] = { 0 };
1260 device_data->vtable.CmdBindVertexBuffers(draw->command_buffer, 0, 1, vertex_buffers, vertex_offset);
1261 device_data->vtable.CmdBindIndexBuffer(draw->command_buffer, draw->index_buffer, 0, VK_INDEX_TYPE_UINT16);
1262
1263 /* Setup viewport */
1264 VkViewport viewport;
1265 viewport.x = 0;
1266 viewport.y = 0;
1267 viewport.width = draw_data->DisplaySize.x;
1268 viewport.height = draw_data->DisplaySize.y;
1269 viewport.minDepth = 0.0f;
1270 viewport.maxDepth = 1.0f;
1271 device_data->vtable.CmdSetViewport(draw->command_buffer, 0, 1, &viewport);
1272
1273
1274 /* Setup scale and translation through push constants :
1275 *
1276 * Our visible imgui space lies from draw_data->DisplayPos (top left) to
1277 * draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin
1278 * is typically (0,0) for single viewport apps.
1279 */
1280 float scale[2];
1281 scale[0] = 2.0f / draw_data->DisplaySize.x;
1282 scale[1] = 2.0f / draw_data->DisplaySize.y;
1283 float translate[2];
1284 translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
1285 translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
1286 device_data->vtable.CmdPushConstants(draw->command_buffer, data->pipeline_layout,
1287 VK_SHADER_STAGE_VERTEX_BIT,
1288 sizeof(float) * 0, sizeof(float) * 2, scale);
1289 device_data->vtable.CmdPushConstants(draw->command_buffer, data->pipeline_layout,
1290 VK_SHADER_STAGE_VERTEX_BIT,
1291 sizeof(float) * 2, sizeof(float) * 2, translate);
1292
1293 // Render the command lists:
1294 int vtx_offset = 0;
1295 int idx_offset = 0;
1296 ImVec2 display_pos = draw_data->DisplayPos;
1297 for (int n = 0; n < draw_data->CmdListsCount; n++)
1298 {
1299 const ImDrawList* cmd_list = draw_data->CmdLists[n];
1300 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
1301 {
1302 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
1303 // Apply scissor/clipping rectangle
1304 // FIXME: We could clamp width/height based on clamped min/max values.
1305 VkRect2D scissor;
1306 scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
1307 scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
1308 scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
1309 scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
1310 device_data->vtable.CmdSetScissor(draw->command_buffer, 0, 1, &scissor);
1311
1312 // Draw
1313 device_data->vtable.CmdDrawIndexed(draw->command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
1314
1315 idx_offset += pcmd->ElemCount;
1316 }
1317 vtx_offset += cmd_list->VtxBuffer.Size;
1318 }
1319
1320 device_data->vtable.CmdEndRenderPass(draw->command_buffer);
1321
1322 if (device_data->graphic_queue->family_index != present_queue->family_index)
1323 {
1324 /* Transfer the image back to the present queue family
1325 * image layout was already changed to present by the render pass
1326 */
1327 imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1328 imb.pNext = nullptr;
1329 imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1330 imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1331 imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1332 imb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1333 imb.image = data->images[image_index];
1334 imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1335 imb.subresourceRange.baseMipLevel = 0;
1336 imb.subresourceRange.levelCount = 1;
1337 imb.subresourceRange.baseArrayLayer = 0;
1338 imb.subresourceRange.layerCount = 1;
1339 imb.srcQueueFamilyIndex = device_data->graphic_queue->family_index;
1340 imb.dstQueueFamilyIndex = present_queue->family_index;
1341 device_data->vtable.CmdPipelineBarrier(draw->command_buffer,
1342 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1343 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1344 0, /* dependency flags */
1345 0, nullptr, /* memory barriers */
1346 0, nullptr, /* buffer memory barriers */
1347 1, &imb); /* image memory barriers */
1348 }
1349
1350 device_data->vtable.EndCommandBuffer(draw->command_buffer);
1351
1352 VkPipelineStageFlags *stages_wait = (VkPipelineStageFlags*) malloc(sizeof(VkPipelineStageFlags) * n_wait_semaphores);
1353 for (unsigned i = 0; i < n_wait_semaphores; i++)
1354 {
1355 // wait in the fragment stage until the swapchain image is ready
1356 stages_wait[i] = VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT;
1357 }
1358
1359 VkSubmitInfo submit_info = {};
1360 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1361 submit_info.commandBufferCount = 1;
1362 submit_info.pCommandBuffers = &draw->command_buffer;
1363 submit_info.pWaitDstStageMask = stages_wait;
1364 submit_info.waitSemaphoreCount = n_wait_semaphores;
1365 submit_info.pWaitSemaphores = wait_semaphores;
1366 submit_info.signalSemaphoreCount = 1;
1367 submit_info.pSignalSemaphores = &draw->semaphore;
1368
1369 device_data->vtable.QueueSubmit(device_data->graphic_queue->queue, 1, &submit_info, draw->fence);
1370
1371 free(stages_wait);
1372
1373 return draw;
1374 }
1375
1376 static const uint32_t overlay_vert_spv[] = {
1377 #include "overlay.vert.spv.h"
1378 };
1379 static const uint32_t overlay_frag_spv[] = {
1380 #include "overlay.frag.spv.h"
1381 };
1382
1383 static void setup_swapchain_data_pipeline(struct swapchain_data *data)
1384 {
1385 struct device_data *device_data = data->device;
1386 VkShaderModule vert_module, frag_module;
1387
1388 /* Create shader modules */
1389 VkShaderModuleCreateInfo vert_info = {};
1390 vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1391 vert_info.codeSize = sizeof(overlay_vert_spv);
1392 vert_info.pCode = overlay_vert_spv;
1393 VK_CHECK(device_data->vtable.CreateShaderModule(device_data->device,
1394 &vert_info, NULL, &vert_module));
1395 VkShaderModuleCreateInfo frag_info = {};
1396 frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1397 frag_info.codeSize = sizeof(overlay_frag_spv);
1398 frag_info.pCode = (uint32_t*)overlay_frag_spv;
1399 VK_CHECK(device_data->vtable.CreateShaderModule(device_data->device,
1400 &frag_info, NULL, &frag_module));
1401
1402 /* Font sampler */
1403 VkSamplerCreateInfo sampler_info = {};
1404 sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
1405 sampler_info.magFilter = VK_FILTER_LINEAR;
1406 sampler_info.minFilter = VK_FILTER_LINEAR;
1407 sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1408 sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1409 sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1410 sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1411 sampler_info.minLod = -1000;
1412 sampler_info.maxLod = 1000;
1413 sampler_info.maxAnisotropy = 1.0f;
1414 VK_CHECK(device_data->vtable.CreateSampler(device_data->device, &sampler_info,
1415 NULL, &data->font_sampler));
1416
1417 /* Descriptor pool */
1418 VkDescriptorPoolSize sampler_pool_size = {};
1419 sampler_pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1420 sampler_pool_size.descriptorCount = 1;
1421 VkDescriptorPoolCreateInfo desc_pool_info = {};
1422 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1423 desc_pool_info.maxSets = 1;
1424 desc_pool_info.poolSizeCount = 1;
1425 desc_pool_info.pPoolSizes = &sampler_pool_size;
1426 VK_CHECK(device_data->vtable.CreateDescriptorPool(device_data->device,
1427 &desc_pool_info,
1428 NULL, &data->descriptor_pool));
1429
1430 /* Descriptor layout */
1431 VkSampler sampler[1] = { data->font_sampler };
1432 VkDescriptorSetLayoutBinding binding[1] = {};
1433 binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1434 binding[0].descriptorCount = 1;
1435 binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1436 binding[0].pImmutableSamplers = sampler;
1437 VkDescriptorSetLayoutCreateInfo set_layout_info = {};
1438 set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
1439 set_layout_info.bindingCount = 1;
1440 set_layout_info.pBindings = binding;
1441 VK_CHECK(device_data->vtable.CreateDescriptorSetLayout(device_data->device,
1442 &set_layout_info,
1443 NULL, &data->descriptor_layout));
1444
1445 /* Descriptor set */
1446 VkDescriptorSetAllocateInfo alloc_info = {};
1447 alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1448 alloc_info.descriptorPool = data->descriptor_pool;
1449 alloc_info.descriptorSetCount = 1;
1450 alloc_info.pSetLayouts = &data->descriptor_layout;
1451 VK_CHECK(device_data->vtable.AllocateDescriptorSets(device_data->device,
1452 &alloc_info,
1453 &data->descriptor_set));
1454
1455 /* Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full
1456 * 3d projection matrix
1457 */
1458 VkPushConstantRange push_constants[1] = {};
1459 push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
1460 push_constants[0].offset = sizeof(float) * 0;
1461 push_constants[0].size = sizeof(float) * 4;
1462 VkPipelineLayoutCreateInfo layout_info = {};
1463 layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
1464 layout_info.setLayoutCount = 1;
1465 layout_info.pSetLayouts = &data->descriptor_layout;
1466 layout_info.pushConstantRangeCount = 1;
1467 layout_info.pPushConstantRanges = push_constants;
1468 VK_CHECK(device_data->vtable.CreatePipelineLayout(device_data->device,
1469 &layout_info,
1470 NULL, &data->pipeline_layout));
1471
1472 VkPipelineShaderStageCreateInfo stage[2] = {};
1473 stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1474 stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
1475 stage[0].module = vert_module;
1476 stage[0].pName = "main";
1477 stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1478 stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
1479 stage[1].module = frag_module;
1480 stage[1].pName = "main";
1481
1482 VkVertexInputBindingDescription binding_desc[1] = {};
1483 binding_desc[0].stride = sizeof(ImDrawVert);
1484 binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1485
1486 VkVertexInputAttributeDescription attribute_desc[3] = {};
1487 attribute_desc[0].location = 0;
1488 attribute_desc[0].binding = binding_desc[0].binding;
1489 attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
1490 attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
1491 attribute_desc[1].location = 1;
1492 attribute_desc[1].binding = binding_desc[0].binding;
1493 attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
1494 attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
1495 attribute_desc[2].location = 2;
1496 attribute_desc[2].binding = binding_desc[0].binding;
1497 attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
1498 attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
1499
1500 VkPipelineVertexInputStateCreateInfo vertex_info = {};
1501 vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1502 vertex_info.vertexBindingDescriptionCount = 1;
1503 vertex_info.pVertexBindingDescriptions = binding_desc;
1504 vertex_info.vertexAttributeDescriptionCount = 3;
1505 vertex_info.pVertexAttributeDescriptions = attribute_desc;
1506
1507 VkPipelineInputAssemblyStateCreateInfo ia_info = {};
1508 ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1509 ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1510
1511 VkPipelineViewportStateCreateInfo viewport_info = {};
1512 viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1513 viewport_info.viewportCount = 1;
1514 viewport_info.scissorCount = 1;
1515
1516 VkPipelineRasterizationStateCreateInfo raster_info = {};
1517 raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1518 raster_info.polygonMode = VK_POLYGON_MODE_FILL;
1519 raster_info.cullMode = VK_CULL_MODE_NONE;
1520 raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1521 raster_info.lineWidth = 1.0f;
1522
1523 VkPipelineMultisampleStateCreateInfo ms_info = {};
1524 ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1525 ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
1526
1527 VkPipelineColorBlendAttachmentState color_attachment[1] = {};
1528 color_attachment[0].blendEnable = VK_TRUE;
1529 color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
1530 color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1531 color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
1532 color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1533 color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
1534 color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
1535 color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
1536 VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1537
1538 VkPipelineDepthStencilStateCreateInfo depth_info = {};
1539 depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1540
1541 VkPipelineColorBlendStateCreateInfo blend_info = {};
1542 blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1543 blend_info.attachmentCount = 1;
1544 blend_info.pAttachments = color_attachment;
1545
1546 VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
1547 VkPipelineDynamicStateCreateInfo dynamic_state = {};
1548 dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1549 dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
1550 dynamic_state.pDynamicStates = dynamic_states;
1551
1552 VkGraphicsPipelineCreateInfo info = {};
1553 info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1554 info.flags = 0;
1555 info.stageCount = 2;
1556 info.pStages = stage;
1557 info.pVertexInputState = &vertex_info;
1558 info.pInputAssemblyState = &ia_info;
1559 info.pViewportState = &viewport_info;
1560 info.pRasterizationState = &raster_info;
1561 info.pMultisampleState = &ms_info;
1562 info.pDepthStencilState = &depth_info;
1563 info.pColorBlendState = &blend_info;
1564 info.pDynamicState = &dynamic_state;
1565 info.layout = data->pipeline_layout;
1566 info.renderPass = data->render_pass;
1567 VK_CHECK(
1568 device_data->vtable.CreateGraphicsPipelines(device_data->device, VK_NULL_HANDLE,
1569 1, &info,
1570 NULL, &data->pipeline));
1571
1572 device_data->vtable.DestroyShaderModule(device_data->device, vert_module, NULL);
1573 device_data->vtable.DestroyShaderModule(device_data->device, frag_module, NULL);
1574
1575 ImGuiIO& io = ImGui::GetIO();
1576 unsigned char* pixels;
1577 int width, height;
1578 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1579
1580 /* Font image */
1581 VkImageCreateInfo image_info = {};
1582 image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1583 image_info.imageType = VK_IMAGE_TYPE_2D;
1584 image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1585 image_info.extent.width = width;
1586 image_info.extent.height = height;
1587 image_info.extent.depth = 1;
1588 image_info.mipLevels = 1;
1589 image_info.arrayLayers = 1;
1590 image_info.samples = VK_SAMPLE_COUNT_1_BIT;
1591 image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
1592 image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1593 image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1594 image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1595 VK_CHECK(device_data->vtable.CreateImage(device_data->device, &image_info,
1596 NULL, &data->font_image));
1597 VkMemoryRequirements font_image_req;
1598 device_data->vtable.GetImageMemoryRequirements(device_data->device,
1599 data->font_image, &font_image_req);
1600 VkMemoryAllocateInfo image_alloc_info = {};
1601 image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1602 image_alloc_info.allocationSize = font_image_req.size;
1603 image_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1604 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1605 font_image_req.memoryTypeBits);
1606 VK_CHECK(device_data->vtable.AllocateMemory(device_data->device, &image_alloc_info,
1607 NULL, &data->font_mem));
1608 VK_CHECK(device_data->vtable.BindImageMemory(device_data->device,
1609 data->font_image,
1610 data->font_mem, 0));
1611
1612 /* Font image view */
1613 VkImageViewCreateInfo view_info = {};
1614 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1615 view_info.image = data->font_image;
1616 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1617 view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1618 view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1619 view_info.subresourceRange.levelCount = 1;
1620 view_info.subresourceRange.layerCount = 1;
1621 VK_CHECK(device_data->vtable.CreateImageView(device_data->device, &view_info,
1622 NULL, &data->font_image_view));
1623
1624 /* Descriptor set */
1625 VkDescriptorImageInfo desc_image[1] = {};
1626 desc_image[0].sampler = data->font_sampler;
1627 desc_image[0].imageView = data->font_image_view;
1628 desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1629 VkWriteDescriptorSet write_desc[1] = {};
1630 write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1631 write_desc[0].dstSet = data->descriptor_set;
1632 write_desc[0].descriptorCount = 1;
1633 write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1634 write_desc[0].pImageInfo = desc_image;
1635 device_data->vtable.UpdateDescriptorSets(device_data->device, 1, write_desc, 0, NULL);
1636 }
1637
1638 static void setup_swapchain_data(struct swapchain_data *data,
1639 const VkSwapchainCreateInfoKHR *pCreateInfo)
1640 {
1641 data->width = pCreateInfo->imageExtent.width;
1642 data->height = pCreateInfo->imageExtent.height;
1643 data->format = pCreateInfo->imageFormat;
1644
1645 data->imgui_context = ImGui::CreateContext();
1646 ImGui::SetCurrentContext(data->imgui_context);
1647
1648 ImGui::GetIO().IniFilename = NULL;
1649 ImGui::GetIO().DisplaySize = ImVec2((float)data->width, (float)data->height);
1650
1651 struct device_data *device_data = data->device;
1652
1653 /* Render pass */
1654 VkAttachmentDescription attachment_desc = {};
1655 attachment_desc.format = pCreateInfo->imageFormat;
1656 attachment_desc.samples = VK_SAMPLE_COUNT_1_BIT;
1657 attachment_desc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
1658 attachment_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
1659 attachment_desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
1660 attachment_desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
1661 attachment_desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1662 attachment_desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1663 VkAttachmentReference color_attachment = {};
1664 color_attachment.attachment = 0;
1665 color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1666 VkSubpassDescription subpass = {};
1667 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
1668 subpass.colorAttachmentCount = 1;
1669 subpass.pColorAttachments = &color_attachment;
1670 VkSubpassDependency dependency = {};
1671 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
1672 dependency.dstSubpass = 0;
1673 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1674 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1675 dependency.srcAccessMask = 0;
1676 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1677 VkRenderPassCreateInfo render_pass_info = {};
1678 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
1679 render_pass_info.attachmentCount = 1;
1680 render_pass_info.pAttachments = &attachment_desc;
1681 render_pass_info.subpassCount = 1;
1682 render_pass_info.pSubpasses = &subpass;
1683 render_pass_info.dependencyCount = 1;
1684 render_pass_info.pDependencies = &dependency;
1685 VK_CHECK(device_data->vtable.CreateRenderPass(device_data->device,
1686 &render_pass_info,
1687 NULL, &data->render_pass));
1688
1689 setup_swapchain_data_pipeline(data);
1690
1691 VK_CHECK(device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1692 data->swapchain,
1693 &data->n_images,
1694 NULL));
1695
1696 data->images = ralloc_array(data, VkImage, data->n_images);
1697 data->image_views = ralloc_array(data, VkImageView, data->n_images);
1698 data->framebuffers = ralloc_array(data, VkFramebuffer, data->n_images);
1699
1700 VK_CHECK(device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1701 data->swapchain,
1702 &data->n_images,
1703 data->images));
1704
1705 /* Image views */
1706 VkImageViewCreateInfo view_info = {};
1707 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1708 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1709 view_info.format = pCreateInfo->imageFormat;
1710 view_info.components.r = VK_COMPONENT_SWIZZLE_R;
1711 view_info.components.g = VK_COMPONENT_SWIZZLE_G;
1712 view_info.components.b = VK_COMPONENT_SWIZZLE_B;
1713 view_info.components.a = VK_COMPONENT_SWIZZLE_A;
1714 view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1715 for (uint32_t i = 0; i < data->n_images; i++) {
1716 view_info.image = data->images[i];
1717 VK_CHECK(device_data->vtable.CreateImageView(device_data->device,
1718 &view_info, NULL,
1719 &data->image_views[i]));
1720 }
1721
1722 /* Framebuffers */
1723 VkImageView attachment[1];
1724 VkFramebufferCreateInfo fb_info = {};
1725 fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1726 fb_info.renderPass = data->render_pass;
1727 fb_info.attachmentCount = 1;
1728 fb_info.pAttachments = attachment;
1729 fb_info.width = data->width;
1730 fb_info.height = data->height;
1731 fb_info.layers = 1;
1732 for (uint32_t i = 0; i < data->n_images; i++) {
1733 attachment[0] = data->image_views[i];
1734 VK_CHECK(device_data->vtable.CreateFramebuffer(device_data->device, &fb_info,
1735 NULL, &data->framebuffers[i]));
1736 }
1737
1738 /* Command buffer pool */
1739 VkCommandPoolCreateInfo cmd_buffer_pool_info = {};
1740 cmd_buffer_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1741 cmd_buffer_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1742 cmd_buffer_pool_info.queueFamilyIndex = device_data->graphic_queue->family_index;
1743 VK_CHECK(device_data->vtable.CreateCommandPool(device_data->device,
1744 &cmd_buffer_pool_info,
1745 NULL, &data->command_pool));
1746 }
1747
1748 static void shutdown_swapchain_data(struct swapchain_data *data)
1749 {
1750 struct device_data *device_data = data->device;
1751
1752 list_for_each_entry_safe(struct overlay_draw, draw, &data->draws, link) {
1753 device_data->vtable.DestroySemaphore(device_data->device, draw->semaphore, NULL);
1754 device_data->vtable.DestroyFence(device_data->device, draw->fence, NULL);
1755 device_data->vtable.DestroyBuffer(device_data->device, draw->vertex_buffer, NULL);
1756 device_data->vtable.DestroyBuffer(device_data->device, draw->index_buffer, NULL);
1757 device_data->vtable.FreeMemory(device_data->device, draw->vertex_buffer_mem, NULL);
1758 device_data->vtable.FreeMemory(device_data->device, draw->index_buffer_mem, NULL);
1759 }
1760
1761 for (uint32_t i = 0; i < data->n_images; i++) {
1762 device_data->vtable.DestroyImageView(device_data->device, data->image_views[i], NULL);
1763 device_data->vtable.DestroyFramebuffer(device_data->device, data->framebuffers[i], NULL);
1764 }
1765
1766 device_data->vtable.DestroyRenderPass(device_data->device, data->render_pass, NULL);
1767
1768 device_data->vtable.DestroyCommandPool(device_data->device, data->command_pool, NULL);
1769
1770 device_data->vtable.DestroyPipeline(device_data->device, data->pipeline, NULL);
1771 device_data->vtable.DestroyPipelineLayout(device_data->device, data->pipeline_layout, NULL);
1772
1773 device_data->vtable.DestroyDescriptorPool(device_data->device,
1774 data->descriptor_pool, NULL);
1775 device_data->vtable.DestroyDescriptorSetLayout(device_data->device,
1776 data->descriptor_layout, NULL);
1777
1778 device_data->vtable.DestroySampler(device_data->device, data->font_sampler, NULL);
1779 device_data->vtable.DestroyImageView(device_data->device, data->font_image_view, NULL);
1780 device_data->vtable.DestroyImage(device_data->device, data->font_image, NULL);
1781 device_data->vtable.FreeMemory(device_data->device, data->font_mem, NULL);
1782
1783 device_data->vtable.DestroyBuffer(device_data->device, data->upload_font_buffer, NULL);
1784 device_data->vtable.FreeMemory(device_data->device, data->upload_font_buffer_mem, NULL);
1785
1786 ImGui::DestroyContext(data->imgui_context);
1787 }
1788
1789 static struct overlay_draw *before_present(struct swapchain_data *swapchain_data,
1790 struct queue_data *present_queue,
1791 const VkSemaphore *wait_semaphores,
1792 unsigned n_wait_semaphores,
1793 unsigned imageIndex)
1794 {
1795 struct instance_data *instance_data = swapchain_data->device->instance;
1796 struct overlay_draw *draw = NULL;
1797
1798 snapshot_swapchain_frame(swapchain_data);
1799
1800 if (!instance_data->params.no_display && swapchain_data->n_frames > 0) {
1801 compute_swapchain_display(swapchain_data);
1802 draw = render_swapchain_display(swapchain_data, present_queue,
1803 wait_semaphores, n_wait_semaphores,
1804 imageIndex);
1805 }
1806
1807 return draw;
1808 }
1809
1810 static VkResult overlay_CreateSwapchainKHR(
1811 VkDevice device,
1812 const VkSwapchainCreateInfoKHR* pCreateInfo,
1813 const VkAllocationCallbacks* pAllocator,
1814 VkSwapchainKHR* pSwapchain)
1815 {
1816 struct device_data *device_data = FIND(struct device_data, device);
1817 VkResult result = device_data->vtable.CreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
1818 if (result != VK_SUCCESS) return result;
1819
1820 struct swapchain_data *swapchain_data = new_swapchain_data(*pSwapchain, device_data);
1821 setup_swapchain_data(swapchain_data, pCreateInfo);
1822 return result;
1823 }
1824
1825 static void overlay_DestroySwapchainKHR(
1826 VkDevice device,
1827 VkSwapchainKHR swapchain,
1828 const VkAllocationCallbacks* pAllocator)
1829 {
1830 struct swapchain_data *swapchain_data =
1831 FIND(struct swapchain_data, swapchain);
1832
1833 shutdown_swapchain_data(swapchain_data);
1834 swapchain_data->device->vtable.DestroySwapchainKHR(device, swapchain, pAllocator);
1835 destroy_swapchain_data(swapchain_data);
1836 }
1837
1838 static VkResult overlay_QueuePresentKHR(
1839 VkQueue queue,
1840 const VkPresentInfoKHR* pPresentInfo)
1841 {
1842 struct queue_data *queue_data = FIND(struct queue_data, queue);
1843 struct device_data *device_data = queue_data->device;
1844 struct instance_data *instance_data = device_data->instance;
1845 uint32_t query_results[OVERLAY_QUERY_COUNT];
1846
1847 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_frame]++;
1848
1849 if (list_length(&queue_data->running_command_buffer) > 0) {
1850 /* Before getting the query results, make sure the operations have
1851 * completed.
1852 */
1853 VK_CHECK(device_data->vtable.ResetFences(device_data->device,
1854 1, &queue_data->queries_fence));
1855 VK_CHECK(device_data->vtable.QueueSubmit(queue, 0, NULL, queue_data->queries_fence));
1856 VK_CHECK(device_data->vtable.WaitForFences(device_data->device,
1857 1, &queue_data->queries_fence,
1858 VK_FALSE, UINT64_MAX));
1859
1860 /* Now get the results. */
1861 list_for_each_entry_safe(struct command_buffer_data, cmd_buffer_data,
1862 &queue_data->running_command_buffer, link) {
1863 list_delinit(&cmd_buffer_data->link);
1864
1865 if (cmd_buffer_data->pipeline_query_pool) {
1866 memset(query_results, 0, sizeof(query_results));
1867 VK_CHECK(device_data->vtable.GetQueryPoolResults(device_data->device,
1868 cmd_buffer_data->pipeline_query_pool,
1869 cmd_buffer_data->query_index, 1,
1870 sizeof(uint32_t) * OVERLAY_QUERY_COUNT,
1871 query_results, 0, VK_QUERY_RESULT_WAIT_BIT));
1872
1873 for (uint32_t i = OVERLAY_PARAM_ENABLED_vertices;
1874 i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
1875 device_data->frame_stats.stats[i] += query_results[i - OVERLAY_PARAM_ENABLED_vertices];
1876 }
1877 }
1878 if (cmd_buffer_data->timestamp_query_pool) {
1879 uint64_t gpu_timestamps[2] = { 0 };
1880 VK_CHECK(device_data->vtable.GetQueryPoolResults(device_data->device,
1881 cmd_buffer_data->timestamp_query_pool,
1882 cmd_buffer_data->query_index * 2, 2,
1883 2 * sizeof(uint64_t), gpu_timestamps, sizeof(uint64_t),
1884 VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT));
1885
1886 gpu_timestamps[0] &= queue_data->timestamp_mask;
1887 gpu_timestamps[1] &= queue_data->timestamp_mask;
1888 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_gpu_timing] +=
1889 (gpu_timestamps[1] - gpu_timestamps[0]) *
1890 device_data->properties.limits.timestampPeriod;
1891 }
1892 }
1893 }
1894
1895 /* Otherwise we need to add our overlay drawing semaphore to the list of
1896 * semaphores to wait on. If we don't do that the presented picture might
1897 * be have incomplete overlay drawings.
1898 */
1899 VkResult result = VK_SUCCESS;
1900 if (instance_data->params.no_display) {
1901 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1902 VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1903 struct swapchain_data *swapchain_data =
1904 FIND(struct swapchain_data, swapchain);
1905
1906 uint32_t image_index = pPresentInfo->pImageIndices[i];
1907
1908 before_present(swapchain_data,
1909 queue_data,
1910 pPresentInfo->pWaitSemaphores,
1911 pPresentInfo->waitSemaphoreCount,
1912 image_index);
1913
1914 VkPresentInfoKHR present_info = *pPresentInfo;
1915 present_info.swapchainCount = 1;
1916 present_info.pSwapchains = &swapchain;
1917 present_info.pImageIndices = &image_index;
1918
1919 uint64_t ts0 = os_time_get();
1920 result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1921 uint64_t ts1 = os_time_get();
1922 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1923 }
1924 } else {
1925 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1926 VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1927 struct swapchain_data *swapchain_data =
1928 FIND(struct swapchain_data, swapchain);
1929
1930 uint32_t image_index = pPresentInfo->pImageIndices[i];
1931
1932 VkPresentInfoKHR present_info = *pPresentInfo;
1933 present_info.swapchainCount = 1;
1934 present_info.pSwapchains = &swapchain;
1935 present_info.pImageIndices = &image_index;
1936
1937 struct overlay_draw *draw = before_present(swapchain_data,
1938 queue_data,
1939 pPresentInfo->pWaitSemaphores,
1940 pPresentInfo->waitSemaphoreCount,
1941 image_index);
1942
1943 /* Because the submission of the overlay draw waits on the semaphores
1944 * handed for present, we don't need to have this present operation
1945 * wait on them as well, we can just wait on the overlay submission
1946 * semaphore.
1947 */
1948 present_info.pWaitSemaphores = &draw->semaphore;
1949 present_info.waitSemaphoreCount = 1;
1950
1951 uint64_t ts0 = os_time_get();
1952 VkResult chain_result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1953 uint64_t ts1 = os_time_get();
1954 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1955 if (pPresentInfo->pResults)
1956 pPresentInfo->pResults[i] = chain_result;
1957 if (chain_result != VK_SUCCESS && result == VK_SUCCESS)
1958 result = chain_result;
1959 }
1960 }
1961 return result;
1962 }
1963
1964 static VkResult overlay_AcquireNextImageKHR(
1965 VkDevice device,
1966 VkSwapchainKHR swapchain,
1967 uint64_t timeout,
1968 VkSemaphore semaphore,
1969 VkFence fence,
1970 uint32_t* pImageIndex)
1971 {
1972 struct swapchain_data *swapchain_data =
1973 FIND(struct swapchain_data, swapchain);
1974 struct device_data *device_data = swapchain_data->device;
1975
1976 uint64_t ts0 = os_time_get();
1977 VkResult result = device_data->vtable.AcquireNextImageKHR(device, swapchain, timeout,
1978 semaphore, fence, pImageIndex);
1979 uint64_t ts1 = os_time_get();
1980
1981 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
1982 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
1983
1984 return result;
1985 }
1986
1987 static VkResult overlay_AcquireNextImage2KHR(
1988 VkDevice device,
1989 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1990 uint32_t* pImageIndex)
1991 {
1992 struct swapchain_data *swapchain_data =
1993 FIND(struct swapchain_data, pAcquireInfo->swapchain);
1994 struct device_data *device_data = swapchain_data->device;
1995
1996 uint64_t ts0 = os_time_get();
1997 VkResult result = device_data->vtable.AcquireNextImage2KHR(device, pAcquireInfo, pImageIndex);
1998 uint64_t ts1 = os_time_get();
1999
2000 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
2001 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
2002
2003 return result;
2004 }
2005
2006 static void overlay_CmdDraw(
2007 VkCommandBuffer commandBuffer,
2008 uint32_t vertexCount,
2009 uint32_t instanceCount,
2010 uint32_t firstVertex,
2011 uint32_t firstInstance)
2012 {
2013 struct command_buffer_data *cmd_buffer_data =
2014 FIND(struct command_buffer_data, commandBuffer);
2015 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw]++;
2016 struct device_data *device_data = cmd_buffer_data->device;
2017 device_data->vtable.CmdDraw(commandBuffer, vertexCount, instanceCount,
2018 firstVertex, firstInstance);
2019 }
2020
2021 static void overlay_CmdDrawIndexed(
2022 VkCommandBuffer commandBuffer,
2023 uint32_t indexCount,
2024 uint32_t instanceCount,
2025 uint32_t firstIndex,
2026 int32_t vertexOffset,
2027 uint32_t firstInstance)
2028 {
2029 struct command_buffer_data *cmd_buffer_data =
2030 FIND(struct command_buffer_data, commandBuffer);
2031 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed]++;
2032 struct device_data *device_data = cmd_buffer_data->device;
2033 device_data->vtable.CmdDrawIndexed(commandBuffer, indexCount, instanceCount,
2034 firstIndex, vertexOffset, firstInstance);
2035 }
2036
2037 static void overlay_CmdDrawIndirect(
2038 VkCommandBuffer commandBuffer,
2039 VkBuffer buffer,
2040 VkDeviceSize offset,
2041 uint32_t drawCount,
2042 uint32_t stride)
2043 {
2044 struct command_buffer_data *cmd_buffer_data =
2045 FIND(struct command_buffer_data, commandBuffer);
2046 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect]++;
2047 struct device_data *device_data = cmd_buffer_data->device;
2048 device_data->vtable.CmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
2049 }
2050
2051 static void overlay_CmdDrawIndexedIndirect(
2052 VkCommandBuffer commandBuffer,
2053 VkBuffer buffer,
2054 VkDeviceSize offset,
2055 uint32_t drawCount,
2056 uint32_t stride)
2057 {
2058 struct command_buffer_data *cmd_buffer_data =
2059 FIND(struct command_buffer_data, commandBuffer);
2060 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect]++;
2061 struct device_data *device_data = cmd_buffer_data->device;
2062 device_data->vtable.CmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
2063 }
2064
2065 static void overlay_CmdDrawIndirectCount(
2066 VkCommandBuffer commandBuffer,
2067 VkBuffer buffer,
2068 VkDeviceSize offset,
2069 VkBuffer countBuffer,
2070 VkDeviceSize countBufferOffset,
2071 uint32_t maxDrawCount,
2072 uint32_t stride)
2073 {
2074 struct command_buffer_data *cmd_buffer_data =
2075 FIND(struct command_buffer_data, commandBuffer);
2076 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect_count]++;
2077 struct device_data *device_data = cmd_buffer_data->device;
2078 device_data->vtable.CmdDrawIndirectCount(commandBuffer, buffer, offset,
2079 countBuffer, countBufferOffset,
2080 maxDrawCount, stride);
2081 }
2082
2083 static void overlay_CmdDrawIndexedIndirectCount(
2084 VkCommandBuffer commandBuffer,
2085 VkBuffer buffer,
2086 VkDeviceSize offset,
2087 VkBuffer countBuffer,
2088 VkDeviceSize countBufferOffset,
2089 uint32_t maxDrawCount,
2090 uint32_t stride)
2091 {
2092 struct command_buffer_data *cmd_buffer_data =
2093 FIND(struct command_buffer_data, commandBuffer);
2094 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect_count]++;
2095 struct device_data *device_data = cmd_buffer_data->device;
2096 device_data->vtable.CmdDrawIndexedIndirectCount(commandBuffer, buffer, offset,
2097 countBuffer, countBufferOffset,
2098 maxDrawCount, stride);
2099 }
2100
2101 static void overlay_CmdDispatch(
2102 VkCommandBuffer commandBuffer,
2103 uint32_t groupCountX,
2104 uint32_t groupCountY,
2105 uint32_t groupCountZ)
2106 {
2107 struct command_buffer_data *cmd_buffer_data =
2108 FIND(struct command_buffer_data, commandBuffer);
2109 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch]++;
2110 struct device_data *device_data = cmd_buffer_data->device;
2111 device_data->vtable.CmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ);
2112 }
2113
2114 static void overlay_CmdDispatchIndirect(
2115 VkCommandBuffer commandBuffer,
2116 VkBuffer buffer,
2117 VkDeviceSize offset)
2118 {
2119 struct command_buffer_data *cmd_buffer_data =
2120 FIND(struct command_buffer_data, commandBuffer);
2121 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch_indirect]++;
2122 struct device_data *device_data = cmd_buffer_data->device;
2123 device_data->vtable.CmdDispatchIndirect(commandBuffer, buffer, offset);
2124 }
2125
2126 static void overlay_CmdBindPipeline(
2127 VkCommandBuffer commandBuffer,
2128 VkPipelineBindPoint pipelineBindPoint,
2129 VkPipeline pipeline)
2130 {
2131 struct command_buffer_data *cmd_buffer_data =
2132 FIND(struct command_buffer_data, commandBuffer);
2133 switch (pipelineBindPoint) {
2134 case VK_PIPELINE_BIND_POINT_GRAPHICS: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_graphics]++; break;
2135 case VK_PIPELINE_BIND_POINT_COMPUTE: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_compute]++; break;
2136 case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_raytracing]++; break;
2137 default: break;
2138 }
2139 struct device_data *device_data = cmd_buffer_data->device;
2140 device_data->vtable.CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
2141 }
2142
2143 static VkResult overlay_BeginCommandBuffer(
2144 VkCommandBuffer commandBuffer,
2145 const VkCommandBufferBeginInfo* pBeginInfo)
2146 {
2147 struct command_buffer_data *cmd_buffer_data =
2148 FIND(struct command_buffer_data, commandBuffer);
2149 struct device_data *device_data = cmd_buffer_data->device;
2150
2151 memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2152
2153 /* We don't record any query in secondary command buffers, just make sure
2154 * we have the right inheritance.
2155 */
2156 if (cmd_buffer_data->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2157 VkCommandBufferBeginInfo *begin_info = (VkCommandBufferBeginInfo *)
2158 clone_chain((const struct VkBaseInStructure *)pBeginInfo);
2159 VkCommandBufferInheritanceInfo *parent_inhe_info = (VkCommandBufferInheritanceInfo *)
2160 vk_find_struct(begin_info, COMMAND_BUFFER_INHERITANCE_INFO);
2161 VkCommandBufferInheritanceInfo inhe_info = {
2162 VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
2163 NULL,
2164 VK_NULL_HANDLE,
2165 0,
2166 VK_NULL_HANDLE,
2167 VK_FALSE,
2168 0,
2169 overlay_query_flags,
2170 };
2171
2172 if (parent_inhe_info)
2173 parent_inhe_info->pipelineStatistics = overlay_query_flags;
2174 else {
2175 inhe_info.pNext = begin_info->pNext;
2176 begin_info->pNext = &inhe_info;
2177 }
2178
2179 VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2180
2181 if (!parent_inhe_info)
2182 begin_info->pNext = inhe_info.pNext;
2183
2184 free_chain((struct VkBaseOutStructure *)begin_info);
2185
2186 return result;
2187 }
2188
2189 /* Otherwise record a begin query as first command. */
2190 VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2191
2192 if (result == VK_SUCCESS) {
2193 if (cmd_buffer_data->pipeline_query_pool) {
2194 device_data->vtable.CmdResetQueryPool(commandBuffer,
2195 cmd_buffer_data->pipeline_query_pool,
2196 cmd_buffer_data->query_index, 1);
2197 }
2198 if (cmd_buffer_data->timestamp_query_pool) {
2199 device_data->vtable.CmdResetQueryPool(commandBuffer,
2200 cmd_buffer_data->timestamp_query_pool,
2201 cmd_buffer_data->query_index * 2, 2);
2202 }
2203 if (cmd_buffer_data->pipeline_query_pool) {
2204 device_data->vtable.CmdBeginQuery(commandBuffer,
2205 cmd_buffer_data->pipeline_query_pool,
2206 cmd_buffer_data->query_index, 0);
2207 }
2208 if (cmd_buffer_data->timestamp_query_pool) {
2209 device_data->vtable.CmdWriteTimestamp(commandBuffer,
2210 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2211 cmd_buffer_data->timestamp_query_pool,
2212 cmd_buffer_data->query_index * 2);
2213 }
2214 }
2215
2216 return result;
2217 }
2218
2219 static VkResult overlay_EndCommandBuffer(
2220 VkCommandBuffer commandBuffer)
2221 {
2222 struct command_buffer_data *cmd_buffer_data =
2223 FIND(struct command_buffer_data, commandBuffer);
2224 struct device_data *device_data = cmd_buffer_data->device;
2225
2226 if (cmd_buffer_data->timestamp_query_pool) {
2227 device_data->vtable.CmdWriteTimestamp(commandBuffer,
2228 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2229 cmd_buffer_data->timestamp_query_pool,
2230 cmd_buffer_data->query_index * 2 + 1);
2231 }
2232 if (cmd_buffer_data->pipeline_query_pool) {
2233 device_data->vtable.CmdEndQuery(commandBuffer,
2234 cmd_buffer_data->pipeline_query_pool,
2235 cmd_buffer_data->query_index);
2236 }
2237
2238 return device_data->vtable.EndCommandBuffer(commandBuffer);
2239 }
2240
2241 static VkResult overlay_ResetCommandBuffer(
2242 VkCommandBuffer commandBuffer,
2243 VkCommandBufferResetFlags flags)
2244 {
2245 struct command_buffer_data *cmd_buffer_data =
2246 FIND(struct command_buffer_data, commandBuffer);
2247 struct device_data *device_data = cmd_buffer_data->device;
2248
2249 memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2250
2251 return device_data->vtable.ResetCommandBuffer(commandBuffer, flags);
2252 }
2253
2254 static void overlay_CmdExecuteCommands(
2255 VkCommandBuffer commandBuffer,
2256 uint32_t commandBufferCount,
2257 const VkCommandBuffer* pCommandBuffers)
2258 {
2259 struct command_buffer_data *cmd_buffer_data =
2260 FIND(struct command_buffer_data, commandBuffer);
2261 struct device_data *device_data = cmd_buffer_data->device;
2262
2263 /* Add the stats of the executed command buffers to the primary one. */
2264 for (uint32_t c = 0; c < commandBufferCount; c++) {
2265 struct command_buffer_data *sec_cmd_buffer_data =
2266 FIND(struct command_buffer_data, pCommandBuffers[c]);
2267
2268 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++)
2269 cmd_buffer_data->stats.stats[s] += sec_cmd_buffer_data->stats.stats[s];
2270 }
2271
2272 device_data->vtable.CmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2273 }
2274
2275 static VkResult overlay_AllocateCommandBuffers(
2276 VkDevice device,
2277 const VkCommandBufferAllocateInfo* pAllocateInfo,
2278 VkCommandBuffer* pCommandBuffers)
2279 {
2280 struct device_data *device_data = FIND(struct device_data, device);
2281 VkResult result =
2282 device_data->vtable.AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
2283 if (result != VK_SUCCESS)
2284 return result;
2285
2286 VkQueryPool pipeline_query_pool = VK_NULL_HANDLE;
2287 VkQueryPool timestamp_query_pool = VK_NULL_HANDLE;
2288 if (device_data->instance->pipeline_statistics_enabled &&
2289 pAllocateInfo->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
2290 VkQueryPoolCreateInfo pool_info = {
2291 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2292 NULL,
2293 0,
2294 VK_QUERY_TYPE_PIPELINE_STATISTICS,
2295 pAllocateInfo->commandBufferCount,
2296 overlay_query_flags,
2297 };
2298 VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2299 NULL, &pipeline_query_pool));
2300 }
2301 if (device_data->instance->params.enabled[OVERLAY_PARAM_ENABLED_gpu_timing]) {
2302 VkQueryPoolCreateInfo pool_info = {
2303 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2304 NULL,
2305 0,
2306 VK_QUERY_TYPE_TIMESTAMP,
2307 pAllocateInfo->commandBufferCount * 2,
2308 0,
2309 };
2310 VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2311 NULL, &timestamp_query_pool));
2312 }
2313
2314 for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++) {
2315 new_command_buffer_data(pCommandBuffers[i], pAllocateInfo->level,
2316 pipeline_query_pool, timestamp_query_pool,
2317 i, device_data);
2318 }
2319
2320 if (pipeline_query_pool)
2321 map_object(HKEY(pipeline_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2322 if (timestamp_query_pool)
2323 map_object(HKEY(timestamp_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2324
2325 return result;
2326 }
2327
2328 static void overlay_FreeCommandBuffers(
2329 VkDevice device,
2330 VkCommandPool commandPool,
2331 uint32_t commandBufferCount,
2332 const VkCommandBuffer* pCommandBuffers)
2333 {
2334 struct device_data *device_data = FIND(struct device_data, device);
2335 for (uint32_t i = 0; i < commandBufferCount; i++) {
2336 struct command_buffer_data *cmd_buffer_data =
2337 FIND(struct command_buffer_data, pCommandBuffers[i]);
2338
2339 /* It is legal to free a NULL command buffer*/
2340 if (!cmd_buffer_data)
2341 continue;
2342
2343 uint64_t count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->pipeline_query_pool));
2344 if (count == 1) {
2345 unmap_object(HKEY(cmd_buffer_data->pipeline_query_pool));
2346 device_data->vtable.DestroyQueryPool(device_data->device,
2347 cmd_buffer_data->pipeline_query_pool, NULL);
2348 } else if (count != 0) {
2349 map_object(HKEY(cmd_buffer_data->pipeline_query_pool), (void *)(uintptr_t)(count - 1));
2350 }
2351 count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->timestamp_query_pool));
2352 if (count == 1) {
2353 unmap_object(HKEY(cmd_buffer_data->timestamp_query_pool));
2354 device_data->vtable.DestroyQueryPool(device_data->device,
2355 cmd_buffer_data->timestamp_query_pool, NULL);
2356 } else if (count != 0) {
2357 map_object(HKEY(cmd_buffer_data->timestamp_query_pool), (void *)(uintptr_t)(count - 1));
2358 }
2359 destroy_command_buffer_data(cmd_buffer_data);
2360 }
2361
2362 device_data->vtable.FreeCommandBuffers(device, commandPool,
2363 commandBufferCount, pCommandBuffers);
2364 }
2365
2366 static VkResult overlay_QueueSubmit(
2367 VkQueue queue,
2368 uint32_t submitCount,
2369 const VkSubmitInfo* pSubmits,
2370 VkFence fence)
2371 {
2372 struct queue_data *queue_data = FIND(struct queue_data, queue);
2373 struct device_data *device_data = queue_data->device;
2374
2375 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_submit]++;
2376
2377 for (uint32_t s = 0; s < submitCount; s++) {
2378 for (uint32_t c = 0; c < pSubmits[s].commandBufferCount; c++) {
2379 struct command_buffer_data *cmd_buffer_data =
2380 FIND(struct command_buffer_data, pSubmits[s].pCommandBuffers[c]);
2381
2382 /* Merge the submitted command buffer stats into the device. */
2383 for (uint32_t st = 0; st < OVERLAY_PARAM_ENABLED_MAX; st++)
2384 device_data->frame_stats.stats[st] += cmd_buffer_data->stats.stats[st];
2385
2386 /* Attach the command buffer to the queue so we remember to read its
2387 * pipeline statistics & timestamps at QueuePresent().
2388 */
2389 if (!cmd_buffer_data->pipeline_query_pool &&
2390 !cmd_buffer_data->timestamp_query_pool)
2391 continue;
2392
2393 if (list_is_empty(&cmd_buffer_data->link)) {
2394 list_addtail(&cmd_buffer_data->link,
2395 &queue_data->running_command_buffer);
2396 } else {
2397 fprintf(stderr, "Command buffer submitted multiple times before present.\n"
2398 "This could lead to invalid data.\n");
2399 }
2400 }
2401 }
2402
2403 return device_data->vtable.QueueSubmit(queue, submitCount, pSubmits, fence);
2404 }
2405
2406 static VkResult overlay_CreateDevice(
2407 VkPhysicalDevice physicalDevice,
2408 const VkDeviceCreateInfo* pCreateInfo,
2409 const VkAllocationCallbacks* pAllocator,
2410 VkDevice* pDevice)
2411 {
2412 struct instance_data *instance_data =
2413 FIND(struct instance_data, physicalDevice);
2414 VkLayerDeviceCreateInfo *chain_info =
2415 get_device_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2416
2417 assert(chain_info->u.pLayerInfo);
2418 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2419 PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
2420 PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
2421 if (fpCreateDevice == NULL) {
2422 return VK_ERROR_INITIALIZATION_FAILED;
2423 }
2424
2425 // Advance the link info for the next element on the chain
2426 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2427
2428 VkPhysicalDeviceFeatures device_features = {};
2429 VkDeviceCreateInfo device_info = *pCreateInfo;
2430
2431 if (pCreateInfo->pEnabledFeatures)
2432 device_features = *(pCreateInfo->pEnabledFeatures);
2433 if (instance_data->pipeline_statistics_enabled) {
2434 device_features.inheritedQueries = true;
2435 device_features.pipelineStatisticsQuery = true;
2436 }
2437 device_info.pEnabledFeatures = &device_features;
2438
2439
2440 VkResult result = fpCreateDevice(physicalDevice, &device_info, pAllocator, pDevice);
2441 if (result != VK_SUCCESS) return result;
2442
2443 struct device_data *device_data = new_device_data(*pDevice, instance_data);
2444 device_data->physical_device = physicalDevice;
2445 vk_load_device_commands(*pDevice, fpGetDeviceProcAddr, &device_data->vtable);
2446
2447 instance_data->vtable.GetPhysicalDeviceProperties(device_data->physical_device,
2448 &device_data->properties);
2449
2450 VkLayerDeviceCreateInfo *load_data_info =
2451 get_device_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
2452 device_data->set_device_loader_data = load_data_info->u.pfnSetDeviceLoaderData;
2453
2454 device_map_queues(device_data, pCreateInfo);
2455
2456 return result;
2457 }
2458
2459 static void overlay_DestroyDevice(
2460 VkDevice device,
2461 const VkAllocationCallbacks* pAllocator)
2462 {
2463 struct device_data *device_data = FIND(struct device_data, device);
2464 device_unmap_queues(device_data);
2465 device_data->vtable.DestroyDevice(device, pAllocator);
2466 destroy_device_data(device_data);
2467 }
2468
2469 static VkResult overlay_CreateInstance(
2470 const VkInstanceCreateInfo* pCreateInfo,
2471 const VkAllocationCallbacks* pAllocator,
2472 VkInstance* pInstance)
2473 {
2474 VkLayerInstanceCreateInfo *chain_info =
2475 get_instance_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2476
2477 assert(chain_info->u.pLayerInfo);
2478 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
2479 chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2480 PFN_vkCreateInstance fpCreateInstance =
2481 (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
2482 if (fpCreateInstance == NULL) {
2483 return VK_ERROR_INITIALIZATION_FAILED;
2484 }
2485
2486 // Advance the link info for the next element on the chain
2487 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2488
2489 VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
2490 if (result != VK_SUCCESS) return result;
2491
2492 struct instance_data *instance_data = new_instance_data(*pInstance);
2493 vk_load_instance_commands(instance_data->instance,
2494 fpGetInstanceProcAddr,
2495 &instance_data->vtable);
2496 instance_data_map_physical_devices(instance_data, true);
2497
2498 parse_overlay_env(&instance_data->params, getenv("VK_LAYER_MESA_OVERLAY_CONFIG"));
2499
2500 /* If there's no control file, and an output_file was specified, start
2501 * capturing fps data right away.
2502 */
2503 instance_data->capture_enabled =
2504 instance_data->params.output_file && instance_data->params.control < 0;
2505 instance_data->capture_started = instance_data->capture_enabled;
2506
2507 for (int i = OVERLAY_PARAM_ENABLED_vertices;
2508 i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
2509 if (instance_data->params.enabled[i]) {
2510 instance_data->pipeline_statistics_enabled = true;
2511 break;
2512 }
2513 }
2514
2515 return result;
2516 }
2517
2518 static void overlay_DestroyInstance(
2519 VkInstance instance,
2520 const VkAllocationCallbacks* pAllocator)
2521 {
2522 struct instance_data *instance_data = FIND(struct instance_data, instance);
2523 instance_data_map_physical_devices(instance_data, false);
2524 instance_data->vtable.DestroyInstance(instance, pAllocator);
2525 destroy_instance_data(instance_data);
2526 }
2527
2528 static const struct {
2529 const char *name;
2530 void *ptr;
2531 } name_to_funcptr_map[] = {
2532 { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr },
2533 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
2534 #define ADD_ALIAS_HOOK(alias, fn) { "vk" # alias, (void *) overlay_ ## fn }
2535 ADD_HOOK(AllocateCommandBuffers),
2536 ADD_HOOK(FreeCommandBuffers),
2537 ADD_HOOK(ResetCommandBuffer),
2538 ADD_HOOK(BeginCommandBuffer),
2539 ADD_HOOK(EndCommandBuffer),
2540 ADD_HOOK(CmdExecuteCommands),
2541
2542 ADD_HOOK(CmdDraw),
2543 ADD_HOOK(CmdDrawIndexed),
2544 ADD_HOOK(CmdDrawIndirect),
2545 ADD_HOOK(CmdDrawIndexedIndirect),
2546 ADD_HOOK(CmdDispatch),
2547 ADD_HOOK(CmdDispatchIndirect),
2548 ADD_HOOK(CmdDrawIndirectCount),
2549 ADD_ALIAS_HOOK(CmdDrawIndirectCountKHR, CmdDrawIndirectCount),
2550 ADD_HOOK(CmdDrawIndexedIndirectCount),
2551 ADD_ALIAS_HOOK(CmdDrawIndexedIndirectCountKHR, CmdDrawIndexedIndirectCount),
2552
2553 ADD_HOOK(CmdBindPipeline),
2554
2555 ADD_HOOK(CreateSwapchainKHR),
2556 ADD_HOOK(QueuePresentKHR),
2557 ADD_HOOK(DestroySwapchainKHR),
2558 ADD_HOOK(AcquireNextImageKHR),
2559 ADD_HOOK(AcquireNextImage2KHR),
2560
2561 ADD_HOOK(QueueSubmit),
2562
2563 ADD_HOOK(CreateDevice),
2564 ADD_HOOK(DestroyDevice),
2565
2566 ADD_HOOK(CreateInstance),
2567 ADD_HOOK(DestroyInstance),
2568 #undef ADD_HOOK
2569 };
2570
2571 static void *find_ptr(const char *name)
2572 {
2573 for (uint32_t i = 0; i < ARRAY_SIZE(name_to_funcptr_map); i++) {
2574 if (strcmp(name, name_to_funcptr_map[i].name) == 0)
2575 return name_to_funcptr_map[i].ptr;
2576 }
2577
2578 return NULL;
2579 }
2580
2581 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev,
2582 const char *funcName)
2583 {
2584 void *ptr = find_ptr(funcName);
2585 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2586
2587 if (dev == NULL) return NULL;
2588
2589 struct device_data *device_data = FIND(struct device_data, dev);
2590 if (device_data->vtable.GetDeviceProcAddr == NULL) return NULL;
2591 return device_data->vtable.GetDeviceProcAddr(dev, funcName);
2592 }
2593
2594 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance,
2595 const char *funcName)
2596 {
2597 void *ptr = find_ptr(funcName);
2598 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2599
2600 if (instance == NULL) return NULL;
2601
2602 struct instance_data *instance_data = FIND(struct instance_data, instance);
2603 if (instance_data->vtable.GetInstanceProcAddr == NULL) return NULL;
2604 return instance_data->vtable.GetInstanceProcAddr(instance, funcName);
2605 }