context.cpp 19.7 KB
Newer Older
1
2
#include <SDL_vulkan.h> // has to be includes before vulkan
#include <sf2/sf2.hpp>  // has to be first so he sf2_struct define is set
3
4
5
6
7
8
9
10
11
12
13
14

#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 <SDL2/SDL.h>
#include <gsl/gsl>

15
#include <cstdio>
16
17
18
19
20
#include <iostream>
#include <sstream>


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

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

45
namespace mirrage::graphic {
46
47
48
49
50

	using namespace util::unit_literals;

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

		void add_present_extensions(std::vector<const char*>& extensions) {
60
			auto present_extensions      = std::vector<const char*>(4);
61
62
			auto present_extensions_size = static_cast<unsigned int>(present_extensions.size());
			if(!SDL_GetVulkanInstanceExtensions(&present_extensions_size, present_extensions.data())) {
63
				FAIL("Unable to determine present extensions: " << SDL_GetError());
64
65
			}

66
67
68
69
			if(present_extensions_size > 0) {
				extensions.insert(extensions.end(),
				                  present_extensions.begin(),
				                  present_extensions.begin() + present_extensions_size);
70
71
72
73
74
75
76
77
78
79
80
81
82
			}
		}

		auto check_extensions(const std::vector<const char*>& required,
		                      const std::vector<const char*>& optional) -> std::vector<const char*> {
			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) {
83
				for(auto i = 0u; i < required.size(); i++) {
84
85
86
87
88
89
90
					if(!strcmp(e.extensionName, required[i])) {
						support_confirmed[i] = true;
						extensions.push_back(required[i]);
						break;
					}
				}

91
				for(auto i = 0u; i < optional.size(); i++) {
92
93
94
95
96
97
98
99
					if(!strcmp(e.extensionName, optional[i])) {
						extensions.push_back(optional[i]);
						break;
					}
				}
			}

			bool all_supported = true;
100
			for(auto i = 0u; i < support_confirmed.size(); i++) {
101
				if(!support_confirmed[i]) {
102
					WARN("Unsupported extension \"" << required[i] << "\"!");
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
					all_supported = false;
				}
			}

			if(!all_supported) {
				FAIL("At least one required extension is not supported (see log for details)!");
			}

			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) {
122
					if(0 == strcmp(l.layerName, req_layer)) {
123
124
125
126
127
128
129
						validation_layers.push_back(req_layer);
						layer_requested = true;
						break;
					}
				}

				if(!layer_requested) {
130
131
					DEBUG("Additional validation layer is available, that hasn't been requested: "
					      << l.layerName);
132
133
134
135
				}
			}

			if(validation_layers.size() != requested.size()) {
136
				auto log = util::error(__func__, __FILE__, __LINE__);
137
138
				log << "Some requested validation layers are not supported: \n";
				for(auto& l : validation_layers) {
139
					log << "  - " << l << "\n";
140
141
142
143
144
145
146
				}
				log << std::endl;
			}

			return validation_layers;
		}

147
148
149
150
151
152
153
154
		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) {
155
156
157
158

			// 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)
159
			if(objType == VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT)
160
161
162
163
				return VK_FALSE;


			if(flags & VK_DEBUG_REPORT_ERROR_BIT_EXT) {
164
165
166
167
				ERROR("[VK | " << layerPrefix << "] " << msg);
			} else if(flags & VK_DEBUG_REPORT_WARNING_BIT_EXT
			          || flags & VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT) {
				WARN("[VK | " << layerPrefix << "] " << msg);
168
			} else {
169
				INFO("[VK | " << layerPrefix << "] " << msg);
170
171
172
173
174
175
176
			}

			return VK_FALSE;
		}
	}


