Window.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. using Ryujinx.Graphics.GAL;
  2. using Ryujinx.Graphics.Vulkan.Effects;
  3. using Silk.NET.Vulkan;
  4. using Silk.NET.Vulkan.Extensions.KHR;
  5. using System;
  6. using System.Linq;
  7. using VkFormat = Silk.NET.Vulkan.Format;
  8. namespace Ryujinx.Graphics.Vulkan
  9. {
  10. class Window : WindowBase, IDisposable
  11. {
  12. private const int SurfaceWidth = 1280;
  13. private const int SurfaceHeight = 720;
  14. private readonly VulkanRenderer _gd;
  15. private readonly SurfaceKHR _surface;
  16. private readonly PhysicalDevice _physicalDevice;
  17. private readonly Device _device;
  18. private SwapchainKHR _swapchain;
  19. private Image[] _swapchainImages;
  20. private Auto<DisposableImageView>[] _swapchainImageViews;
  21. private Semaphore _imageAvailableSemaphore;
  22. private Semaphore _renderFinishedSemaphore;
  23. private int _width;
  24. private int _height;
  25. private bool _vsyncEnabled;
  26. private bool _vsyncModeChanged;
  27. private VkFormat _format;
  28. private AntiAliasing _currentAntiAliasing;
  29. private bool _updateEffect;
  30. private IPostProcessingEffect _effect;
  31. private IScalingFilter _scalingFilter;
  32. private bool _isLinear;
  33. private float _scalingFilterLevel;
  34. private bool _updateScalingFilter;
  35. private ScalingFilter _currentScalingFilter;
  36. public unsafe Window(VulkanRenderer gd, SurfaceKHR surface, PhysicalDevice physicalDevice, Device device)
  37. {
  38. _gd = gd;
  39. _physicalDevice = physicalDevice;
  40. _device = device;
  41. _surface = surface;
  42. CreateSwapchain();
  43. var semaphoreCreateInfo = new SemaphoreCreateInfo
  44. {
  45. SType = StructureType.SemaphoreCreateInfo,
  46. };
  47. gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _imageAvailableSemaphore).ThrowOnError();
  48. gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _renderFinishedSemaphore).ThrowOnError();
  49. }
  50. private void RecreateSwapchain()
  51. {
  52. var oldSwapchain = _swapchain;
  53. _vsyncModeChanged = false;
  54. for (int i = 0; i < _swapchainImageViews.Length; i++)
  55. {
  56. _swapchainImageViews[i].Dispose();
  57. }
  58. // Destroy old Swapchain.
  59. _gd.Api.DeviceWaitIdle(_device);
  60. _gd.SwapchainApi.DestroySwapchain(_device, oldSwapchain, Span<AllocationCallbacks>.Empty);
  61. CreateSwapchain();
  62. }
  63. private unsafe void CreateSwapchain()
  64. {
  65. _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out var capabilities);
  66. uint surfaceFormatsCount;
  67. _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, null);
  68. var surfaceFormats = new SurfaceFormatKHR[surfaceFormatsCount];
  69. fixed (SurfaceFormatKHR* pSurfaceFormats = surfaceFormats)
  70. {
  71. _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, pSurfaceFormats);
  72. }
  73. uint presentModesCount;
  74. _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, null);
  75. var presentModes = new PresentModeKHR[presentModesCount];
  76. fixed (PresentModeKHR* pPresentModes = presentModes)
  77. {
  78. _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, pPresentModes);
  79. }
  80. uint imageCount = capabilities.MinImageCount + 1;
  81. if (capabilities.MaxImageCount > 0 && imageCount > capabilities.MaxImageCount)
  82. {
  83. imageCount = capabilities.MaxImageCount;
  84. }
  85. var surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats);
  86. var extent = ChooseSwapExtent(capabilities);
  87. _width = (int)extent.Width;
  88. _height = (int)extent.Height;
  89. _format = surfaceFormat.Format;
  90. var oldSwapchain = _swapchain;
  91. var swapchainCreateInfo = new SwapchainCreateInfoKHR
  92. {
  93. SType = StructureType.SwapchainCreateInfoKhr,
  94. Surface = _surface,
  95. MinImageCount = imageCount,
  96. ImageFormat = surfaceFormat.Format,
  97. ImageColorSpace = surfaceFormat.ColorSpace,
  98. ImageExtent = extent,
  99. ImageUsage = ImageUsageFlags.ColorAttachmentBit | ImageUsageFlags.TransferDstBit | ImageUsageFlags.StorageBit,
  100. ImageSharingMode = SharingMode.Exclusive,
  101. ImageArrayLayers = 1,
  102. PreTransform = capabilities.CurrentTransform,
  103. CompositeAlpha = ChooseCompositeAlpha(capabilities.SupportedCompositeAlpha),
  104. PresentMode = ChooseSwapPresentMode(presentModes, _vsyncEnabled),
  105. Clipped = true,
  106. };
  107. _gd.SwapchainApi.CreateSwapchain(_device, swapchainCreateInfo, null, out _swapchain).ThrowOnError();
  108. _gd.SwapchainApi.GetSwapchainImages(_device, _swapchain, &imageCount, null);
  109. _swapchainImages = new Image[imageCount];
  110. fixed (Image* pSwapchainImages = _swapchainImages)
  111. {
  112. _gd.SwapchainApi.GetSwapchainImages(_device, _swapchain, &imageCount, pSwapchainImages);
  113. }
  114. _swapchainImageViews = new Auto<DisposableImageView>[imageCount];
  115. for (int i = 0; i < _swapchainImageViews.Length; i++)
  116. {
  117. _swapchainImageViews[i] = CreateSwapchainImageView(_swapchainImages[i], surfaceFormat.Format);
  118. }
  119. }
  120. private unsafe Auto<DisposableImageView> CreateSwapchainImageView(Image swapchainImage, VkFormat format)
  121. {
  122. var componentMapping = new ComponentMapping(
  123. ComponentSwizzle.R,
  124. ComponentSwizzle.G,
  125. ComponentSwizzle.B,
  126. ComponentSwizzle.A);
  127. var aspectFlags = ImageAspectFlags.ColorBit;
  128. var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1);
  129. var imageCreateInfo = new ImageViewCreateInfo
  130. {
  131. SType = StructureType.ImageViewCreateInfo,
  132. Image = swapchainImage,
  133. ViewType = ImageViewType.Type2D,
  134. Format = format,
  135. Components = componentMapping,
  136. SubresourceRange = subresourceRange,
  137. };
  138. _gd.Api.CreateImageView(_device, imageCreateInfo, null, out var imageView).ThrowOnError();
  139. return new Auto<DisposableImageView>(new DisposableImageView(_gd.Api, _device, imageView));
  140. }
  141. private static SurfaceFormatKHR ChooseSwapSurfaceFormat(SurfaceFormatKHR[] availableFormats)
  142. {
  143. if (availableFormats.Length == 1 && availableFormats[0].Format == VkFormat.Undefined)
  144. {
  145. return new SurfaceFormatKHR(VkFormat.B8G8R8A8Unorm, ColorSpaceKHR.PaceSrgbNonlinearKhr);
  146. }
  147. foreach (var format in availableFormats)
  148. {
  149. if (format.Format == VkFormat.B8G8R8A8Unorm && format.ColorSpace == ColorSpaceKHR.PaceSrgbNonlinearKhr)
  150. {
  151. return format;
  152. }
  153. }
  154. return availableFormats[0];
  155. }
  156. private static CompositeAlphaFlagsKHR ChooseCompositeAlpha(CompositeAlphaFlagsKHR supportedFlags)
  157. {
  158. if (supportedFlags.HasFlag(CompositeAlphaFlagsKHR.OpaqueBitKhr))
  159. {
  160. return CompositeAlphaFlagsKHR.OpaqueBitKhr;
  161. }
  162. else if (supportedFlags.HasFlag(CompositeAlphaFlagsKHR.PreMultipliedBitKhr))
  163. {
  164. return CompositeAlphaFlagsKHR.PreMultipliedBitKhr;
  165. }
  166. else
  167. {
  168. return CompositeAlphaFlagsKHR.InheritBitKhr;
  169. }
  170. }
  171. private static PresentModeKHR ChooseSwapPresentMode(PresentModeKHR[] availablePresentModes, bool vsyncEnabled)
  172. {
  173. if (!vsyncEnabled && availablePresentModes.Contains(PresentModeKHR.ImmediateKhr))
  174. {
  175. return PresentModeKHR.ImmediateKhr;
  176. }
  177. else if (availablePresentModes.Contains(PresentModeKHR.MailboxKhr))
  178. {
  179. return PresentModeKHR.MailboxKhr;
  180. }
  181. else
  182. {
  183. return PresentModeKHR.FifoKhr;
  184. }
  185. }
  186. public static Extent2D ChooseSwapExtent(SurfaceCapabilitiesKHR capabilities)
  187. {
  188. if (capabilities.CurrentExtent.Width != uint.MaxValue)
  189. {
  190. return capabilities.CurrentExtent;
  191. }
  192. uint width = Math.Max(capabilities.MinImageExtent.Width, Math.Min(capabilities.MaxImageExtent.Width, SurfaceWidth));
  193. uint height = Math.Max(capabilities.MinImageExtent.Height, Math.Min(capabilities.MaxImageExtent.Height, SurfaceHeight));
  194. return new Extent2D(width, height);
  195. }
  196. public unsafe override void Present(ITexture texture, ImageCrop crop, Action swapBuffersCallback)
  197. {
  198. _gd.PipelineInternal.AutoFlush.Present();
  199. uint nextImage = 0;
  200. while (true)
  201. {
  202. var acquireResult = _gd.SwapchainApi.AcquireNextImage(
  203. _device,
  204. _swapchain,
  205. ulong.MaxValue,
  206. _imageAvailableSemaphore,
  207. new Fence(),
  208. ref nextImage);
  209. if (acquireResult == Result.ErrorOutOfDateKhr ||
  210. acquireResult == Result.SuboptimalKhr ||
  211. _vsyncModeChanged)
  212. {
  213. RecreateSwapchain();
  214. }
  215. else
  216. {
  217. acquireResult.ThrowOnError();
  218. break;
  219. }
  220. }
  221. var swapchainImage = _swapchainImages[nextImage];
  222. _gd.FlushAllCommands();
  223. var cbs = _gd.CommandBufferPool.Rent();
  224. Transition(
  225. cbs.CommandBuffer,
  226. swapchainImage,
  227. 0,
  228. AccessFlags.TransferWriteBit,
  229. ImageLayout.Undefined,
  230. ImageLayout.General);
  231. var view = (TextureView)texture;
  232. UpdateEffect();
  233. if (_effect != null)
  234. {
  235. view = _effect.Run(view, cbs, _width, _height);
  236. }
  237. int srcX0, srcX1, srcY0, srcY1;
  238. float scale = view.ScaleFactor;
  239. if (crop.Left == 0 && crop.Right == 0)
  240. {
  241. srcX0 = 0;
  242. srcX1 = (int)(view.Width / scale);
  243. }
  244. else
  245. {
  246. srcX0 = crop.Left;
  247. srcX1 = crop.Right;
  248. }
  249. if (crop.Top == 0 && crop.Bottom == 0)
  250. {
  251. srcY0 = 0;
  252. srcY1 = (int)(view.Height / scale);
  253. }
  254. else
  255. {
  256. srcY0 = crop.Top;
  257. srcY1 = crop.Bottom;
  258. }
  259. if (scale != 1f)
  260. {
  261. srcX0 = (int)(srcX0 * scale);
  262. srcY0 = (int)(srcY0 * scale);
  263. srcX1 = (int)Math.Ceiling(srcX1 * scale);
  264. srcY1 = (int)Math.Ceiling(srcY1 * scale);
  265. }
  266. if (ScreenCaptureRequested)
  267. {
  268. if (_effect != null)
  269. {
  270. _gd.CommandBufferPool.Return(
  271. cbs,
  272. null,
  273. stackalloc[] { PipelineStageFlags.ColorAttachmentOutputBit },
  274. null);
  275. _gd.FlushAllCommands();
  276. cbs.GetFence().Wait();
  277. cbs = _gd.CommandBufferPool.Rent();
  278. }
  279. CaptureFrame(view, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0, view.Info.Format.IsBgr(), crop.FlipX, crop.FlipY);
  280. ScreenCaptureRequested = false;
  281. }
  282. float ratioX = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _height * crop.AspectRatioX / (_width * crop.AspectRatioY));
  283. float ratioY = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _width * crop.AspectRatioY / (_height * crop.AspectRatioX));
  284. int dstWidth = (int)(_width * ratioX);
  285. int dstHeight = (int)(_height * ratioY);
  286. int dstPaddingX = (_width - dstWidth) / 2;
  287. int dstPaddingY = (_height - dstHeight) / 2;
  288. int dstX0 = crop.FlipX ? _width - dstPaddingX : dstPaddingX;
  289. int dstX1 = crop.FlipX ? dstPaddingX : _width - dstPaddingX;
  290. int dstY0 = crop.FlipY ? dstPaddingY : _height - dstPaddingY;
  291. int dstY1 = crop.FlipY ? _height - dstPaddingY : dstPaddingY;
  292. if (_scalingFilter != null)
  293. {
  294. _scalingFilter.Run(
  295. view,
  296. cbs,
  297. _swapchainImageViews[nextImage],
  298. _format,
  299. _width,
  300. _height,
  301. new Extents2D(srcX0, srcY0, srcX1, srcY1),
  302. new Extents2D(dstX0, dstY0, dstX1, dstY1)
  303. );
  304. }
  305. else
  306. {
  307. _gd.HelperShader.BlitColor(
  308. _gd,
  309. cbs,
  310. view,
  311. _swapchainImageViews[nextImage],
  312. _width,
  313. _height,
  314. 1,
  315. _format,
  316. false,
  317. new Extents2D(srcX0, srcY0, srcX1, srcY1),
  318. new Extents2D(dstX0, dstY1, dstX1, dstY0),
  319. _isLinear,
  320. true);
  321. }
  322. Transition(
  323. cbs.CommandBuffer,
  324. swapchainImage,
  325. 0,
  326. 0,
  327. ImageLayout.General,
  328. ImageLayout.PresentSrcKhr);
  329. _gd.CommandBufferPool.Return(
  330. cbs,
  331. stackalloc[] { _imageAvailableSemaphore },
  332. stackalloc[] { PipelineStageFlags.ColorAttachmentOutputBit },
  333. stackalloc[] { _renderFinishedSemaphore });
  334. // TODO: Present queue.
  335. var semaphore = _renderFinishedSemaphore;
  336. var swapchain = _swapchain;
  337. Result result;
  338. var presentInfo = new PresentInfoKHR
  339. {
  340. SType = StructureType.PresentInfoKhr,
  341. WaitSemaphoreCount = 1,
  342. PWaitSemaphores = &semaphore,
  343. SwapchainCount = 1,
  344. PSwapchains = &swapchain,
  345. PImageIndices = &nextImage,
  346. PResults = &result,
  347. };
  348. lock (_gd.QueueLock)
  349. {
  350. _gd.SwapchainApi.QueuePresent(_gd.Queue, presentInfo);
  351. }
  352. }
  353. public override void SetAntiAliasing(AntiAliasing effect)
  354. {
  355. if (_currentAntiAliasing == effect && _effect != null)
  356. {
  357. return;
  358. }
  359. _currentAntiAliasing = effect;
  360. _updateEffect = true;
  361. }
  362. public override void SetScalingFilter(ScalingFilter type)
  363. {
  364. if (_currentScalingFilter == type && _effect != null)
  365. {
  366. return;
  367. }
  368. _currentScalingFilter = type;
  369. _updateScalingFilter = true;
  370. }
  371. private void UpdateEffect()
  372. {
  373. if (_updateEffect)
  374. {
  375. _updateEffect = false;
  376. switch (_currentAntiAliasing)
  377. {
  378. case AntiAliasing.Fxaa:
  379. _effect?.Dispose();
  380. _effect = new FxaaPostProcessingEffect(_gd, _device);
  381. break;
  382. case AntiAliasing.None:
  383. _effect?.Dispose();
  384. _effect = null;
  385. break;
  386. case AntiAliasing.SmaaLow:
  387. case AntiAliasing.SmaaMedium:
  388. case AntiAliasing.SmaaHigh:
  389. case AntiAliasing.SmaaUltra:
  390. var quality = _currentAntiAliasing - AntiAliasing.SmaaLow;
  391. if (_effect is SmaaPostProcessingEffect smaa)
  392. {
  393. smaa.Quality = quality;
  394. }
  395. else
  396. {
  397. _effect?.Dispose();
  398. _effect = new SmaaPostProcessingEffect(_gd, _device, quality);
  399. }
  400. break;
  401. }
  402. }
  403. if (_updateScalingFilter)
  404. {
  405. _updateScalingFilter = false;
  406. switch (_currentScalingFilter)
  407. {
  408. case ScalingFilter.Bilinear:
  409. case ScalingFilter.Nearest:
  410. _scalingFilter?.Dispose();
  411. _scalingFilter = null;
  412. _isLinear = _currentScalingFilter == ScalingFilter.Bilinear;
  413. break;
  414. case ScalingFilter.Fsr:
  415. if (_scalingFilter is not FsrScalingFilter)
  416. {
  417. _scalingFilter?.Dispose();
  418. _scalingFilter = new FsrScalingFilter(_gd, _device);
  419. }
  420. _scalingFilter.Level = _scalingFilterLevel;
  421. break;
  422. }
  423. }
  424. }
  425. public override void SetScalingFilterLevel(float level)
  426. {
  427. _scalingFilterLevel = level;
  428. _updateScalingFilter = true;
  429. }
  430. private unsafe void Transition(
  431. CommandBuffer commandBuffer,
  432. Image image,
  433. AccessFlags srcAccess,
  434. AccessFlags dstAccess,
  435. ImageLayout srcLayout,
  436. ImageLayout dstLayout)
  437. {
  438. var subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1);
  439. var barrier = new ImageMemoryBarrier
  440. {
  441. SType = StructureType.ImageMemoryBarrier,
  442. SrcAccessMask = srcAccess,
  443. DstAccessMask = dstAccess,
  444. OldLayout = srcLayout,
  445. NewLayout = dstLayout,
  446. SrcQueueFamilyIndex = Vk.QueueFamilyIgnored,
  447. DstQueueFamilyIndex = Vk.QueueFamilyIgnored,
  448. Image = image,
  449. SubresourceRange = subresourceRange,
  450. };
  451. _gd.Api.CmdPipelineBarrier(
  452. commandBuffer,
  453. PipelineStageFlags.TopOfPipeBit,
  454. PipelineStageFlags.AllCommandsBit,
  455. 0,
  456. 0,
  457. null,
  458. 0,
  459. null,
  460. 1,
  461. barrier);
  462. }
  463. private void CaptureFrame(TextureView texture, int x, int y, int width, int height, bool isBgra, bool flipX, bool flipY)
  464. {
  465. byte[] bitmap = texture.GetData(x, y, width, height);
  466. _gd.OnScreenCaptured(new ScreenCaptureImageInfo(width, height, isBgra, bitmap, flipX, flipY));
  467. }
  468. public override void SetSize(int width, int height)
  469. {
  470. // Not needed as we can get the size from the surface.
  471. }
  472. public override void ChangeVSyncMode(bool vsyncEnabled)
  473. {
  474. _vsyncEnabled = vsyncEnabled;
  475. _vsyncModeChanged = true;
  476. }
  477. protected virtual void Dispose(bool disposing)
  478. {
  479. if (disposing)
  480. {
  481. unsafe
  482. {
  483. _gd.Api.DestroySemaphore(_device, _renderFinishedSemaphore, null);
  484. _gd.Api.DestroySemaphore(_device, _imageAvailableSemaphore, null);
  485. for (int i = 0; i < _swapchainImageViews.Length; i++)
  486. {
  487. _swapchainImageViews[i].Dispose();
  488. }
  489. _gd.SwapchainApi.DestroySwapchain(_device, _swapchain, null);
  490. }
  491. _effect?.Dispose();
  492. _scalingFilter?.Dispose();
  493. }
  494. }
  495. public override void Dispose()
  496. {
  497. Dispose(true);
  498. }
  499. }
  500. }