a2f6f24bdecd81c1d7d7d43f96231e1c9b15e6f1
[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_dispatch_table_helper.h>
30 #include <vulkan/vk_layer.h>
31 #include <vulkan/vk_layer_data.h>
32 #include <vulkan/vk_layer_extension_utils.h>
33 #include <vulkan/vk_loader_platform.h>
34 #include "vk_layer_table.h"
35
36 #include "imgui.h"
37
38 #include "overlay_params.h"
39
40 #include "util/debug.h"
41 #include "util/hash_table.h"
42 #include "util/ralloc.h"
43 #include "util/os_time.h"
44 #include "util/simple_mtx.h"
45
46 #include "vk_enum_to_str.h"
47
48 /* Mapped from VkInstace/VkPhysicalDevice */
49 struct instance_data {
50 VkLayerInstanceDispatchTable vtable;
51 VkInstance instance;
52
53 struct overlay_params params;
54 };
55
56 struct frame_stat {
57 uint32_t stats[OVERLAY_PARAM_ENABLED_MAX];
58 };
59
60 /* Mapped from VkDevice/VkCommandBuffer */
61 struct queue_data;
62 struct device_data {
63 struct instance_data *instance;
64
65 VkLayerDispatchTable 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 struct frame_stat stats;
77 };
78
79 /* Mapped from VkQueue */
80 struct queue_data {
81 struct device_data *device;
82
83 VkQueue queue;
84 VkQueueFlags flags;
85 uint32_t family_index;
86 };
87
88 /* Mapped from VkSwapchainKHR */
89 struct swapchain_data {
90 struct device_data *device;
91
92 VkSwapchainKHR swapchain;
93 unsigned width, height;
94 VkFormat format;
95
96 uint32_t n_images;
97 VkImage *images;
98 VkImageView *image_views;
99 VkFramebuffer *framebuffers;
100
101 VkRenderPass render_pass;
102
103 VkDescriptorPool descriptor_pool;
104 VkDescriptorSetLayout descriptor_layout;
105 VkDescriptorSet descriptor_set;
106
107 VkSampler font_sampler;
108
109 VkPipelineLayout pipeline_layout;
110 VkPipeline pipeline;
111
112 VkCommandPool command_pool;
113
114 struct {
115 VkCommandBuffer command_buffer;
116
117 VkBuffer vertex_buffer;
118 VkDeviceMemory vertex_buffer_mem;
119 VkDeviceSize vertex_buffer_size;
120
121 VkBuffer index_buffer;
122 VkDeviceMemory index_buffer_mem;
123 VkDeviceSize index_buffer_size;
124 } frame_data[2];
125
126 bool font_uploaded;
127 VkImage font_image;
128 VkImageView font_image_view;
129 VkDeviceMemory font_mem;
130 VkBuffer upload_font_buffer;
131 VkDeviceMemory upload_font_buffer_mem;
132
133 VkFence fence;
134 VkSemaphore submission_semaphore;
135
136 /**/
137 ImGuiContext* imgui_context;
138 ImVec2 window_size;
139
140 /**/
141 uint64_t n_frames;
142 uint64_t last_present_time;
143
144 unsigned n_frames_since_update;
145 uint64_t last_fps_update;
146 double fps;
147
148 double frame_times[200];
149
150 double acquire_times[200];
151 uint64_t n_acquire;
152
153 enum overlay_param_enabled stat_selector;
154 struct frame_stat stats_min, stats_max;
155 struct frame_stat stats[200];
156 };
157
158 static struct hash_table *vk_object_to_data = NULL;
159 static simple_mtx_t vk_object_to_data_mutex = _SIMPLE_MTX_INITIALIZER_NP;
160
161 thread_local ImGuiContext* __MesaImGui;
162
163 static inline void ensure_vk_object_map(void)
164 {
165 if (!vk_object_to_data) {
166 vk_object_to_data = _mesa_hash_table_create(NULL,
167 _mesa_hash_pointer,
168 _mesa_key_pointer_equal);
169 }
170 }
171
172 #define FIND_SWAPCHAIN_DATA(obj) ((struct swapchain_data *)find_object_data((void *) obj))
173 #define FIND_DEVICE_DATA(obj) ((struct device_data *)find_object_data((void *) obj))
174 #define FIND_QUEUE_DATA(obj) ((struct queue_data *)find_object_data((void *) obj))
175 #define FIND_PHYSICAL_DEVICE_DATA(obj) ((struct instance_data *)find_object_data((void *) obj))
176 #define FIND_INSTANCE_DATA(obj) ((struct instance_data *)find_object_data((void *) obj))
177 static void *find_object_data(void *obj)
178 {
179 simple_mtx_lock(&vk_object_to_data_mutex);
180 ensure_vk_object_map();
181 struct hash_entry *entry = _mesa_hash_table_search(vk_object_to_data, obj);
182 void *data = entry ? entry->data : NULL;
183 simple_mtx_unlock(&vk_object_to_data_mutex);
184 return data;
185 }
186
187 static void map_object(void *obj, void *data)
188 {
189 simple_mtx_lock(&vk_object_to_data_mutex);
190 ensure_vk_object_map();
191 _mesa_hash_table_insert(vk_object_to_data, obj, data);
192 simple_mtx_unlock(&vk_object_to_data_mutex);
193 }
194
195 static void unmap_object(void *obj)
196 {
197 simple_mtx_lock(&vk_object_to_data_mutex);
198 struct hash_entry *entry = _mesa_hash_table_search(vk_object_to_data, obj);
199 _mesa_hash_table_remove(vk_object_to_data, entry);
200 simple_mtx_unlock(&vk_object_to_data_mutex);
201 }
202
203 /**/
204 static struct instance_data *new_instance_data(VkInstance instance)
205 {
206 struct instance_data *data = rzalloc(NULL, struct instance_data);
207 data->instance = instance;
208 map_object(data->instance, data);
209 return data;
210 }
211
212 static void destroy_instance_data(struct instance_data *data)
213 {
214 if (data->params.output_file)
215 fclose(data->params.output_file);
216 unmap_object(data->instance);
217 ralloc_free(data);
218 }
219
220 static void instance_data_map_physical_devices(struct instance_data *instance_data,
221 bool map)
222 {
223 uint32_t physicalDeviceCount = 0;
224 instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
225 &physicalDeviceCount,
226 NULL);
227
228 VkPhysicalDevice *physicalDevices = (VkPhysicalDevice *) malloc(sizeof(VkPhysicalDevice) * physicalDeviceCount);
229 instance_data->vtable.EnumeratePhysicalDevices(instance_data->instance,
230 &physicalDeviceCount,
231 physicalDevices);
232
233 for (uint32_t i = 0; i < physicalDeviceCount; i++) {
234 if (map)
235 map_object(physicalDevices[i], instance_data);
236 else
237 unmap_object(physicalDevices[i]);
238 }
239
240 free(physicalDevices);
241 }
242
243 /**/
244 static struct device_data *new_device_data(VkDevice device, struct instance_data *instance)
245 {
246 struct device_data *data = rzalloc(NULL, struct device_data);
247 data->instance = instance;
248 data->device = device;
249 map_object(data->device, data);
250 return data;
251 }
252
253 static struct queue_data *new_queue_data(VkQueue queue,
254 const VkQueueFamilyProperties *family_props,
255 uint32_t family_index,
256 struct device_data *device_data)
257 {
258 struct queue_data *data = rzalloc(device_data, struct queue_data);
259 data->device = device_data;
260 data->queue = queue;
261 data->flags = family_props->queueFlags;
262 data->family_index = family_index;
263 map_object(data->queue, data);
264
265 if (data->flags & VK_QUEUE_GRAPHICS_BIT)
266 device_data->graphic_queue = data;
267
268 return data;
269 }
270
271 static void device_map_queues(struct device_data *data,
272 const VkDeviceCreateInfo *pCreateInfo)
273 {
274 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++)
275 data->n_queues += pCreateInfo->pQueueCreateInfos[i].queueCount;
276 data->queues = ralloc_array(data, struct queue_data *, data->n_queues);
277
278 struct instance_data *instance_data = data->instance;
279 uint32_t n_family_props;
280 instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
281 &n_family_props,
282 NULL);
283 VkQueueFamilyProperties *family_props =
284 (VkQueueFamilyProperties *)malloc(sizeof(VkQueueFamilyProperties) * n_family_props);
285 instance_data->vtable.GetPhysicalDeviceQueueFamilyProperties(data->physical_device,
286 &n_family_props,
287 family_props);
288
289 uint32_t queue_index = 0;
290 for (uint32_t i = 0; i < pCreateInfo->queueCreateInfoCount; i++) {
291 for (uint32_t j = 0; j < pCreateInfo->pQueueCreateInfos[i].queueCount; j++) {
292 VkQueue queue;
293 data->vtable.GetDeviceQueue(data->device,
294 pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex,
295 j, &queue);
296 data->queues[queue_index++] =
297 new_queue_data(queue, &family_props[pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex],
298 pCreateInfo->pQueueCreateInfos[i].queueFamilyIndex, data);
299 }
300 }
301
302 free(family_props);
303 }
304
305 static void device_unmap_queues(struct device_data *data)
306 {
307 for (uint32_t i = 0; i < data->n_queues; i++)
308 unmap_object(data->queues[i]->queue);
309 }
310
311 static void destroy_device_data(struct device_data *data)
312 {
313 unmap_object(data->device);
314 ralloc_free(data);
315 }
316
317 static void check_vk_result(VkResult err)
318 {
319 if (err != VK_SUCCESS)
320 printf("ERROR!\n");
321 }
322
323 /**/
324 static struct swapchain_data *new_swapchain_data(VkSwapchainKHR swapchain,
325 struct device_data *device_data)
326 {
327 struct swapchain_data *data = rzalloc(NULL, struct swapchain_data);
328 data->device = device_data;
329 data->swapchain = swapchain;
330 data->window_size = ImVec2(300, 300);
331 map_object((void *) data->swapchain, data);
332 return data;
333 }
334
335 static void destroy_swapchain_data(struct swapchain_data *data)
336 {
337 unmap_object((void *) data->swapchain);
338 ralloc_free(data);
339 }
340
341 static void snapshot_swapchain_frame(struct swapchain_data *data)
342 {
343 struct instance_data *instance_data = data->device->instance;
344 uint64_t now = os_time_get(); /* us */
345
346 if (data->last_present_time) {
347 data->frame_times[(data->n_frames - 1) % ARRAY_SIZE(data->frame_times)] =
348 ((double)now - (double)data->last_present_time) / 1000.0;
349 }
350
351 if (data->last_fps_update) {
352 double elapsed = (double)(now - data->last_fps_update); /* us */
353 if (elapsed >= instance_data->params.fps_sampling_period) {
354 data->fps = 1000000.0f * data->n_frames_since_update / elapsed;
355 data->n_frames_since_update = 0;
356 data->last_fps_update = now;
357 if (instance_data->params.output_file) {
358 fprintf(instance_data->params.output_file, "%.2f\n", data->fps);
359 fflush(instance_data->params.output_file);
360 }
361 }
362 } else {
363 data->last_fps_update = now;
364 }
365
366 struct device_data *device_data = data->device;
367 data->stats[data->n_frames % ARRAY_SIZE(data->frame_times)] = device_data->stats;
368 memset(&device_data->stats, 0, sizeof(device_data->stats));
369
370 data->last_present_time = now;
371 data->n_frames++;
372 data->n_frames_since_update++;
373 }
374
375 static float get_frame_timing(void *_data, int _idx)
376 {
377 struct swapchain_data *data = (struct swapchain_data *) _data;
378 if ((ARRAY_SIZE(data->frame_times) - _idx) > (data->n_frames - 2))
379 return 0.0f;
380 int idx = ARRAY_SIZE(data->frame_times) +
381 (data->n_frames - 2) < ARRAY_SIZE(data->frame_times) ?
382 _idx - (data->n_frames - 2) :
383 _idx + (data->n_frames - 2);
384 idx %= ARRAY_SIZE(data->frame_times);
385 return data->frame_times[idx];
386 }
387
388 static float get_acquire_timing(void *_data, int _idx)
389 {
390 struct swapchain_data *data = (struct swapchain_data *) _data;
391 if ((ARRAY_SIZE(data->acquire_times) - _idx) > data->n_acquire)
392 return 0.0f;
393 int idx = ARRAY_SIZE(data->acquire_times) +
394 data->n_acquire < ARRAY_SIZE(data->acquire_times) ?
395 _idx - data->n_acquire :
396 _idx + data->n_acquire;
397 idx %= ARRAY_SIZE(data->acquire_times);
398 return data->acquire_times[idx];
399 }
400
401 static float get_stat(void *_data, int _idx)
402 {
403 struct swapchain_data *data = (struct swapchain_data *) _data;
404 if ((ARRAY_SIZE(data->stats) - _idx) > data->n_frames)
405 return 0.0f;
406 int idx = ARRAY_SIZE(data->stats) +
407 data->n_frames < ARRAY_SIZE(data->stats) ?
408 _idx - data->n_frames :
409 _idx + data->n_frames;
410 idx %= ARRAY_SIZE(data->stats);
411 return data->stats[idx].stats[data->stat_selector];
412 }
413
414 static void position_layer(struct swapchain_data *data)
415
416 {
417 struct device_data *device_data = data->device;
418 struct instance_data *instance_data = device_data->instance;
419
420 ImGui::SetNextWindowBgAlpha(0.5);
421 ImGui::SetNextWindowSize(data->window_size, ImGuiCond_Always);
422 switch (instance_data->params.position) {
423 case LAYER_POSITION_TOP_LEFT:
424 ImGui::SetNextWindowPos(ImVec2(0, 0), ImGuiCond_Always);
425 break;
426 case LAYER_POSITION_TOP_RIGHT:
427 ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x, 0),
428 ImGuiCond_Always);
429 break;
430 case LAYER_POSITION_BOTTOM_LEFT:
431 ImGui::SetNextWindowPos(ImVec2(0, data->height - data->window_size.y),
432 ImGuiCond_Always);
433 break;
434 case LAYER_POSITION_BOTTOM_RIGHT:
435 ImGui::SetNextWindowPos(ImVec2(data->width - data->window_size.x,
436 data->height - data->window_size.y),
437 ImGuiCond_Always);
438 break;
439 }
440 }
441
442 static void compute_swapchain_display(struct swapchain_data *data)
443 {
444 struct device_data *device_data = data->device;
445 struct instance_data *instance_data = device_data->instance;
446
447 ImGui::SetCurrentContext(data->imgui_context);
448 ImGui::NewFrame();
449 position_layer(data);
450 ImGui::Begin("Mesa overlay");
451 ImGui::Text("Device: %s", device_data->properties.deviceName);
452
453 const char *format_name = vk_Format_to_str(data->format);
454 format_name = format_name ? (format_name + strlen("VK_FORMAT_")) : "unknown";
455 ImGui::Text("Swapchain format: %s", format_name);
456 ImGui::Text("Frames: %" PRIu64, data->n_frames);
457 if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_fps])
458 ImGui::Text("FPS: %.2f" , data->fps);
459
460 if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_frame_timing]){
461 double min_time = FLT_MAX, max_time = 0.0f;
462 for (uint32_t i = 0; i < MIN2(data->n_frames - 2, ARRAY_SIZE(data->frame_times)); i++) {
463 min_time = MIN2(min_time, data->frame_times[i]);
464 max_time = MAX2(max_time, data->frame_times[i]);
465 }
466 ImGui::PlotHistogram("##Frame timings", get_frame_timing, data,
467 ARRAY_SIZE(data->frame_times), 0,
468 NULL, min_time, max_time,
469 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
470 ImGui::Text("Frame timing: %.3fms [%.3f, %.3f]",
471 get_frame_timing(data, ARRAY_SIZE(data->frame_times) - 1),
472 min_time, max_time);
473 }
474
475 if (instance_data->params.enabled[OVERLAY_PARAM_ENABLED_acquire_timing]) {
476 double min_time = FLT_MAX, max_time = 0.0f;
477 for (uint32_t i = 0; i < MIN2(data->n_acquire - 2, ARRAY_SIZE(data->acquire_times)); i++) {
478 min_time = MIN2(min_time, data->acquire_times[i]);
479 max_time = MAX2(max_time, data->acquire_times[i]);
480 }
481 ImGui::PlotHistogram("##Acquire timings", get_acquire_timing, data,
482 ARRAY_SIZE(data->acquire_times), 0,
483 NULL, min_time, max_time,
484 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
485 ImGui::Text("Acquire timing: %.3fms [%.3f, %.3f]",
486 get_acquire_timing(data, ARRAY_SIZE(data->acquire_times) - 1),
487 min_time, max_time);
488 }
489
490 for (uint32_t i = 0; i < ARRAY_SIZE(data->stats_min.stats); i++) {
491 data->stats_min.stats[i] = UINT32_MAX;
492 data->stats_max.stats[i] = 0;
493 }
494 for (uint32_t i = 0; i < MIN2(data->n_frames - 1, ARRAY_SIZE(data->stats)); i++) {
495 for (uint32_t j = 0; j < ARRAY_SIZE(data->stats[0].stats); j++) {
496 data->stats_min.stats[j] = MIN2(data->stats[i].stats[j],
497 data->stats_min.stats[j]);
498 data->stats_max.stats[j] = MAX2(data->stats[i].stats[j],
499 data->stats_max.stats[j]);
500 }
501 }
502
503 for (uint32_t i = 0; i < ARRAY_SIZE(device_data->stats.stats); i++) {
504 if (!instance_data->params.enabled[i] ||
505 i == OVERLAY_PARAM_ENABLED_fps ||
506 i == OVERLAY_PARAM_ENABLED_frame_timing ||
507 i == OVERLAY_PARAM_ENABLED_acquire_timing)
508 continue;
509
510 char hash[40];
511 snprintf(hash, sizeof(hash), "##%s", overlay_param_names[i]);
512 data->stat_selector = (enum overlay_param_enabled) i;
513
514 ImGui::PlotHistogram(hash, get_stat, data,
515 ARRAY_SIZE(data->stats), 0,
516 NULL,
517 data->stats_min.stats[i],
518 data->stats_max.stats[i],
519 ImVec2(ImGui::GetContentRegionAvailWidth(), 30));
520 ImGui::Text("%s: %.0f [%u, %u]", overlay_param_names[i],
521 get_stat(data, ARRAY_SIZE(data->stats) - 1),
522 data->stats_min.stats[i], data->stats_max.stats[i]);
523 }
524 data->window_size = ImVec2(data->window_size.x, ImGui::GetCursorPosY() + 10.0f);
525 ImGui::End();
526 ImGui::EndFrame();
527 ImGui::Render();
528 }
529
530 static uint32_t vk_memory_type(struct device_data *data,
531 VkMemoryPropertyFlags properties,
532 uint32_t type_bits)
533 {
534 VkPhysicalDeviceMemoryProperties prop;
535 data->instance->vtable.GetPhysicalDeviceMemoryProperties(data->physical_device, &prop);
536 for (uint32_t i = 0; i < prop.memoryTypeCount; i++)
537 if ((prop.memoryTypes[i].propertyFlags & properties) == properties && type_bits & (1<<i))
538 return i;
539 return 0xFFFFFFFF; // Unable to find memoryType
540 }
541
542 static void ensure_swapchain_fonts(struct swapchain_data *data,
543 VkCommandBuffer command_buffer)
544 {
545 if (data->font_uploaded)
546 return;
547
548 data->font_uploaded = true;
549
550 struct device_data *device_data = data->device;
551 VkResult err;
552 ImGuiIO& io = ImGui::GetIO();
553 unsigned char* pixels;
554 int width, height;
555 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
556 size_t upload_size = width * height * 4 * sizeof(char);
557
558 /* Upload buffer */
559 VkBufferCreateInfo buffer_info = {};
560 buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
561 buffer_info.size = upload_size;
562 buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
563 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
564 err = device_data->vtable.CreateBuffer(device_data->device, &buffer_info,
565 NULL, &data->upload_font_buffer);
566 check_vk_result(err);
567 VkMemoryRequirements upload_buffer_req;
568 device_data->vtable.GetBufferMemoryRequirements(device_data->device,
569 data->upload_font_buffer,
570 &upload_buffer_req);
571 VkMemoryAllocateInfo upload_alloc_info = {};
572 upload_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
573 upload_alloc_info.allocationSize = upload_buffer_req.size;
574 upload_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
575 VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,
576 upload_buffer_req.memoryTypeBits);
577 err = device_data->vtable.AllocateMemory(device_data->device,
578 &upload_alloc_info,
579 NULL,
580 &data->upload_font_buffer_mem);
581 check_vk_result(err);
582 err = device_data->vtable.BindBufferMemory(device_data->device,
583 data->upload_font_buffer,
584 data->upload_font_buffer_mem, 0);
585 check_vk_result(err);
586
587 /* Upload to Buffer */
588 char* map = NULL;
589 err = device_data->vtable.MapMemory(device_data->device,
590 data->upload_font_buffer_mem,
591 0, upload_size, 0, (void**)(&map));
592 check_vk_result(err);
593 memcpy(map, pixels, upload_size);
594 VkMappedMemoryRange range[1] = {};
595 range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
596 range[0].memory = data->upload_font_buffer_mem;
597 range[0].size = upload_size;
598 err = device_data->vtable.FlushMappedMemoryRanges(device_data->device, 1, range);
599 check_vk_result(err);
600 device_data->vtable.UnmapMemory(device_data->device,
601 data->upload_font_buffer_mem);
602
603 /* Copy buffer to image */
604 VkImageMemoryBarrier copy_barrier[1] = {};
605 copy_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
606 copy_barrier[0].dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
607 copy_barrier[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED;
608 copy_barrier[0].newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
609 copy_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
610 copy_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
611 copy_barrier[0].image = data->font_image;
612 copy_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
613 copy_barrier[0].subresourceRange.levelCount = 1;
614 copy_barrier[0].subresourceRange.layerCount = 1;
615 device_data->vtable.CmdPipelineBarrier(command_buffer,
616 VK_PIPELINE_STAGE_HOST_BIT,
617 VK_PIPELINE_STAGE_TRANSFER_BIT,
618 0, 0, NULL, 0, NULL,
619 1, copy_barrier);
620
621 VkBufferImageCopy region = {};
622 region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
623 region.imageSubresource.layerCount = 1;
624 region.imageExtent.width = width;
625 region.imageExtent.height = height;
626 region.imageExtent.depth = 1;
627 device_data->vtable.CmdCopyBufferToImage(command_buffer,
628 data->upload_font_buffer,
629 data->font_image,
630 VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
631 1, &region);
632
633 VkImageMemoryBarrier use_barrier[1] = {};
634 use_barrier[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
635 use_barrier[0].srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
636 use_barrier[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT;
637 use_barrier[0].oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
638 use_barrier[0].newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
639 use_barrier[0].srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
640 use_barrier[0].dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
641 use_barrier[0].image = data->font_image;
642 use_barrier[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
643 use_barrier[0].subresourceRange.levelCount = 1;
644 use_barrier[0].subresourceRange.layerCount = 1;
645 device_data->vtable.CmdPipelineBarrier(command_buffer,
646 VK_PIPELINE_STAGE_TRANSFER_BIT,
647 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
648 0,
649 0, NULL,
650 0, NULL,
651 1, use_barrier);
652
653 /* Store our identifier */
654 io.Fonts->TexID = (ImTextureID)(intptr_t)data->font_image;
655 }
656
657 static void CreateOrResizeBuffer(struct device_data *data,
658 VkBuffer *buffer,
659 VkDeviceMemory *buffer_memory,
660 VkDeviceSize *buffer_size,
661 size_t new_size, VkBufferUsageFlagBits usage)
662 {
663 VkResult err;
664 if (*buffer != VK_NULL_HANDLE)
665 data->vtable.DestroyBuffer(data->device, *buffer, NULL);
666 if (*buffer_memory)
667 data->vtable.FreeMemory(data->device, *buffer_memory, NULL);
668
669 VkBufferCreateInfo buffer_info = {};
670 buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
671 buffer_info.size = new_size;
672 buffer_info.usage = usage;
673 buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
674 err = data->vtable.CreateBuffer(data->device, &buffer_info, NULL, buffer);
675 check_vk_result(err);
676
677 VkMemoryRequirements req;
678 data->vtable.GetBufferMemoryRequirements(data->device, *buffer, &req);
679 VkMemoryAllocateInfo alloc_info = {};
680 alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
681 alloc_info.allocationSize = req.size;
682 alloc_info.memoryTypeIndex =
683 vk_memory_type(data, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, req.memoryTypeBits);
684 err = data->vtable.AllocateMemory(data->device, &alloc_info, NULL, buffer_memory);
685 check_vk_result(err);
686
687 err = data->vtable.BindBufferMemory(data->device, *buffer, *buffer_memory, 0);
688 check_vk_result(err);
689 *buffer_size = new_size;
690 }
691
692 static void render_swapchain_display(struct swapchain_data *data, unsigned image_index)
693 {
694 ImDrawData* draw_data = ImGui::GetDrawData();
695 if (draw_data->TotalVtxCount == 0)
696 return;
697
698 struct device_data *device_data = data->device;
699 uint32_t idx = data->n_frames % ARRAY_SIZE(data->frame_data);
700 VkCommandBuffer command_buffer = data->frame_data[idx].command_buffer;
701 VkResult err;
702
703 device_data->vtable.ResetCommandBuffer(command_buffer, 0);
704
705 VkRenderPassBeginInfo render_pass_info = {};
706 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
707 render_pass_info.renderPass = data->render_pass;
708 render_pass_info.framebuffer = data->framebuffers[image_index];
709 render_pass_info.renderArea.extent.width = data->width;
710 render_pass_info.renderArea.extent.height = data->height;
711
712 VkCommandBufferBeginInfo buffer_begin_info = {};
713 buffer_begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
714
715 device_data->vtable.BeginCommandBuffer(command_buffer, &buffer_begin_info);
716
717 ensure_swapchain_fonts(data, command_buffer);
718
719 /* Bounce the image to display back to color attachment layout for
720 * rendering on top of it.
721 */
722 VkImageMemoryBarrier imb;
723 imb.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER;
724 imb.pNext = nullptr;
725 imb.dstAccessMask = VK_ACCESS_MEMORY_READ_BIT;
726 imb.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
727 imb.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
728 imb.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
729 imb.image = data->images[image_index];
730 imb.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
731 imb.subresourceRange.baseMipLevel = 0;
732 imb.subresourceRange.levelCount = 1;
733 imb.subresourceRange.baseArrayLayer = 0;
734 imb.subresourceRange.layerCount = 1;
735 imb.srcQueueFamilyIndex = device_data->graphic_queue->family_index;
736 imb.dstQueueFamilyIndex = device_data->graphic_queue->family_index;
737 device_data->vtable.CmdPipelineBarrier(command_buffer,
738 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
739 VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
740 0, /* dependency flags */
741 0, nullptr, /* memory barriers */
742 0, nullptr, /* buffer memory barriers */
743 1, &imb); /* image memory barriers */
744
745 device_data->vtable.CmdBeginRenderPass(command_buffer, &render_pass_info,
746 VK_SUBPASS_CONTENTS_INLINE);
747
748 /* Create/Resize vertex & index buffers */
749 size_t vertex_size = draw_data->TotalVtxCount * sizeof(ImDrawVert);
750 size_t index_size = draw_data->TotalIdxCount * sizeof(ImDrawIdx);
751 if (data->frame_data[idx].vertex_buffer_size < vertex_size) {
752 CreateOrResizeBuffer(device_data,
753 &data->frame_data[idx].vertex_buffer,
754 &data->frame_data[idx].vertex_buffer_mem,
755 &data->frame_data[idx].vertex_buffer_size,
756 vertex_size, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
757 }
758 if (data->frame_data[idx].index_buffer_size < index_size) {
759 CreateOrResizeBuffer(device_data,
760 &data->frame_data[idx].index_buffer,
761 &data->frame_data[idx].index_buffer_mem,
762 &data->frame_data[idx].index_buffer_size,
763 index_size, VK_BUFFER_USAGE_INDEX_BUFFER_BIT);
764 }
765
766 /* Upload vertex & index data */
767 VkBuffer vertex_buffer = data->frame_data[idx].vertex_buffer;
768 VkDeviceMemory vertex_mem = data->frame_data[idx].vertex_buffer_mem;
769 VkBuffer index_buffer = data->frame_data[idx].index_buffer;
770 VkDeviceMemory index_mem = data->frame_data[idx].index_buffer_mem;
771 ImDrawVert* vtx_dst = NULL;
772 ImDrawIdx* idx_dst = NULL;
773 err = device_data->vtable.MapMemory(device_data->device, vertex_mem,
774 0, vertex_size, 0, (void**)(&vtx_dst));
775 check_vk_result(err);
776 err = device_data->vtable.MapMemory(device_data->device, index_mem,
777 0, index_size, 0, (void**)(&idx_dst));
778 check_vk_result(err);
779 for (int n = 0; n < draw_data->CmdListsCount; n++)
780 {
781 const ImDrawList* cmd_list = draw_data->CmdLists[n];
782 memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert));
783 memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx));
784 vtx_dst += cmd_list->VtxBuffer.Size;
785 idx_dst += cmd_list->IdxBuffer.Size;
786 }
787 VkMappedMemoryRange range[2] = {};
788 range[0].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
789 range[0].memory = vertex_mem;
790 range[0].size = VK_WHOLE_SIZE;
791 range[1].sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;
792 range[1].memory = index_mem;
793 range[1].size = VK_WHOLE_SIZE;
794 err = device_data->vtable.FlushMappedMemoryRanges(device_data->device, 2, range);
795 check_vk_result(err);
796 device_data->vtable.UnmapMemory(device_data->device, vertex_mem);
797 device_data->vtable.UnmapMemory(device_data->device, index_mem);
798
799 /* Bind pipeline and descriptor sets */
800 device_data->vtable.CmdBindPipeline(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, data->pipeline);
801 VkDescriptorSet desc_set[1] = { data->descriptor_set };
802 device_data->vtable.CmdBindDescriptorSets(command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
803 data->pipeline_layout, 0, 1, desc_set, 0, NULL);
804
805 /* Bind vertex & index buffers */
806 VkBuffer vertex_buffers[1] = { vertex_buffer };
807 VkDeviceSize vertex_offset[1] = { 0 };
808 device_data->vtable.CmdBindVertexBuffers(command_buffer, 0, 1, vertex_buffers, vertex_offset);
809 device_data->vtable.CmdBindIndexBuffer(command_buffer, index_buffer, 0, VK_INDEX_TYPE_UINT16);
810
811 /* Setup viewport */
812 VkViewport viewport;
813 viewport.x = 0;
814 viewport.y = 0;
815 viewport.width = draw_data->DisplaySize.x;
816 viewport.height = draw_data->DisplaySize.y;
817 viewport.minDepth = 0.0f;
818 viewport.maxDepth = 1.0f;
819 device_data->vtable.CmdSetViewport(command_buffer, 0, 1, &viewport);
820
821
822 /* Setup scale and translation through push constants :
823 *
824 * Our visible imgui space lies from draw_data->DisplayPos (top left) to
825 * draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayMin
826 * is typically (0,0) for single viewport apps.
827 */
828 float scale[2];
829 scale[0] = 2.0f / draw_data->DisplaySize.x;
830 scale[1] = 2.0f / draw_data->DisplaySize.y;
831 float translate[2];
832 translate[0] = -1.0f - draw_data->DisplayPos.x * scale[0];
833 translate[1] = -1.0f - draw_data->DisplayPos.y * scale[1];
834 device_data->vtable.CmdPushConstants(command_buffer, data->pipeline_layout,
835 VK_SHADER_STAGE_VERTEX_BIT,
836 sizeof(float) * 0, sizeof(float) * 2, scale);
837 device_data->vtable.CmdPushConstants(command_buffer, data->pipeline_layout,
838 VK_SHADER_STAGE_VERTEX_BIT,
839 sizeof(float) * 2, sizeof(float) * 2, translate);
840
841 // Render the command lists:
842 int vtx_offset = 0;
843 int idx_offset = 0;
844 ImVec2 display_pos = draw_data->DisplayPos;
845 for (int n = 0; n < draw_data->CmdListsCount; n++)
846 {
847 const ImDrawList* cmd_list = draw_data->CmdLists[n];
848 for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
849 {
850 const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
851 // Apply scissor/clipping rectangle
852 // FIXME: We could clamp width/height based on clamped min/max values.
853 VkRect2D scissor;
854 scissor.offset.x = (int32_t)(pcmd->ClipRect.x - display_pos.x) > 0 ? (int32_t)(pcmd->ClipRect.x - display_pos.x) : 0;
855 scissor.offset.y = (int32_t)(pcmd->ClipRect.y - display_pos.y) > 0 ? (int32_t)(pcmd->ClipRect.y - display_pos.y) : 0;
856 scissor.extent.width = (uint32_t)(pcmd->ClipRect.z - pcmd->ClipRect.x);
857 scissor.extent.height = (uint32_t)(pcmd->ClipRect.w - pcmd->ClipRect.y + 1); // FIXME: Why +1 here?
858 device_data->vtable.CmdSetScissor(command_buffer, 0, 1, &scissor);
859
860 // Draw
861 device_data->vtable.CmdDrawIndexed(command_buffer, pcmd->ElemCount, 1, idx_offset, vtx_offset, 0);
862
863 idx_offset += pcmd->ElemCount;
864 }
865 vtx_offset += cmd_list->VtxBuffer.Size;
866 }
867
868 device_data->vtable.CmdEndRenderPass(command_buffer);
869 device_data->vtable.EndCommandBuffer(command_buffer);
870
871 if (data->submission_semaphore) {
872 device_data->vtable.DestroySemaphore(device_data->device,
873 data->submission_semaphore,
874 NULL);
875 }
876 /* Submission semaphore */
877 VkSemaphoreCreateInfo semaphore_info = {};
878 semaphore_info.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
879 err = device_data->vtable.CreateSemaphore(device_data->device, &semaphore_info,
880 NULL, &data->submission_semaphore);
881 check_vk_result(err);
882
883 VkSubmitInfo submit_info = {};
884 submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
885 submit_info.commandBufferCount = 1;
886 submit_info.pCommandBuffers = &command_buffer;
887 submit_info.signalSemaphoreCount = 1;
888 submit_info.pSignalSemaphores = &data->submission_semaphore;
889
890 device_data->vtable.WaitForFences(device_data->device, 1, &data->fence, VK_TRUE, UINT64_MAX);
891 device_data->vtable.ResetFences(device_data->device, 1, &data->fence);
892 device_data->vtable.QueueSubmit(device_data->graphic_queue->queue, 1, &submit_info, data->fence);
893 }
894
895 static const uint32_t overlay_vert_spv[] = {
896 #include "overlay.vert.spv.h"
897 };
898 static const uint32_t overlay_frag_spv[] = {
899 #include "overlay.frag.spv.h"
900 };
901
902 static void setup_swapchain_data_pipeline(struct swapchain_data *data)
903 {
904 struct device_data *device_data = data->device;
905 VkShaderModule vert_module, frag_module;
906 VkResult err;
907
908 /* Create shader modules */
909 VkShaderModuleCreateInfo vert_info = {};
910 vert_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
911 vert_info.codeSize = sizeof(overlay_vert_spv);
912 vert_info.pCode = overlay_vert_spv;
913 err = device_data->vtable.CreateShaderModule(device_data->device,
914 &vert_info, NULL, &vert_module);
915 check_vk_result(err);
916 VkShaderModuleCreateInfo frag_info = {};
917 frag_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
918 frag_info.codeSize = sizeof(overlay_frag_spv);
919 frag_info.pCode = (uint32_t*)overlay_frag_spv;
920 err = device_data->vtable.CreateShaderModule(device_data->device,
921 &frag_info, NULL, &frag_module);
922 check_vk_result(err);
923
924 /* Font sampler */
925 VkSamplerCreateInfo sampler_info = {};
926 sampler_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
927 sampler_info.magFilter = VK_FILTER_LINEAR;
928 sampler_info.minFilter = VK_FILTER_LINEAR;
929 sampler_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR;
930 sampler_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT;
931 sampler_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT;
932 sampler_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT;
933 sampler_info.minLod = -1000;
934 sampler_info.maxLod = 1000;
935 sampler_info.maxAnisotropy = 1.0f;
936 err = device_data->vtable.CreateSampler(device_data->device, &sampler_info,
937 NULL, &data->font_sampler);
938 check_vk_result(err);
939
940 /* Descriptor pool */
941 VkDescriptorPoolSize sampler_pool_size = {};
942 sampler_pool_size.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
943 sampler_pool_size.descriptorCount = 1;
944 VkDescriptorPoolCreateInfo desc_pool_info = {};
945 desc_pool_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
946 desc_pool_info.maxSets = 1;
947 desc_pool_info.poolSizeCount = 1;
948 desc_pool_info.pPoolSizes = &sampler_pool_size;
949 err = device_data->vtable.CreateDescriptorPool(device_data->device,
950 &desc_pool_info,
951 NULL, &data->descriptor_pool);
952 check_vk_result(err);
953
954 /* Descriptor layout */
955 VkSampler sampler[1] = { data->font_sampler };
956 VkDescriptorSetLayoutBinding binding[1] = {};
957 binding[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
958 binding[0].descriptorCount = 1;
959 binding[0].stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
960 binding[0].pImmutableSamplers = sampler;
961 VkDescriptorSetLayoutCreateInfo set_layout_info = {};
962 set_layout_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
963 set_layout_info.bindingCount = 1;
964 set_layout_info.pBindings = binding;
965 err = device_data->vtable.CreateDescriptorSetLayout(device_data->device,
966 &set_layout_info,
967 NULL, &data->descriptor_layout);
968 check_vk_result(err);
969
970 /* Descriptor set */
971 VkDescriptorSetAllocateInfo alloc_info = {};
972 alloc_info.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
973 alloc_info.descriptorPool = data->descriptor_pool;
974 alloc_info.descriptorSetCount = 1;
975 alloc_info.pSetLayouts = &data->descriptor_layout;
976 err = device_data->vtable.AllocateDescriptorSets(device_data->device,
977 &alloc_info,
978 &data->descriptor_set);
979 check_vk_result(err);
980
981 /* Constants: we are using 'vec2 offset' and 'vec2 scale' instead of a full
982 * 3d projection matrix
983 */
984 VkPushConstantRange push_constants[1] = {};
985 push_constants[0].stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
986 push_constants[0].offset = sizeof(float) * 0;
987 push_constants[0].size = sizeof(float) * 4;
988 VkPipelineLayoutCreateInfo layout_info = {};
989 layout_info.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
990 layout_info.setLayoutCount = 1;
991 layout_info.pSetLayouts = &data->descriptor_layout;
992 layout_info.pushConstantRangeCount = 1;
993 layout_info.pPushConstantRanges = push_constants;
994 err = device_data->vtable.CreatePipelineLayout(device_data->device,
995 &layout_info,
996 NULL, &data->pipeline_layout);
997 check_vk_result(err);
998
999
1000 VkPipelineShaderStageCreateInfo stage[2] = {};
1001 stage[0].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1002 stage[0].stage = VK_SHADER_STAGE_VERTEX_BIT;
1003 stage[0].module = vert_module;
1004 stage[0].pName = "main";
1005 stage[1].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
1006 stage[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT;
1007 stage[1].module = frag_module;
1008 stage[1].pName = "main";
1009
1010 VkVertexInputBindingDescription binding_desc[1] = {};
1011 binding_desc[0].stride = sizeof(ImDrawVert);
1012 binding_desc[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
1013
1014 VkVertexInputAttributeDescription attribute_desc[3] = {};
1015 attribute_desc[0].location = 0;
1016 attribute_desc[0].binding = binding_desc[0].binding;
1017 attribute_desc[0].format = VK_FORMAT_R32G32_SFLOAT;
1018 attribute_desc[0].offset = IM_OFFSETOF(ImDrawVert, pos);
1019 attribute_desc[1].location = 1;
1020 attribute_desc[1].binding = binding_desc[0].binding;
1021 attribute_desc[1].format = VK_FORMAT_R32G32_SFLOAT;
1022 attribute_desc[1].offset = IM_OFFSETOF(ImDrawVert, uv);
1023 attribute_desc[2].location = 2;
1024 attribute_desc[2].binding = binding_desc[0].binding;
1025 attribute_desc[2].format = VK_FORMAT_R8G8B8A8_UNORM;
1026 attribute_desc[2].offset = IM_OFFSETOF(ImDrawVert, col);
1027
1028 VkPipelineVertexInputStateCreateInfo vertex_info = {};
1029 vertex_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
1030 vertex_info.vertexBindingDescriptionCount = 1;
1031 vertex_info.pVertexBindingDescriptions = binding_desc;
1032 vertex_info.vertexAttributeDescriptionCount = 3;
1033 vertex_info.pVertexAttributeDescriptions = attribute_desc;
1034
1035 VkPipelineInputAssemblyStateCreateInfo ia_info = {};
1036 ia_info.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
1037 ia_info.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
1038
1039 VkPipelineViewportStateCreateInfo viewport_info = {};
1040 viewport_info.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
1041 viewport_info.viewportCount = 1;
1042 viewport_info.scissorCount = 1;
1043
1044 VkPipelineRasterizationStateCreateInfo raster_info = {};
1045 raster_info.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
1046 raster_info.polygonMode = VK_POLYGON_MODE_FILL;
1047 raster_info.cullMode = VK_CULL_MODE_NONE;
1048 raster_info.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
1049 raster_info.lineWidth = 1.0f;
1050
1051 VkPipelineMultisampleStateCreateInfo ms_info = {};
1052 ms_info.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
1053 ms_info.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
1054
1055 VkPipelineColorBlendAttachmentState color_attachment[1] = {};
1056 color_attachment[0].blendEnable = VK_TRUE;
1057 color_attachment[0].srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
1058 color_attachment[0].dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1059 color_attachment[0].colorBlendOp = VK_BLEND_OP_ADD;
1060 color_attachment[0].srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
1061 color_attachment[0].dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
1062 color_attachment[0].alphaBlendOp = VK_BLEND_OP_ADD;
1063 color_attachment[0].colorWriteMask = VK_COLOR_COMPONENT_R_BIT |
1064 VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
1065
1066 VkPipelineDepthStencilStateCreateInfo depth_info = {};
1067 depth_info.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
1068
1069 VkPipelineColorBlendStateCreateInfo blend_info = {};
1070 blend_info.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
1071 blend_info.attachmentCount = 1;
1072 blend_info.pAttachments = color_attachment;
1073
1074 VkDynamicState dynamic_states[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
1075 VkPipelineDynamicStateCreateInfo dynamic_state = {};
1076 dynamic_state.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
1077 dynamic_state.dynamicStateCount = (uint32_t)IM_ARRAYSIZE(dynamic_states);
1078 dynamic_state.pDynamicStates = dynamic_states;
1079
1080 VkGraphicsPipelineCreateInfo info = {};
1081 info.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
1082 info.flags = 0;
1083 info.stageCount = 2;
1084 info.pStages = stage;
1085 info.pVertexInputState = &vertex_info;
1086 info.pInputAssemblyState = &ia_info;
1087 info.pViewportState = &viewport_info;
1088 info.pRasterizationState = &raster_info;
1089 info.pMultisampleState = &ms_info;
1090 info.pDepthStencilState = &depth_info;
1091 info.pColorBlendState = &blend_info;
1092 info.pDynamicState = &dynamic_state;
1093 info.layout = data->pipeline_layout;
1094 info.renderPass = data->render_pass;
1095 err = device_data->vtable.CreateGraphicsPipelines(device_data->device, VK_NULL_HANDLE,
1096 1, &info,
1097 NULL, &data->pipeline);
1098 check_vk_result(err);
1099
1100 device_data->vtable.DestroyShaderModule(device_data->device, vert_module, NULL);
1101 device_data->vtable.DestroyShaderModule(device_data->device, frag_module, NULL);
1102
1103 ImGuiIO& io = ImGui::GetIO();
1104 unsigned char* pixels;
1105 int width, height;
1106 io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
1107
1108 /* Font image */
1109 VkImageCreateInfo image_info = {};
1110 image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
1111 image_info.imageType = VK_IMAGE_TYPE_2D;
1112 image_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1113 image_info.extent.width = width;
1114 image_info.extent.height = height;
1115 image_info.extent.depth = 1;
1116 image_info.mipLevels = 1;
1117 image_info.arrayLayers = 1;
1118 image_info.samples = VK_SAMPLE_COUNT_1_BIT;
1119 image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
1120 image_info.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
1121 image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
1122 image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
1123 err = device_data->vtable.CreateImage(device_data->device, &image_info,
1124 NULL, &data->font_image);
1125 check_vk_result(err);
1126 VkMemoryRequirements font_image_req;
1127 device_data->vtable.GetImageMemoryRequirements(device_data->device,
1128 data->font_image, &font_image_req);
1129 VkMemoryAllocateInfo image_alloc_info = {};
1130 image_alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
1131 image_alloc_info.allocationSize = font_image_req.size;
1132 image_alloc_info.memoryTypeIndex = vk_memory_type(device_data,
1133 VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT,
1134 font_image_req.memoryTypeBits);
1135 err = device_data->vtable.AllocateMemory(device_data->device, &image_alloc_info,
1136 NULL, &data->font_mem);
1137 check_vk_result(err);
1138 err = device_data->vtable.BindImageMemory(device_data->device,
1139 data->font_image,
1140 data->font_mem, 0);
1141 check_vk_result(err);
1142
1143 /* Font image view */
1144 VkImageViewCreateInfo view_info = {};
1145 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1146 view_info.image = data->font_image;
1147 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1148 view_info.format = VK_FORMAT_R8G8B8A8_UNORM;
1149 view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
1150 view_info.subresourceRange.levelCount = 1;
1151 view_info.subresourceRange.layerCount = 1;
1152 err = device_data->vtable.CreateImageView(device_data->device, &view_info,
1153 NULL, &data->font_image_view);
1154 check_vk_result(err);
1155
1156 /* Descriptor set */
1157 VkDescriptorImageInfo desc_image[1] = {};
1158 desc_image[0].sampler = data->font_sampler;
1159 desc_image[0].imageView = data->font_image_view;
1160 desc_image[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
1161 VkWriteDescriptorSet write_desc[1] = {};
1162 write_desc[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
1163 write_desc[0].dstSet = data->descriptor_set;
1164 write_desc[0].descriptorCount = 1;
1165 write_desc[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
1166 write_desc[0].pImageInfo = desc_image;
1167 device_data->vtable.UpdateDescriptorSets(device_data->device, 1, write_desc, 0, NULL);
1168 }
1169
1170 static void setup_swapchain_data(struct swapchain_data *data,
1171 const VkSwapchainCreateInfoKHR *pCreateInfo)
1172 {
1173 data->width = pCreateInfo->imageExtent.width;
1174 data->height = pCreateInfo->imageExtent.height;
1175 data->format = pCreateInfo->imageFormat;
1176
1177 data->imgui_context = ImGui::CreateContext();
1178 ImGui::SetCurrentContext(data->imgui_context);
1179
1180 ImGui::GetIO().IniFilename = NULL;
1181 ImGui::GetIO().DisplaySize = ImVec2((float)data->width, (float)data->height);
1182
1183 struct device_data *device_data = data->device;
1184 VkResult err;
1185
1186 /* Render pass */
1187 VkAttachmentDescription attachment_desc = {};
1188 attachment_desc.format = pCreateInfo->imageFormat;
1189 attachment_desc.samples = VK_SAMPLE_COUNT_1_BIT;
1190 attachment_desc.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
1191 attachment_desc.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
1192 attachment_desc.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
1193 attachment_desc.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
1194 attachment_desc.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1195 attachment_desc.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
1196 VkAttachmentReference color_attachment = {};
1197 color_attachment.attachment = 0;
1198 color_attachment.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
1199 VkSubpassDescription subpass = {};
1200 subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
1201 subpass.colorAttachmentCount = 1;
1202 subpass.pColorAttachments = &color_attachment;
1203 VkSubpassDependency dependency = {};
1204 dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
1205 dependency.dstSubpass = 0;
1206 dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1207 dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
1208 dependency.srcAccessMask = 0;
1209 dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
1210 VkRenderPassCreateInfo render_pass_info = {};
1211 render_pass_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
1212 render_pass_info.attachmentCount = 1;
1213 render_pass_info.pAttachments = &attachment_desc;
1214 render_pass_info.subpassCount = 1;
1215 render_pass_info.pSubpasses = &subpass;
1216 render_pass_info.dependencyCount = 1;
1217 render_pass_info.pDependencies = &dependency;
1218 err = device_data->vtable.CreateRenderPass(device_data->device,
1219 &render_pass_info,
1220 NULL, &data->render_pass);
1221 check_vk_result(err);
1222
1223 setup_swapchain_data_pipeline(data);
1224
1225 device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1226 data->swapchain,
1227 &data->n_images,
1228 NULL);
1229 data->images = ralloc_array(data, VkImage, data->n_images);
1230 data->image_views = ralloc_array(data, VkImageView, data->n_images);
1231 data->framebuffers = ralloc_array(data, VkFramebuffer, data->n_images);
1232
1233 device_data->vtable.GetSwapchainImagesKHR(device_data->device,
1234 data->swapchain,
1235 &data->n_images,
1236 data->images);
1237
1238 /* Image views */
1239 VkImageViewCreateInfo view_info = {};
1240 view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
1241 view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
1242 view_info.format = pCreateInfo->imageFormat;
1243 view_info.components.r = VK_COMPONENT_SWIZZLE_R;
1244 view_info.components.g = VK_COMPONENT_SWIZZLE_G;
1245 view_info.components.b = VK_COMPONENT_SWIZZLE_B;
1246 view_info.components.a = VK_COMPONENT_SWIZZLE_A;
1247 view_info.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 };
1248 for (uint32_t i = 0; i < data->n_images; i++) {
1249 view_info.image = data->images[i];
1250 err = device_data->vtable.CreateImageView(device_data->device, &view_info,
1251 NULL, &data->image_views[i]);
1252 check_vk_result(err);
1253 }
1254
1255 /* Framebuffers */
1256 VkImageView attachment[1];
1257 VkFramebufferCreateInfo fb_info = {};
1258 fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
1259 fb_info.renderPass = data->render_pass;
1260 fb_info.attachmentCount = 1;
1261 fb_info.pAttachments = attachment;
1262 fb_info.width = data->width;
1263 fb_info.height = data->height;
1264 fb_info.layers = 1;
1265 for (uint32_t i = 0; i < data->n_images; i++) {
1266 attachment[0] = data->image_views[i];
1267 err = device_data->vtable.CreateFramebuffer(device_data->device, &fb_info,
1268 NULL, &data->framebuffers[i]);
1269 check_vk_result(err);
1270 }
1271
1272 /* Command buffer */
1273 VkCommandPoolCreateInfo cmd_buffer_pool_info = {};
1274 cmd_buffer_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
1275 cmd_buffer_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
1276 cmd_buffer_pool_info.queueFamilyIndex = device_data->graphic_queue->family_index;
1277 err = device_data->vtable.CreateCommandPool(device_data->device,
1278 &cmd_buffer_pool_info,
1279 NULL, &data->command_pool);
1280 check_vk_result(err);
1281
1282 VkCommandBuffer cmd_bufs[ARRAY_SIZE(data->frame_data)];
1283
1284 VkCommandBufferAllocateInfo cmd_buffer_info = {};
1285 cmd_buffer_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
1286 cmd_buffer_info.commandPool = data->command_pool;
1287 cmd_buffer_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
1288 cmd_buffer_info.commandBufferCount = 2;
1289 err = device_data->vtable.AllocateCommandBuffers(device_data->device,
1290 &cmd_buffer_info,
1291 cmd_bufs);
1292 check_vk_result(err);
1293
1294 for (uint32_t i = 0; i < ARRAY_SIZE(data->frame_data); i++)
1295 data->frame_data[i].command_buffer = cmd_bufs[i];
1296
1297
1298 /* Submission fence */
1299 VkFenceCreateInfo fence_info = {};
1300 fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
1301 fence_info.flags = VK_FENCE_CREATE_SIGNALED_BIT;
1302 err = device_data->vtable.CreateFence(device_data->device, &fence_info,
1303 NULL, &data->fence);
1304 check_vk_result(err);
1305
1306 }
1307
1308 static void shutdown_swapchain_data(struct swapchain_data *data)
1309 {
1310 struct device_data *device_data = data->device;
1311
1312 for (uint32_t i = 0; i < data->n_images; i++) {
1313 device_data->vtable.DestroyImageView(device_data->device, data->image_views[i], NULL);
1314 device_data->vtable.DestroyFramebuffer(device_data->device, data->framebuffers[i], NULL);
1315 }
1316
1317 device_data->vtable.DestroyRenderPass(device_data->device, data->render_pass, NULL);
1318
1319 for (uint32_t i = 0; i < ARRAY_SIZE(data->frame_data); i++) {
1320 device_data->vtable.FreeCommandBuffers(device_data->device,
1321 data->command_pool,
1322 1, &data->frame_data[i].command_buffer);
1323 if (data->frame_data[i].vertex_buffer)
1324 device_data->vtable.DestroyBuffer(device_data->device, data->frame_data[i].vertex_buffer, NULL);
1325 if (data->frame_data[i].index_buffer)
1326 device_data->vtable.DestroyBuffer(device_data->device, data->frame_data[i].index_buffer, NULL);
1327 if (data->frame_data[i].vertex_buffer_mem)
1328 device_data->vtable.FreeMemory(device_data->device, data->frame_data[i].vertex_buffer_mem, NULL);
1329 if (data->frame_data[i].index_buffer_mem)
1330 device_data->vtable.FreeMemory(device_data->device, data->frame_data[i].index_buffer_mem, NULL);
1331 }
1332 device_data->vtable.DestroyCommandPool(device_data->device, data->command_pool, NULL);
1333
1334 device_data->vtable.DestroyFence(device_data->device, data->fence, NULL);
1335 if (data->submission_semaphore)
1336 device_data->vtable.DestroySemaphore(device_data->device, data->submission_semaphore, NULL);
1337
1338 device_data->vtable.DestroyPipeline(device_data->device, data->pipeline, NULL);
1339 device_data->vtable.DestroyPipelineLayout(device_data->device, data->pipeline_layout, NULL);
1340
1341 device_data->vtable.FreeDescriptorSets(device_data->device, data->descriptor_pool,
1342 1, &data->descriptor_set);
1343 device_data->vtable.DestroyDescriptorPool(device_data->device,
1344 data->descriptor_pool, NULL);
1345 device_data->vtable.DestroyDescriptorSetLayout(device_data->device,
1346 data->descriptor_layout, NULL);
1347
1348 device_data->vtable.DestroySampler(device_data->device, data->font_sampler, NULL);
1349 device_data->vtable.DestroyImageView(device_data->device, data->font_image_view, NULL);
1350 device_data->vtable.DestroyImage(device_data->device, data->font_image, NULL);
1351 device_data->vtable.FreeMemory(device_data->device, data->font_mem, NULL);
1352
1353 device_data->vtable.DestroyBuffer(device_data->device, data->upload_font_buffer, NULL);
1354 device_data->vtable.FreeMemory(device_data->device, data->upload_font_buffer_mem, NULL);
1355
1356 ImGui::DestroyContext(data->imgui_context);
1357 }
1358
1359 static void before_present(struct swapchain_data *swapchain_data,
1360 unsigned imageIndex)
1361 {
1362 snapshot_swapchain_frame(swapchain_data);
1363
1364 compute_swapchain_display(swapchain_data);
1365 render_swapchain_display(swapchain_data, imageIndex);
1366 }
1367
1368 VKAPI_ATTR VkResult VKAPI_CALL overlay_CreateSwapchainKHR(
1369 VkDevice device,
1370 const VkSwapchainCreateInfoKHR* pCreateInfo,
1371 const VkAllocationCallbacks* pAllocator,
1372 VkSwapchainKHR* pSwapchain)
1373 {
1374 struct device_data *device_data = FIND_DEVICE_DATA(device);
1375 VkResult result = device_data->vtable.CreateSwapchainKHR(device, pCreateInfo, pAllocator, pSwapchain);
1376 if (result != VK_SUCCESS) return result;
1377
1378 struct swapchain_data *swapchain_data = new_swapchain_data(*pSwapchain, device_data);
1379 setup_swapchain_data(swapchain_data, pCreateInfo);
1380 return result;
1381 }
1382
1383 VKAPI_ATTR void VKAPI_CALL overlay_DestroySwapchainKHR(
1384 VkDevice device,
1385 VkSwapchainKHR swapchain,
1386 const VkAllocationCallbacks* pAllocator)
1387 {
1388 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(swapchain);
1389
1390 shutdown_swapchain_data(swapchain_data);
1391 swapchain_data->device->vtable.DestroySwapchainKHR(device, swapchain, pAllocator);
1392 destroy_swapchain_data(swapchain_data);
1393 }
1394
1395 VKAPI_ATTR VkResult VKAPI_CALL overlay_QueuePresentKHR(
1396 VkQueue queue,
1397 const VkPresentInfoKHR* pPresentInfo)
1398 {
1399 struct queue_data *queue_data = FIND_QUEUE_DATA(queue);
1400 struct device_data *device_data = queue_data->device;
1401
1402 /* If we present on the graphic queue this layer is using to draw an
1403 * overlay, we don't need more than submitting the overlay draw prior to
1404 * present.
1405 */
1406 if (queue_data == device_data->graphic_queue) {
1407 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1408 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(pPresentInfo->pSwapchains[i]);
1409 before_present(swapchain_data, pPresentInfo->pImageIndices[i]);
1410 }
1411 return queue_data->device->vtable.QueuePresentKHR(queue, pPresentInfo);
1412 }
1413
1414 /* Otherwise we need to do cross queue synchronization to tie the overlay
1415 * draw into the present queue.
1416 */
1417 VkPresentInfoKHR present_info = *pPresentInfo;
1418 VkSemaphore *semaphores =
1419 (VkSemaphore *)malloc(sizeof(VkSemaphore) * (pPresentInfo->waitSemaphoreCount + pPresentInfo->swapchainCount));
1420 for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; i++)
1421 semaphores[i] = pPresentInfo->pWaitSemaphores[i];
1422 for (uint32_t i = 0; i < pPresentInfo->swapchainCount; i++) {
1423 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(pPresentInfo->pSwapchains[i]);
1424 before_present(swapchain_data, pPresentInfo->pImageIndices[i]);
1425 semaphores[pPresentInfo->waitSemaphoreCount + i] = swapchain_data->submission_semaphore;
1426 }
1427 present_info.pWaitSemaphores = semaphores;
1428 present_info.waitSemaphoreCount = pPresentInfo->waitSemaphoreCount + pPresentInfo->swapchainCount;
1429 VkResult result = queue_data->device->vtable.QueuePresentKHR(queue, &present_info);
1430 free(semaphores);
1431 return result;
1432 }
1433
1434 VKAPI_ATTR VkResult VKAPI_CALL overlay_AcquireNextImageKHR(
1435 VkDevice device,
1436 VkSwapchainKHR swapchain,
1437 uint64_t timeout,
1438 VkSemaphore semaphore,
1439 VkFence fence,
1440 uint32_t* pImageIndex)
1441 {
1442 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(swapchain);
1443 struct device_data *device_data = swapchain_data->device;
1444
1445 uint64_t ts0 = os_time_get();
1446 VkResult result = device_data->vtable.AcquireNextImageKHR(device, swapchain, timeout,
1447 semaphore, fence, pImageIndex);
1448 uint64_t ts1 = os_time_get();
1449
1450 swapchain_data->acquire_times[swapchain_data->n_acquire %
1451 ARRAY_SIZE(swapchain_data->acquire_times)] =
1452 ((double)ts1 - (double)ts0) / 1000.0;
1453 swapchain_data->n_acquire++;
1454
1455 return result;
1456 }
1457
1458 VKAPI_ATTR VkResult VKAPI_CALL overlay_AcquireNextImage2KHR(
1459 VkDevice device,
1460 const VkAcquireNextImageInfoKHR* pAcquireInfo,
1461 uint32_t* pImageIndex)
1462 {
1463 struct swapchain_data *swapchain_data = FIND_SWAPCHAIN_DATA(pAcquireInfo->swapchain);
1464 struct device_data *device_data = swapchain_data->device;
1465
1466 uint64_t ts0 = os_time_get();
1467 VkResult result = device_data->vtable.AcquireNextImage2KHR(device, pAcquireInfo, pImageIndex);
1468 uint64_t ts1 = os_time_get();
1469
1470 swapchain_data->acquire_times[swapchain_data->n_acquire %
1471 ARRAY_SIZE(swapchain_data->acquire_times)] =
1472 ((double)ts1 - (double)ts0) / 1000.0;
1473 swapchain_data->n_acquire++;
1474
1475 return result;
1476 }
1477
1478 VKAPI_ATTR void VKAPI_CALL overlay_CmdDraw(
1479 VkCommandBuffer commandBuffer,
1480 uint32_t vertexCount,
1481 uint32_t instanceCount,
1482 uint32_t firstVertex,
1483 uint32_t firstInstance)
1484 {
1485 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1486 device_data->vtable.CmdDraw(commandBuffer, vertexCount, instanceCount,
1487 firstVertex, firstInstance);
1488 device_data->stats.stats[OVERLAY_PARAM_ENABLED_draw]++;
1489 }
1490
1491 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndexed(
1492 VkCommandBuffer commandBuffer,
1493 uint32_t indexCount,
1494 uint32_t instanceCount,
1495 uint32_t firstIndex,
1496 int32_t vertexOffset,
1497 uint32_t firstInstance)
1498 {
1499 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1500 device_data->vtable.CmdDrawIndexed(commandBuffer, indexCount, instanceCount,
1501 firstIndex, vertexOffset, firstInstance);
1502 device_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed]++;
1503 }
1504
1505 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndirect(
1506 VkCommandBuffer commandBuffer,
1507 VkBuffer buffer,
1508 VkDeviceSize offset,
1509 uint32_t drawCount,
1510 uint32_t stride)
1511 {
1512 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1513 device_data->vtable.CmdDrawIndirect(commandBuffer, buffer, offset, drawCount, stride);
1514 device_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect]++;
1515 }
1516
1517 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndexedIndirect(
1518 VkCommandBuffer commandBuffer,
1519 VkBuffer buffer,
1520 VkDeviceSize offset,
1521 uint32_t drawCount,
1522 uint32_t stride)
1523 {
1524 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1525 device_data->vtable.CmdDrawIndexedIndirect(commandBuffer, buffer, offset, drawCount, stride);
1526 device_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect]++;
1527 }
1528
1529 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndirectCountKHR(
1530 VkCommandBuffer commandBuffer,
1531 VkBuffer buffer,
1532 VkDeviceSize offset,
1533 VkBuffer countBuffer,
1534 VkDeviceSize countBufferOffset,
1535 uint32_t maxDrawCount,
1536 uint32_t stride)
1537 {
1538 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1539 device_data->vtable.CmdDrawIndirectCountKHR(commandBuffer, buffer, offset,
1540 countBuffer, countBufferOffset,
1541 maxDrawCount, stride);
1542 device_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indirect_count]++;
1543 }
1544
1545 VKAPI_ATTR void VKAPI_CALL overlay_CmdDrawIndexedIndirectCountKHR(
1546 VkCommandBuffer commandBuffer,
1547 VkBuffer buffer,
1548 VkDeviceSize offset,
1549 VkBuffer countBuffer,
1550 VkDeviceSize countBufferOffset,
1551 uint32_t maxDrawCount,
1552 uint32_t stride)
1553 {
1554 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1555 device_data->vtable.CmdDrawIndexedIndirectCountKHR(commandBuffer, buffer, offset,
1556 countBuffer, countBufferOffset,
1557 maxDrawCount, stride);
1558 device_data->stats.stats[OVERLAY_PARAM_ENABLED_draw_indexed_indirect_count]++;
1559 }
1560
1561 VKAPI_ATTR void VKAPI_CALL overlay_CmdDispatch(
1562 VkCommandBuffer commandBuffer,
1563 uint32_t groupCountX,
1564 uint32_t groupCountY,
1565 uint32_t groupCountZ)
1566 {
1567 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1568 device_data->vtable.CmdDispatch(commandBuffer, groupCountX, groupCountY, groupCountZ);
1569 device_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch]++;
1570 }
1571
1572 VKAPI_ATTR void VKAPI_CALL overlay_CmdDispatchIndirect(
1573 VkCommandBuffer commandBuffer,
1574 VkBuffer buffer,
1575 VkDeviceSize offset)
1576 {
1577 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1578 device_data->vtable.CmdDispatchIndirect(commandBuffer, buffer, offset);
1579 device_data->stats.stats[OVERLAY_PARAM_ENABLED_dispatch_indirect]++;
1580 }
1581
1582 VKAPI_ATTR void VKAPI_CALL overlay_CmdBindPipeline(
1583 VkCommandBuffer commandBuffer,
1584 VkPipelineBindPoint pipelineBindPoint,
1585 VkPipeline pipeline)
1586 {
1587 struct device_data *device_data = FIND_DEVICE_DATA(commandBuffer);
1588 device_data->vtable.CmdBindPipeline(commandBuffer, pipelineBindPoint, pipeline);
1589 switch (pipelineBindPoint) {
1590 case VK_PIPELINE_BIND_POINT_GRAPHICS: device_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_graphics]++; break;
1591 case VK_PIPELINE_BIND_POINT_COMPUTE: device_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_compute]++; break;
1592 case VK_PIPELINE_BIND_POINT_RAY_TRACING_NV: device_data->stats.stats[OVERLAY_PARAM_ENABLED_pipeline_raytracing]++; break;
1593 default: break;
1594 }
1595 }
1596
1597 VKAPI_ATTR VkResult VKAPI_CALL overlay_AllocateCommandBuffers(VkDevice device,
1598 const VkCommandBufferAllocateInfo* pAllocateInfo,
1599 VkCommandBuffer* pCommandBuffers)
1600 {
1601 struct device_data *device_data = FIND_DEVICE_DATA(device);
1602
1603 VkResult result =
1604 device_data->vtable.AllocateCommandBuffers(device, pAllocateInfo, pCommandBuffers);
1605 if (result != VK_SUCCESS) return result;
1606
1607 for (uint32_t i = 0; i < pAllocateInfo->commandBufferCount; i++)
1608 map_object(pCommandBuffers[i], device_data);
1609
1610 return result;
1611 }
1612
1613 VKAPI_ATTR void VKAPI_CALL overlay_FreeCommandBuffers(VkDevice device,
1614 VkCommandPool commandPool,
1615 uint32_t commandBufferCount,
1616 const VkCommandBuffer* pCommandBuffers)
1617 {
1618 struct device_data *device_data = FIND_DEVICE_DATA(device);
1619
1620 for (uint32_t i = 0; i < commandBufferCount; i++)
1621 unmap_object(pCommandBuffers[i]);
1622
1623 device_data->vtable.FreeCommandBuffers(device, commandPool,
1624 commandBufferCount, pCommandBuffers);
1625 }
1626
1627 VKAPI_ATTR VkResult VKAPI_CALL overlay_QueueSubmit(
1628 VkQueue queue,
1629 uint32_t submitCount,
1630 const VkSubmitInfo* pSubmits,
1631 VkFence fence)
1632 {
1633 struct queue_data *queue_data = FIND_QUEUE_DATA(queue);
1634 struct device_data *device_data = queue_data->device;
1635
1636 device_data->stats.stats[OVERLAY_PARAM_ENABLED_submit]++;
1637
1638 return device_data->vtable.QueueSubmit(queue, submitCount, pSubmits, fence);
1639 }
1640
1641 VKAPI_ATTR VkResult VKAPI_CALL overlay_CreateDevice(
1642 VkPhysicalDevice physicalDevice,
1643 const VkDeviceCreateInfo* pCreateInfo,
1644 const VkAllocationCallbacks* pAllocator,
1645 VkDevice* pDevice)
1646 {
1647 struct instance_data *instance_data = FIND_PHYSICAL_DEVICE_DATA(physicalDevice);
1648 VkLayerDeviceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
1649
1650 assert(chain_info->u.pLayerInfo);
1651 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr = chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
1652 PFN_vkGetDeviceProcAddr fpGetDeviceProcAddr = chain_info->u.pLayerInfo->pfnNextGetDeviceProcAddr;
1653 PFN_vkCreateDevice fpCreateDevice = (PFN_vkCreateDevice)fpGetInstanceProcAddr(NULL, "vkCreateDevice");
1654 if (fpCreateDevice == NULL) {
1655 return VK_ERROR_INITIALIZATION_FAILED;
1656 }
1657
1658 // Advance the link info for the next element on the chain
1659 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
1660
1661 VkResult result = fpCreateDevice(physicalDevice, pCreateInfo, pAllocator, pDevice);
1662 if (result != VK_SUCCESS) return result;
1663
1664 struct device_data *device_data = new_device_data(*pDevice, instance_data);
1665 device_data->physical_device = physicalDevice;
1666 layer_init_device_dispatch_table(*pDevice, &device_data->vtable, fpGetDeviceProcAddr);
1667
1668 instance_data->vtable.GetPhysicalDeviceProperties(device_data->physical_device,
1669 &device_data->properties);
1670
1671 device_map_queues(device_data, pCreateInfo);
1672
1673 return result;
1674 }
1675
1676 VKAPI_ATTR void VKAPI_CALL overlay_DestroyDevice(
1677 VkDevice device,
1678 const VkAllocationCallbacks* pAllocator)
1679 {
1680 struct device_data *device_data = FIND_DEVICE_DATA(device);
1681 device_unmap_queues(device_data);
1682 device_data->vtable.DestroyDevice(device, pAllocator);
1683 destroy_device_data(device_data);
1684 }
1685
1686 VKAPI_ATTR VkResult VKAPI_CALL overlay_CreateInstance(
1687 const VkInstanceCreateInfo* pCreateInfo,
1688 const VkAllocationCallbacks* pAllocator,
1689 VkInstance* pInstance)
1690 {
1691 VkLayerInstanceCreateInfo *chain_info = get_chain_info(pCreateInfo, VK_LAYER_LINK_INFO);
1692
1693 assert(chain_info->u.pLayerInfo);
1694 PFN_vkGetInstanceProcAddr fpGetInstanceProcAddr =
1695 chain_info->u.pLayerInfo->pfnNextGetInstanceProcAddr;
1696 PFN_vkCreateInstance fpCreateInstance =
1697 (PFN_vkCreateInstance)fpGetInstanceProcAddr(NULL, "vkCreateInstance");
1698 if (fpCreateInstance == NULL) {
1699 return VK_ERROR_INITIALIZATION_FAILED;
1700 }
1701
1702 // Advance the link info for the next element on the chain
1703 chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext;
1704
1705 VkResult result = fpCreateInstance(pCreateInfo, pAllocator, pInstance);
1706 if (result != VK_SUCCESS) return result;
1707
1708 struct instance_data *instance_data = new_instance_data(*pInstance);
1709 layer_init_instance_dispatch_table(instance_data->instance,
1710 &instance_data->vtable,
1711 fpGetInstanceProcAddr);
1712 instance_data_map_physical_devices(instance_data, true);
1713
1714 parse_overlay_env(&instance_data->params, getenv("VK_LAYER_MESA_OVERLAY_CONFIG"));
1715
1716 return result;
1717 }
1718
1719 VKAPI_ATTR void VKAPI_CALL overlay_DestroyInstance(
1720 VkInstance instance,
1721 const VkAllocationCallbacks* pAllocator)
1722 {
1723 struct instance_data *instance_data = FIND_INSTANCE_DATA(instance);
1724 instance_data_map_physical_devices(instance_data, false);
1725 instance_data->vtable.DestroyInstance(instance, pAllocator);
1726 destroy_instance_data(instance_data);
1727 }
1728
1729 static const struct {
1730 const char *name;
1731 void *ptr;
1732 } name_to_funcptr_map[] = {
1733 { "vkGetDeviceProcAddr", (void *) vkGetDeviceProcAddr },
1734 #define ADD_HOOK(fn) { "vk" # fn, (void *) overlay_ ## fn }
1735 ADD_HOOK(AllocateCommandBuffers),
1736
1737 ADD_HOOK(CmdDraw),
1738 ADD_HOOK(CmdDrawIndexed),
1739 ADD_HOOK(CmdDrawIndexedIndirect),
1740 ADD_HOOK(CmdDispatch),
1741 ADD_HOOK(CmdDispatchIndirect),
1742 ADD_HOOK(CmdDrawIndirectCountKHR),
1743 ADD_HOOK(CmdDrawIndexedIndirectCountKHR),
1744
1745 ADD_HOOK(CmdBindPipeline),
1746
1747 ADD_HOOK(CreateSwapchainKHR),
1748 ADD_HOOK(QueuePresentKHR),
1749 ADD_HOOK(DestroySwapchainKHR),
1750 ADD_HOOK(AcquireNextImageKHR),
1751 ADD_HOOK(AcquireNextImage2KHR),
1752
1753 ADD_HOOK(QueueSubmit),
1754 ADD_HOOK(CreateInstance),
1755 ADD_HOOK(DestroyInstance),
1756 ADD_HOOK(CreateDevice),
1757 ADD_HOOK(DestroyDevice),
1758 #undef ADD_HOOK
1759 };
1760
1761 static void *find_ptr(const char *name)
1762 {
1763 for (uint32_t i = 0; i < ARRAY_SIZE(name_to_funcptr_map); i++) {
1764 if (strcmp(name, name_to_funcptr_map[i].name) == 0)
1765 return name_to_funcptr_map[i].ptr;
1766 }
1767
1768 return NULL;
1769 }
1770
1771 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice dev,
1772 const char *funcName)
1773 {
1774 void *ptr = find_ptr(funcName);
1775 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
1776
1777 if (dev == NULL) return NULL;
1778
1779 struct device_data *device_data = FIND_DEVICE_DATA(dev);
1780 if (device_data->vtable.GetDeviceProcAddr == NULL) return NULL;
1781 return device_data->vtable.GetDeviceProcAddr(dev, funcName);
1782 }
1783
1784 VK_LAYER_EXPORT VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance,
1785 const char *funcName)
1786 {
1787 void *ptr = find_ptr(funcName);
1788 if (ptr) return reinterpret_cast<PFN_vkVoidFunction>(ptr);
1789
1790 if (instance == NULL) return NULL;
1791
1792 struct instance_data *instance_data = FIND_INSTANCE_DATA(instance);
1793 if (instance_data->vtable.GetInstanceProcAddr == NULL) return NULL;
1794 return instance_data->vtable.GetInstanceProcAddr(instance, funcName);
1795 }