177
178
179
180
181
182
183
	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) {
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200

		auto maybe_settings = assets.load_maybe<Graphics_settings>("cfg:graphics"_aid);
		if(maybe_settings.is_nothing()) {
			if(!settings(default_settings())) {
				FAIL("Invalid graphics settings");
			}
		} else {
			_settings = maybe_settings.get_or_throw();
		}

		if(!settings(*_settings)) { //< apply actual size/settings
			FAIL("Couldn't apply graphics settings");
		}

		sdl_error_check();

		auto instanceCreateInfo = vk::InstanceCreateInfo{};
201
202
		auto appInfo            = vk::ApplicationInfo{
		        appName.c_str(), appVersion, engineName.c_str(), engineVersion, VK_API_VERSION_1_0};
203

204
		auto required_extensions = std::vector<const char*>{VK_KHR_SURFACE_EXTENSION_NAME};
205
		add_present_extensions(required_extensions);
206
		auto optional_extensions = std::vector<const char*>{};
207
208
209


		if(debug) {
210
			_enabled_layers = check_layers({"VK_LAYER_LUNARG_standard_validation"});
211
212
213
214
215
216

			required_extensions.push_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
		}

		auto extensions = check_extensions(required_extensions, optional_extensions);

217
		auto log = util::info(__func__, __FILE__, __LINE__);
218
219
220
		log << "Initializing vulkan...\n";
		log << "Enabled extensions:\n";
		for(auto e : extensions) {
221
			log << "  - " << e << "\n";
222
223
224
		}
		log << "Enabled validation layers:\n";
		for(auto l : _enabled_layers) {
225
			log << "  - " << l << "\n";
226
227
228
229
230
231
232
233
234
235
236
		}
		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) {
237
238
239
240
241
			_debug_callback = _instance->createDebugReportCallbackEXTUnique(
			        {/*	vk::DebugReportFlagBitsEXT::eDebug | vk::DebugReportFlagBitsEXT::eInformation | */
			         vk::DebugReportFlagBitsEXT::eError | vk::DebugReportFlagBitsEXT::ePerformanceWarning
			                 | vk::DebugReportFlagBitsEXT::eWarning,
			         debugCallback});
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
		}
	}
	Context::~Context() = default;

	bool Context::settings(Graphics_settings new_settings) {
		// TODO: update windows
		/*
		for(auto device : children()) {
			if(!device->settings_changed(new_settings)) {
				WARN("New graphics settings are not supported");
				return false;
			}
		}*/

		_assets.save<Graphics_settings>("cfg:graphics"_aid, new_settings);
		_settings = _assets.load<Graphics_settings>("cfg:graphics"_aid);

		return true;
	}

	auto Context::create_window(std::string name, int width, int height) -> Window_ptr {
263
264
265
266
267
268
269
270
271
		auto settings = _find_window_settings(name, width, height);

		return std::make_unique<Window>(*this,
		                                name,
		                                app_name() + " | " + name,
		                                settings.display,
		                                settings.width,
		                                settings.height,
		                                settings.fullscreen);
272
	}
