VulkanInitialization.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. using Ryujinx.Common.Configuration;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Silk.NET.Vulkan;
  5. using Silk.NET.Vulkan.Extensions.EXT;
  6. using Silk.NET.Vulkan.Extensions.KHR;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Runtime.InteropServices;
  11. namespace Ryujinx.Graphics.Vulkan
  12. {
  13. public unsafe static class VulkanInitialization
  14. {
  15. private const uint InvalidIndex = uint.MaxValue;
  16. private const string AppName = "Ryujinx.Graphics.Vulkan";
  17. private const int QueuesCount = 2;
  18. public static string[] DesirableExtensions { get; } = new string[]
  19. {
  20. ExtConditionalRendering.ExtensionName,
  21. ExtExtendedDynamicState.ExtensionName,
  22. ExtTransformFeedback.ExtensionName,
  23. KhrDrawIndirectCount.ExtensionName,
  24. KhrPushDescriptor.ExtensionName,
  25. "VK_EXT_custom_border_color",
  26. "VK_EXT_descriptor_indexing", // Enabling this works around an issue with disposed buffer bindings on RADV.
  27. "VK_EXT_fragment_shader_interlock",
  28. "VK_EXT_index_type_uint8",
  29. "VK_EXT_robustness2",
  30. "VK_EXT_shader_stencil_export",
  31. "VK_KHR_shader_float16_int8",
  32. "VK_EXT_shader_subgroup_ballot",
  33. "VK_EXT_subgroup_size_control",
  34. "VK_NV_geometry_shader_passthrough"
  35. };
  36. public static string[] RequiredExtensions { get; } = new string[]
  37. {
  38. KhrSwapchain.ExtensionName
  39. };
  40. private static string[] _excludedMessages = new string[]
  41. {
  42. // NOTE: Done on purpose right now.
  43. "UNASSIGNED-CoreValidation-Shader-OutputNotConsumed",
  44. // TODO: Figure out if fixable
  45. "VUID-vkCmdDrawIndexed-None-04584",
  46. // TODO: Might be worth looking into making this happy to possibly optimize copies.
  47. "UNASSIGNED-CoreValidation-DrawState-InvalidImageLayout",
  48. // TODO: Fix this, it's causing too much noise right now.
  49. "VUID-VkSubpassDependency-srcSubpass-00867"
  50. };
  51. internal static Instance CreateInstance(Vk api, GraphicsDebugLevel logLevel, string[] requiredExtensions, out ExtDebugUtils debugUtils, out DebugUtilsMessengerEXT debugUtilsMessenger)
  52. {
  53. var enabledLayers = new List<string>();
  54. void AddAvailableLayer(string layerName)
  55. {
  56. uint layerPropertiesCount;
  57. api.EnumerateInstanceLayerProperties(&layerPropertiesCount, null).ThrowOnError();
  58. LayerProperties[] layerProperties = new LayerProperties[layerPropertiesCount];
  59. fixed (LayerProperties* pLayerProperties = layerProperties)
  60. {
  61. api.EnumerateInstanceLayerProperties(&layerPropertiesCount, layerProperties).ThrowOnError();
  62. for (int i = 0; i < layerPropertiesCount; i++)
  63. {
  64. string currentLayerName = Marshal.PtrToStringAnsi((IntPtr)pLayerProperties[i].LayerName);
  65. if (currentLayerName == layerName)
  66. {
  67. enabledLayers.Add(layerName);
  68. return;
  69. }
  70. }
  71. }
  72. Logger.Warning?.Print(LogClass.Gpu, $"Missing layer {layerName}");
  73. }
  74. if (logLevel != GraphicsDebugLevel.None)
  75. {
  76. AddAvailableLayer("VK_LAYER_KHRONOS_validation");
  77. }
  78. var enabledExtensions = requiredExtensions.Append(ExtDebugUtils.ExtensionName).ToArray();
  79. var appName = Marshal.StringToHGlobalAnsi(AppName);
  80. var applicationInfo = new ApplicationInfo
  81. {
  82. PApplicationName = (byte*)appName,
  83. ApplicationVersion = 1,
  84. PEngineName = (byte*)appName,
  85. EngineVersion = 1,
  86. ApiVersion = Vk.Version12.Value
  87. };
  88. IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
  89. IntPtr* ppEnabledLayers = stackalloc IntPtr[enabledLayers.Count];
  90. for (int i = 0; i < enabledExtensions.Length; i++)
  91. {
  92. ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
  93. }
  94. for (int i = 0; i < enabledLayers.Count; i++)
  95. {
  96. ppEnabledLayers[i] = Marshal.StringToHGlobalAnsi(enabledLayers[i]);
  97. }
  98. var instanceCreateInfo = new InstanceCreateInfo
  99. {
  100. SType = StructureType.InstanceCreateInfo,
  101. PApplicationInfo = &applicationInfo,
  102. PpEnabledExtensionNames = (byte**)ppEnabledExtensions,
  103. PpEnabledLayerNames = (byte**)ppEnabledLayers,
  104. EnabledExtensionCount = (uint)enabledExtensions.Length,
  105. EnabledLayerCount = (uint)enabledLayers.Count
  106. };
  107. api.CreateInstance(in instanceCreateInfo, null, out var instance).ThrowOnError();
  108. Marshal.FreeHGlobal(appName);
  109. for (int i = 0; i < enabledExtensions.Length; i++)
  110. {
  111. Marshal.FreeHGlobal(ppEnabledExtensions[i]);
  112. }
  113. for (int i = 0; i < enabledLayers.Count; i++)
  114. {
  115. Marshal.FreeHGlobal(ppEnabledLayers[i]);
  116. }
  117. CreateDebugMessenger(api, logLevel, instance, out debugUtils, out debugUtilsMessenger);
  118. return instance;
  119. }
  120. private unsafe static uint DebugMessenger(
  121. DebugUtilsMessageSeverityFlagsEXT messageSeverity,
  122. DebugUtilsMessageTypeFlagsEXT messageTypes,
  123. DebugUtilsMessengerCallbackDataEXT* pCallbackData,
  124. void* pUserData)
  125. {
  126. var msg = Marshal.PtrToStringAnsi((IntPtr)pCallbackData->PMessage);
  127. foreach (string excludedMessagePart in _excludedMessages)
  128. {
  129. if (msg.Contains(excludedMessagePart))
  130. {
  131. return 0;
  132. }
  133. }
  134. if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt))
  135. {
  136. Logger.Error?.Print(LogClass.Gpu, msg);
  137. }
  138. else if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.WarningBitExt))
  139. {
  140. Logger.Warning?.Print(LogClass.Gpu, msg);
  141. }
  142. else if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.InfoBitExt))
  143. {
  144. Logger.Info?.Print(LogClass.Gpu, msg);
  145. }
  146. else // if (messageSeverity.HasFlag(DebugUtilsMessageSeverityFlagsEXT.VerboseBitExt))
  147. {
  148. Logger.Debug?.Print(LogClass.Gpu, msg);
  149. }
  150. return 0;
  151. }
  152. internal static PhysicalDevice FindSuitablePhysicalDevice(Vk api, Instance instance, SurfaceKHR surface, string preferredGpuId)
  153. {
  154. uint physicalDeviceCount;
  155. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, null).ThrowOnError();
  156. PhysicalDevice[] physicalDevices = new PhysicalDevice[physicalDeviceCount];
  157. fixed (PhysicalDevice* pPhysicalDevices = physicalDevices)
  158. {
  159. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, pPhysicalDevices).ThrowOnError();
  160. }
  161. // First we try to pick the the user preferred GPU.
  162. for (int i = 0; i < physicalDevices.Length; i++)
  163. {
  164. if (IsPreferredAndSuitableDevice(api, physicalDevices[i], surface, preferredGpuId))
  165. {
  166. return physicalDevices[i];
  167. }
  168. }
  169. // If we fail to do that, just use the first compatible GPU.
  170. for (int i = 0; i < physicalDevices.Length; i++)
  171. {
  172. if (IsSuitableDevice(api, physicalDevices[i], surface))
  173. {
  174. return physicalDevices[i];
  175. }
  176. }
  177. throw new VulkanException("Initialization failed, none of the available GPUs meets the minimum requirements.");
  178. }
  179. internal static DeviceInfo[] GetSuitablePhysicalDevices(Vk api)
  180. {
  181. var appName = Marshal.StringToHGlobalAnsi(AppName);
  182. var applicationInfo = new ApplicationInfo
  183. {
  184. PApplicationName = (byte*)appName,
  185. ApplicationVersion = 1,
  186. PEngineName = (byte*)appName,
  187. EngineVersion = 1,
  188. ApiVersion = Vk.Version12.Value
  189. };
  190. var instanceCreateInfo = new InstanceCreateInfo
  191. {
  192. SType = StructureType.InstanceCreateInfo,
  193. PApplicationInfo = &applicationInfo,
  194. PpEnabledExtensionNames = null,
  195. PpEnabledLayerNames = null,
  196. EnabledExtensionCount = 0,
  197. EnabledLayerCount = 0
  198. };
  199. api.CreateInstance(in instanceCreateInfo, null, out var instance).ThrowOnError();
  200. Marshal.FreeHGlobal(appName);
  201. uint physicalDeviceCount;
  202. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, null).ThrowOnError();
  203. PhysicalDevice[] physicalDevices = new PhysicalDevice[physicalDeviceCount];
  204. fixed (PhysicalDevice* pPhysicalDevices = physicalDevices)
  205. {
  206. api.EnumeratePhysicalDevices(instance, &physicalDeviceCount, pPhysicalDevices).ThrowOnError();
  207. }
  208. DeviceInfo[] devices = new DeviceInfo[physicalDevices.Length];
  209. for (int i = 0; i < physicalDevices.Length; i++)
  210. {
  211. var physicalDevice = physicalDevices[i];
  212. api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
  213. devices[i] = new DeviceInfo(
  214. StringFromIdPair(properties.VendorID, properties.DeviceID),
  215. VendorUtils.GetNameFromId(properties.VendorID),
  216. Marshal.PtrToStringAnsi((IntPtr)properties.DeviceName),
  217. properties.DeviceType == PhysicalDeviceType.DiscreteGpu);
  218. }
  219. api.DestroyInstance(instance, null);
  220. return devices;
  221. }
  222. public static string StringFromIdPair(uint vendorId, uint deviceId)
  223. {
  224. return $"0x{vendorId:X}_0x{deviceId:X}";
  225. }
  226. private static bool IsPreferredAndSuitableDevice(Vk api, PhysicalDevice physicalDevice, SurfaceKHR surface, string preferredGpuId)
  227. {
  228. api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
  229. if (StringFromIdPair(properties.VendorID, properties.DeviceID) != preferredGpuId)
  230. {
  231. return false;
  232. }
  233. return IsSuitableDevice(api, physicalDevice, surface);
  234. }
  235. private static bool IsSuitableDevice(Vk api, PhysicalDevice physicalDevice, SurfaceKHR surface)
  236. {
  237. int extensionMatches = 0;
  238. uint propertiesCount;
  239. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, null).ThrowOnError();
  240. ExtensionProperties[] extensionProperties = new ExtensionProperties[propertiesCount];
  241. fixed (ExtensionProperties* pExtensionProperties = extensionProperties)
  242. {
  243. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, pExtensionProperties).ThrowOnError();
  244. for (int i = 0; i < propertiesCount; i++)
  245. {
  246. string extensionName = Marshal.PtrToStringAnsi((IntPtr)pExtensionProperties[i].ExtensionName);
  247. if (RequiredExtensions.Contains(extensionName))
  248. {
  249. extensionMatches++;
  250. }
  251. }
  252. }
  253. return extensionMatches == RequiredExtensions.Length && FindSuitableQueueFamily(api, physicalDevice, surface, out _) != InvalidIndex;
  254. }
  255. internal static uint FindSuitableQueueFamily(Vk api, PhysicalDevice physicalDevice, SurfaceKHR surface, out uint queueCount)
  256. {
  257. const QueueFlags RequiredFlags = QueueFlags.GraphicsBit | QueueFlags.ComputeBit;
  258. var khrSurface = new KhrSurface(api.Context);
  259. uint propertiesCount;
  260. api.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, &propertiesCount, null);
  261. QueueFamilyProperties[] properties = new QueueFamilyProperties[propertiesCount];
  262. fixed (QueueFamilyProperties* pProperties = properties)
  263. {
  264. api.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, &propertiesCount, pProperties);
  265. }
  266. for (uint index = 0; index < propertiesCount; index++)
  267. {
  268. var queueFlags = properties[index].QueueFlags;
  269. khrSurface.GetPhysicalDeviceSurfaceSupport(physicalDevice, index, surface, out var surfaceSupported).ThrowOnError();
  270. if (queueFlags.HasFlag(RequiredFlags) && surfaceSupported)
  271. {
  272. queueCount = properties[index].QueueCount;
  273. return index;
  274. }
  275. }
  276. queueCount = 0;
  277. return InvalidIndex;
  278. }
  279. public static Device CreateDevice(Vk api, PhysicalDevice physicalDevice, uint queueFamilyIndex, string[] supportedExtensions, uint queueCount)
  280. {
  281. if (queueCount > QueuesCount)
  282. {
  283. queueCount = QueuesCount;
  284. }
  285. float* queuePriorities = stackalloc float[(int)queueCount];
  286. for (int i = 0; i < queueCount; i++)
  287. {
  288. queuePriorities[i] = 1f;
  289. }
  290. var queueCreateInfo = new DeviceQueueCreateInfo()
  291. {
  292. SType = StructureType.DeviceQueueCreateInfo,
  293. QueueFamilyIndex = queueFamilyIndex,
  294. QueueCount = queueCount,
  295. PQueuePriorities = queuePriorities
  296. };
  297. api.GetPhysicalDeviceProperties(physicalDevice, out var properties);
  298. bool useRobustBufferAccess = VendorUtils.FromId(properties.VendorID) == Vendor.Nvidia;
  299. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  300. {
  301. SType = StructureType.PhysicalDeviceFeatures2
  302. };
  303. PhysicalDeviceVulkan11Features supportedFeaturesVk11 = new PhysicalDeviceVulkan11Features()
  304. {
  305. SType = StructureType.PhysicalDeviceVulkan11Features,
  306. PNext = features2.PNext
  307. };
  308. features2.PNext = &supportedFeaturesVk11;
  309. PhysicalDeviceCustomBorderColorFeaturesEXT supportedFeaturesCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  310. {
  311. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
  312. PNext = features2.PNext
  313. };
  314. if (supportedExtensions.Contains("VK_EXT_custom_border_color"))
  315. {
  316. features2.PNext = &supportedFeaturesCustomBorderColor;
  317. }
  318. PhysicalDeviceTransformFeedbackFeaturesEXT supportedFeaturesTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT()
  319. {
  320. SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt,
  321. PNext = features2.PNext
  322. };
  323. if (supportedExtensions.Contains(ExtTransformFeedback.ExtensionName))
  324. {
  325. features2.PNext = &supportedFeaturesTransformFeedback;
  326. }
  327. PhysicalDeviceRobustness2FeaturesEXT supportedFeaturesRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  328. {
  329. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt
  330. };
  331. if (supportedExtensions.Contains("VK_EXT_robustness2"))
  332. {
  333. supportedFeaturesRobustness2.PNext = features2.PNext;
  334. features2.PNext = &supportedFeaturesRobustness2;
  335. }
  336. api.GetPhysicalDeviceFeatures2(physicalDevice, &features2);
  337. var supportedFeatures = features2.Features;
  338. var features = new PhysicalDeviceFeatures()
  339. {
  340. DepthBiasClamp = true,
  341. DepthClamp = supportedFeatures.DepthClamp,
  342. DualSrcBlend = supportedFeatures.DualSrcBlend,
  343. FragmentStoresAndAtomics = true,
  344. GeometryShader = supportedFeatures.GeometryShader,
  345. ImageCubeArray = true,
  346. IndependentBlend = true,
  347. LogicOp = supportedFeatures.LogicOp,
  348. OcclusionQueryPrecise = supportedFeatures.OcclusionQueryPrecise,
  349. MultiViewport = supportedFeatures.MultiViewport,
  350. PipelineStatisticsQuery = supportedFeatures.PipelineStatisticsQuery,
  351. SamplerAnisotropy = true,
  352. ShaderClipDistance = true,
  353. ShaderFloat64 = supportedFeatures.ShaderFloat64,
  354. ShaderImageGatherExtended = supportedFeatures.ShaderImageGatherExtended,
  355. ShaderStorageImageMultisample = supportedFeatures.ShaderStorageImageMultisample,
  356. // ShaderStorageImageReadWithoutFormat = true,
  357. // ShaderStorageImageWriteWithoutFormat = true,
  358. TessellationShader = supportedFeatures.TessellationShader,
  359. VertexPipelineStoresAndAtomics = true,
  360. RobustBufferAccess = useRobustBufferAccess
  361. };
  362. void* pExtendedFeatures = null;
  363. PhysicalDeviceTransformFeedbackFeaturesEXT featuresTransformFeedback;
  364. if (supportedExtensions.Contains(ExtTransformFeedback.ExtensionName))
  365. {
  366. featuresTransformFeedback = new PhysicalDeviceTransformFeedbackFeaturesEXT()
  367. {
  368. SType = StructureType.PhysicalDeviceTransformFeedbackFeaturesExt,
  369. PNext = pExtendedFeatures,
  370. TransformFeedback = supportedFeaturesTransformFeedback.TransformFeedback
  371. };
  372. pExtendedFeatures = &featuresTransformFeedback;
  373. }
  374. PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2;
  375. if (supportedExtensions.Contains("VK_EXT_robustness2"))
  376. {
  377. featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  378. {
  379. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt,
  380. PNext = pExtendedFeatures,
  381. NullDescriptor = supportedFeaturesRobustness2.NullDescriptor
  382. };
  383. pExtendedFeatures = &featuresRobustness2;
  384. }
  385. var featuresExtendedDynamicState = new PhysicalDeviceExtendedDynamicStateFeaturesEXT()
  386. {
  387. SType = StructureType.PhysicalDeviceExtendedDynamicStateFeaturesExt,
  388. PNext = pExtendedFeatures,
  389. ExtendedDynamicState = supportedExtensions.Contains(ExtExtendedDynamicState.ExtensionName)
  390. };
  391. pExtendedFeatures = &featuresExtendedDynamicState;
  392. var featuresVk11 = new PhysicalDeviceVulkan11Features()
  393. {
  394. SType = StructureType.PhysicalDeviceVulkan11Features,
  395. PNext = pExtendedFeatures,
  396. ShaderDrawParameters = supportedFeaturesVk11.ShaderDrawParameters
  397. };
  398. pExtendedFeatures = &featuresVk11;
  399. var featuresVk12 = new PhysicalDeviceVulkan12Features()
  400. {
  401. SType = StructureType.PhysicalDeviceVulkan12Features,
  402. PNext = pExtendedFeatures,
  403. DescriptorIndexing = supportedExtensions.Contains("VK_EXT_descriptor_indexing"),
  404. DrawIndirectCount = supportedExtensions.Contains(KhrDrawIndirectCount.ExtensionName),
  405. UniformBufferStandardLayout = supportedExtensions.Contains("VK_KHR_uniform_buffer_standard_layout")
  406. };
  407. pExtendedFeatures = &featuresVk12;
  408. PhysicalDeviceIndexTypeUint8FeaturesEXT featuresIndexU8;
  409. if (supportedExtensions.Contains("VK_EXT_index_type_uint8"))
  410. {
  411. featuresIndexU8 = new PhysicalDeviceIndexTypeUint8FeaturesEXT()
  412. {
  413. SType = StructureType.PhysicalDeviceIndexTypeUint8FeaturesExt,
  414. PNext = pExtendedFeatures,
  415. IndexTypeUint8 = true
  416. };
  417. pExtendedFeatures = &featuresIndexU8;
  418. }
  419. PhysicalDeviceFragmentShaderInterlockFeaturesEXT featuresFragmentShaderInterlock;
  420. if (supportedExtensions.Contains("VK_EXT_fragment_shader_interlock"))
  421. {
  422. featuresFragmentShaderInterlock = new PhysicalDeviceFragmentShaderInterlockFeaturesEXT()
  423. {
  424. SType = StructureType.PhysicalDeviceFragmentShaderInterlockFeaturesExt,
  425. PNext = pExtendedFeatures,
  426. FragmentShaderPixelInterlock = true
  427. };
  428. pExtendedFeatures = &featuresFragmentShaderInterlock;
  429. }
  430. PhysicalDeviceSubgroupSizeControlFeaturesEXT featuresSubgroupSizeControl;
  431. if (supportedExtensions.Contains("VK_EXT_subgroup_size_control"))
  432. {
  433. featuresSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlFeaturesEXT()
  434. {
  435. SType = StructureType.PhysicalDeviceSubgroupSizeControlFeaturesExt,
  436. PNext = pExtendedFeatures,
  437. SubgroupSizeControl = true
  438. };
  439. pExtendedFeatures = &featuresSubgroupSizeControl;
  440. }
  441. PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor;
  442. if (supportedExtensions.Contains("VK_EXT_custom_border_color") &&
  443. supportedFeaturesCustomBorderColor.CustomBorderColors &&
  444. supportedFeaturesCustomBorderColor.CustomBorderColorWithoutFormat)
  445. {
  446. featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  447. {
  448. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt,
  449. PNext = pExtendedFeatures,
  450. CustomBorderColors = true,
  451. CustomBorderColorWithoutFormat = true,
  452. };
  453. pExtendedFeatures = &featuresCustomBorderColor;
  454. }
  455. var enabledExtensions = RequiredExtensions.Union(DesirableExtensions.Intersect(supportedExtensions)).ToArray();
  456. IntPtr* ppEnabledExtensions = stackalloc IntPtr[enabledExtensions.Length];
  457. for (int i = 0; i < enabledExtensions.Length; i++)
  458. {
  459. ppEnabledExtensions[i] = Marshal.StringToHGlobalAnsi(enabledExtensions[i]);
  460. }
  461. var deviceCreateInfo = new DeviceCreateInfo()
  462. {
  463. SType = StructureType.DeviceCreateInfo,
  464. PNext = pExtendedFeatures,
  465. QueueCreateInfoCount = 1,
  466. PQueueCreateInfos = &queueCreateInfo,
  467. PpEnabledExtensionNames = (byte**)ppEnabledExtensions,
  468. EnabledExtensionCount = (uint)enabledExtensions.Length,
  469. PEnabledFeatures = &features
  470. };
  471. api.CreateDevice(physicalDevice, in deviceCreateInfo, null, out var device).ThrowOnError();
  472. for (int i = 0; i < enabledExtensions.Length; i++)
  473. {
  474. Marshal.FreeHGlobal(ppEnabledExtensions[i]);
  475. }
  476. return device;
  477. }
  478. public static string[] GetSupportedExtensions(Vk api, PhysicalDevice physicalDevice)
  479. {
  480. uint propertiesCount;
  481. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, null).ThrowOnError();
  482. ExtensionProperties[] extensionProperties = new ExtensionProperties[propertiesCount];
  483. fixed (ExtensionProperties* pExtensionProperties = extensionProperties)
  484. {
  485. api.EnumerateDeviceExtensionProperties(physicalDevice, (byte*)null, &propertiesCount, pExtensionProperties).ThrowOnError();
  486. }
  487. return extensionProperties.Select(x => Marshal.PtrToStringAnsi((IntPtr)x.ExtensionName)).ToArray();
  488. }
  489. internal static CommandBufferPool CreateCommandBufferPool(Vk api, Device device, Queue queue, object queueLock, uint queueFamilyIndex)
  490. {
  491. return new CommandBufferPool(api, device, queue, queueLock, queueFamilyIndex);
  492. }
  493. internal unsafe static void CreateDebugMessenger(
  494. Vk api,
  495. GraphicsDebugLevel logLevel,
  496. Instance instance,
  497. out ExtDebugUtils debugUtils,
  498. out DebugUtilsMessengerEXT debugUtilsMessenger)
  499. {
  500. debugUtils = default;
  501. if (logLevel != GraphicsDebugLevel.None)
  502. {
  503. if (!api.TryGetInstanceExtension(instance, out debugUtils))
  504. {
  505. debugUtilsMessenger = default;
  506. return;
  507. }
  508. var filterLogType = logLevel switch
  509. {
  510. GraphicsDebugLevel.Error => DebugUtilsMessageTypeFlagsEXT.ValidationBitExt,
  511. GraphicsDebugLevel.Slowdowns => DebugUtilsMessageTypeFlagsEXT.ValidationBitExt |
  512. DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
  513. GraphicsDebugLevel.All => DebugUtilsMessageTypeFlagsEXT.GeneralBitExt |
  514. DebugUtilsMessageTypeFlagsEXT.ValidationBitExt |
  515. DebugUtilsMessageTypeFlagsEXT.PerformanceBitExt,
  516. _ => throw new ArgumentException($"Invalid log level \"{logLevel}\".")
  517. };
  518. var filterLogSeverity = logLevel switch
  519. {
  520. GraphicsDebugLevel.Error => DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
  521. GraphicsDebugLevel.Slowdowns => DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt |
  522. DebugUtilsMessageSeverityFlagsEXT.WarningBitExt,
  523. GraphicsDebugLevel.All => DebugUtilsMessageSeverityFlagsEXT.InfoBitExt |
  524. DebugUtilsMessageSeverityFlagsEXT.WarningBitExt |
  525. DebugUtilsMessageSeverityFlagsEXT.VerboseBitExt |
  526. DebugUtilsMessageSeverityFlagsEXT.ErrorBitExt,
  527. _ => throw new ArgumentException($"Invalid log level \"{logLevel}\".")
  528. };
  529. var debugUtilsMessengerCreateInfo = new DebugUtilsMessengerCreateInfoEXT()
  530. {
  531. SType = StructureType.DebugUtilsMessengerCreateInfoExt,
  532. MessageType = filterLogType,
  533. MessageSeverity = filterLogSeverity,
  534. PfnUserCallback = new PfnDebugUtilsMessengerCallbackEXT(DebugMessenger)
  535. };
  536. debugUtils.CreateDebugUtilsMessenger(instance, in debugUtilsMessengerCreateInfo, null, out debugUtilsMessenger).ThrowOnError();
  537. }
  538. else
  539. {
  540. debugUtilsMessenger = default;
  541. }
  542. }
  543. }
  544. }