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