VulkanRenderer.cs 33 KB

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