VulkanRenderer.cs 34 KB

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