273
	auto Context::_find_window_settings(const std::string& name, int width, int height) -> Window_settings {
274
275
		auto& cfg = settings();

276
277
		auto win_cfg = std::find_if(
		        std::begin(cfg.windows), std::end(cfg.windows), [&](auto& w) { return w.first == name; });
278

279
		if(win_cfg == std::end(cfg.windows)) { // no config create new
280
281
			auto new_settings = cfg;
			auto win_settings = default_window_settings(0);
282
283
284
285
			if(width > 0)
				win_settings.width = width;
			if(height > 0)
				win_settings.height    = height;
286
287
288
289
290
291
292
293
294
295
296
297
298
299
			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();
			auto sc_ext = std::find_if(supported_extensions.begin(), supported_extensions.end(), [](auto& e) {
300
				return std::strcmp(e.extensionName, VK_KHR_SWAPCHAIN_EXTENSION_NAME) == 0;
301
302
			});

303
			if(sc_ext == supported_extensions.end()) {
304
305
306
307
308
309
310
311
312
313
314
315
316
				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;
		}
317
318
319
320

		auto find_graphics_queue(vk::PhysicalDevice& gpu, const std::vector<Window*>& can_present_to)
		        -> util::maybe<std::uint32_t> {
			auto i = 0;
321
322

			for(auto& queue_family : gpu.getQueueFamilyProperties()) {
323
324
325
326
327
328
329
330
331
				auto can_present =
				        can_present_to.empty()
				        || std::all_of(can_present_to.begin(), can_present_to.end(), [&](auto window) {
					           return gpu.getSurfaceSupportKHR(i, window->surface());
					       });

				if(queue_family.queueCount > 0 && can_present
				   && queue_family.timestampValidBits
				              >= 32 // only accept queues with >=32bit timer support, for now
332
333
334
335
336
337
338
339
340
341
342
343
				   && (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();
344

345
			auto i = 0;
346

347
348
			// check for transfer-only queue
			for(auto& queue_family : families) {
349
350
				if(queue_family.queueCount > 0 && (queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
				   && !(queue_family.queueFlags & vk::QueueFlagBits::eGraphics)) {
351
352
353
354
355
					return i;
				}

				i++;
			}
356
357

			i = 0;
358
			for(auto& queue_family : families) {
359
				if(queue_family.queueCount > 0
360
				   && ((queue_family.queueFlags & vk::QueueFlagBits::eTransfer)
361
362
				       || (queue_family.queueFlags & vk::QueueFlagBits::eGraphics)
				       || (queue_family.queueFlags & vk::QueueFlagBits::eCompute))) {
363
364
365
366
367
					return i;
				}

				i++;
			}
368

369
370
371
			FAIL("No queue found, that supports transfer operations!");
		}

372
373
374
375
		auto find_surface_format(vk::PhysicalDevice& gpu,
		                         Window&             window,
		                         vk::Format          target_format,
		                         vk::ColorSpaceKHR   target_space) -> vk::SurfaceFormatKHR {
376
377

			auto formats = gpu.getSurfaceFormatsKHR(window.surface());
378
			if(formats.size() == 1 && formats.front().format == vk::Format::eUndefined) {
379
380
381
382
				return {target_format, target_space};
			}

			auto opt_found = std::find_if(formats.begin(), formats.end(), [&](auto& f) {
383
				return f.format == target_format && f.colorSpace == target_space;
384
			});
385
			if(opt_found != formats.end()) {
386
387
388
				return {target_format, target_space};
			}

389
390
391
			opt_found = std::find_if(
			        formats.begin(), formats.end(), [&](auto& f) { return f.format == target_format; });
			if(opt_found != formats.end()) {
392
393
394
395
				return *opt_found;
			}

			if(!formats.empty()) {
396
397
				WARN("Requested format is not supported by the device, fallback to first reported "
				     "format");
398
399
400
401
402
403
				return formats.front();
			} else {
				FAIL("The device doesn't support any surface formats!");
			}
		}

404
405
		auto create_swapchain_create_info(vk::PhysicalDevice          gpu,
		                                  bool                        srgb,
406
407
		                                  const std::vector<Window*>& can_present_to) {
			auto swapchains = Swapchain_create_infos();
408

409
410
			for(auto window : can_present_to) {
				auto capabilities = gpu.getSurfaceCapabilitiesKHR(window->surface());
411
412


413
414
415
416
417
418
419
420
				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);
				sc_info.setMinImageCount(std::max(2u, capabilities.minImageCount));
421
				if(capabilities.maxImageCount > 0 && capabilities.maxImageCount < sc_info.minImageCount) {
422
423
					sc_info.setMinImageCount(capabilities.maxImageCount);
				}
424

425
				auto present_modes = gpu.getSurfacePresentModesKHR(window->surface());
426
427
428
				auto mailbox_supported =
				        std::find(present_modes.begin(), present_modes.end(), vk::PresentModeKHR::eMailbox)
				        != present_modes.end();
429
430
431
432
433
				if(mailbox_supported) {
					sc_info.setPresentMode(vk::PresentModeKHR::eMailbox);
				} else {
					sc_info.setPresentMode(vk::PresentModeKHR::eFifo);
				}
434

435
				if(capabilities.currentExtent.width == std::numeric_limits<uint32_t>::max()) {
436
437
438
439
440
441
442
443
444
					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);
445
				}
446

447
				sc_info.setImageExtent(capabilities.currentExtent);
448
449
450
451
452
453
454

				auto format =
				        find_surface_format(gpu,
				                            *window,
				                            srgb ? vk::Format::eB8G8R8A8Srgb : vk::Format::eB8G8R8A8Unorm,
				                            vk::ColorSpaceKHR::eSrgbNonlinear);

455
456
				sc_info.setImageFormat(format.format);
				sc_info.setImageColorSpace(format.colorSpace);
457

458
459
				swapchains.emplace(window->name(), std::make_tuple(window, sc_info));
			}
460

461
462
463
			return swapchains;
		}
	}
464
465
466
467
	auto Context::instantiate_device(Device_selector             selector,
	                                 Device_factory              factory,
	                                 const std::vector<Window*>& can_present_to,
	                                 bool                        srgb) -> Device_ptr {
468
469
470
471
472
473
474
		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;
			}
475

476
477
478
			auto graphics_queue = find_graphics_queue(gpu, can_present_to);

			auto score = selector(gpu, graphics_queue);
479
			if(score > top_score) {
480
				top_score = score;
481
				top_gpu   = gpu;
482
483
484
485
486
487
488
489
490
491
492
			}
		}

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

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

493
		auto extensions           = std::vector<const char*>();
494
		auto supported_extensions = top_gpu.enumerateDeviceExtensionProperties();
495
496
497
498
499
		auto extension_supported  = [&](const char* e) {
			return supported_extensions.end()
			       != std::find_if(supported_extensions.begin(), supported_extensions.end(), [&](auto& se) {
				          return !strcmp(se.extensionName, e);
				      });
500
		};
501

502
		auto dedicated_alloc_supported = false;
503

504
505
506
507
508
509
#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
510

511
512
513
		if(!can_present_to.empty()) {
			extensions.emplace_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
		}
514

515
516
		cfg.setEnabledExtensionCount(extensions.size());
		cfg.setPpEnabledExtensionNames(extensions.data());
517

518
519
520
		auto create_info = factory(top_gpu, find_graphics_queue(top_gpu, can_present_to));

		cfg.setPEnabledFeatures(&create_info.features);
521

522
		// familyId => (count, priorities)
523
524
525
		auto queue_families =
		        std::unordered_map<std::uint32_t, std::tuple<std::uint32_t, std::vector<float>>>();

526
		auto available_families = top_gpu.getQueueFamilyProperties();
527

528
529
530
		auto queue_mapping = Queue_family_mapping();

		auto transfer_queue_tag = "_transfer"_strid;
531
532
		create_info.queue_families.emplace(transfer_queue_tag,
		                                   Queue_create_info{find_transfer_queue(top_gpu), 0.2f});
533
534

		for(auto& qf : create_info.queue_families) {
535
536
			auto tag      = qf.first;
			auto family   = qf.second.family_id;
537
			auto priority = qf.second.priority;
538

539
			auto& entry = queue_families[family];
540

541
542
543
544
545
			if(available_families[family].queueCount > 0) {
				available_families[family].queueCount--;
				std::get<0>(entry) += 1;
				std::get<1>(entry).emplace_back(priority);
			} else {
546
547
548
				WARN("More queues requested than are availbalbe from family "
				     << family
				     << ". Collapsed with previous queue!");
549
550
			}

551
			queue_mapping.emplace(tag, std::make_tuple(family, std::get<1>(entry).size() - 1));
552
553
554
555
556
		}

		auto used_queues = std::vector<vk::DeviceQueueCreateInfo>{};
		used_queues.reserve(queue_families.size());
		for(auto& qf : queue_families) {
557
558
			INVARIANT(std::get<1>(qf.second).size() == std::get<0>(qf.second), "Size mismatch");

559
560
561
562
563
			used_queues.emplace_back(vk::DeviceQueueCreateFlags(),
			                         qf.first,
			                         std::get<0>(qf.second),
			                         std::get<1>(qf.second).data());
		}
564

565
566
		cfg.setQueueCreateInfoCount(gsl::narrow<std::uint32_t>(used_queues.size()));
		cfg.setPQueueCreateInfos(used_queues.data());
567

568
569
		auto swapchains = create_swapchain_create_info(top_gpu, srgb, can_present_to);

570
571
572
573
574
575
576
577
578
		return std::make_unique<Device>(*this,
		                                _assets,
		                                top_gpu.createDeviceUnique(cfg),
		                                top_gpu,
		                                transfer_queue_tag,
		                                std::move(queue_mapping),
		                                std::move(swapchains),
		                                dedicated_alloc_supported);
	}
579
}