context.cpp 22 KB
Newer Older
1
2
3
4
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>

#include <sf2/sf2.hpp> // has to be first so he sf2_struct define is set
5
6
7
8
9
10
11
12
13
14
15

#include <mirrage/graphic/context.hpp>
#include <mirrage/graphic/device.hpp>
#include <mirrage/graphic/window.hpp>

#include <mirrage/asset/asset_manager.hpp>
#include <mirrage/utils/log.hpp>
#include <mirrage/utils/template_utils.hpp>

#include <gsl/gsl>

16
#include <cstdio>
17
18
#include <iostream>
#include <sstream>
19
#include <unordered_set>
20
21
22


extern "C" {
23
24
25
26
VkResult vkCreateDebugReportCallbackEXT(VkInstance                                instance,
                                        const VkDebugReportCallbackCreateInfoEXT* pCreateInfo,
                                        const VkAllocationCallbacks*              pAllocator,
                                        VkDebugReportCallbackEXT*                 pCallback) {
Florian Oetke's avatar
Florian Oetke committed
27
28
	auto func = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr(
	        instance, "vkCreateDebugReportCallbackEXT");
29
30
31
32
	if(func != nullptr) {
		return func(instance, pCreateInfo, pAllocator, pCallback);
	} else {
		return VK_ERROR_EXTENSION_NOT_PRESENT;
33
	}
34
}
35

36
37
38
39
40
41
42
void vkDestroyDebugReportCallbackEXT(VkInstance                   instance,
                                     VkDebugReportCallbackEXT     callback,
                                     const VkAllocationCallbacks* pAllocator) {
	auto func = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr(
	        instance, "vkDestroyDebugReportCallbackEXT");
	if(func != nullptr) {
		func(instance, callback, pAllocator);
43
44
	}
}
45
}
46

47
namespace mirrage::graphic {
48
49
50
51
52

	using namespace util::unit_literals;

	namespace {
		void sdl_error_check() {
53
			const char* err = SDL_GetError();
54
55
56
			if(*err != '\0') {
				std::string errorStr(err);
				SDL_ClearError();
57
				MIRRAGE_FAIL("SDL: " << errorStr);
58
59
60
			}
		}

61
62
63
64
65
66
67
68
69
70
		void add_presnet_extensions(std::vector<const char*>& extensions, SDL_Window* window) {
			auto count = static_cast<unsigned int>(0);
			if(!SDL_Vulkan_GetInstanceExtensions(window, &count, nullptr)) {
				MIRRAGE_FAIL("Unable to determine present extensions: " << SDL_GetError());
			}

			auto begin = extensions.size();
			extensions.resize(begin + count);

			if(!SDL_Vulkan_GetInstanceExtensions(window, &count, extensions.data() + begin)) {
71
				MIRRAGE_FAIL("Unable to determine present extensions: " << SDL_GetError());
72
			}
73
74
75
76
		}

		void add_present_extensions(std::vector<const char*>&                          extensions,
		                            const std::unordered_map<std::string, Window_ptr>& windows) {
77

78
			extensions.reserve(extensions.size() + windows.size() * 4);
79

80
81
82
			for(auto && [_, window] : windows) {
				(void) _;
				add_presnet_extensions(extensions, window->window_handle());
83
84
85
			}
		}

86
87
88
89
90
91
92
93
94
95
96
97
		void sort_and_unique(std::vector<const char*>& extensions) {
			std::sort(extensions.begin(), extensions.end(), [](auto lhs, auto rhs) {
				return std::strcmp(lhs, rhs) < 0;
			});
			auto new_end =
			        std::unique(extensions.begin(), extensions.end(), [](auto lhs, auto rhs) {
				        return std::strcmp(lhs, rhs) == 0;
			        });

			extensions.erase(new_end, extensions.end());
		}

98
		auto check_extensions(const std::vector<const char*>& required,
Florian Oetke's avatar
Florian Oetke committed
99
100
		                      const std::vector<const char*>& optional)
		        -> std::vector<const char*> {
101
102
103
104
105
106
107
108
			auto extensions = std::vector<const char*>();
			extensions.reserve(required.size() + optional.size());

			auto supported_extensions = vk::enumerateInstanceExtensionProperties();

			auto support_confirmed = std::vector<bool>(required.size());

			for(auto& e : supported_extensions) {
109
				for(auto i = 0u; i < required.size(); i++) {
110
111
112
113
114
115
116
					if(!strcmp(e.extensionName, required[i])) {
						support_confirmed[i] = true;
						extensions.push_back(required[i]);
						break;
					}
				}

117
				for(auto i = 0u; i < optional.size(); i++) {
118
119
120
121
122
123
124
125
					if(!strcmp(e.extensionName, optional[i])) {
						extensions.push_back(optional[i]);
						break;
					}
				}
			}

			bool all_supported = true;
126
			for(auto i = 0u; i < support_confirmed.size(); i++) {
127
				if(!support_confirmed[i]) {
128
					MIRRAGE_WARN("Unsupported extension \"" << required[i] << "\"!");
129
130
131
132
133
					all_supported = false;
				}
			}

			if(!all_supported) {
Florian Oetke's avatar
Florian Oetke committed
134
135
				MIRRAGE_FAIL(
				        "At least one required extension is not supported (see log for details)!");
136
137
138
139
140
141
142
143
144
145
146
147
148
			}

			return extensions;
		}

