VulkanRenderer.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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.Queries;
  7. using Silk.NET.Vulkan;
  8. using Silk.NET.Vulkan.Extensions.EXT;
  9. using Silk.NET.Vulkan.Extensions.KHR;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Linq;
  13. using System.Runtime.InteropServices;
  14. namespace Ryujinx.Graphics.Vulkan
  15. {
  16. public sealed class VulkanRenderer : IRenderer
  17. {
  18. private Instance _instance;
  19. private SurfaceKHR _surface;
  20. private PhysicalDevice _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 ExtDebugUtils DebugUtilsApi { 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 BufferManager BufferManager { get; private set; }
  47. internal HashSet<ShaderCollection> Shaders { get; }
  48. internal HashSet<ITexture> Textures { get; }
  49. internal HashSet<SamplerHolder> Samplers { get; }
  50. private Counters _counters;
  51. private SyncManager _syncManager;
  52. private PipelineFull _pipeline;
  53. private DebugUtilsMessengerEXT _debugUtilsMessenger;
  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. public string GpuVendor { get; private set; }
  66. public string GpuRenderer { get; private set; }
  67. public string GpuVersion { get; private set; }
  68. public bool PreferThreading => true;
  69. public event EventHandler<ScreenCaptureImageInfo> ScreenCaptured;
  70. public VulkanRenderer(Func<Instance, Vk, SurfaceKHR> surfaceFunc, Func<string[]> requiredExtensionsFunc, string preferredGpuId)
  71. {
  72. _getSurface = surfaceFunc;
  73. _getRequiredExtensions = requiredExtensionsFunc;
  74. _preferredGpuId = preferredGpuId;
  75. Shaders = new HashSet<ShaderCollection>();
  76. Textures = new HashSet<ITexture>();
  77. Samplers = new HashSet<SamplerHolder>();
  78. }
  79. private unsafe void LoadFeatures(string[] supportedExtensions, uint maxQueueCount, uint queueFamilyIndex)
  80. {
  81. FormatCapabilities = new FormatCapabilities(Api, _physicalDevice);
  82. var supportedFeatures = Api.GetPhysicalDeviceFeature(_physicalDevice);
  83. if (Api.TryGetDeviceExtension(_instance, _device, out ExtConditionalRendering conditionalRenderingApi))
  84. {
  85. ConditionalRenderingApi = conditionalRenderingApi;
  86. }
  87. if (Api.TryGetDeviceExtension(_instance, _device, out ExtExtendedDynamicState extendedDynamicStateApi))
  88. {
  89. ExtendedDynamicStateApi = extendedDynamicStateApi;
  90. }
  91. if (Api.TryGetDeviceExtension(_instance, _device, out KhrPushDescriptor pushDescriptorApi))
  92. {
  93. PushDescriptorApi = pushDescriptorApi;
  94. }
  95. if (Api.TryGetDeviceExtension(_instance, _device, out ExtTransformFeedback transformFeedbackApi))
  96. {
  97. TransformFeedbackApi = transformFeedbackApi;
  98. }
  99. if (Api.TryGetDeviceExtension(_instance, _device, out KhrDrawIndirectCount drawIndirectCountApi))
  100. {
  101. DrawIndirectCountApi = drawIndirectCountApi;
  102. }
  103. if (maxQueueCount >= 2)
  104. {
  105. Api.GetDeviceQueue(_device, queueFamilyIndex, 1, out var backgroundQueue);
  106. BackgroundQueue = backgroundQueue;
  107. BackgroundQueueLock = new object();
  108. }
  109. PhysicalDeviceProperties2 properties2 = new PhysicalDeviceProperties2()
  110. {
  111. SType = StructureType.PhysicalDeviceProperties2
  112. };
  113. PhysicalDeviceSubgroupSizeControlPropertiesEXT propertiesSubgroupSizeControl = new PhysicalDeviceSubgroupSizeControlPropertiesEXT()
  114. {
  115. SType = StructureType.PhysicalDeviceSubgroupSizeControlPropertiesExt
  116. };
  117. if (Capabilities.SupportsSubgroupSizeControl)
  118. {
  119. properties2.PNext = &propertiesSubgroupSizeControl;
  120. }
  121. bool supportsTransformFeedback = supportedExtensions.Contains(ExtTransformFeedback.ExtensionName);
  122. PhysicalDeviceTransformFeedbackPropertiesEXT propertiesTransformFeedback = new PhysicalDeviceTransformFeedbackPropertiesEXT()
  123. {
  124. SType = StructureType.PhysicalDeviceTransformFeedbackPropertiesExt
  125. };
  126. if (supportsTransformFeedback)
  127. {
  128. propertiesTransformFeedback.PNext = properties2.PNext;
  129. properties2.PNext = &propertiesTransformFeedback;
  130. }
  131. Api.GetPhysicalDeviceProperties2(_physicalDevice, &properties2);
  132. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  133. {
  134. SType = StructureType.PhysicalDeviceFeatures2
  135. };
  136. PhysicalDeviceRobustness2FeaturesEXT featuresRobustness2 = new PhysicalDeviceRobustness2FeaturesEXT()
  137. {
  138. SType = StructureType.PhysicalDeviceRobustness2FeaturesExt
  139. };
  140. PhysicalDeviceShaderFloat16Int8FeaturesKHR featuresShaderInt8 = new PhysicalDeviceShaderFloat16Int8FeaturesKHR()
  141. {
  142. SType = StructureType.PhysicalDeviceShaderFloat16Int8Features
  143. };
  144. PhysicalDeviceCustomBorderColorFeaturesEXT featuresCustomBorderColor = new PhysicalDeviceCustomBorderColorFeaturesEXT()
  145. {
  146. SType = StructureType.PhysicalDeviceCustomBorderColorFeaturesExt
  147. };
  148. if (supportedExtensions.Contains("VK_EXT_robustness2"))
  149. {
  150. features2.PNext = &featuresRobustness2;
  151. }
  152. if (supportedExtensions.Contains("VK_KHR_shader_float16_int8"))
  153. {
  154. featuresShaderInt8.PNext = features2.PNext;
  155. features2.PNext = &featuresShaderInt8;
  156. }
  157. if (supportedExtensions.Contains("VK_EXT_custom_border_color"))
  158. {
  159. featuresCustomBorderColor.PNext = features2.PNext;
  160. features2.PNext = &featuresCustomBorderColor;
  161. }
  162. Api.GetPhysicalDeviceFeatures2(_physicalDevice, &features2);
  163. bool customBorderColorSupported = supportedExtensions.Contains("VK_EXT_custom_border_color") &&
  164. featuresCustomBorderColor.CustomBorderColors &&
  165. featuresCustomBorderColor.CustomBorderColorWithoutFormat;
  166. ref var properties = ref properties2.Properties;
  167. SampleCountFlags supportedSampleCounts =
  168. properties.Limits.FramebufferColorSampleCounts &
  169. properties.Limits.FramebufferDepthSampleCounts &
  170. properties.Limits.FramebufferStencilSampleCounts;
  171. Capabilities = new HardwareCapabilities(
  172. supportedExtensions.Contains("VK_EXT_index_type_uint8"),
  173. customBorderColorSupported,
  174. supportedExtensions.Contains(KhrDrawIndirectCount.ExtensionName),
  175. supportedExtensions.Contains("VK_EXT_fragment_shader_interlock"),
  176. supportedExtensions.Contains("VK_NV_geometry_shader_passthrough"),
  177. supportedExtensions.Contains("VK_EXT_subgroup_size_control"),
  178. featuresShaderInt8.ShaderInt8,
  179. supportedExtensions.Contains(ExtConditionalRendering.ExtensionName),
  180. supportedExtensions.Contains(ExtExtendedDynamicState.ExtensionName),
  181. features2.Features.MultiViewport,
  182. featuresRobustness2.NullDescriptor,
  183. supportedExtensions.Contains(KhrPushDescriptor.ExtensionName),
  184. supportsTransformFeedback,
  185. propertiesTransformFeedback.TransformFeedbackQueries,
  186. supportedFeatures.GeometryShader,
  187. propertiesSubgroupSizeControl.MinSubgroupSize,
  188. propertiesSubgroupSizeControl.MaxSubgroupSize,
  189. propertiesSubgroupSizeControl.RequiredSubgroupSizeStages,
  190. supportedSampleCounts);
  191. MemoryAllocator = new MemoryAllocator(Api, _device, properties.Limits.MaxMemoryAllocationCount);
  192. CommandBufferPool = VulkanInitialization.CreateCommandBufferPool(Api, _device, Queue, QueueLock, queueFamilyIndex);
  193. DescriptorSetManager = new DescriptorSetManager(_device);
  194. PipelineLayoutCache = new PipelineLayoutCache();
  195. BackgroundResources = new BackgroundResources(this, _device);
  196. BufferManager = new BufferManager(this, _physicalDevice, _device);
  197. _syncManager = new SyncManager(this, _device);
  198. _pipeline = new PipelineFull(this, _device);
  199. _pipeline.Initialize();
  200. HelperShader = new HelperShader(this, _device);
  201. _counters = new Counters(this, _device, _pipeline);
  202. }
  203. private unsafe void SetupContext(GraphicsDebugLevel logLevel)
  204. {
  205. var api = Vk.GetApi();
  206. Api = api;
  207. _instance = VulkanInitialization.CreateInstance(api, logLevel, _getRequiredExtensions(), out ExtDebugUtils debugUtils, out _debugUtilsMessenger);
  208. DebugUtilsApi = debugUtils;
  209. if (api.TryGetInstanceExtension(_instance, out KhrSurface surfaceApi))
  210. {
  211. SurfaceApi = surfaceApi;
  212. }
  213. _surface = _getSurface(_instance, api);
  214. _physicalDevice = VulkanInitialization.FindSuitablePhysicalDevice(api, _instance, _surface, _preferredGpuId);
  215. var queueFamilyIndex = VulkanInitialization.FindSuitableQueueFamily(api, _physicalDevice, _surface, out uint maxQueueCount);
  216. var supportedExtensions = VulkanInitialization.GetSupportedExtensions(api, _physicalDevice);
  217. _device = VulkanInitialization.CreateDevice(api, _physicalDevice, queueFamilyIndex, supportedExtensions, maxQueueCount);
  218. if (api.TryGetDeviceExtension(_instance, _device, out KhrSwapchain swapchainApi))
  219. {
  220. SwapchainApi = swapchainApi;
  221. }
  222. api.GetDeviceQueue(_device, queueFamilyIndex, 0, out var queue);
  223. Queue = queue;
  224. QueueLock = new object();
  225. LoadFeatures(supportedExtensions, maxQueueCount, queueFamilyIndex);
  226. _window = new Window(this, _surface, _physicalDevice, _device);
  227. _initialized = true;
  228. }
  229. public BufferHandle CreateBuffer(int size)
  230. {
  231. return BufferManager.CreateWithHandle(this, size, false);
  232. }
  233. public IProgram CreateProgram(ShaderSource[] sources, ShaderInfo info)
  234. {
  235. bool isCompute = sources.Length == 1 && sources[0].Stage == ShaderStage.Compute;
  236. if (info.State.HasValue || isCompute)
  237. {
  238. return new ShaderCollection(this, _device, sources, info.State ?? default, info.FromCache);
  239. }
  240. else
  241. {
  242. return new ShaderCollection(this, _device, sources);
  243. }
  244. }
  245. internal ShaderCollection CreateProgramWithMinimalLayout(ShaderSource[] sources, SpecDescription[] specDescription = null)
  246. {
  247. return new ShaderCollection(this, _device, sources, specDescription: specDescription, isMinimal: true);
  248. }
  249. public ISampler CreateSampler(GAL.SamplerCreateInfo info)
  250. {
  251. return new SamplerHolder(this, _device, info);
  252. }
  253. public ITexture CreateTexture(TextureCreateInfo info, float scale)
  254. {
  255. if (info.Target == Target.TextureBuffer)
  256. {
  257. return new TextureBuffer(this, info, scale);
  258. }
  259. return CreateTextureView(info, scale);
  260. }
  261. internal TextureView CreateTextureView(TextureCreateInfo info, float scale)
  262. {
  263. // This should be disposed when all views are destroyed.
  264. var storage = CreateTextureStorage(info, scale);
  265. return storage.CreateView(info, 0, 0);
  266. }
  267. internal TextureStorage CreateTextureStorage(TextureCreateInfo info, float scale)
  268. {
  269. return new TextureStorage(this, _physicalDevice, _device, info, scale);
  270. }
  271. public void DeleteBuffer(BufferHandle buffer)
  272. {
  273. BufferManager.Delete(buffer);
  274. }
  275. internal void FlushAllCommands()
  276. {
  277. _pipeline?.FlushCommandsImpl();
  278. }
  279. internal void RegisterFlush()
  280. {
  281. _syncManager.RegisterFlush();
  282. }
  283. public ReadOnlySpan<byte> GetBufferData(BufferHandle buffer, int offset, int size)
  284. {
  285. return BufferManager.GetData(buffer, offset, size);
  286. }
  287. public unsafe Capabilities GetCapabilities()
  288. {
  289. FormatFeatureFlags compressedFormatFeatureFlags =
  290. FormatFeatureFlags.SampledImageBit |
  291. FormatFeatureFlags.SampledImageFilterLinearBit |
  292. FormatFeatureFlags.BlitSrcBit |
  293. FormatFeatureFlags.TransferSrcBit |
  294. FormatFeatureFlags.TransferDstBit;
  295. bool supportsBc123CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  296. GAL.Format.Bc1RgbaSrgb,
  297. GAL.Format.Bc1RgbaUnorm,
  298. GAL.Format.Bc2Srgb,
  299. GAL.Format.Bc2Unorm,
  300. GAL.Format.Bc3Srgb,
  301. GAL.Format.Bc3Unorm);
  302. bool supportsBc45CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  303. GAL.Format.Bc4Snorm,
  304. GAL.Format.Bc4Unorm,
  305. GAL.Format.Bc5Snorm,
  306. GAL.Format.Bc5Unorm);
  307. bool supportsBc67CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  308. GAL.Format.Bc6HSfloat,
  309. GAL.Format.Bc6HUfloat,
  310. GAL.Format.Bc7Srgb,
  311. GAL.Format.Bc7Unorm);
  312. bool supportsEtc2CompressionFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  313. GAL.Format.Etc2RgbaSrgb,
  314. GAL.Format.Etc2RgbaUnorm,
  315. GAL.Format.Etc2RgbPtaSrgb,
  316. GAL.Format.Etc2RgbPtaUnorm,
  317. GAL.Format.Etc2RgbSrgb,
  318. GAL.Format.Etc2RgbUnorm);
  319. bool supports5BitComponentFormat = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  320. GAL.Format.R5G6B5Unorm,
  321. GAL.Format.R5G5B5A1Unorm,
  322. GAL.Format.R5G5B5X1Unorm,
  323. GAL.Format.B5G6R5Unorm,
  324. GAL.Format.B5G5R5A1Unorm,
  325. GAL.Format.A1B5G5R5Unorm);
  326. bool supportsR4G4B4A4Format = FormatCapabilities.OptimalFormatsSupport(compressedFormatFeatureFlags,
  327. GAL.Format.R4G4B4A4Unorm);
  328. PhysicalDeviceVulkan12Features featuresVk12 = new PhysicalDeviceVulkan12Features()
  329. {
  330. SType = StructureType.PhysicalDeviceVulkan12Features
  331. };
  332. PhysicalDeviceFeatures2 features2 = new PhysicalDeviceFeatures2()
  333. {
  334. SType = StructureType.PhysicalDeviceFeatures2,
  335. PNext = &featuresVk12
  336. };
  337. Api.GetPhysicalDeviceFeatures2(_physicalDevice, &features2);
  338. Api.GetPhysicalDeviceProperties(_physicalDevice, out var properties);
  339. var limits = properties.Limits;
  340. return new Capabilities(
  341. api: TargetApi.Vulkan,
  342. GpuVendor,
  343. hasFrontFacingBug: IsIntelWindows,
  344. hasVectorIndexingBug: Vendor == Vendor.Qualcomm,
  345. supportsAstcCompression: features2.Features.TextureCompressionAstcLdr,
  346. supportsBc123Compression: supportsBc123CompressionFormat,
  347. supportsBc45Compression: supportsBc45CompressionFormat,
  348. supportsBc67Compression: supportsBc67CompressionFormat,
  349. supportsEtc2Compression: supportsEtc2CompressionFormat,
  350. supports3DTextureCompression: true,
  351. supportsBgraFormat: true,
  352. supportsR4G4Format: false,
  353. supportsR4G4B4A4Format: supportsR4G4B4A4Format,
  354. supportsSnormBufferTextureFormat: true,
  355. supports5BitComponentFormat: supports5BitComponentFormat,
  356. supportsFragmentShaderInterlock: Capabilities.SupportsFragmentShaderInterlock,
  357. supportsFragmentShaderOrderingIntel: false,
  358. supportsGeometryShaderPassthrough: Capabilities.SupportsGeometryShaderPassthrough,
  359. supportsImageLoadFormatted: features2.Features.ShaderStorageImageReadWithoutFormat,
  360. supportsLayerVertexTessellation: featuresVk12.ShaderOutputLayer,
  361. supportsMismatchingViewFormat: true,
  362. supportsCubemapView: !IsAmdGcn,
  363. supportsNonConstantTextureOffset: false,
  364. supportsShaderBallot: false,
  365. supportsTextureShadowLod: false,
  366. supportsViewportIndex: featuresVk12.ShaderOutputViewportIndex,
  367. supportsViewportSwizzle: false,
  368. supportsIndirectParameters: true,
  369. maximumUniformBuffersPerStage: Constants.MaxUniformBuffersPerStage,
  370. maximumStorageBuffersPerStage: Constants.MaxStorageBuffersPerStage,
  371. maximumTexturesPerStage: Constants.MaxTexturesPerStage,
  372. maximumImagesPerStage: Constants.MaxImagesPerStage,
  373. maximumComputeSharedMemorySize: (int)limits.MaxComputeSharedMemorySize,
  374. maximumSupportedAnisotropy: (int)limits.MaxSamplerAnisotropy,
  375. storageBufferOffsetAlignment: (int)limits.MinStorageBufferOffsetAlignment);
  376. }
  377. public HardwareInfo GetHardwareInfo()
  378. {
  379. return new HardwareInfo(GpuVendor, GpuRenderer);
  380. }
  381. public static DeviceInfo[] GetPhysicalDevices()
  382. {
  383. try
  384. {
  385. return VulkanInitialization.GetSuitablePhysicalDevices(Vk.GetApi());
  386. }
  387. catch (Exception)
  388. {
  389. // If we got an exception here, Vulkan is most likely not supported.
  390. return Array.Empty<DeviceInfo>();
  391. }
  392. }
  393. private static string ParseStandardVulkanVersion(uint version)
  394. {
  395. return $"{version >> 22}.{(version >> 12) & 0x3FF}.{version & 0xFFF}";
  396. }
  397. private static string ParseDriverVersion(ref PhysicalDeviceProperties properties)
  398. {
  399. uint driverVersionRaw = properties.DriverVersion;
  400. // NVIDIA differ from the standard here and uses a different format.
  401. if (properties.VendorID == 0x10DE)
  402. {
  403. return $"{(driverVersionRaw >> 22) & 0x3FF}.{(driverVersionRaw >> 14) & 0xFF}.{(driverVersionRaw >> 6) & 0xFF}.{driverVersionRaw & 0x3F}";
  404. }
  405. else
  406. {
  407. return ParseStandardVulkanVersion(driverVersionRaw);
  408. }
  409. }
  410. private unsafe void PrintGpuInformation()
  411. {
  412. Api.GetPhysicalDeviceProperties(_physicalDevice, out var properties);
  413. string vendorName = VendorUtils.GetNameFromId(properties.VendorID);
  414. Vendor = VendorUtils.FromId(properties.VendorID);
  415. IsAmdWindows = Vendor == Vendor.Amd && RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  416. IsIntelWindows = Vendor == Vendor.Intel && RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
  417. GpuVendor = vendorName;
  418. GpuRenderer = Marshal.PtrToStringAnsi((IntPtr)properties.DeviceName);
  419. GpuVersion = $"Vulkan v{ParseStandardVulkanVersion(properties.ApiVersion)}, Driver v{ParseDriverVersion(ref properties)}";
  420. IsAmdGcn = Vendor == Vendor.Amd && VendorUtils.AmdGcnRegex().IsMatch(GpuRenderer);
  421. Logger.Notice.Print(LogClass.Gpu, $"{GpuVendor} {GpuRenderer} ({GpuVersion})");
  422. }
  423. public GAL.PrimitiveTopology TopologyRemap(GAL.PrimitiveTopology topology)
  424. {
  425. return topology switch
  426. {
  427. GAL.PrimitiveTopology.Quads => GAL.PrimitiveTopology.Triangles,
  428. GAL.PrimitiveTopology.QuadStrip => GAL.PrimitiveTopology.TriangleStrip,
  429. _ => topology
  430. };
  431. }
  432. public bool TopologyUnsupported(GAL.PrimitiveTopology topology)
  433. {
  434. return topology switch
  435. {
  436. GAL.PrimitiveTopology.Quads => true,
  437. _ => false
  438. };
  439. }
  440. public void Initialize(GraphicsDebugLevel logLevel)
  441. {
  442. SetupContext(logLevel);
  443. PrintGpuInformation();
  444. }
  445. public bool NeedsVertexBufferAlignment(int attrScalarAlignment, out int alignment)
  446. {
  447. if (Vendor != Vendor.Nvidia)
  448. {
  449. // Vulkan requires that vertex attributes are globally aligned by their component size,
  450. // so buffer strides that don't divide by the largest scalar element are invalid.
  451. // Guest applications do this, NVIDIA GPUs are OK with it, others are not.
  452. alignment = attrScalarAlignment;
  453. return true;
  454. }
  455. alignment = 1;
  456. return false;
  457. }
  458. public void PreFrame()
  459. {
  460. _syncManager.Cleanup();
  461. }
  462. public ICounterEvent ReportCounter(CounterType type, EventHandler<ulong> resultHandler, bool hostReserved)
  463. {
  464. return _counters.QueueReport(type, resultHandler, hostReserved);
  465. }
  466. public void ResetCounter(CounterType type)
  467. {
  468. _counters.QueueReset(type);
  469. }
  470. public void SetBufferData(BufferHandle buffer, int offset, ReadOnlySpan<byte> data)
  471. {
  472. BufferManager.SetData(buffer, offset, data, _pipeline.CurrentCommandBuffer, _pipeline.EndRenderPass);
  473. }
  474. public void UpdateCounters()
  475. {
  476. _counters.Update();
  477. }
  478. public void BackgroundContextAction(Action action, bool alwaysBackground = false)
  479. {
  480. action();
  481. }
  482. public void CreateSync(ulong id, bool strict)
  483. {
  484. _syncManager.Create(id, strict);
  485. }
  486. public IProgram LoadProgramBinary(byte[] programBinary, bool isFragment, ShaderInfo info)
  487. {
  488. throw new NotImplementedException();
  489. }
  490. public void WaitSync(ulong id)
  491. {
  492. _syncManager.Wait(id);
  493. }
  494. public ulong GetCurrentSync()
  495. {
  496. return _syncManager.GetCurrent();
  497. }
  498. public void SetInterruptAction(Action<Action> interruptAction)
  499. {
  500. InterruptAction = interruptAction;
  501. }
  502. public void Screenshot()
  503. {
  504. _window.ScreenCaptureRequested = true;
  505. }
  506. public void OnScreenCaptured(ScreenCaptureImageInfo bitmap)
  507. {
  508. ScreenCaptured?.Invoke(this, bitmap);
  509. }
  510. public unsafe void Dispose()
  511. {
  512. if (!_initialized)
  513. {
  514. return;
  515. }
  516. CommandBufferPool.Dispose();
  517. BackgroundResources.Dispose();
  518. _counters.Dispose();
  519. _window.Dispose();
  520. HelperShader.Dispose();
  521. _pipeline.Dispose();
  522. BufferManager.Dispose();
  523. DescriptorSetManager.Dispose();
  524. PipelineLayoutCache.Dispose();
  525. MemoryAllocator.Dispose();
  526. if (_debugUtilsMessenger.Handle != 0)
  527. {
  528. DebugUtilsApi.DestroyDebugUtilsMessenger(_instance, _debugUtilsMessenger, null);
  529. }
  530. foreach (var shader in Shaders)
  531. {
  532. shader.Dispose();
  533. }
  534. foreach (var texture in Textures)
  535. {
  536. texture.Release();
  537. }
  538. foreach (var sampler in Samplers)
  539. {
  540. sampler.Dispose();
  541. }
  542. SurfaceApi.DestroySurface(_instance, _surface, null);
  543. Api.DestroyDevice(_device, null);
  544. // Last step destroy the instance
  545. Api.DestroyInstance(_instance, null);
  546. }
  547. }
  548. }