VulkanInitialization.cs 29 KB

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