		auto check_layers(const std::vector<const char*>& requested) -> std::vector<const char*> {
			auto validation_layers = std::vector<const char*>();
			validation_layers.reserve(requested.size());

			auto supported_layers = vk::enumerateInstanceLayerProperties();
			for(auto& l : supported_layers) {
				bool layer_requested = false;
				for(auto& req_layer : requested) {
149
					if(0 == strcmp(l.layerName, req_layer)) {
150
151
152
153
154
155
156
						validation_layers.push_back(req_layer);
						layer_requested = true;
						break;
					}
				}

				if(!layer_requested) {
Florian Oetke's avatar
Florian Oetke committed
157
158
159
					MIRRAGE_DEBUG(
					        "Additional validation layer is available, that hasn't been requested: "
					        << l.layerName);
160
161
162
163
				}
			}

			if(validation_layers.size() != requested.size()) {
164
				auto log = util::error(__func__, __FILE__, __LINE__);
165
166
				log << "Some requested validation layers are not supported: \n";
				for(auto& l : validation_layers) {
167
					log << "  - " << l << "\n";
168
169
170
171
172
173
174
				}
				log << std::endl;
			}

			return validation_layers;
		}

175
176
177
178
179
180
181
182
		VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(VkDebugReportFlagsEXT      flags,
		                                             VkDebugReportObjectTypeEXT objType,
		                                             uint64_t                   obj,
		                                             size_t                     location,
		                                             int32_t                    code,
		                                             const char*                layerPrefix,
		                                             const char*                msg,
		                                             void*                      userData) {
183
184
185
186

			// silences: DescriptorSet 0x3f previously bound as set #1 is incompatible with set
			//             0x1cc99c0 newly bound as set #1 so set #2 and any subsequent sets were
			//             disturbed by newly bound pipelineLayout (0x4f)
187
			if(objType == VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT)
188
189
190
191
				return VK_FALSE;


			if(flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
192
				MIRRAGE_ERROR("[VK | " << layerPrefix << "] " << msg);
193
194
			} else if(flags & VK_DEBUG_REPORT_WARNING_BIT_EXT
			          || flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
195
				MIRRAGE_WARN("[VK | " << layerPrefix << "] " << msg);
196
			} else {
197
				MIRRAGE_INFO("[VK | " << layerPrefix << "] " << msg);
198
199
200
201
			}

			return VK_FALSE;
		}
202
	} // namespace
203
204


205
206
207
208
209
210
211
	Context::Context(const std::string&    appName,
	                 uint32_t              appVersion,
	                 const std::string&    engineName,
	                 uint32_t              engineVersion,
	                 bool                  debug,
	                 asset::Asset_manager& assets)
	  : _assets(assets), _name(appName) {
212
213
214
215

		auto maybe_settings = assets.load_maybe<Graphics_settings>("cfg:graphics"_aid);
		if(maybe_settings.is_nothing()) {
			if(!settings(default_settings())) {
216
				MIRRAGE_FAIL("Invalid graphics settings");
217
218
			}
		} else {
219
			_settings = maybe_settings.get_or_throw().get();
220
221
222
		}

		if(!settings(*_settings)) { //< apply actual size/settings
223
			MIRRAGE_FAIL("Couldn't apply graphics settings");
224
225
226
227
		}

		sdl_error_check();

228
229
230
231
232
233
234
235
236
237
		for(auto && [title, win] : _settings->windows) {
			_windows.emplace(title,
			                 std::make_unique<Window>(title,
			                                          app_name() + " | " + title,
			                                          win.display,
			                                          win.width,
			                                          win.height,
			                                          win.fullscreen));
		}

238
		auto instanceCreateInfo = vk::InstanceCreateInfo{};
239
		auto appInfo            = vk::ApplicationInfo{
240
                appName.c_str(), appVersion, engineName.c_str(), engineVersion, VK_API_VERSION_1_0};
241

242
		auto required_extensions = std::vector<const char*>{VK_KHR_SURFACE_EXTENSION_NAME};
243
		add_present_extensions(required_extensions, _windows);
244
		auto optional_extensions = std::vector<const char*>{};
245
246
247


		if(debug) {
248
			_enabled_layers = check_layers({"VK_LAYER_LUNARG_standard_validation"});
249
250
251
252

			required_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
		}

253
254
		sort_and_unique(required_extensions);
		sort_and_unique(optional_extensions);
255
256
		auto extensions = check_extensions(required_extensions, optional_extensions);

257
		auto log = util::info(__func__, __FILE__, __LINE__);
258
259
260
		log << "Initializing vulkan...\n";
		log << "Enabled extensions:\n";
		for(auto e : extensions) {
261
			log << "  - " << e << "\n";
262
263
264
		}
		log << "Enabled validation layers:\n";
		for(auto l : _enabled_layers) {
265
			log << "  - " << l << "\n";
266
267
268
269
270
271
272
273
274
275
276
		}
		log << std::endl;

		instanceCreateInfo.setPApplicationInfo(&appInfo);
		instanceCreateInfo.setEnabledExtensionCount(gsl::narrow<uint32_t>(extensions.size()));
		instanceCreateInfo.setPpEnabledExtensionNames(extensions.data());
		instanceCreateInfo.setEnabledLayerCount(gsl::narrow<uint32_t>(_enabled_layers.size()));
		instanceCreateInfo.setPpEnabledLayerNames(_enabled_layers.data());
		_instance = vk::createInstanceUnique(instanceCreateInfo);

		if(debug) {
277
278
			_debug_callback = _instance->createDebugReportCallbackEXTUnique(
			        {/*	vk::DebugReportFlagBitsEXT::eDebug | vk::DebugReportFlagBitsEXT::eInformation | */
Florian Oetke's avatar
Florian Oetke committed
279
280
			         vk::DebugReportFlagBitsEXT::eError
			                 | vk::DebugReportFlagBitsEXT::ePerformanceWarning
281
282
			                 | vk::DebugReportFlagBitsEXT::eWarning,
			         debugCallback});
283
		}
284
285
286
287
288

		for(auto && [_, window] : _windows) {
			(void) _;
			window->create_surface(*this);
		}
289
290
291
292
293
	}
	Context::~Context() = default;

