VulkanInitialization.cs 30 KB

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