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