	bool Context::settings(Graphics_settings new_settings) {
		_assets.save<Graphics_settings>("cfg:graphics"_aid, new_settings);
294
		_settings = _assets.load<Graphics_settings>("cfg:graphics"_aid).get();
295
296
297
298

		return true;
	}

299
300
301
	auto Context::find_window(std::string name) -> util::maybe<Window&> {
		auto iter = _windows.find(name);
		return iter == _windows.end() ? util::nothing : util::justPtr(&*iter->second);
302
	}
Florian Oetke's avatar
Florian Oetke committed
303
304
	auto Context::_find_window_settings(const std::string& name, int width, int height)
	        -> Window_settings {
305
306
		auto& cfg = settings();

Florian Oetke's avatar
Florian Oetke committed
307
308
309
		auto win_cfg = std::find_if(std::begin(cfg.windows), std::end(cfg.windows), [&](auto& w) {
			return w.first == name;
		});
310

311
		if(win_cfg == std::end(cfg.windows)) { // no config create new
312
313
			auto new_settings = cfg;
			auto win_settings = default_window_settings(0);
314
315
316
			if(width > 0)
				win_settings.width = width;
			if(height > 0)
317
				win_settings.height = height;
318
319
320
321
322
323
324
325
326
327
328
329
330
			new_settings.windows[name] = win_settings;

			settings(new_settings);

			return win_settings;
		}

		return win_cfg->second;
	}

