VulkanRenderer.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. using Ryujinx.Common.Configuration;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.Shader;
  5. using Ryujinx.Graphics.Shader.Translation;
  6. using Ryujinx.Graphics.Vulkan.MoltenVK;
  7. using Ryujinx.Graphics.Vulkan.Queries;
  8. using Silk.NET.Vulkan;
  9. using Silk.NET.Vulkan.Extensions.EXT;
  10. using Silk.NET.Vulkan.Extensions.KHR;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Runtime.InteropServices;
  15. namespace Ryujinx.Graphics.Vulkan
  16. {
  17. public sealed class VulkanRenderer : IRenderer
  18. {
  19. private VulkanInstance _instance;
  20. private SurfaceKHR _surface;
  21. private VulkanPhysicalDevice _physicalDevice;
  22. private Device _device;
  23. private WindowBase _window;
  24. private bool _initialized;
  25. internal FormatCapabilities FormatCapabilities { get; private set; }
  26. internal HardwareCapabilities Capabilities;
  27. internal Vk Api { get; private set; }
  28. internal KhrSurface SurfaceApi { get; private set; }
  29. internal KhrSwapchain SwapchainApi { get; private set; }
  30. internal ExtConditionalRendering ConditionalRenderingApi { get; private set; }
  31. internal ExtExtendedDynamicState ExtendedDynamicStateApi { get; private set; }
  32. internal KhrPushDescriptor PushDescriptorApi { get; private set; }
  33. internal ExtTransformFeedback TransformFeedbackApi { get; private set; }
  34. internal KhrDrawIndirectCount DrawIndirectCountApi { get; private set; }
  35. internal uint QueueFamilyIndex { get; private set; }
  36. internal Queue Queue { get; private set; }
  37. internal Queue BackgroundQueue { get; private set; }
  38. internal object BackgroundQueueLock { get; private set; }
  39. internal object QueueLock { get; private set; }
  40. internal MemoryAllocator MemoryAllocator { get; private set; }
  41. internal CommandBufferPool CommandBufferPool { get; private set; }
  42. internal DescriptorSetManager DescriptorSetManager { get; private set; }
  43. internal PipelineLayoutCache PipelineLayoutCache { get; private set; }
  44. internal BackgroundResources BackgroundResources { get; private set; }
  45. internal Action<Action> InterruptAction { get; private set; }
  46. internal SyncManager SyncManager { get; private set; }
  47. internal BufferManager BufferManager { get; private set; }
  48. internal HashSet<ShaderCollection> Shaders { get; }
  49. internal HashSet<ITexture> Textures { get; }
  50. internal HashSet<SamplerHolder> Samplers { get; }
  51. private VulkanDebugMessenger _debugMessenger;
  52. private Counters _counters;
  53. private PipelineFull _pipeline;
  54. internal HelperShader HelperShader { get; private set; }
  55. internal PipelineFull PipelineInternal => _pipeline;
  56. public IPipeline Pipeline => _pipeline;
  57. public IWindow Window => _window;
  58. private readonly Func<Instance, Vk, SurfaceKHR> _getSurface;
  59. private readonly Func<string[]> _getRequiredExtensions;
  60. private readonly string _preferredGpuId;
  61. internal Vendor Vendor { get; private set; }
  62. internal bool IsAmdWindows { get; private set; }
  63. internal bool IsIntelWindows { get; private set; }
  64. internal bool IsAmdGcn { get; private set; }
  65. internal bool IsMoltenVk { get; private set; }
  66. internal bool IsTBDR { get; private set; }
  67. internal bool IsSharedMemory { get; private set; }
  68. public string GpuVendor { get; private set; }
  69. public string GpuRenderer { get; private set; }
  70. public string GpuVersion { get; private set; }
  71. public bool PreferThreading => true;
  72. public event EventHandler<ScreenCaptureImageInfo> ScreenCaptured;
  73. public VulkanRenderer(Func<Instance, Vk, SurfaceKHR> surfaceFunc, Func<string[]> requiredExtensionsFunc, string preferredGpuId)
  74. {
  75. _getSurface = surfaceFunc;
  76. _getRequiredExtensions = requiredExtensionsFunc;
  77. _preferredGpuId = preferredGpuId;
  78. Shaders = new HashSet<ShaderCollection>();
  79. Textures = new HashSet<ITexture>();
  80. Samplers = new HashSet<SamplerHolder>();
  81. if (OperatingSystem.IsMacOS())
  82. {
  83. MVKInitialization.Initialize();
  84. // Any device running on MacOS is using MoltenVK, even Intel and AMD vendors.
  85. IsMoltenVk = true;
  86. }
  87. }
  88. private unsafe void LoadFeatures(uint maxQueueCount, uint queueFamilyIndex)
  89. {
  90. FormatCapabilities = new FormatCapabilities(Api, _physicalDevice.PhysicalDevice);
  91. if (Api.TryGetDeviceExtension(_instance.Instance, _device, out ExtConditionalRendering conditionalRenderingApi))
  92. {
  93. ConditionalRenderingApi = conditionalRenderingApi;
  94. }
  95. if (Api.TryGetDeviceExtension(_instance.Instance, _device, out ExtExtendedDynamicState extendedDynamicStateApi))
  96. {
  97. ExtendedDynamicStateApi = extendedDynamicStateApi;
  98. }
  99. if (Api.TryGetDeviceExtension(_instance.Instance, _device, out KhrPushDescriptor pushDescriptorApi))
  100. {
  101. PushDescriptorApi = pushDescriptorApi;
  102. }
  103. if (Api.TryGetDeviceExtension(_instance.Instance, _device, out ExtTransformFeedback transformFeedbackApi))
  104. {
  105. TransformFeedbackApi = transformFeedbackApi;
  106. }
  107. if (Api.TryGetDeviceExtension(_instance.Instance, _device, out KhrDrawIndirectCount drawIndirectCountApi))
  108. {
  109. DrawIndirectCountApi = drawIndirectCountApi;
  110. }
  111. if (maxQueueCount >= 2)
  112. {
  113. Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out var backgroundQueue);
  114. BackgroundQueue = backgroundQueue;
  115. BackgroundQueueLock = new object();
  116. }
  117. PhysicalDeviceProperties2 properties2 = new PhysicalDeviceProperties2()
  118. {
  119. SType = StructureType.PhysicalDeviceProperties2
  120. };
  121. PhysicalDeviceBlendOperationAdvancedPropertiesEXT propertiesBlendOperationAdvanced = new PhysicalDeviceBlendOperationAdvancedPropertiesEXT()
  122. {
  123. SType = StructureType.PhysicalDeviceBlendOperationAdvancedPropertiesExt
  124. };
  125. bool supportsBlendOperationAdvanced = _physicalDevice.IsDeviceExtensionPresent("VK_EXT_blend_operation_advanced");
  126. if (supportsBlendOperationAdvanced)
  127. {
  128. propertiesBlendOperationAdvanced.PNext = properties2.PNext;
  129. properties2.PNext = &propertiesBlendOperationAdvanced;
  130. }
  131. PhysicalDeviceSubgroupSizeControlPropertiesEXT propertiesSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlPropertiesEXT()
  132. {
  133. SType = StructureType.PhysicalDeviceSubgroupSizeControlPropertiesExt
  134. };
  135. bool supportsSubgroupSizeControl = _physicalDevice.IsDeviceExtensionPresent("VK_EXT_subgroup_size_control");
  136. if (supportsSubgroupSizeControl)
  137. {
  138. properties2.PNext = &propertiesSubgroupSizeControl;
  139. }
  140. bool supportsTransformFeedback = _physicalDevice.IsDeviceExtensionPresent(ExtTransformFeedback.ExtensionName);
  141. PhysicalDeviceTransformFeedbackPropertiesEXT propertiesTransformFeedback = new PhysicalDeviceTransformFeedbackPropertiesEXT()
  142. {
  143. SType = StructureType.PhysicalDeviceTransformFeedbackPropertiesExt
  144. };
  145. if (supportsTransformFeedback)
  146. {
  147. propertiesTransformFeedback.PNext = properties2.PNext;
  148. properties2.PNext = &propertiesTransformFeedback;
  149. }
  150. PhysicalDevicePortabilitySubsetPropertiesKHR propertiesPortabilitySubset = new PhysicalDevicePortabilitySubsetPropertiesKHR()
  151. {
  152. SType = StructureType.PhysicalDevicePortabilitySubsetPropertiesKhr
  153. };
  154. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  155. {
  156. SType = StructureType.PhysicalDeviceFeatures2
  157. };
  158. PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT featuresPrimitiveTopologyListRestart = new PhysicalDevicePrimitiveTopologyListRestartFeaturesEXT()
  159. {
  160. SType = StructureType.PhysicalDevicePrimitiveTopologyListRestartFeaturesExt
  161. };
  162. PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  163. {
  164. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt
  165. };
  166. PhysicalDeviceShaderFloat16Int8FeaturesKHR featuresShaderInt8 = new PhysicalDeviceShaderFloat16Int8FeaturesKHR()
  167. {
  168. SType = StructureType.PhysicalDeviceShaderFloat16Int8Features
  169. };
  170. PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  171. {
  172. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt
  173. };
  174. PhysicalDevicePortabilitySubsetFeaturesKHR featuresPortabilitySubset = new PhysicalDevicePortabilitySubsetFeaturesKHR()
  175. {
  176. SType = StructureType.PhysicalDevicePortabilitySubsetFeaturesKhr
  177. };
  178. if (_physicalDevice.IsDeviceExtensionPresent("VK_EXT_primitive_topology_list_restart"))
  179. {
  180. features2.PNext = &featuresPrimitiveTopologyListRestart;
  181. }
  182. if (_physicalDevice.IsDeviceExtensionPresent("VK_EXT_robustness2"))
  183. {
  184. featuresRobustness2.PNext = features2.PNext;
  185. features2.PNext = &featuresRobustness2;
  186. }
  187. if (_physicalDevice.IsDeviceExtensionPresent("VK_KHR_shader_float16_int8"))
  188. {
  189. featuresShaderInt8.PNext = features2.PNext;
  190. features2.PNext = &featuresShaderInt8;
  191. }
  192. if (_physicalDevice.IsDeviceExtensionPresent("VK_EXT_custom_border_color"))
  193. {
  194. featuresCustomBorderColor.PNext = features2.PNext;
  195. features2.PNext = &featuresCustomBorderColor;
  196. }
  197. bool usePortability = _physicalDevice.IsDeviceExtensionPresent("VK_KHR_portability_subset");
  198. if (usePortability)
  199. {
  200. propertiesPortabilitySubset.PNext = properties2.PNext;
  201. properties2.PNext = &propertiesPortabilitySubset;
  202. featuresPortabilitySubset.PNext = features2.PNext;
  203. features2.PNext = &featuresPortabilitySubset;
  204. }
  205. Api.GetPhysicalDeviceProperties2(_physicalDevice.PhysicalDevice, &properties2);
  206. Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2);
  207. var portabilityFlags = PortabilitySubsetFlags.None;
  208. uint vertexBufferAlignment = 1;
  209. if (usePortability)
  210. {
  211. vertexBufferAlignment = propertiesPortabilitySubset.MinVertexInputBindingStrideAlignment;
  212. portabilityFlags |= featuresPortabilitySubset.TriangleFans ? 0 : PortabilitySubsetFlags.NoTriangleFans;
  213. portabilityFlags |= featuresPortabilitySubset.PointPolygons ? 0 : PortabilitySubsetFlags.NoPointMode;
  214. portabilityFlags |= featuresPortabilitySubset.ImageView2DOn3DImage ? 0 : PortabilitySubsetFlags.No3DImageView;
  215. portabilityFlags |= featuresPortabilitySubset.SamplerMipLodBias ? 0 : PortabilitySubsetFlags.NoLodBias;
  216. }
  217. bool supportsCustomBorderColor = _physicalDevice.IsDeviceExtensionPresent("VK_EXT_custom_border_color") &&
  218. featuresCustomBorderColor.CustomBorderColors &&
  219. featuresCustomBorderColor.CustomBorderColorWithoutFormat;
  220. ref var properties = ref properties2.Properties;
  221. SampleCountFlags supportedSampleCounts =
  222. properties.Limits.FramebufferColorSampleCounts &
  223. properties.Limits.FramebufferDepthSampleCounts &
  224. properties.Limits.FramebufferStencilSampleCounts;
  225. Capabilities = new HardwareCapabilities(
  226. _physicalDevice.IsDeviceExtensionPresent("VK_EXT_index_type_uint8"),
  227. supportsCustomBorderColor,
  228. supportsBlendOperationAdvanced,
  229. propertiesBlendOperationAdvanced.AdvancedBlendCorrelatedOverlap,
  230. propertiesBlendOperationAdvanced.AdvancedBlendNonPremultipliedSrcColor,
  231. propertiesBlendOperationAdvanced.AdvancedBlendNonPremultipliedDstColor,
  232. _physicalDevice.IsDeviceExtensionPresent(KhrDrawIndirectCount.ExtensionName),
  233. _physicalDevice.IsDeviceExtensionPresent("VK_EXT_fragment_shader_interlock"),
  234. _physicalDevice.IsDeviceExtensionPresent("VK_NV_geometry_shader_passthrough"),
  235. supportsSubgroupSizeControl,
  236. featuresShaderInt8.ShaderInt8,
  237. _physicalDevice.IsDeviceExtensionPresent("VK_EXT_shader_stencil_export"),
  238. _physicalDevice.IsDeviceExtensionPresent(ExtConditionalRendering.ExtensionName),
  239. _physicalDevice.IsDeviceExtensionPresent(ExtExtendedDynamicState.ExtensionName),
  240. features2.Features.MultiViewport,
  241. featuresRobustness2.NullDescriptor || IsMoltenVk,
  242. _physicalDevice.IsDeviceExtensionPresent(KhrPushDescriptor.ExtensionName),
  243. featuresPrimitiveTopologyListRestart.PrimitiveTopologyListRestart,
  244. featuresPrimitiveTopologyListRestart.PrimitiveTopologyPatchListRestart,
  245. supportsTransformFeedback,
  246. propertiesTransformFeedback.TransformFeedbackQueries,
  247. features2.Features.OcclusionQueryPrecise,
  248. _physicalDevice.PhysicalDeviceFeatures.PipelineStatisticsQuery,
  249. _physicalDevice.PhysicalDeviceFeatures.GeometryShader,
  250. propertiesSubgroupSizeControl.MinSubgroupSize,
  251. propertiesSubgroupSizeControl.MaxSubgroupSize,
  252. propertiesSubgroupSizeControl.RequiredSubgroupSizeStages,
  253. supportedSampleCounts,
  254. portabilityFlags,
  255. vertexBufferAlignment);
  256. IsSharedMemory = MemoryAllocator.IsDeviceMemoryShared(_physicalDevice);
  257. MemoryAllocator = new MemoryAllocator(Api, _physicalDevice, _device);
  258. CommandBufferPool = new CommandBufferPool(Api, _device, Queue, QueueLock, queueFamilyIndex);
  259. DescriptorSetManager = new DescriptorSetManager(_device);
  260. PipelineLayoutCache = new PipelineLayoutCache();
  261. BackgroundResources = new BackgroundResources(this, _device);
  262. BufferManager = new BufferManager(this, _device);
  263. SyncManager = new SyncManager(this, _device);
  264. _pipeline = new PipelineFull(this, _device);
  265. _pipeline.Initialize();
  266. HelperShader = new HelperShader(this, _device);
  267. _counters = new Counters(this, _device, _pipeline);
  268. }
  269. private unsafe void SetupContext(GraphicsDebugLevel logLevel)
  270. {
  271. var api = Vk.GetApi();
  272. Api = api;
  273. _instance = VulkanInitialization.CreateInstance(api, logLevel, _getRequiredExtensions());
  274. _debugMessenger = new VulkanDebugMessenger(api, _instance.Instance, logLevel);
  275. if (api.TryGetInstanceExtension(_instance.Instance, out KhrSurface surfaceApi))
  276. {
  277. SurfaceApi = surfaceApi;
  278. }
  279. _surface = _getSurface(_instance.Instance, api);
  280. _physicalDevice = VulkanInitialization.FindSuitablePhysicalDevice(api, _instance, _surface, _preferredGpuId);
  281. var queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(api, _physicalDevice, _surface, out uint maxQueueCount);
  282. _device = VulkanInitialization.CreateDevice(api, _physicalDevice, queueFamilyIndex, maxQueueCount);
  283. if (api.TryGetDeviceExtension(_instance.Instance, _device, out KhrSwapchain swapchainApi))
  284. {
  285. SwapchainApi = swapchainApi;
  286. }
  287. api.GetDeviceQueue(_device, queueFamilyIndex, 0, out var queue);
  288. Queue = queue;
  289. QueueLock = new object();
  290. LoadFeatures(maxQueueCount, queueFamilyIndex);
  291. _window = new Window(this, _surface, _physicalDevice.PhysicalDevice, _device);
  292. _initialized = true;
  293. }
  294. public BufferHandle CreateBuffer(int size, BufferHandle storageHint)
  295. {
  296. return BufferManager.CreateWithHandle(this, size, BufferAllocationType.Auto, storageHint);
  297. }
  298. public IProgram CreateProgram(ShaderSource[] sources, ShaderInfo info)
  299. {
  300. bool isCompute = sources.Length == 1 && sources[0].Stage == ShaderStage.Compute;
  301. if (info.State.HasValue || isCompute)
  302. {
  303. return new ShaderCollection(this, _device, sources, info.State ?? default, info.FromCache);
  304. }
  305. else
  306. {
  307. return new ShaderCollection(this, _device, sources);
  308. }
  309. }
  310. internal ShaderCollection CreateProgramWithMinimalLayout(ShaderSource[] sources, SpecDescription[] specDescription = null)
  311. {
  312. return new ShaderCollection(this, _device, sources, specDescription: specDescription, isMinimal: true);
  313. }
  314. public ISampler CreateSampler(GAL.SamplerCreateInfo info)
  315. {
  316. return new SamplerHolder(this, _device, info);
  317. }
  318. public ITexture CreateTexture(TextureCreateInfo info, float scale)
  319. {
  320. if (info.Target == Target.TextureBuffer)
  321. {
  322. return new TextureBuffer(this, info, scale);
  323. }
  324. return CreateTextureView(info, scale);
  325. }
  326. internal TextureView CreateTextureView(TextureCreateInfo info, float scale)
  327. {
  328. // This should be disposed when all views are destroyed.
  329. var storage = CreateTextureStorage(info, scale);
  330. return storage.CreateView(info, 0, 0);
  331. }
  332. internal TextureStorage CreateTextureStorage(TextureCreateInfo info, float scale)
  333. {
  334. return new TextureStorage(this, _device, info, scale);
  335. }
  336. public void DeleteBuffer(BufferHandle buffer)
  337. {
  338. BufferManager.Delete(buffer);
  339. }
  340. internal void FlushAllCommands()
  341. {
  342. _pipeline?.FlushCommandsImpl();
  343. }
  344. internal void RegisterFlush()
  345. {
  346. SyncManager.RegisterFlush();
  347. }
  348. public PinnedSpan<byte> GetBufferData(BufferHandle buffer, int offset, int size)
  349. {
  350. return BufferManager.GetData(buffer, offset, size);
  351. }
  352. public unsafe Capabilities GetCapabilities()
  353. {
  354. FormatFeatureFlags compressedFormatFeatureFlags =
  355. FormatFeatureFlags.SampledImageBit |
  356. FormatFeatureFlags.SampledImageFilterLinearBit |
  357. FormatFeatureFlags.BlitSrcBit |
  358. FormatFeatureFlags.TransferSrcBit |
  359. FormatFeatureFlags.TransferDstBit;
  360. bool supportsBc123CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  361. GAL.Format.Bc1RgbaSrgb,
  362. GAL.Format.Bc1RgbaUnorm,
  363. GAL.Format.Bc2Srgb,
  364. GAL.Format.Bc2Unorm,
  365. GAL.Format.Bc3Srgb,
  366. GAL.Format.Bc3Unorm);
  367. bool supportsBc45CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  368. GAL.Format.Bc4Snorm,
  369. GAL.Format.Bc4Unorm,
  370. GAL.Format.Bc5Snorm,
  371. GAL.Format.Bc5Unorm);
  372. bool supportsBc67CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  373. GAL.Format.Bc6HSfloat,
  374. GAL.Format.Bc6HUfloat,
  375. GAL.Format.Bc7Srgb,
  376. GAL.Format.Bc7Unorm);
  377. bool supportsEtc2CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  378. GAL.Format.Etc2RgbaSrgb,
  379. GAL.Format.Etc2RgbaUnorm,
  380. GAL.Format.Etc2RgbPtaSrgb,
  381. GAL.Format.Etc2RgbPtaUnorm,
  382. GAL.Format.Etc2RgbSrgb,
  383. GAL.Format.Etc2RgbUnorm);
  384. bool supports5BitComponentFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  385. GAL.Format.R5G6B5Unorm,
  386. GAL.Format.R5G5B5A1Unorm,
  387. GAL.Format.R5G5B5X1Unorm,
  388. GAL.Format.B5G6R5Unorm,
  389. GAL.Format.B5G5R5A1Unorm,
  390. GAL.Format.A1B5G5R5Unorm);
  391. bool supportsR4G4B4A4Format = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  392. GAL.Format.R4G4B4A4Unorm);
  393. bool supportsAstcFormats = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  394. GAL.Format.Astc4x4Unorm,
  395. GAL.Format.Astc5x4Unorm,
  396. GAL.Format.Astc5x5Unorm,
  397. GAL.Format.Astc6x5Unorm,
  398. GAL.Format.Astc6x6Unorm,
  399. GAL.Format.Astc8x5Unorm,
  400. GAL.Format.Astc8x6Unorm,
  401. GAL.Format.Astc8x8Unorm,
  402. GAL.Format.Astc10x5Unorm,
  403. GAL.Format.Astc10x6Unorm,
  404. GAL.Format.Astc10x8Unorm,
  405. GAL.Format.Astc10x10Unorm,
  406. GAL.Format.Astc12x10Unorm,
  407. GAL.Format.Astc12x12Unorm,
  408. GAL.Format.Astc4x4Srgb,
  409. GAL.Format.Astc5x4Srgb,
  410. GAL.Format.Astc5x5Srgb,
  411. GAL.Format.Astc6x5Srgb,
  412. GAL.Format.Astc6x6Srgb,
  413. GAL.Format.Astc8x5Srgb,
  414. GAL.Format.Astc8x6Srgb,
  415. GAL.Format.Astc8x8Srgb,
  416. GAL.Format.Astc10x5Srgb,
  417. GAL.Format.Astc10x6Srgb,
  418. GAL.Format.Astc10x8Srgb,
  419. GAL.Format.Astc10x10Srgb,
  420. GAL.Format.Astc12x10Srgb,
  421. GAL.Format.Astc12x12Srgb);
  422. PhysicalDeviceVulkan12Features featuresVk12 = new PhysicalDeviceVulkan12Features()
  423. {
  424. SType = StructureType.PhysicalDeviceVulkan12Features
  425. };
  426. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  427. {
  428. SType = StructureType.PhysicalDeviceFeatures2,
  429. PNext = &featuresVk12
  430. };
  431. Api.GetPhysicalDeviceFeatures2(_physicalDevice.PhysicalDevice, &features2);
  432. var limits = _physicalDevice.PhysicalDeviceProperties.Limits;
  433. return new Capabilities(
  434. api: TargetApi.Vulkan,
  435. GpuVendor,
  436. hasFrontFacingBug: IsIntelWindows,
  437. hasVectorIndexingBug: Vendor == Vendor.Qualcomm,
  438. needsFragmentOutputSpecialization: IsMoltenVk,
  439. reduceShaderPrecision: IsMoltenVk,
  440. supportsAstcCompression: features2.Features.TextureCompressionAstcLdr && supportsAstcFormats,
  441. supportsBc123Compression: supportsBc123CompressionFormat,
  442. supportsBc45Compression: supportsBc45CompressionFormat,
  443. supportsBc67Compression: supportsBc67CompressionFormat,
  444. supportsEtc2Compression: supportsEtc2CompressionFormat,
  445. supports3DTextureCompression: true,
  446. supportsBgraFormat: true,
  447. supportsR4G4Format: false,
  448. supportsR4G4B4A4Format: supportsR4G4B4A4Format,
  449. supportsSnormBufferTextureFormat: true,
  450. supports5BitComponentFormat: supports5BitComponentFormat,
  451. supportsBlendEquationAdvanced: Capabilities.SupportsBlendEquationAdvanced,
  452. supportsFragmentShaderInterlock: Capabilities.SupportsFragmentShaderInterlock,
  453. supportsFragmentShaderOrderingIntel: false,
  454. supportsGeometryShader: Capabilities.SupportsGeometryShader,
  455. supportsGeometryShaderPassthrough: Capabilities.SupportsGeometryShaderPassthrough,
  456. supportsImageLoadFormatted: features2.Features.ShaderStorageImageReadWithoutFormat,
  457. supportsLayerVertexTessellation: featuresVk12.ShaderOutputLayer,
  458. supportsMismatchingViewFormat: true,
  459. supportsCubemapView: !IsAmdGcn,
  460. supportsNonConstantTextureOffset: false,
  461. supportsShaderBallot: false,
  462. supportsTextureShadowLod: false,
  463. supportsViewportIndex: featuresVk12.ShaderOutputViewportIndex,
  464. supportsViewportSwizzle: false,
  465. supportsIndirectParameters: true,
  466. maximumUniformBuffersPerStage: Constants.MaxUniformBuffersPerStage,
  467. maximumStorageBuffersPerStage: Constants.MaxStorageBuffersPerStage,
  468. maximumTexturesPerStage: Constants.MaxTexturesPerStage,
  469. maximumImagesPerStage: Constants.MaxImagesPerStage,
  470. maximumComputeSharedMemorySize: (int)limits.MaxComputeSharedMemorySize,
  471. maximumSupportedAnisotropy: (int)limits.MaxSamplerAnisotropy,
  472. storageBufferOffsetAlignment: (int)limits.MinStorageBufferOffsetAlignment);
  473. }
  474. public HardwareInfo GetHardwareInfo()
  475. {
  476. return new HardwareInfo(GpuVendor, GpuRenderer);
  477. }
  478. public static DeviceInfo[] GetPhysicalDevices()
  479. {
  480. try
  481. {
  482. return VulkanInitialization.GetSuitablePhysicalDevices(Vk.GetApi());
  483. }
  484. catch (Exception)
  485. {
  486. // If we got an exception here, Vulkan is most likely not supported.
  487. return Array.Empty<DeviceInfo>();
  488. }
  489. }
  490. private static string ParseStandardVulkanVersion(uint version)
  491. {
  492. return $"{version >> 22}.{(version >> 12) & 0x3FF}.{version & 0xFFF}";
  493. }
  494. private static string ParseDriverVersion(ref PhysicalDeviceProperties properties)
  495. {
  496. uint driverVersionRaw = properties.DriverVersion;
  497. // NVIDIA differ from the standard here and uses a different format.
  498. if (properties.VendorID == 0x10DE)
  499. {
  500. return $"{(driverVersionRaw >> 22) & 0x3FF}.{(driverVersionRaw >> 14) & 0xFF}.{(driverVersionRaw >> 6) & 0xFF}.{driverVersionRaw & 0x3F}";
  501. }
  502. else
  503. {
  504. return ParseStandardVulkanVersion(driverVersionRaw);
  505. }
  506. }
  507. private unsafe void PrintGpuInformation()
  508. {
  509. var properties = _physicalDevice.PhysicalDeviceProperties;
  510. string vendorName = VendorUtils.GetNameFromId(properties.VendorID);
  511. Vendor = VendorUtils.FromId(properties.VendorID);
  512. IsAmdWindows = Vendor == Vendor.Amd && OperatingSystem.IsWindows();
  513. IsIntelWindows = Vendor == Vendor.Intel && OperatingSystem.IsWindows();
  514. IsTBDR = IsMoltenVk ||
  515. Vendor == Vendor.Qualcomm ||
  516. Vendor == Vendor.ARM ||
  517. Vendor == Vendor.Broadcom ||
  518. Vendor == Vendor.ImgTec;
  519. GpuVendor = vendorName;
  520. GpuRenderer = Marshal.PtrToStringAnsi((IntPtr)properties.DeviceName);
  521. GpuVersion = $"Vulkan v{ParseStandardVulkanVersion(properties.ApiVersion)}, Driver v{ParseDriverVersion(ref properties)}";
  522. IsAmdGcn = !IsMoltenVk && Vendor == Vendor.Amd && VendorUtils.AmdGcnRegex().IsMatch(GpuRenderer);
  523. Logger.Notice.Print(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})");
  524. }
  525. public GAL.PrimitiveTopology TopologyRemap(GAL.PrimitiveTopology topology)
  526. {
  527. return topology switch
  528. {
  529. GAL.PrimitiveTopology.Quads => GAL.PrimitiveTopology.Triangles,
  530. GAL.PrimitiveTopology.QuadStrip => GAL.PrimitiveTopology.TriangleStrip,
  531. GAL.PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans) ? GAL.PrimitiveTopology.Triangles : topology,
  532. _ => topology
  533. };
  534. }
  535. public bool TopologyUnsupported(GAL.PrimitiveTopology topology)
  536. {
  537. return topology switch
  538. {
  539. GAL.PrimitiveTopology.Quads => true,
  540. GAL.PrimitiveTopology.TriangleFan => Capabilities.PortabilitySubset.HasFlag(PortabilitySubsetFlags.NoTriangleFans),
  541. _ => false
  542. };
  543. }
  544. public void Initialize(GraphicsDebugLevel logLevel)
  545. {
  546. SetupContext(logLevel);
  547. PrintGpuInformation();
  548. }
  549. internal bool NeedsVertexBufferAlignment(int attrScalarAlignment, out int alignment)
  550. {
  551. if (Capabilities.VertexBufferAlignment > 1)
  552. {
  553. alignment = (int)Capabilities.VertexBufferAlignment;
  554. return true;
  555. }
  556. else if (Vendor != Vendor.Nvidia)
  557. {
  558. // Vulkan requires that vertex attributes are globally aligned by their component size,
  559. // so buffer strides that don't divide by the largest scalar element are invalid.
  560. // Guest applications do this, NVIDIA GPUs are OK with it, others are not.
  561. alignment = attrScalarAlignment;
  562. return true;
  563. }
  564. alignment = 1;
  565. return false;
  566. }
  567. public void PreFrame()
  568. {
  569. SyncManager.Cleanup();
  570. }
  571. public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler, bool hostReserved)
  572. {
  573. return _counters.QueueReport(type, resultHandler, hostReserved);
  574. }
  575. public void ResetCounter(CounterType type)
  576. {
  577. _counters.QueueReset(type);
  578. }
  579. public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
  580. {
  581. BufferManager.SetData(buffer, offset, data, _pipeline.CurrentCommandBuffer, _pipeline.EndRenderPass);
  582. }
  583. public void UpdateCounters()
  584. {
  585. _counters.Update();
  586. }
  587. public void ResetCounterPool()
  588. {
  589. _counters.ResetCounterPool();
  590. }
  591. public void ResetFutureCounters(CommandBuffer cmd, int count)
  592. {
  593. _counters?.ResetFutureCounters(cmd, count);
  594. }
  595. public void BackgroundContextAction(Action action, bool alwaysBackground = false)
  596. {
  597. action();
  598. }
  599. public void CreateSync(ulong id, bool strict)
  600. {
  601. SyncManager.Create(id, strict);
  602. }
  603. public IProgram LoadProgramBinary(byte[] programBinary, bool isFragment, ShaderInfo info)
  604. {
  605. throw new NotImplementedException();
  606. }
  607. public void WaitSync(ulong id)
  608. {
  609. SyncManager.Wait(id);
  610. }
  611. public ulong GetCurrentSync()
  612. {
  613. return SyncManager.GetCurrent();
  614. }
  615. public void SetInterruptAction(Action<Action> interruptAction)
  616. {
  617. InterruptAction = interruptAction;
  618. }
  619. public void Screenshot()
  620. {
  621. _window.ScreenCaptureRequested = true;
  622. }
  623. public void OnScreenCaptured(ScreenCaptureImageInfo bitmap)
  624. {
  625. ScreenCaptured?.Invoke(this, bitmap);
  626. }
  627. public unsafe void Dispose()
  628. {
  629. if (!_initialized)
  630. {
  631. return;
  632. }
  633. CommandBufferPool.Dispose();
  634. BackgroundResources.Dispose();
  635. _counters.Dispose();
  636. _window.Dispose();
  637. HelperShader.Dispose();
  638. _pipeline.Dispose();
  639. BufferManager.Dispose();
  640. DescriptorSetManager.Dispose();
  641. PipelineLayoutCache.Dispose();
  642. MemoryAllocator.Dispose();
  643. foreach (var shader in Shaders)
  644. {
  645. shader.Dispose();
  646. }
  647. foreach (var texture in Textures)
  648. {
  649. texture.Release();
  650. }
  651. foreach (var sampler in Samplers)
  652. {
  653. sampler.Dispose();
  654. }
  655. SurfaceApi.DestroySurface(_instance.Instance, _surface, null);
  656. Api.DestroyDevice(_device, null);
  657. _debugMessenger.Dispose();
  658. // Last step destroy the instance
  659. _instance.Dispose();
  660. }
  661. }
  662. }