zink: only inspect dual-src limit if feature enabled
[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 before_present(swapchain_data,
1907 queue_data,
1908 pPresentInfo->pWaitSemaphores,
1909 pPresentInfo->waitSemaphoreCount,
1910 pPresentInfo->pImageIndices[i]);
1911
1912 VkPresentInfoKHR present_info = *pPresentInfo;
1913 present_info.swapchainCount = 1;
1914 present_info.pSwapchains = &swapchain;
1915
1916 uint64_t ts0 = os_time_get();
1917 result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1918 uint64_t ts1 = os_time_get();
1919 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1920 }
1921 } else {
1922 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1923 VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1924 struct swapchain_data *swapchain_data =
1925 FIND(struct swapchain_data, swapchain);
1926 VkPresentInfoKHR present_info = *pPresentInfo;
1927 present_info.swapchainCount = 1;
1928 present_info.pSwapchains = &swapchain;
1929
1930 uint32_t image_index = pPresentInfo->pImageIndices[i];
1931
1932 struct overlay_draw *draw = before_present(swapchain_data,
1933 queue_data,
1934 pPresentInfo->pWaitSemaphores,
1935 pPresentInfo->waitSemaphoreCount,
1936 image_index);
1937
1938 /* Because the submission of the overlay draw waits on the semaphores
1939 * handed for present, we don't need to have this present operation
1940 * wait on them as well, we can just wait on the overlay submission
1941 * semaphore.
1942 */
1943 present_info.pWaitSemaphores = &draw->semaphore;
1944 present_info.waitSemaphoreCount = 1;
1945
1946 uint64_t ts0 = os_time_get();
1947 VkResult chain_result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1948 uint64_t ts1 = os_time_get();
1949 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1950 if (pPresentInfo->pResults)
1951 pPresentInfo->pResults[i] = chain_result;
1952 if (chain_result != VK_SUCCESS && result == VK_SUCCESS)
1953 result = chain_result;
1954 }
1955 }
1956 return result;
1957 }
1958
1959 static VkResult overlay_AcquireNextImageKHR(
1960 VkDevice device,
1961 VkSwapchainKHR swapchain,
1962 uint64_t timeout,
1963 VkSemaphore semaphore,
1964 VkFence fence,
1965 uint32_t* pImageIndex)
1966 {
1967 struct swapchain_data *swapchain_data =
1968 FIND(struct swapchain_data, swapchain);
1969 struct device_data *device_data = swapchain_data->device;
1970
1971 uint64_t ts0 = os_time_get();
1972 VkResult result = device_data->vtable.AcquireNextImageKHR(device, swapchain, timeout,
1973 semaphore, fence, pImageIndex);
1974 uint64_t ts1 = os_time_get();
1975
1976 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
1977 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
1978
1979 return result;
1980 }
1981
1982 static VkResult overlay_AcquireNextImage2KHR(
1983 VkDevice device,
1984 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1985 uint32_t* pImageIndex)
1986 {
1987 struct swapchain_data *swapchain_data =
1988 FIND(struct swapchain_data, pAcquireInfo->swapchain);
1989 struct device_data *device_data = swapchain_data->device;
1990
1991 uint64_t ts0 = os_time_get();
1992 VkResult result = device_data->vtable.AcquireNextImage2KHR(device, pAcquireInfo, pImageIndex);
1993 uint64_t ts1 = os_time_get();
1994
1995 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
1996 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
1997
1998 return result;
1999 }
2000
2001 static void overlay_CmdDraw(
2002 VkCommandBuffer commandBuffer,
2003 uint32_t vertexCount,
2004 uint32_t instanceCount,
2005 uint32_t firstVertex,
2006 uint32_t firstInstance)
2007 {
2008 struct command_buffer_data *cmd_buffer_data =
2009 FIND(struct command_buffer_data, commandBuffer);
2010 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw]++;
2011 struct device_data *device_data = cmd_buffer_data->device;
2012 device_data->vtable.CmdDraw(commandBuffer, vertexCount, instanceCount,
2013 firstVertex, firstInstance);
2014 }
2015
2016 static void overlay_CmdDrawIndexed(
2017 VkCommandBuffer commandBuffer,
2018 uint32_t indexCount,
2019 uint32_t instanceCount,
2020 uint32_t firstIndex,
2021 int32_t vertexOffset,
2022 uint32_t firstInstance)
2023 {
2024 struct command_buffer_data *cmd_buffer_data =
2025 FIND(struct command_buffer_data, commandBuffer);
2026 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed]++;
2027 struct device_data *device_data = cmd_buffer_data->device;
2028 device_data->vtable.CmdDrawIndexed(commandBuffer, indexCount, instanceCount,
2029 firstIndex, vertexOffset, firstInstance);
2030 }
2031
2032 static void overlay_CmdDrawIndirect(
2033 VkCommandBuffer commandBuffer,
2034 VkBuffer buffer,
2035 VkDeviceSize offset,
2036 uint32_t drawCount,
2037 uint32_t stride)
2038 {
2039 struct command_buffer_data *cmd_buffer_data =
2040 FIND(struct command_buffer_data, commandBuffer);
2041 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect]++;
2042 struct device_data *device_data = cmd_buffer_data->device;
2043 device_data->vtable.CmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
2044 }
2045
2046 static void overlay_CmdDrawIndexedIndirect(
2047 VkCommandBuffer commandBuffer,
2048 VkBuffer buffer,
2049 VkDeviceSize offset,
2050 uint32_t drawCount,
2051 uint32_t stride)
2052 {
2053 struct command_buffer_data *cmd_buffer_data =
2054 FIND(struct command_buffer_data, commandBuffer);
2055 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect]++;
2056 struct device_data *device_data = cmd_buffer_data->device;
2057 device_data->vtable.CmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
2058 }
2059
2060 static void overlay_CmdDrawIndirectCount(
2061 VkCommandBuffer commandBuffer,
2062 VkBuffer buffer,
2063 VkDeviceSize offset,
2064 VkBuffer countBuffer,
2065 VkDeviceSize countBufferOffset,
2066 uint32_t maxDrawCount,
2067 uint32_t stride)
2068 {
2069 struct command_buffer_data *cmd_buffer_data =
2070 FIND(struct command_buffer_data, commandBuffer);
2071 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect_count]++;
2072 struct device_data *device_data = cmd_buffer_data->device;
2073 device_data->vtable.CmdDrawIndirectCount(commandBuffer, buffer, offset,
2074 countBuffer, countBufferOffset,
2075 maxDrawCount, stride);
2076 }
2077
2078 static void overlay_CmdDrawIndexedIndirectCount(
2079 VkCommandBuffer commandBuffer,
2080 VkBuffer buffer,
2081 VkDeviceSize offset,
2082 VkBuffer countBuffer,
2083 VkDeviceSize countBufferOffset,
2084 uint32_t maxDrawCount,
2085 uint32_t stride)
2086 {
2087 struct command_buffer_data *cmd_buffer_data =
2088 FIND(struct command_buffer_data, commandBuffer);
2089 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect_count]++;
2090 struct device_data *device_data = cmd_buffer_data->device;
2091 device_data->vtable.CmdDrawIndexedIndirectCount(commandBuffer, buffer, offset,
2092 countBuffer, countBufferOffset,
2093 maxDrawCount, stride);
2094 }
2095
2096 static void overlay_CmdDispatch(
2097 VkCommandBuffer commandBuffer,
2098 uint32_t groupCountX,
2099 uint32_t groupCountY,
2100 uint32_t groupCountZ)
2101 {
2102 struct command_buffer_data *cmd_buffer_data =
2103 FIND(struct command_buffer_data, commandBuffer);
2104 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch]++;
2105 struct device_data *device_data = cmd_buffer_data->device;
2106 device_data->vtable.CmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ);
2107 }
2108
2109 static void overlay_CmdDispatchIndirect(
2110 VkCommandBuffer commandBuffer,
2111 VkBuffer buffer,
2112 VkDeviceSize offset)
2113 {
2114 struct command_buffer_data *cmd_buffer_data =
2115 FIND(struct command_buffer_data, commandBuffer);
2116 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch_indirect]++;
2117 struct device_data *device_data = cmd_buffer_data->device;
2118 device_data->vtable.CmdDispatchIndirect(commandBuffer, buffer, offset);
2119 }
2120
2121 static void overlay_CmdBindPipeline(
2122 VkCommandBuffer commandBuffer,
2123 VkPipelineBindPoint pipelineBindPoint,
2124 VkPipeline pipeline)
2125 {
2126 struct command_buffer_data *cmd_buffer_data =
2127 FIND(struct command_buffer_data, commandBuffer);
2128 switch (pipelineBindPoint) {
2129 case VK_PIPELINE_BIND_POINT_GRAPHICS: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_graphics]++; break;
2130 case VK_PIPELINE_BIND_POINT_COMPUTE: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_compute]++; break;
2131 case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_raytracing]++; break;
2132 default: break;
2133 }
2134 struct device_data *device_data = cmd_buffer_data->device;
2135 device_data->vtable.CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
2136 }
2137
2138 static VkResult overlay_BeginCommandBuffer(
2139 VkCommandBuffer commandBuffer,
2140 const VkCommandBufferBeginInfo* pBeginInfo)
2141 {
2142 struct command_buffer_data *cmd_buffer_data =
2143 FIND(struct command_buffer_data, commandBuffer);
2144 struct device_data *device_data = cmd_buffer_data->device;
2145
2146 memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2147
2148 /* We don't record any query in secondary command buffers, just make sure
2149 * we have the right inheritance.
2150 */
2151 if (cmd_buffer_data->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2152 VkCommandBufferBeginInfo *begin_info = (VkCommandBufferBeginInfo *)
2153 clone_chain((const struct VkBaseInStructure *)pBeginInfo);
2154 VkCommandBufferInheritanceInfo *parent_inhe_info = (VkCommandBufferInheritanceInfo *)
2155 vk_find_struct(begin_info, COMMAND_BUFFER_INHERITANCE_INFO);
2156 VkCommandBufferInheritanceInfo inhe_info = {
2157 VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
2158 NULL,
2159 VK_NULL_HANDLE,
2160 0,
2161 VK_NULL_HANDLE,
2162 VK_FALSE,
2163 0,
2164 overlay_query_flags,
2165 };
2166
2167 if (parent_inhe_info)
2168 parent_inhe_info->pipelineStatistics = overlay_query_flags;
2169 else {
2170 inhe_info.pNext = begin_info->pNext;
2171 begin_info->pNext = &inhe_info;
2172 }
2173
2174 VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2175
2176 if (!parent_inhe_info)
2177 begin_info->pNext = inhe_info.pNext;
2178
2179 free_chain((struct VkBaseOutStructure *)begin_info);
2180
2181 return result;
2182 }
2183
2184 /* Otherwise record a begin query as first command. */
2185 VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2186
2187 if (result == VK_SUCCESS) {
2188 if (cmd_buffer_data->pipeline_query_pool) {
2189 device_data->vtable.CmdResetQueryPool(commandBuffer,
2190 cmd_buffer_data->pipeline_query_pool,
2191 cmd_buffer_data->query_index, 1);
2192 }
2193 if (cmd_buffer_data->timestamp_query_pool) {
2194 device_data->vtable.CmdResetQueryPool(commandBuffer,
2195 cmd_buffer_data->timestamp_query_pool,
2196 cmd_buffer_data->query_index * 2, 2);
2197 }
2198 if (cmd_buffer_data->pipeline_query_pool) {
2199 device_data->vtable.CmdBeginQuery(commandBuffer,
2200 cmd_buffer_data->pipeline_query_pool,
2201 cmd_buffer_data->query_index, 0);
2202 }
2203 if (cmd_buffer_data->timestamp_query_pool) {
2204 device_data->vtable.CmdWriteTimestamp(commandBuffer,
2205 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2206 cmd_buffer_data->timestamp_query_pool,
2207 cmd_buffer_data->query_index * 2);
2208 }
2209 }
2210
2211 return result;
2212 }
2213
2214 static VkResult overlay_EndCommandBuffer(
2215 VkCommandBuffer commandBuffer)
2216 {
2217 struct command_buffer_data *cmd_buffer_data =
2218 FIND(struct command_buffer_data, commandBuffer);
2219 struct device_data *device_data = cmd_buffer_data->device;
2220
2221 if (cmd_buffer_data->timestamp_query_pool) {
2222 device_data->vtable.CmdWriteTimestamp(commandBuffer,
2223 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2224 cmd_buffer_data->timestamp_query_pool,
2225 cmd_buffer_data->query_index * 2 + 1);
2226 }
2227 if (cmd_buffer_data->pipeline_query_pool) {
2228 device_data->vtable.CmdEndQuery(commandBuffer,
2229 cmd_buffer_data->pipeline_query_pool,
2230 cmd_buffer_data->query_index);
2231 }
2232
2233 return device_data->vtable.EndCommandBuffer(commandBuffer);
2234 }
2235
2236 static VkResult overlay_ResetCommandBuffer(
2237 VkCommandBuffer commandBuffer,
2238 VkCommandBufferResetFlags flags)
2239 {
2240 struct command_buffer_data *cmd_buffer_data =
2241 FIND(struct command_buffer_data, commandBuffer);
2242 struct device_data *device_data = cmd_buffer_data->device;
2243
2244 memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2245
2246 return device_data->vtable.ResetCommandBuffer(commandBuffer, flags);
2247 }
2248
2249 static void overlay_CmdExecuteCommands(
2250 VkCommandBuffer commandBuffer,
2251 uint32_t commandBufferCount,
2252 const VkCommandBuffer* pCommandBuffers)
2253 {
2254 struct command_buffer_data *cmd_buffer_data =
2255 FIND(struct command_buffer_data, commandBuffer);
2256 struct device_data *device_data = cmd_buffer_data->device;
2257
2258 /* Add the stats of the executed command buffers to the primary one. */
2259 for (uint32_t c = 0; c < commandBufferCount; c++) {
2260 struct command_buffer_data *sec_cmd_buffer_data =
2261 FIND(struct command_buffer_data, pCommandBuffers[c]);
2262
2263 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++)
2264 cmd_buffer_data->stats.stats[s] += sec_cmd_buffer_data->stats.stats[s];
2265 }
2266
2267 device_data->vtable.CmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2268 }
2269
2270 static VkResult overlay_AllocateCommandBuffers(
2271 VkDevice device,
2272 const VkCommandBufferAllocateInfo* pAllocateInfo,
2273 VkCommandBuffer* pCommandBuffers)
2274 {
2275 struct device_data *device_data = FIND(struct device_data, device);
2276 VkResult result =
2277 device_data->vtable.AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
2278 if (result != VK_SUCCESS)
2279 return result;
2280
2281 VkQueryPool pipeline_query_pool = VK_NULL_HANDLE;
2282 VkQueryPool timestamp_query_pool = VK_NULL_HANDLE;
2283 if (device_data->instance->pipeline_statistics_enabled &&
2284 pAllocateInfo->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
2285 VkQueryPoolCreateInfo pool_info = {
2286 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2287 NULL,
2288 0,
2289 VK_QUERY_TYPE_PIPELINE_STATISTICS,
2290 pAllocateInfo->commandBufferCount,
2291 overlay_query_flags,
2292 };
2293 VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2294 NULL, &pipeline_query_pool));
2295 }
2296 if (device_data->instance->params.enabled[OVERLAY_PARAM_ENABLED_gpu_timing]) {
2297 VkQueryPoolCreateInfo pool_info = {
2298 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2299 NULL,
2300 0,
2301 VK_QUERY_TYPE_TIMESTAMP,
2302 pAllocateInfo->commandBufferCount * 2,
2303 0,
2304 };
2305 VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2306 NULL, &timestamp_query_pool));
2307 }
2308
2309 for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++) {
2310 new_command_buffer_data(pCommandBuffers[i], pAllocateInfo->level,
2311 pipeline_query_pool, timestamp_query_pool,
2312 i, device_data);
2313 }
2314
2315 if (pipeline_query_pool)
2316 map_object(HKEY(pipeline_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2317 if (timestamp_query_pool)
2318 map_object(HKEY(timestamp_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2319
2320 return result;
2321 }
2322
2323 static void overlay_FreeCommandBuffers(
2324 VkDevice device,
2325 VkCommandPool commandPool,
2326 uint32_t commandBufferCount,
2327 const VkCommandBuffer* pCommandBuffers)
2328 {
2329 struct device_data *device_data = FIND(struct device_data, device);
2330 for (uint32_t i = 0; i < commandBufferCount; i++) {
2331 struct command_buffer_data *cmd_buffer_data =
2332 FIND(struct command_buffer_data, pCommandBuffers[i]);
2333
2334 /* It is legal to free a NULL command buffer*/
2335 if (!cmd_buffer_data)
2336 continue;
2337
2338 uint64_t count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->pipeline_query_pool));
2339 if (count == 1) {
2340 unmap_object(HKEY(cmd_buffer_data->pipeline_query_pool));
2341 device_data->vtable.DestroyQueryPool(device_data->device,
2342 cmd_buffer_data->pipeline_query_pool, NULL);
2343 } else if (count != 0) {
2344 map_object(HKEY(cmd_buffer_data->pipeline_query_pool), (void *)(uintptr_t)(count - 1));
2345 }
2346 count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->timestamp_query_pool));
2347 if (count == 1) {
2348 unmap_object(HKEY(cmd_buffer_data->timestamp_query_pool));
2349 device_data->vtable.DestroyQueryPool(device_data->device,
2350 cmd_buffer_data->timestamp_query_pool, NULL);
2351 } else if (count != 0) {
2352 map_object(HKEY(cmd_buffer_data->timestamp_query_pool), (void *)(uintptr_t)(count - 1));
2353 }
2354 destroy_command_buffer_data(cmd_buffer_data);
2355 }
2356
2357 device_data->vtable.FreeCommandBuffers(device, commandPool,
2358 commandBufferCount, pCommandBuffers);
2359 }
2360
2361 static VkResult overlay_QueueSubmit(
2362 VkQueue queue,
2363 uint32_t submitCount,
2364 const VkSubmitInfo* pSubmits,
2365 VkFence fence)
2366 {
2367 struct queue_data *queue_data = FIND(struct queue_data, queue);
2368 struct device_data *device_data = queue_data->device;
2369
2370 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_submit]++;
2371
2372 for (uint32_t s = 0; s < submitCount; s++) {
2373 for (uint32_t c = 0; c < pSubmits[s].commandBufferCount; c++) {
2374 struct command_buffer_data *cmd_buffer_data =
2375 FIND(struct command_buffer_data, pSubmits[s].pCommandBuffers[c]);
2376
2377 /* Merge the submitted command buffer stats into the device. */
2378 for (uint32_t st = 0; st < OVERLAY_PARAM_ENABLED_MAX; st++)
2379 device_data->frame_stats.stats[st] += cmd_buffer_data->stats.stats[st];
2380
2381 /* Attach the command buffer to the queue so we remember to read its
2382 * pipeline statistics & timestamps at QueuePresent().
2383 */
2384 if (!cmd_buffer_data->pipeline_query_pool &&
2385 !cmd_buffer_data->timestamp_query_pool)
2386 continue;
2387
2388 if (list_is_empty(&cmd_buffer_data->link)) {
2389 list_addtail(&cmd_buffer_data->link,
2390 &queue_data->running_command_buffer);
2391 } else {
2392 fprintf(stderr, "Command buffer submitted multiple times before present.\n"
2393 "This could lead to invalid data.\n");
2394 }
2395 }
2396 }
2397
2398 return device_data->vtable.QueueSubmit(queue, submitCount, pSubmits, fence);
2399 }
2400
2401 static VkResult overlay_CreateDevice(
2402 VkPhysicalDevice physicalDevice,
2403 const VkDeviceCreateInfo* pCreateInfo,
2404 const VkAllocationCallbacks* pAllocator,
2405 VkDevice* pDevice)
2406 {
2407 struct instance_data *instance_data =
2408 FIND(struct instance_data, physicalDevice);
2409 VkLayerDeviceCreateInfo *chain_info =
2410 get_device_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2411
2412 assert(chain_info->u.pLayerInfo);
2413 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2414 PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
2415 PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
2416 if (fpCreateDevice == NULL) {
2417 return VK_ERROR_INITIALIZATION_FAILED;
2418 }
2419
2420 // Advance the link info for the next element on the chain
2421 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2422
2423 VkPhysicalDeviceFeatures device_features = {};
2424 VkDeviceCreateInfo device_info = *pCreateInfo;
2425
2426 if (pCreateInfo->pEnabledFeatures)
2427 device_features = *(pCreateInfo->pEnabledFeatures);
2428 if (instance_data->pipeline_statistics_enabled) {
2429 device_features.inheritedQueries = true;
2430 device_features.pipelineStatisticsQuery = true;
2431 }
2432 device_info.pEnabledFeatures = &device_features;
2433
2434
2435 VkResult result = fpCreateDevice(physicalDevice, &device_info, pAllocator, pDevice);
2436 if (result != VK_SUCCESS) return result;
2437
2438 struct device_data *device_data = new_device_data(*pDevice, instance_data);
2439 device_data->physical_device = physicalDevice;
2440 vk_load_device_commands(*pDevice, fpGetDeviceProcAddr, &device_data->vtable);
2441
2442 instance_data->vtable.GetPhysicalDeviceProperties(device_data->physical_device,
2443 &device_data->properties);
2444
2445 VkLayerDeviceCreateInfo *load_data_info =
2446 get_device_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
2447 device_data->set_device_loader_data = load_data_info->u.pfnSetDeviceLoaderData;
2448
2449 device_map_queues(device_data, pCreateInfo);
2450
2451 return result;
2452 }
2453
2454 static void overlay_DestroyDevice(
2455 VkDevice device,
2456 const VkAllocationCallbacks* pAllocator)
2457 {
2458 struct device_data *device_data = FIND(struct device_data, device);
2459 device_unmap_queues(device_data);
2460 device_data->vtable.DestroyDevice(device, pAllocator);
2461 destroy_device_data(device_data);
2462 }
2463
2464 static VkResult overlay_CreateInstance(
2465 const VkInstanceCreateInfo* pCreateInfo,
2466 const VkAllocationCallbacks* pAllocator,
2467 VkInstance* pInstance)
2468 {
2469 VkLayerInstanceCreateInfo *chain_info =
2470 get_instance_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2471
2472 assert(chain_info->u.pLayerInfo);
2473 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
2474 chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2475 PFN_vkCreateInstance fpCreateInstance =
2476 (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
2477 if (fpCreateInstance == NULL) {
2478 return VK_ERROR_INITIALIZATION_FAILED;
2479 }
2480
2481 // Advance the link info for the next element on the chain
2482 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2483
2484 VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
2485 if (result != VK_SUCCESS) return result;
2486
2487 struct instance_data *instance_data = new_instance_data(*pInstance);
2488 vk_load_instance_commands(instance_data->instance,
2489 fpGetInstanceProcAddr,
2490 &instance_data->vtable);
2491 instance_data_map_physical_devices(instance_data, true);
2492
2493 parse_overlay_env(&instance_data->params, getenv("VK_LAYER_MESA_OVERLAY_CONFIG"));
2494
2495 /* If there's no control file, and an output_file was specified, start
2496 * capturing fps data right away.
2497 */
2498 instance_data->capture_enabled =
2499 instance_data->params.output_file && instance_data->params.control < 0;
2500 instance_data->capture_started = instance_data->capture_enabled;
2501
2502 for (int i = OVERLAY_PARAM_ENABLED_vertices;
2503 i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
2504 if (instance_data->params.enabled[i]) {
2505 instance_data->pipeline_statistics_enabled = true;
2506 break;
2507 }
2508 }
2509
2510 return result;
2511 }
2512
2513 static void overlay_DestroyInstance(
2514 VkInstance instance,
2515 const VkAllocationCallbacks* pAllocator)
2516 {
2517 struct instance_data *instance_data = FIND(struct instance_data, instance);
2518 instance_data_map_physical_devices(instance_data, false);
2519 instance_data->vtable.DestroyInstance(instance, pAllocator);
2520 destroy_instance_data(instance_data);
2521 }
2522
2523 static const struct {
2524 const char *name;
2525 void *ptr;
2526 } name_to_funcptr_map[] = {
2527 { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr },
2528 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
2529 #define ADD_ALIAS_HOOK(alias, fn) { "vk" # alias, (void *) overlay_ ## fn }
2530 ADD_HOOK(AllocateCommandBuffers),
2531 ADD_HOOK(FreeCommandBuffers),
2532 ADD_HOOK(ResetCommandBuffer),
2533 ADD_HOOK(BeginCommandBuffer),
2534 ADD_HOOK(EndCommandBuffer),
2535 ADD_HOOK(CmdExecuteCommands),
2536
2537 ADD_HOOK(CmdDraw),
2538 ADD_HOOK(CmdDrawIndexed),
2539 ADD_HOOK(CmdDrawIndirect),
2540 ADD_HOOK(CmdDrawIndexedIndirect),
2541 ADD_HOOK(CmdDispatch),
2542 ADD_HOOK(CmdDispatchIndirect),
2543 ADD_HOOK(CmdDrawIndirectCount),
2544 ADD_ALIAS_HOOK(CmdDrawIndirectCountKHR, CmdDrawIndirectCount),
2545 ADD_HOOK(CmdDrawIndexedIndirectCount),
2546 ADD_ALIAS_HOOK(CmdDrawIndexedIndirectCountKHR, CmdDrawIndexedIndirectCount),
2547
2548 ADD_HOOK(CmdBindPipeline),
2549
2550 ADD_HOOK(CreateSwapchainKHR),
2551 ADD_HOOK(QueuePresentKHR),
2552 ADD_HOOK(DestroySwapchainKHR),
2553 ADD_HOOK(AcquireNextImageKHR),
2554 ADD_HOOK(AcquireNextImage2KHR),
2555
2556 ADD_HOOK(QueueSubmit),
2557
2558 ADD_HOOK(CreateDevice),
2559 ADD_HOOK(DestroyDevice),
2560
2561 ADD_HOOK(CreateInstance),
2562 ADD_HOOK(DestroyInstance),
2563 #undef ADD_HOOK
2564 };
2565
2566 static void *find_ptr(const char *name)
2567 {
2568 for (uint32_t i = 0; i < ARRAY_SIZE(name_to_funcptr_map); i++) {
2569 if (strcmp(name, name_to_funcptr_map[i].name) == 0)
2570 return name_to_funcptr_map[i].ptr;
2571 }
2572
2573 return NULL;
2574 }
2575
2576 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev,
2577 const char *funcName)
2578 {
2579 void *ptr = find_ptr(funcName);
2580 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2581
2582 if (dev == NULL) return NULL;
2583
2584 struct device_data *device_data = FIND(struct device_data, dev);
2585 if (device_data->vtable.GetDeviceProcAddr == NULL) return NULL;
2586 return device_data->vtable.GetDeviceProcAddr(dev, funcName);
2587 }
2588
2589 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance,
2590 const char *funcName)
2591 {
2592 void *ptr = find_ptr(funcName);
2593 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2594
2595 if (instance == NULL) return NULL;
2596
2597 struct instance_data *instance_data = FIND(struct instance_data, instance);
2598 if (instance_data->vtable.GetInstanceProcAddr == NULL) return NULL;
2599 return instance_data->vtable.GetInstanceProcAddr(instance, funcName);
2600 }