	namespace {
		bool supports_present(vk::PhysicalDevice& gpu, const std::vector<Window*>& can_present_to) {
			auto supported_extensions = gpu.enumerateDeviceExtensionProperties();
Florian Oetke's avatar
Florian Oetke committed
331
332
333
334
			auto sc_ext               = std::find_if(
                    supported_extensions.begin(), supported_extensions.end(), [](auto& e) {
                        return std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0;
                    });
335

336
			if(sc_ext == supported_extensions.end()) {
337
338
339
340
341
342
343
344
345
346
347
348
349
				return false;
			}

			for(auto window : can_present_to) {
				auto formats       = gpu.getSurfaceFormatsKHR(window->surface());
				auto present_modes = gpu.getSurfacePresentModesKHR(window->surface());

				if(formats.empty() || present_modes.empty())
					return false;
			}

			return true;
		}
350

Florian Oetke's avatar
Florian Oetke committed
351
352
		auto find_graphics_queue(vk::PhysicalDevice&         gpu,
		                         const std::vector<Window*>& can_present_to)
353
354
		        -> util::maybe<std::uint32_t> {
			auto i = 0;
355
356

			for(auto& queue_family : gpu.getQueueFamilyProperties()) {
357
358
				auto can_present =
				        can_present_to.empty()
Florian Oetke's avatar
Florian Oetke committed
359
360
361
362
				        || std::all_of(
				                   can_present_to.begin(), can_present_to.end(), [&](auto window) {
					                   return gpu.getSurfaceSupportKHR(i, window->surface());
				                   });
363
364
365
366

				if(queue_family.queueCount > 0 && can_present
				   && queue_family.timestampValidBits
				              >= 32 // only accept queues with >=32bit timer support, for now
367
368
369
370
371
372
373
374
375
376
377
378
				   && (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)) {
					return i;
				}

				i++;
			}

			return util::nothing;
		}

