6ec2f05826a1b51aea42d23ffffe0275819aef13
[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 /* Bounce the image to display back to present layout. */
1323 imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
1324 imb.pNext = nullptr;
1325 imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1326 imb.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1327 imb.oldLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1328 imb.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1329 imb.image = data->images[image_index];
1330 imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1331 imb.subresourceRange.baseMipLevel = 0;
1332 imb.subresourceRange.levelCount = 1;
1333 imb.subresourceRange.baseArrayLayer = 0;
1334 imb.subresourceRange.layerCount = 1;
1335 imb.srcQueueFamilyIndex = device_data->graphic_queue->family_index;
1336 imb.dstQueueFamilyIndex = present_queue->family_index;
1337 device_data->vtable.CmdPipelineBarrier(draw->command_buffer,
1338 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1339 VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT,
1340 0, /* dependency flags */
1341 0, nullptr, /* memory barriers */
1342 0, nullptr, /* buffer memory barriers */
1343 1, &imb); /* image memory barriers */
1344
1345 device_data->vtable.EndCommandBuffer(draw->command_buffer);
1346
1347 VkSubmitInfo submit_info = {};
1348 VkPipelineStageFlags stage_wait = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT;
1349 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
1350 submit_info.commandBufferCount = 1;
1351 submit_info.pCommandBuffers = &draw->command_buffer;
1352 submit_info.pWaitDstStageMask = &stage_wait;
1353 submit_info.waitSemaphoreCount = n_wait_semaphores;
1354 submit_info.pWaitSemaphores = wait_semaphores;
1355 submit_info.signalSemaphoreCount = 1;
1356 submit_info.pSignalSemaphores = &draw->semaphore;
1357
1358 device_data->vtable.QueueSubmit(device_data->graphic_queue->queue, 1, &submit_info, draw->fence);
1359
1360 return draw;
1361 }
1362
1363 static const uint32_t overlay_vert_spv[] = {
1364 #include "overlay.vert.spv.h"
1365 };
1366 static const uint32_t overlay_frag_spv[] = {
1367 #include "overlay.frag.spv.h"
1368 };
1369
1370 static void setup_swapchain_data_pipeline(struct swapchain_data *data)
1371 {
1372 struct device_data *device_data = data->device;
1373 VkShaderModule vert_module, frag_module;
1374
1375 /* Create shader modules */
1376 VkShaderModuleCreateInfo vert_info = {};
1377 vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1378 vert_info.codeSize = sizeof(overlay_vert_spv);
1379 vert_info.pCode = overlay_vert_spv;
1380 VK_CHECK(device_data->vtable.CreateShaderModule(device_data->device,
1381 &vert_info, NULL, &vert_module));
1382 VkShaderModuleCreateInfo frag_info = {};
1383 frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
1384 frag_info.codeSize = sizeof(overlay_frag_spv);
1385 frag_info.pCode = (uint32_t*)overlay_frag_spv;
1386 VK_CHECK(device_data->vtable.CreateShaderModule(device_data->device,
1387 &frag_info, NULL, &frag_module));
1388
1389 /* Font sampler */
1390 VkSamplerCreateInfo sampler_info = {};
1391 sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
1392 sampler_info.magFilter = VK_FILTER_LINEAR;
1393 sampler_info.minFilter = VK_FILTER_LINEAR;
1394 sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
1395 sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1396 sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1397 sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
1398 sampler_info.minLod = -1000;
1399 sampler_info.maxLod = 1000;
1400 sampler_info.maxAnisotropy = 1.0f;
1401 VK_CHECK(device_data->vtable.CreateSampler(device_data->device, &sampler_info,
1402 NULL, &data->font_sampler));
1403
1404 /* Descriptor pool */
1405 VkDescriptorPoolSize sampler_pool_size = {};
1406 sampler_pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1407 sampler_pool_size.descriptorCount = 1;
1408 VkDescriptorPoolCreateInfo desc_pool_info = {};
1409 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
1410 desc_pool_info.maxSets = 1;
1411 desc_pool_info.poolSizeCount = 1;
1412 desc_pool_info.pPoolSizes = &sampler_pool_size;
1413 VK_CHECK(device_data->vtable.CreateDescriptorPool(device_data->device,
1414 &desc_pool_info,
1415 NULL, &data->descriptor_pool));
1416
1417 /* Descriptor layout */
1418 VkSampler sampler[1] = { data->font_sampler };
1419 VkDescriptorSetLayoutBinding binding[1] = {};
1420 binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1421 binding[0].descriptorCount = 1;
1422 binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
1423 binding[0].pImmutableSamplers = sampler;
1424 VkDescriptorSetLayoutCreateInfo set_layout_info = {};
1425 set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
1426 set_layout_info.bindingCount = 1;
1427 set_layout_info.pBindings = binding;
1428 VK_CHECK(device_data->vtable.CreateDescriptorSetLayout(device_data->device,
1429 &set_layout_info,
1430 NULL, &data->descriptor_layout));
1431
1432 /* Descriptor set */
1433 VkDescriptorSetAllocateInfo alloc_info = {};
1434 alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
1435 alloc_info.descriptorPool = data->descriptor_pool;
1436 alloc_info.descriptorSetCount = 1;
1437 alloc_info.pSetLayouts = &data->descriptor_layout;
1438 VK_CHECK(device_data->vtable.AllocateDescriptorSets(device_data->device,
1439 &alloc_info,
1440 &data->descriptor_set));
1441
1442 /* Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full
1443 * 3d projection matrix
1444 */
1445 VkPushConstantRange push_constants[1] = {};
1446 push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
1447 push_constants[0].offset = sizeof(float) * 0;
1448 push_constants[0].size = sizeof(float) * 4;
1449 VkPipelineLayoutCreateInfo layout_info = {};
1450 layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
1451 layout_info.setLayoutCount = 1;
1452 layout_info.pSetLayouts = &data->descriptor_layout;
1453 layout_info.pushConstantRangeCount = 1;
1454 layout_info.pPushConstantRanges = push_constants;
1455 VK_CHECK(device_data->vtable.CreatePipelineLayout(device_data->device,
1456 &layout_info,
1457 NULL, &data->pipeline_layout));
1458
1459 VkPipelineShaderStageCreateInfo stage[2] = {};
1460 stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1461 stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
1462 stage[0].module = vert_module;
1463 stage[0].pName = "main";
1464 stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1465 stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
1466 stage[1].module = frag_module;
1467 stage[1].pName = "main";
1468
1469 VkVertexInputBindingDescription binding_desc[1] = {};
1470 binding_desc[0].stride = sizeof(ImDrawVert);
1471 binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1472
1473 VkVertexInputAttributeDescription attribute_desc[3] = {};
1474 attribute_desc[0].location = 0;
1475 attribute_desc[0].binding = binding_desc[0].binding;
1476 attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
1477 attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
1478 attribute_desc[1].location = 1;
1479 attribute_desc[1].binding = binding_desc[0].binding;
1480 attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
1481 attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
1482 attribute_desc[2].location = 2;
1483 attribute_desc[2].binding = binding_desc[0].binding;
1484 attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
1485 attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
1486
1487 VkPipelineVertexInputStateCreateInfo vertex_info = {};
1488 vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1489 vertex_info.vertexBindingDescriptionCount = 1;
1490 vertex_info.pVertexBindingDescriptions = binding_desc;
1491 vertex_info.vertexAttributeDescriptionCount = 3;
1492 vertex_info.pVertexAttributeDescriptions = attribute_desc;
1493
1494 VkPipelineInputAssemblyStateCreateInfo ia_info = {};
1495 ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1496 ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1497
1498 VkPipelineViewportStateCreateInfo viewport_info = {};
1499 viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1500 viewport_info.viewportCount = 1;
1501 viewport_info.scissorCount = 1;
1502
1503 VkPipelineRasterizationStateCreateInfo raster_info = {};
1504 raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1505 raster_info.polygonMode = VK_POLYGON_MODE_FILL;
1506 raster_info.cullMode = VK_CULL_MODE_NONE;
1507 raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1508 raster_info.lineWidth = 1.0f;
1509
1510 VkPipelineMultisampleStateCreateInfo ms_info = {};
1511 ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1512 ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
1513
1514 VkPipelineColorBlendAttachmentState color_attachment[1] = {};
1515 color_attachment[0].blendEnable = VK_TRUE;
1516 color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
1517 color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1518 color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
1519 color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1520 color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
1521 color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
1522 color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
1523 VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1524
1525 VkPipelineDepthStencilStateCreateInfo depth_info = {};
1526 depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1527
1528 VkPipelineColorBlendStateCreateInfo blend_info = {};
1529 blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1530 blend_info.attachmentCount = 1;
1531 blend_info.pAttachments = color_attachment;
1532
1533 VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
1534 VkPipelineDynamicStateCreateInfo dynamic_state = {};
1535 dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1536 dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
1537 dynamic_state.pDynamicStates = dynamic_states;
1538
1539 VkGraphicsPipelineCreateInfo info = {};
1540 info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1541 info.flags = 0;
1542 info.stageCount = 2;
1543 info.pStages = stage;
1544 info.pVertexInputState = &vertex_info;
1545 info.pInputAssemblyState = &ia_info;
1546 info.pViewportState = &viewport_info;
1547 info.pRasterizationState = &raster_info;
1548 info.pMultisampleState = &ms_info;
1549 info.pDepthStencilState = &depth_info;
1550 info.pColorBlendState = &blend_info;
1551 info.pDynamicState = &dynamic_state;
1552 info.layout = data->pipeline_layout;
1553 info.renderPass = data->render_pass;
1554 VK_CHECK(
1555 device_data->vtable.CreateGraphicsPipelines(device_data->device, VK_NULL_HANDLE,
1556 1, &info,
1557 NULL, &data->pipeline));
1558
1559 device_data->vtable.DestroyShaderModule(device_data->device, vert_module, NULL);
1560 device_data->vtable.DestroyShaderModule(device_data->device, frag_module, NULL);
1561
1562 ImGuiIO& io = ImGui::GetIO();
1563 unsigned char* pixels;
1564 int width, height;
1565 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1566
1567 /* Font image */
1568 VkImageCreateInfo image_info = {};
1569 image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1570 image_info.imageType = VK_IMAGE_TYPE_2D;
1571 image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1572 image_info.extent.width = width;
1573 image_info.extent.height = height;
1574 image_info.extent.depth = 1;
1575 image_info.mipLevels = 1;
1576 image_info.arrayLayers = 1;
1577 image_info.samples = VK_SAMPLE_COUNT_1_BIT;
1578 image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
1579 image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1580 image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1581 image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1582 VK_CHECK(device_data->vtable.CreateImage(device_data->device, &image_info,
1583 NULL, &data->font_image));
1584 VkMemoryRequirements font_image_req;
1585 device_data->vtable.GetImageMemoryRequirements(device_data->device,
1586 data->font_image, &font_image_req);
1587 VkMemoryAllocateInfo image_alloc_info = {};
1588 image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1589 image_alloc_info.allocationSize = font_image_req.size;
1590 image_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1591 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1592 font_image_req.memoryTypeBits);
1593 VK_CHECK(device_data->vtable.AllocateMemory(device_data->device, &image_alloc_info,
1594 NULL, &data->font_mem));
1595 VK_CHECK(device_data->vtable.BindImageMemory(device_data->device,
1596 data->font_image,
1597 data->font_mem, 0));
1598
1599 /* Font image view */
1600 VkImageViewCreateInfo view_info = {};
1601 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1602 view_info.image = data->font_image;
1603 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1604 view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1605 view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1606 view_info.subresourceRange.levelCount = 1;
1607 view_info.subresourceRange.layerCount = 1;
1608 VK_CHECK(device_data->vtable.CreateImageView(device_data->device, &view_info,
1609 NULL, &data->font_image_view));
1610
1611 /* Descriptor set */
1612 VkDescriptorImageInfo desc_image[1] = {};
1613 desc_image[0].sampler = data->font_sampler;
1614 desc_image[0].imageView = data->font_image_view;
1615 desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1616 VkWriteDescriptorSet write_desc[1] = {};
1617 write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1618 write_desc[0].dstSet = data->descriptor_set;
1619 write_desc[0].descriptorCount = 1;
1620 write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1621 write_desc[0].pImageInfo = desc_image;
1622 device_data->vtable.UpdateDescriptorSets(device_data->device, 1, write_desc, 0, NULL);
1623 }
1624
1625 static void setup_swapchain_data(struct swapchain_data *data,
1626 const VkSwapchainCreateInfoKHR *pCreateInfo)
1627 {
1628 data->width = pCreateInfo->imageExtent.width;
1629 data->height = pCreateInfo->imageExtent.height;
1630 data->format = pCreateInfo->imageFormat;
1631
1632 data->imgui_context = ImGui::CreateContext();
1633 ImGui::SetCurrentContext(data->imgui_context);
1634
1635 ImGui::GetIO().IniFilename = NULL;
1636 ImGui::GetIO().DisplaySize = ImVec2((float)data->width, (float)data->height);
1637
1638 struct device_data *device_data = data->device;
1639
1640 /* Render pass */
1641 VkAttachmentDescription attachment_desc = {};
1642 attachment_desc.format = pCreateInfo->imageFormat;
1643 attachment_desc.samples = VK_SAMPLE_COUNT_1_BIT;
1644 attachment_desc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
1645 attachment_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
1646 attachment_desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
1647 attachment_desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
1648 attachment_desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1649 attachment_desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1650 VkAttachmentReference color_attachment = {};
1651 color_attachment.attachment = 0;
1652 color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1653 VkSubpassDescription subpass = {};
1654 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
1655 subpass.colorAttachmentCount = 1;
1656 subpass.pColorAttachments = &color_attachment;
1657 VkSubpassDependency dependency = {};
1658 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
1659 dependency.dstSubpass = 0;
1660 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1661 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1662 dependency.srcAccessMask = 0;
1663 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1664 VkRenderPassCreateInfo render_pass_info = {};
1665 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
1666 render_pass_info.attachmentCount = 1;
1667 render_pass_info.pAttachments = &attachment_desc;
1668 render_pass_info.subpassCount = 1;
1669 render_pass_info.pSubpasses = &subpass;
1670 render_pass_info.dependencyCount = 1;
1671 render_pass_info.pDependencies = &dependency;
1672 VK_CHECK(device_data->vtable.CreateRenderPass(device_data->device,
1673 &render_pass_info,
1674 NULL, &data->render_pass));
1675
1676 setup_swapchain_data_pipeline(data);
1677
1678 VK_CHECK(device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1679 data->swapchain,
1680 &data->n_images,
1681 NULL));
1682
1683 data->images = ralloc_array(data, VkImage, data->n_images);
1684 data->image_views = ralloc_array(data, VkImageView, data->n_images);
1685 data->framebuffers = ralloc_array(data, VkFramebuffer, data->n_images);
1686
1687 VK_CHECK(device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1688 data->swapchain,
1689 &data->n_images,
1690 data->images));
1691
1692 /* Image views */
1693 VkImageViewCreateInfo view_info = {};
1694 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1695 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1696 view_info.format = pCreateInfo->imageFormat;
1697 view_info.components.r = VK_COMPONENT_SWIZZLE_R;
1698 view_info.components.g = VK_COMPONENT_SWIZZLE_G;
1699 view_info.components.b = VK_COMPONENT_SWIZZLE_B;
1700 view_info.components.a = VK_COMPONENT_SWIZZLE_A;
1701 view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1702 for (uint32_t i = 0; i < data->n_images; i++) {
1703 view_info.image = data->images[i];
1704 VK_CHECK(device_data->vtable.CreateImageView(device_data->device,
1705 &view_info, NULL,
1706 &data->image_views[i]));
1707 }
1708
1709 /* Framebuffers */
1710 VkImageView attachment[1];
1711 VkFramebufferCreateInfo fb_info = {};
1712 fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1713 fb_info.renderPass = data->render_pass;
1714 fb_info.attachmentCount = 1;
1715 fb_info.pAttachments = attachment;
1716 fb_info.width = data->width;
1717 fb_info.height = data->height;
1718 fb_info.layers = 1;
1719 for (uint32_t i = 0; i < data->n_images; i++) {
1720 attachment[0] = data->image_views[i];
1721 VK_CHECK(device_data->vtable.CreateFramebuffer(device_data->device, &fb_info,
1722 NULL, &data->framebuffers[i]));
1723 }
1724
1725 /* Command buffer pool */
1726 VkCommandPoolCreateInfo cmd_buffer_pool_info = {};
1727 cmd_buffer_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1728 cmd_buffer_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1729 cmd_buffer_pool_info.queueFamilyIndex = device_data->graphic_queue->family_index;
1730 VK_CHECK(device_data->vtable.CreateCommandPool(device_data->device,
1731 &cmd_buffer_pool_info,
1732 NULL, &data->command_pool));
1733 }
1734
1735 static void shutdown_swapchain_data(struct swapchain_data *data)
1736 {
1737 struct device_data *device_data = data->device;
1738
1739 list_for_each_entry_safe(struct overlay_draw, draw, &data->draws, link) {
1740 device_data->vtable.DestroySemaphore(device_data->device, draw->semaphore, NULL);
1741 device_data->vtable.DestroyFence(device_data->device, draw->fence, NULL);
1742 device_data->vtable.DestroyBuffer(device_data->device, draw->vertex_buffer, NULL);
1743 device_data->vtable.DestroyBuffer(device_data->device, draw->index_buffer, NULL);
1744 device_data->vtable.FreeMemory(device_data->device, draw->vertex_buffer_mem, NULL);
1745 device_data->vtable.FreeMemory(device_data->device, draw->index_buffer_mem, NULL);
1746 }
1747
1748 for (uint32_t i = 0; i < data->n_images; i++) {
1749 device_data->vtable.DestroyImageView(device_data->device, data->image_views[i], NULL);
1750 device_data->vtable.DestroyFramebuffer(device_data->device, data->framebuffers[i], NULL);
1751 }
1752
1753 device_data->vtable.DestroyRenderPass(device_data->device, data->render_pass, NULL);
1754
1755 device_data->vtable.DestroyCommandPool(device_data->device, data->command_pool, NULL);
1756
1757 device_data->vtable.DestroyPipeline(device_data->device, data->pipeline, NULL);
1758 device_data->vtable.DestroyPipelineLayout(device_data->device, data->pipeline_layout, NULL);
1759
1760 device_data->vtable.DestroyDescriptorPool(device_data->device,
1761 data->descriptor_pool, NULL);
1762 device_data->vtable.DestroyDescriptorSetLayout(device_data->device,
1763 data->descriptor_layout, NULL);
1764
1765 device_data->vtable.DestroySampler(device_data->device, data->font_sampler, NULL);
1766 device_data->vtable.DestroyImageView(device_data->device, data->font_image_view, NULL);
1767 device_data->vtable.DestroyImage(device_data->device, data->font_image, NULL);
1768 device_data->vtable.FreeMemory(device_data->device, data->font_mem, NULL);
1769
1770 device_data->vtable.DestroyBuffer(device_data->device, data->upload_font_buffer, NULL);
1771 device_data->vtable.FreeMemory(device_data->device, data->upload_font_buffer_mem, NULL);
1772
1773 ImGui::DestroyContext(data->imgui_context);
1774 }
1775
1776 static struct overlay_draw *before_present(struct swapchain_data *swapchain_data,
1777 struct queue_data *present_queue,
1778 const VkSemaphore *wait_semaphores,
1779 unsigned n_wait_semaphores,
1780 unsigned imageIndex)
1781 {
1782 struct instance_data *instance_data = swapchain_data->device->instance;
1783 struct overlay_draw *draw = NULL;
1784
1785 snapshot_swapchain_frame(swapchain_data);
1786
1787 if (!instance_data->params.no_display && swapchain_data->n_frames > 0) {
1788 compute_swapchain_display(swapchain_data);
1789 draw = render_swapchain_display(swapchain_data, present_queue,
1790 wait_semaphores, n_wait_semaphores,
1791 imageIndex);
1792 }
1793
1794 return draw;
1795 }
1796
1797 static VkResult overlay_CreateSwapchainKHR(
1798 VkDevice device,
1799 const VkSwapchainCreateInfoKHR* pCreateInfo,
1800 const VkAllocationCallbacks* pAllocator,
1801 VkSwapchainKHR* pSwapchain)
1802 {
1803 struct device_data *device_data = FIND(struct device_data, device);
1804 VkResult result = device_data->vtable.CreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
1805 if (result != VK_SUCCESS) return result;
1806
1807 struct swapchain_data *swapchain_data = new_swapchain_data(*pSwapchain, device_data);
1808 setup_swapchain_data(swapchain_data, pCreateInfo);
1809 return result;
1810 }
1811
1812 static void overlay_DestroySwapchainKHR(
1813 VkDevice device,
1814 VkSwapchainKHR swapchain,
1815 const VkAllocationCallbacks* pAllocator)
1816 {
1817 struct swapchain_data *swapchain_data =
1818 FIND(struct swapchain_data, swapchain);
1819
1820 shutdown_swapchain_data(swapchain_data);
1821 swapchain_data->device->vtable.DestroySwapchainKHR(device, swapchain, pAllocator);
1822 destroy_swapchain_data(swapchain_data);
1823 }
1824
1825 static VkResult overlay_QueuePresentKHR(
1826 VkQueue queue,
1827 const VkPresentInfoKHR* pPresentInfo)
1828 {
1829 struct queue_data *queue_data = FIND(struct queue_data, queue);
1830 struct device_data *device_data = queue_data->device;
1831 struct instance_data *instance_data = device_data->instance;
1832 uint32_t query_results[OVERLAY_QUERY_COUNT];
1833
1834 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_frame]++;
1835
1836 if (list_length(&queue_data->running_command_buffer) > 0) {
1837 /* Before getting the query results, make sure the operations have
1838 * completed.
1839 */
1840 VK_CHECK(device_data->vtable.ResetFences(device_data->device,
1841 1, &queue_data->queries_fence));
1842 VK_CHECK(device_data->vtable.QueueSubmit(queue, 0, NULL, queue_data->queries_fence));
1843 VK_CHECK(device_data->vtable.WaitForFences(device_data->device,
1844 1, &queue_data->queries_fence,
1845 VK_FALSE, UINT64_MAX));
1846
1847 /* Now get the results. */
1848 list_for_each_entry_safe(struct command_buffer_data, cmd_buffer_data,
1849 &queue_data->running_command_buffer, link) {
1850 list_delinit(&cmd_buffer_data->link);
1851
1852 if (cmd_buffer_data->pipeline_query_pool) {
1853 memset(query_results, 0, sizeof(query_results));
1854 VK_CHECK(device_data->vtable.GetQueryPoolResults(device_data->device,
1855 cmd_buffer_data->pipeline_query_pool,
1856 cmd_buffer_data->query_index, 1,
1857 sizeof(uint32_t) * OVERLAY_QUERY_COUNT,
1858 query_results, 0, VK_QUERY_RESULT_WAIT_BIT));
1859
1860 for (uint32_t i = OVERLAY_PARAM_ENABLED_vertices;
1861 i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
1862 device_data->frame_stats.stats[i] += query_results[i - OVERLAY_PARAM_ENABLED_vertices];
1863 }
1864 }
1865 if (cmd_buffer_data->timestamp_query_pool) {
1866 uint64_t gpu_timestamps[2] = { 0 };
1867 VK_CHECK(device_data->vtable.GetQueryPoolResults(device_data->device,
1868 cmd_buffer_data->timestamp_query_pool,
1869 cmd_buffer_data->query_index * 2, 2,
1870 2 * sizeof(uint64_t), gpu_timestamps, sizeof(uint64_t),
1871 VK_QUERY_RESULT_WAIT_BIT | VK_QUERY_RESULT_64_BIT));
1872
1873 gpu_timestamps[0] &= queue_data->timestamp_mask;
1874 gpu_timestamps[1] &= queue_data->timestamp_mask;
1875 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_gpu_timing] +=
1876 (gpu_timestamps[1] - gpu_timestamps[0]) *
1877 device_data->properties.limits.timestampPeriod;
1878 }
1879 }
1880 }
1881
1882 /* Otherwise we need to add our overlay drawing semaphore to the list of
1883 * semaphores to wait on. If we don't do that the presented picture might
1884 * be have incomplete overlay drawings.
1885 */
1886 VkResult result = VK_SUCCESS;
1887 if (instance_data->params.no_display) {
1888 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1889 VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1890 struct swapchain_data *swapchain_data =
1891 FIND(struct swapchain_data, swapchain);
1892
1893 before_present(swapchain_data,
1894 queue_data,
1895 pPresentInfo->pWaitSemaphores,
1896 pPresentInfo->waitSemaphoreCount,
1897 pPresentInfo->pImageIndices[i]);
1898
1899 VkPresentInfoKHR present_info = *pPresentInfo;
1900 present_info.swapchainCount = 1;
1901 present_info.pSwapchains = &swapchain;
1902
1903 uint64_t ts0 = os_time_get();
1904 result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1905 uint64_t ts1 = os_time_get();
1906 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1907 }
1908 } else {
1909 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1910 VkSwapchainKHR swapchain = pPresentInfo->pSwapchains[i];
1911 struct swapchain_data *swapchain_data =
1912 FIND(struct swapchain_data, swapchain);
1913 VkPresentInfoKHR present_info = *pPresentInfo;
1914 present_info.swapchainCount = 1;
1915 present_info.pSwapchains = &swapchain;
1916
1917 uint32_t image_index = pPresentInfo->pImageIndices[i];
1918
1919 struct overlay_draw *draw = before_present(swapchain_data,
1920 queue_data,
1921 pPresentInfo->pWaitSemaphores,
1922 pPresentInfo->waitSemaphoreCount,
1923 image_index);
1924
1925 /* Because the submission of the overlay draw waits on the semaphores
1926 * handed for present, we don't need to have this present operation
1927 * wait on them as well, we can just wait on the overlay submission
1928 * semaphore.
1929 */
1930 present_info.pWaitSemaphores = &draw->semaphore;
1931 present_info.waitSemaphoreCount = 1;
1932
1933 uint64_t ts0 = os_time_get();
1934 VkResult chain_result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1935 uint64_t ts1 = os_time_get();
1936 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_present_timing] += ts1 - ts0;
1937 if (pPresentInfo->pResults)
1938 pPresentInfo->pResults[i] = chain_result;
1939 if (chain_result != VK_SUCCESS && result == VK_SUCCESS)
1940 result = chain_result;
1941 }
1942 }
1943 return result;
1944 }
1945
1946 static VkResult overlay_AcquireNextImageKHR(
1947 VkDevice device,
1948 VkSwapchainKHR swapchain,
1949 uint64_t timeout,
1950 VkSemaphore semaphore,
1951 VkFence fence,
1952 uint32_t* pImageIndex)
1953 {
1954 struct swapchain_data *swapchain_data =
1955 FIND(struct swapchain_data, swapchain);
1956 struct device_data *device_data = swapchain_data->device;
1957
1958 uint64_t ts0 = os_time_get();
1959 VkResult result = device_data->vtable.AcquireNextImageKHR(device, swapchain, timeout,
1960 semaphore, fence, pImageIndex);
1961 uint64_t ts1 = os_time_get();
1962
1963 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
1964 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
1965
1966 return result;
1967 }
1968
1969 static VkResult overlay_AcquireNextImage2KHR(
1970 VkDevice device,
1971 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1972 uint32_t* pImageIndex)
1973 {
1974 struct swapchain_data *swapchain_data =
1975 FIND(struct swapchain_data, pAcquireInfo->swapchain);
1976 struct device_data *device_data = swapchain_data->device;
1977
1978 uint64_t ts0 = os_time_get();
1979 VkResult result = device_data->vtable.AcquireNextImage2KHR(device, pAcquireInfo, pImageIndex);
1980 uint64_t ts1 = os_time_get();
1981
1982 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire_timing] += ts1 - ts0;
1983 swapchain_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_acquire]++;
1984
1985 return result;
1986 }
1987
1988 static void overlay_CmdDraw(
1989 VkCommandBuffer commandBuffer,
1990 uint32_t vertexCount,
1991 uint32_t instanceCount,
1992 uint32_t firstVertex,
1993 uint32_t firstInstance)
1994 {
1995 struct command_buffer_data *cmd_buffer_data =
1996 FIND(struct command_buffer_data, commandBuffer);
1997 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw]++;
1998 struct device_data *device_data = cmd_buffer_data->device;
1999 device_data->vtable.CmdDraw(commandBuffer, vertexCount, instanceCount,
2000 firstVertex, firstInstance);
2001 }
2002
2003 static void overlay_CmdDrawIndexed(
2004 VkCommandBuffer commandBuffer,
2005 uint32_t indexCount,
2006 uint32_t instanceCount,
2007 uint32_t firstIndex,
2008 int32_t vertexOffset,
2009 uint32_t firstInstance)
2010 {
2011 struct command_buffer_data *cmd_buffer_data =
2012 FIND(struct command_buffer_data, commandBuffer);
2013 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed]++;
2014 struct device_data *device_data = cmd_buffer_data->device;
2015 device_data->vtable.CmdDrawIndexed(commandBuffer, indexCount, instanceCount,
2016 firstIndex, vertexOffset, firstInstance);
2017 }
2018
2019 static void overlay_CmdDrawIndirect(
2020 VkCommandBuffer commandBuffer,
2021 VkBuffer buffer,
2022 VkDeviceSize offset,
2023 uint32_t drawCount,
2024 uint32_t stride)
2025 {
2026 struct command_buffer_data *cmd_buffer_data =
2027 FIND(struct command_buffer_data, commandBuffer);
2028 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect]++;
2029 struct device_data *device_data = cmd_buffer_data->device;
2030 device_data->vtable.CmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
2031 }
2032
2033 static void overlay_CmdDrawIndexedIndirect(
2034 VkCommandBuffer commandBuffer,
2035 VkBuffer buffer,
2036 VkDeviceSize offset,
2037 uint32_t drawCount,
2038 uint32_t stride)
2039 {
2040 struct command_buffer_data *cmd_buffer_data =
2041 FIND(struct command_buffer_data, commandBuffer);
2042 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect]++;
2043 struct device_data *device_data = cmd_buffer_data->device;
2044 device_data->vtable.CmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
2045 }
2046
2047 static void overlay_CmdDrawIndirectCount(
2048 VkCommandBuffer commandBuffer,
2049 VkBuffer buffer,
2050 VkDeviceSize offset,
2051 VkBuffer countBuffer,
2052 VkDeviceSize countBufferOffset,
2053 uint32_t maxDrawCount,
2054 uint32_t stride)
2055 {
2056 struct command_buffer_data *cmd_buffer_data =
2057 FIND(struct command_buffer_data, commandBuffer);
2058 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect_count]++;
2059 struct device_data *device_data = cmd_buffer_data->device;
2060 device_data->vtable.CmdDrawIndirectCount(commandBuffer, buffer, offset,
2061 countBuffer, countBufferOffset,
2062 maxDrawCount, stride);
2063 }
2064
2065 static void overlay_CmdDrawIndexedIndirectCount(
2066 VkCommandBuffer commandBuffer,
2067 VkBuffer buffer,
2068 VkDeviceSize offset,
2069 VkBuffer countBuffer,
2070 VkDeviceSize countBufferOffset,
2071 uint32_t maxDrawCount,
2072 uint32_t stride)
2073 {
2074 struct command_buffer_data *cmd_buffer_data =
2075 FIND(struct command_buffer_data, commandBuffer);
2076 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect_count]++;
2077 struct device_data *device_data = cmd_buffer_data->device;
2078 device_data->vtable.CmdDrawIndexedIndirectCount(commandBuffer, buffer, offset,
2079 countBuffer, countBufferOffset,
2080 maxDrawCount, stride);
2081 }
2082
2083 static void overlay_CmdDispatch(
2084 VkCommandBuffer commandBuffer,
2085 uint32_t groupCountX,
2086 uint32_t groupCountY,
2087 uint32_t groupCountZ)
2088 {
2089 struct command_buffer_data *cmd_buffer_data =
2090 FIND(struct command_buffer_data, commandBuffer);
2091 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch]++;
2092 struct device_data *device_data = cmd_buffer_data->device;
2093 device_data->vtable.CmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ);
2094 }
2095
2096 static void overlay_CmdDispatchIndirect(
2097 VkCommandBuffer commandBuffer,
2098 VkBuffer buffer,
2099 VkDeviceSize offset)
2100 {
2101 struct command_buffer_data *cmd_buffer_data =
2102 FIND(struct command_buffer_data, commandBuffer);
2103 cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch_indirect]++;
2104 struct device_data *device_data = cmd_buffer_data->device;
2105 device_data->vtable.CmdDispatchIndirect(commandBuffer, buffer, offset);
2106 }
2107
2108 static void overlay_CmdBindPipeline(
2109 VkCommandBuffer commandBuffer,
2110 VkPipelineBindPoint pipelineBindPoint,
2111 VkPipeline pipeline)
2112 {
2113 struct command_buffer_data *cmd_buffer_data =
2114 FIND(struct command_buffer_data, commandBuffer);
2115 switch (pipelineBindPoint) {
2116 case VK_PIPELINE_BIND_POINT_GRAPHICS: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_graphics]++; break;
2117 case VK_PIPELINE_BIND_POINT_COMPUTE: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_compute]++; break;
2118 case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV: cmd_buffer_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_raytracing]++; break;
2119 default: break;
2120 }
2121 struct device_data *device_data = cmd_buffer_data->device;
2122 device_data->vtable.CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
2123 }
2124
2125 static VkResult overlay_BeginCommandBuffer(
2126 VkCommandBuffer commandBuffer,
2127 const VkCommandBufferBeginInfo* pBeginInfo)
2128 {
2129 struct command_buffer_data *cmd_buffer_data =
2130 FIND(struct command_buffer_data, commandBuffer);
2131 struct device_data *device_data = cmd_buffer_data->device;
2132
2133 memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2134
2135 /* We don't record any query in secondary command buffers, just make sure
2136 * we have the right inheritance.
2137 */
2138 if (cmd_buffer_data->level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) {
2139 VkCommandBufferBeginInfo *begin_info = (VkCommandBufferBeginInfo *)
2140 clone_chain((const struct VkBaseInStructure *)pBeginInfo);
2141 VkCommandBufferInheritanceInfo *parent_inhe_info = (VkCommandBufferInheritanceInfo *)
2142 vk_find_struct(begin_info, COMMAND_BUFFER_INHERITANCE_INFO);
2143 VkCommandBufferInheritanceInfo inhe_info = {
2144 VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO,
2145 NULL,
2146 VK_NULL_HANDLE,
2147 0,
2148 VK_NULL_HANDLE,
2149 VK_FALSE,
2150 0,
2151 overlay_query_flags,
2152 };
2153
2154 if (parent_inhe_info)
2155 parent_inhe_info->pipelineStatistics = overlay_query_flags;
2156 else {
2157 inhe_info.pNext = begin_info->pNext;
2158 begin_info->pNext = &inhe_info;
2159 }
2160
2161 VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2162
2163 if (!parent_inhe_info)
2164 begin_info->pNext = inhe_info.pNext;
2165
2166 free_chain((struct VkBaseOutStructure *)begin_info);
2167
2168 return result;
2169 }
2170
2171 /* Otherwise record a begin query as first command. */
2172 VkResult result = device_data->vtable.BeginCommandBuffer(commandBuffer, pBeginInfo);
2173
2174 if (result == VK_SUCCESS) {
2175 if (cmd_buffer_data->pipeline_query_pool) {
2176 device_data->vtable.CmdResetQueryPool(commandBuffer,
2177 cmd_buffer_data->pipeline_query_pool,
2178 cmd_buffer_data->query_index, 1);
2179 }
2180 if (cmd_buffer_data->timestamp_query_pool) {
2181 device_data->vtable.CmdResetQueryPool(commandBuffer,
2182 cmd_buffer_data->timestamp_query_pool,
2183 cmd_buffer_data->query_index * 2, 2);
2184 }
2185 if (cmd_buffer_data->pipeline_query_pool) {
2186 device_data->vtable.CmdBeginQuery(commandBuffer,
2187 cmd_buffer_data->pipeline_query_pool,
2188 cmd_buffer_data->query_index, 0);
2189 }
2190 if (cmd_buffer_data->timestamp_query_pool) {
2191 device_data->vtable.CmdWriteTimestamp(commandBuffer,
2192 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2193 cmd_buffer_data->timestamp_query_pool,
2194 cmd_buffer_data->query_index * 2);
2195 }
2196 }
2197
2198 return result;
2199 }
2200
2201 static VkResult overlay_EndCommandBuffer(
2202 VkCommandBuffer commandBuffer)
2203 {
2204 struct command_buffer_data *cmd_buffer_data =
2205 FIND(struct command_buffer_data, commandBuffer);
2206 struct device_data *device_data = cmd_buffer_data->device;
2207
2208 if (cmd_buffer_data->timestamp_query_pool) {
2209 device_data->vtable.CmdWriteTimestamp(commandBuffer,
2210 VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
2211 cmd_buffer_data->timestamp_query_pool,
2212 cmd_buffer_data->query_index * 2 + 1);
2213 }
2214 if (cmd_buffer_data->pipeline_query_pool) {
2215 device_data->vtable.CmdEndQuery(commandBuffer,
2216 cmd_buffer_data->pipeline_query_pool,
2217 cmd_buffer_data->query_index);
2218 }
2219
2220 return device_data->vtable.EndCommandBuffer(commandBuffer);
2221 }
2222
2223 static VkResult overlay_ResetCommandBuffer(
2224 VkCommandBuffer commandBuffer,
2225 VkCommandBufferResetFlags flags)
2226 {
2227 struct command_buffer_data *cmd_buffer_data =
2228 FIND(struct command_buffer_data, commandBuffer);
2229 struct device_data *device_data = cmd_buffer_data->device;
2230
2231 memset(&cmd_buffer_data->stats, 0, sizeof(cmd_buffer_data->stats));
2232
2233 return device_data->vtable.ResetCommandBuffer(commandBuffer, flags);
2234 }
2235
2236 static void overlay_CmdExecuteCommands(
2237 VkCommandBuffer commandBuffer,
2238 uint32_t commandBufferCount,
2239 const VkCommandBuffer* pCommandBuffers)
2240 {
2241 struct command_buffer_data *cmd_buffer_data =
2242 FIND(struct command_buffer_data, commandBuffer);
2243 struct device_data *device_data = cmd_buffer_data->device;
2244
2245 /* Add the stats of the executed command buffers to the primary one. */
2246 for (uint32_t c = 0; c < commandBufferCount; c++) {
2247 struct command_buffer_data *sec_cmd_buffer_data =
2248 FIND(struct command_buffer_data, pCommandBuffers[c]);
2249
2250 for (uint32_t s = 0; s < OVERLAY_PARAM_ENABLED_MAX; s++)
2251 cmd_buffer_data->stats.stats[s] += sec_cmd_buffer_data->stats.stats[s];
2252 }
2253
2254 device_data->vtable.CmdExecuteCommands(commandBuffer, commandBufferCount, pCommandBuffers);
2255 }
2256
2257 static VkResult overlay_AllocateCommandBuffers(
2258 VkDevice device,
2259 const VkCommandBufferAllocateInfo* pAllocateInfo,
2260 VkCommandBuffer* pCommandBuffers)
2261 {
2262 struct device_data *device_data = FIND(struct device_data, device);
2263 VkResult result =
2264 device_data->vtable.AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
2265 if (result != VK_SUCCESS)
2266 return result;
2267
2268 VkQueryPool pipeline_query_pool = VK_NULL_HANDLE;
2269 VkQueryPool timestamp_query_pool = VK_NULL_HANDLE;
2270 if (device_data->instance->pipeline_statistics_enabled &&
2271 pAllocateInfo->level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) {
2272 VkQueryPoolCreateInfo pool_info = {
2273 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2274 NULL,
2275 0,
2276 VK_QUERY_TYPE_PIPELINE_STATISTICS,
2277 pAllocateInfo->commandBufferCount,
2278 overlay_query_flags,
2279 };
2280 VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2281 NULL, &pipeline_query_pool));
2282 }
2283 if (device_data->instance->params.enabled[OVERLAY_PARAM_ENABLED_gpu_timing]) {
2284 VkQueryPoolCreateInfo pool_info = {
2285 VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
2286 NULL,
2287 0,
2288 VK_QUERY_TYPE_TIMESTAMP,
2289 pAllocateInfo->commandBufferCount * 2,
2290 0,
2291 };
2292 VK_CHECK(device_data->vtable.CreateQueryPool(device_data->device, &pool_info,
2293 NULL, &timestamp_query_pool));
2294 }
2295
2296 for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++) {
2297 new_command_buffer_data(pCommandBuffers[i], pAllocateInfo->level,
2298 pipeline_query_pool, timestamp_query_pool,
2299 i, device_data);
2300 }
2301
2302 if (pipeline_query_pool)
2303 map_object(HKEY(pipeline_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2304 if (timestamp_query_pool)
2305 map_object(HKEY(timestamp_query_pool), (void *)(uintptr_t) pAllocateInfo->commandBufferCount);
2306
2307 return result;
2308 }
2309
2310 static void overlay_FreeCommandBuffers(
2311 VkDevice device,
2312 VkCommandPool commandPool,
2313 uint32_t commandBufferCount,
2314 const VkCommandBuffer* pCommandBuffers)
2315 {
2316 struct device_data *device_data = FIND(struct device_data, device);
2317 for (uint32_t i = 0; i < commandBufferCount; i++) {
2318 struct command_buffer_data *cmd_buffer_data =
2319 FIND(struct command_buffer_data, pCommandBuffers[i]);
2320
2321 /* It is legal to free a NULL command buffer*/
2322 if (!cmd_buffer_data)
2323 continue;
2324
2325 uint64_t count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->pipeline_query_pool));
2326 if (count == 1) {
2327 unmap_object(HKEY(cmd_buffer_data->pipeline_query_pool));
2328 device_data->vtable.DestroyQueryPool(device_data->device,
2329 cmd_buffer_data->pipeline_query_pool, NULL);
2330 } else if (count != 0) {
2331 map_object(HKEY(cmd_buffer_data->pipeline_query_pool), (void *)(uintptr_t)(count - 1));
2332 }
2333 count = (uintptr_t)find_object_data(HKEY(cmd_buffer_data->timestamp_query_pool));
2334 if (count == 1) {
2335 unmap_object(HKEY(cmd_buffer_data->timestamp_query_pool));
2336 device_data->vtable.DestroyQueryPool(device_data->device,
2337 cmd_buffer_data->timestamp_query_pool, NULL);
2338 } else if (count != 0) {
2339 map_object(HKEY(cmd_buffer_data->timestamp_query_pool), (void *)(uintptr_t)(count - 1));
2340 }
2341 destroy_command_buffer_data(cmd_buffer_data);
2342 }
2343
2344 device_data->vtable.FreeCommandBuffers(device, commandPool,
2345 commandBufferCount, pCommandBuffers);
2346 }
2347
2348 static VkResult overlay_QueueSubmit(
2349 VkQueue queue,
2350 uint32_t submitCount,
2351 const VkSubmitInfo* pSubmits,
2352 VkFence fence)
2353 {
2354 struct queue_data *queue_data = FIND(struct queue_data, queue);
2355 struct device_data *device_data = queue_data->device;
2356
2357 device_data->frame_stats.stats[OVERLAY_PARAM_ENABLED_submit]++;
2358
2359 for (uint32_t s = 0; s < submitCount; s++) {
2360 for (uint32_t c = 0; c < pSubmits[s].commandBufferCount; c++) {
2361 struct command_buffer_data *cmd_buffer_data =
2362 FIND(struct command_buffer_data, pSubmits[s].pCommandBuffers[c]);
2363
2364 /* Merge the submitted command buffer stats into the device. */
2365 for (uint32_t st = 0; st < OVERLAY_PARAM_ENABLED_MAX; st++)
2366 device_data->frame_stats.stats[st] += cmd_buffer_data->stats.stats[st];
2367
2368 /* Attach the command buffer to the queue so we remember to read its
2369 * pipeline statistics & timestamps at QueuePresent().
2370 */
2371 if (!cmd_buffer_data->pipeline_query_pool &&
2372 !cmd_buffer_data->timestamp_query_pool)
2373 continue;
2374
2375 if (list_is_empty(&cmd_buffer_data->link)) {
2376 list_addtail(&cmd_buffer_data->link,
2377 &queue_data->running_command_buffer);
2378 } else {
2379 fprintf(stderr, "Command buffer submitted multiple times before present.\n"
2380 "This could lead to invalid data.\n");
2381 }
2382 }
2383 }
2384
2385 return device_data->vtable.QueueSubmit(queue, submitCount, pSubmits, fence);
2386 }
2387
2388 static VkResult overlay_CreateDevice(
2389 VkPhysicalDevice physicalDevice,
2390 const VkDeviceCreateInfo* pCreateInfo,
2391 const VkAllocationCallbacks* pAllocator,
2392 VkDevice* pDevice)
2393 {
2394 struct instance_data *instance_data =
2395 FIND(struct instance_data, physicalDevice);
2396 VkLayerDeviceCreateInfo *chain_info =
2397 get_device_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2398
2399 assert(chain_info->u.pLayerInfo);
2400 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2401 PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
2402 PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
2403 if (fpCreateDevice == NULL) {
2404 return VK_ERROR_INITIALIZATION_FAILED;
2405 }
2406
2407 // Advance the link info for the next element on the chain
2408 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2409
2410 VkPhysicalDeviceFeatures device_features = {};
2411 VkDeviceCreateInfo device_info = *pCreateInfo;
2412
2413 if (pCreateInfo->pEnabledFeatures)
2414 device_features = *(pCreateInfo->pEnabledFeatures);
2415 if (instance_data->pipeline_statistics_enabled) {
2416 device_features.inheritedQueries = true;
2417 device_features.pipelineStatisticsQuery = true;
2418 }
2419 device_info.pEnabledFeatures = &device_features;
2420
2421
2422 VkResult result = fpCreateDevice(physicalDevice, &device_info, pAllocator, pDevice);
2423 if (result != VK_SUCCESS) return result;
2424
2425 struct device_data *device_data = new_device_data(*pDevice, instance_data);
2426 device_data->physical_device = physicalDevice;
2427 vk_load_device_commands(*pDevice, fpGetDeviceProcAddr, &device_data->vtable);
2428
2429 instance_data->vtable.GetPhysicalDeviceProperties(device_data->physical_device,
2430 &device_data->properties);
2431
2432 VkLayerDeviceCreateInfo *load_data_info =
2433 get_device_chain_info(pCreateInfo, VK_LOADER_DATA_CALLBACK);
2434 device_data->set_device_loader_data = load_data_info->u.pfnSetDeviceLoaderData;
2435
2436 device_map_queues(device_data, pCreateInfo);
2437
2438 return result;
2439 }
2440
2441 static void overlay_DestroyDevice(
2442 VkDevice device,
2443 const VkAllocationCallbacks* pAllocator)
2444 {
2445 struct device_data *device_data = FIND(struct device_data, device);
2446 device_unmap_queues(device_data);
2447 device_data->vtable.DestroyDevice(device, pAllocator);
2448 destroy_device_data(device_data);
2449 }
2450
2451 static VkResult overlay_CreateInstance(
2452 const VkInstanceCreateInfo* pCreateInfo,
2453 const VkAllocationCallbacks* pAllocator,
2454 VkInstance* pInstance)
2455 {
2456 VkLayerInstanceCreateInfo *chain_info =
2457 get_instance_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
2458
2459 assert(chain_info->u.pLayerInfo);
2460 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
2461 chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
2462 PFN_vkCreateInstance fpCreateInstance =
2463 (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
2464 if (fpCreateInstance == NULL) {
2465 return VK_ERROR_INITIALIZATION_FAILED;
2466 }
2467
2468 // Advance the link info for the next element on the chain
2469 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
2470
2471 VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
2472 if (result != VK_SUCCESS) return result;
2473
2474 struct instance_data *instance_data = new_instance_data(*pInstance);
2475 vk_load_instance_commands(instance_data->instance,
2476 fpGetInstanceProcAddr,
2477 &instance_data->vtable);
2478 instance_data_map_physical_devices(instance_data, true);
2479
2480 parse_overlay_env(&instance_data->params, getenv("VK_LAYER_MESA_OVERLAY_CONFIG"));
2481
2482 /* If there's no control file, and an output_file was specified, start
2483 * capturing fps data right away.
2484 */
2485 instance_data->capture_enabled =
2486 instance_data->params.output_file && instance_data->params.control < 0;
2487 instance_data->capture_started = instance_data->capture_enabled;
2488
2489 for (int i = OVERLAY_PARAM_ENABLED_vertices;
2490 i <= OVERLAY_PARAM_ENABLED_compute_invocations; i++) {
2491 if (instance_data->params.enabled[i]) {
2492 instance_data->pipeline_statistics_enabled = true;
2493 break;
2494 }
2495 }
2496
2497 return result;
2498 }
2499
2500 static void overlay_DestroyInstance(
2501 VkInstance instance,
2502 const VkAllocationCallbacks* pAllocator)
2503 {
2504 struct instance_data *instance_data = FIND(struct instance_data, instance);
2505 instance_data_map_physical_devices(instance_data, false);
2506 instance_data->vtable.DestroyInstance(instance, pAllocator);
2507 destroy_instance_data(instance_data);
2508 }
2509
2510 static const struct {
2511 const char *name;
2512 void *ptr;
2513 } name_to_funcptr_map[] = {
2514 { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr },
2515 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
2516 #define ADD_ALIAS_HOOK(alias, fn) { "vk" # alias, (void *) overlay_ ## fn }
2517 ADD_HOOK(AllocateCommandBuffers),
2518 ADD_HOOK(FreeCommandBuffers),
2519 ADD_HOOK(ResetCommandBuffer),
2520 ADD_HOOK(BeginCommandBuffer),
2521 ADD_HOOK(EndCommandBuffer),
2522 ADD_HOOK(CmdExecuteCommands),
2523
2524 ADD_HOOK(CmdDraw),
2525 ADD_HOOK(CmdDrawIndexed),
2526 ADD_HOOK(CmdDrawIndirect),
2527 ADD_HOOK(CmdDrawIndexedIndirect),
2528 ADD_HOOK(CmdDispatch),
2529 ADD_HOOK(CmdDispatchIndirect),
2530 ADD_HOOK(CmdDrawIndirectCount),
2531 ADD_ALIAS_HOOK(CmdDrawIndirectCountKHR, CmdDrawIndirectCount),
2532 ADD_HOOK(CmdDrawIndexedIndirectCount),
2533 ADD_ALIAS_HOOK(CmdDrawIndexedIndirectCountKHR, CmdDrawIndexedIndirectCount),
2534
2535 ADD_HOOK(CmdBindPipeline),
2536
2537 ADD_HOOK(CreateSwapchainKHR),
2538 ADD_HOOK(QueuePresentKHR),
2539 ADD_HOOK(DestroySwapchainKHR),
2540 ADD_HOOK(AcquireNextImageKHR),
2541 ADD_HOOK(AcquireNextImage2KHR),
2542
2543 ADD_HOOK(QueueSubmit),
2544
2545 ADD_HOOK(CreateDevice),
2546 ADD_HOOK(DestroyDevice),
2547
2548 ADD_HOOK(CreateInstance),
2549 ADD_HOOK(DestroyInstance),
2550 #undef ADD_HOOK
2551 };
2552
2553 static void *find_ptr(const char *name)
2554 {
2555 for (uint32_t i = 0; i < ARRAY_SIZE(name_to_funcptr_map); i++) {
2556 if (strcmp(name, name_to_funcptr_map[i].name) == 0)
2557 return name_to_funcptr_map[i].ptr;
2558 }
2559
2560 return NULL;
2561 }
2562
2563 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev,
2564 const char *funcName)
2565 {
2566 void *ptr = find_ptr(funcName);
2567 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2568
2569 if (dev == NULL) return NULL;
2570
2571 struct device_data *device_data = FIND(struct device_data, dev);
2572 if (device_data->vtable.GetDeviceProcAddr == NULL) return NULL;
2573 return device_data->vtable.GetDeviceProcAddr(dev, funcName);
2574 }
2575
2576 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance,
2577 const char *funcName)
2578 {
2579 void *ptr = find_ptr(funcName);
2580 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
2581
2582 if (instance == NULL) return NULL;
2583
2584 struct instance_data *instance_data = FIND(struct instance_data, instance);
2585 if (instance_data->vtable.GetInstanceProcAddr == NULL) return NULL;
2586 return instance_data->vtable.GetInstanceProcAddr(instance, funcName);
2587 }