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