		auto find_transfer_queue(vk::PhysicalDevice& gpu) -> std::uint32_t {
			auto families = gpu.getQueueFamilyProperties();
379

380
			auto i = 0;
381

382
383
			// check for transfer-only queue
			for(auto& queue_family : families) {
Florian Oetke's avatar
Florian Oetke committed
384
385
				if(queue_family.queueCount > 0
				   && (queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
386
				   && !(queue_family.queueFlags & vk::QueueFlagBits::eGraphics)) {
387
388
389
390
391
					return i;
				}

				i++;
			}
392
393

			i = 0;
394
			for(auto& queue_family : families) {
395
				if(queue_family.queueCount > 0
396
				   && ((queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
397
398
				       || (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)
				       || (queue_family.queueFlags & vk::QueueFlagBits::eCompute))) {
399
400
401
402
403
					return i;
				}

				i++;
			}
404

405
			MIRRAGE_FAIL("No queue found, that supports transfer operations!");
406
407
		}

408
409
410
411
		auto find_surface_format(vk::PhysicalDevice& gpu,
		                         Window&             window,
		                         vk::Format          target_format,
		                         vk::ColorSpaceKHR   target_space) -> vk::SurfaceFormatKHR {
412
413

			auto formats = gpu.getSurfaceFormatsKHR(window.surface());
414
			if(formats.size() == 1 && formats.front().format == vk::Format::eUndefined) {
415
416
417
418
				auto surface_format       = vk::SurfaceFormatKHR{};
				surface_format.format     = target_format;
				surface_format.colorSpace = target_space;
				return surface_format;
419
420
421
			}

			auto opt_found = std::find_if(formats.begin(), formats.end(), [&](auto& f) {
422
				return f.format == target_format && f.colorSpace == target_space;
423
			});
424
			if(opt_found != formats.end()) {
425
426
427
428
				auto surface_format       = vk::SurfaceFormatKHR{};
				surface_format.format     = target_format;
				surface_format.colorSpace = target_space;
				return surface_format;
429
430
			}

Florian Oetke's avatar
Florian Oetke committed
431
432
433
			opt_found = std::find_if(formats.begin(), formats.end(), [&](auto& f) {
				return f.format == target_format;
			});
434
			if(opt_found != formats.end()) {
435
436
437
438
				return *opt_found;
			}

			if(!formats.empty()) {
439
				MIRRAGE_WARN(
440
441
				        "Requested format is not supported by the device, fallback to first "
				        "reported "
442
				        "format");
443
444
				return formats.front();
			} else {
445
				MIRRAGE_FAIL("The device doesn't support any surface formats!");
446
447
448
			}
		}

449
450
		auto create_swapchain_create_info(vk::PhysicalDevice          gpu,
		                                  bool                        srgb,
451
452
		                                  const std::vector<Window*>& can_present_to) {
			auto swapchains = Swapchain_create_infos();
453

454
455
			for(auto window : can_present_to) {
				auto capabilities = gpu.getSurfaceCapabilitiesKHR(window->surface());
456
457


458
459
460
461
462
463
464
				auto sc_info = vk::SwapchainCreateInfoKHR{};
				sc_info.setSurface(window->surface());
				sc_info.setClipped(true);
				sc_info.setPreTransform(capabilities.currentTransform);
				sc_info.setImageSharingMode(vk::SharingMode::eExclusive);
				sc_info.setImageUsage(vk::ImageUsageFlagBits::eColorAttachment);
				sc_info.setImageArrayLayers(1);
465
				sc_info.setMinImageCount(std::max(3u, capabilities.minImageCount));
Florian Oetke's avatar
Florian Oetke committed
466
467
				if(capabilities.maxImageCount > 0
				   && capabilities.maxImageCount < sc_info.minImageCount) {
468
469
					sc_info.setMinImageCount(capabilities.maxImageCount);
				}
470

Florian Oetke's avatar
Florian Oetke committed
471
472
473
474
475
				auto present_modes     = gpu.getSurfacePresentModesKHR(window->surface());
				auto mailbox_supported = std::find(present_modes.begin(),
				                                   present_modes.end(),
				                                   vk::PresentModeKHR::eMailbox)
				                         != present_modes.end();
476
477
478
479
480
				if(mailbox_supported) {
					sc_info.setPresentMode(vk::PresentModeKHR::eMailbox);
				} else {
					sc_info.setPresentMode(vk::PresentModeKHR::eFifo);
				}
481

482
				if(capabilities.currentExtent.width == std::numeric_limits<uint32_t>::max()) {
483
484
485
486
487
488
489
490
491
					capabilities.currentExtent.width =
					        std::min(std::max(gsl::narrow<std::uint32_t>(window->width()),
					                          capabilities.minImageExtent.width),
					                 capabilities.maxImageExtent.width);

					capabilities.currentExtent.height =
					        std::min(std::max(gsl::narrow<std::uint32_t>(window->height()),
					                          capabilities.minImageExtent.height),
					                 capabilities.maxImageExtent.height);
492
				}
493

494
				sc_info.setImageExtent(capabilities.currentExtent);
495

Florian Oetke's avatar
Florian Oetke committed
496
497
498
499
500
				auto format = find_surface_format(gpu,
				                                  *window,
				                                  srgb ? vk::Format::eB8G8R8A8Srgb
				                                       : vk::Format::eB8G8R8A8Unorm,
				                                  vk::ColorSpaceKHR::eSrgbNonlinear);
501

502
503
				sc_info.setImageFormat(format.format);
				sc_info.setImageColorSpace(format.colorSpace);
504

505
506
				swapchains.emplace(window->name(), std::make_tuple(window, sc_info));
			}
507

508
509
			return swapchains;
		}
510
	} // namespace
511
512
513
514
	auto Context::instantiate_device(Device_selector             selector,
	                                 Device_factory              factory,
	                                 const std::vector<Window*>& can_present_to,
	                                 bool                        srgb) -> Device_ptr {
515
516
517
518
519
520
521
		auto top_score = std::numeric_limits<int>::min();
		auto top_gpu   = vk::PhysicalDevice{};

		for(auto& gpu : _instance->enumeratePhysicalDevices()) {
			if(!can_present_to.empty() && !supports_present(gpu, can_present_to)) {
				continue;
			}
522

523
524
525
			auto graphics_queue = find_graphics_queue(gpu, can_present_to);

			auto score = selector(gpu, graphics_queue);
Florian Oetke's avatar
Florian Oetke committed
526
527
528
529
530
531
532
533

			auto gpu_name = std::string(gpu.getProperties().deviceName);
			MIRRAGE_INFO("Detected GPU: " << gpu_name);

			if(!_settings->gpu_preference.empty() && _settings->gpu_preference == gpu_name) {
				score = std::numeric_limits<int>::max();
			}

534
			if(score > top_score) {
535
				top_score = score;
536
				top_gpu   = gpu;
537
538
539
540
			}
		}

		if(!top_gpu) {
541
			MIRRAGE_FAIL("Couldn't find a GPU that supports vulkan and all required features.");
542
543
		}

Florian Oetke's avatar
Florian Oetke committed
544
545
		MIRRAGE_INFO("Selected GPU: " << top_gpu.getProperties().deviceName);

546
547
548
549
		auto cfg = vk::DeviceCreateInfo{};
		cfg.setEnabledLayerCount(gsl::narrow<uint32_t>(_enabled_layers.size()));
		cfg.setPpEnabledLayerNames(_enabled_layers.data());

550
		auto extensions           = std::vector<const char*>();
551
		auto supported_extensions = top_gpu.enumerateDeviceExtensionProperties();
552
		auto extension_supported  = [&](const char* e) {
553
            return supported_extensions.end()
Florian Oetke's avatar
Florian Oetke committed
554
555
556
                   != std::find_if(supported_extensions.begin(),
                                   supported_extensions.end(),
                                   [&](auto& se) { return !strcmp(se.extensionName, e); });
557
		};
558

559
		auto dedicated_alloc_supported = false;
560

561
562
563
564
565
566
#ifdef VK_NV_dedicated_allocation
		if(extension_supported(VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME)) {
			extensions.emplace_back(VK_NV_DEDICATED_ALLOCATION_EXTENSION_NAME);
			dedicated_alloc_supported = true;
		}
#endif
567

568
569
570
		if(!can_present_to.empty()) {
			extensions.emplace_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
		}
571

572
573
		cfg.setEnabledExtensionCount(extensions.size());
		cfg.setPpEnabledExtensionNames(extensions.data());
574

575
576
577
		auto create_info = factory(top_gpu, find_graphics_queue(top_gpu, can_present_to));

		cfg.setPEnabledFeatures(&create_info.features);
578

579
		// familyId => (count, priorities)
580
581
582
		auto queue_families =
		        std::unordered_map<std::uint32_t, std::tuple<std::uint32_t, std::vector<float>>>();

583
		auto available_families = top_gpu.getQueueFamilyProperties();
584

585
586
587
		auto queue_mapping = Queue_family_mapping();

		auto transfer_queue_tag = "_transfer"_strid;
588
589
		create_info.queue_families.emplace(transfer_queue_tag,
		                                   Queue_create_info{find_transfer_queue(top_gpu), 0.2f});
590

591
592
		auto draw_queue_tag = util::maybe<util::Str_id>(util::nothing);

593
		for(auto& qf : create_info.queue_families) {
594
595
			auto tag      = qf.first;
			auto family   = qf.second.family_id;
596
			auto priority = qf.second.priority;
597

598
			auto& entry = queue_families[family];
599

600
601
602
603
604
605
			if(available_families[family].queueFlags & vk::QueueFlagBits::eGraphics) {
				draw_queue_tag = qf.first;
			} else if(draw_queue_tag.is_nothing()
			          && (available_families[family].queueFlags & vk::QueueFlagBits::eCompute))
				draw_queue_tag = qf.first;

606
607
608
609
610
			if(available_families[family].queueCount > 0) {
				available_families[family].queueCount--;
				std::get<0>(entry) += 1;
				std::get<1>(entry).emplace_back(priority);
			} else {
611
612
				MIRRAGE_WARN("More queues requested than are availbalbe from family "
				             << family << ". Collapsed with previous queue!");
613
614
			}

615
			queue_mapping.emplace(tag, std::make_tuple(family, std::get<1>(entry).size() - 1));
616
617
618
619
620
		}

		auto used_queues = std::vector<vk::DeviceQueueCreateInfo>{};
		used_queues.reserve(queue_families.size());
		for(auto& qf : queue_families) {
Florian Oetke's avatar
Florian Oetke committed
621
622
			MIRRAGE_INVARIANT(std::get<1>(qf.second).size() == std::get<0>(qf.second),
			                  "Size mismatch");
623

624
625
626
627
628
			used_queues.emplace_back(vk::DeviceQueueCreateFlags(),
			                         qf.first,
			                         std::get<0>(qf.second),
			                         std::get<1>(qf.second).data());
		}
629

630
631
		cfg.setQueueCreateInfoCount(gsl::narrow<std::uint32_t>(used_queues.size()));
		cfg.setPQueueCreateInfos(used_queues.data());
632

633
634
		auto swapchains = create_swapchain_create_info(top_gpu, srgb, can_present_to);

635
636
637
638
639
640
641
642
643
644
		return std::make_unique<Device>(
		        *this,
		        _assets,
		        top_gpu.createDeviceUnique(cfg),
		        top_gpu,
		        transfer_queue_tag,
		        draw_queue_tag.get_or_throw("No draw or compute queue! That doesn't seem right."),
		        std::move(queue_mapping),
		        std::move(swapchains),
		        dedicated_alloc_supported);
645
	}
646
} // namespace mirrage::graphic