Window.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. using Ryujinx.Graphics.GAL;
  2. using Silk.NET.Vulkan;
  3. using System;
  4. using System.Linq;
  5. using VkFormat = Silk.NET.Vulkan.Format;
  6. namespace Ryujinx.Graphics.Vulkan
  7. {
  8. class Window : WindowBase, IDisposable
  9. {
  10. private const int SurfaceWidth = 1280;
  11. private const int SurfaceHeight = 720;
  12. private readonly VulkanRenderer _gd;
  13. private readonly SurfaceKHR _surface;
  14. private readonly PhysicalDevice _physicalDevice;
  15. private readonly Device _device;
  16. private SwapchainKHR _swapchain;
  17. private Image[] _swapchainImages;
  18. private Auto<DisposableImageView>[] _swapchainImageViews;
  19. private Semaphore _imageAvailableSemaphore;
  20. private Semaphore _renderFinishedSemaphore;
  21. private int _width;
  22. private int _height;
  23. private bool _vsyncEnabled;
  24. private bool _vsyncModeChanged;
  25. private VkFormat _format;
  26. public unsafe Window(VulkanRenderer gd, SurfaceKHR surface, PhysicalDevice physicalDevice, Device device)
  27. {
  28. _gd = gd;
  29. _physicalDevice = physicalDevice;
  30. _device = device;
  31. _surface = surface;
  32. CreateSwapchain();
  33. var semaphoreCreateInfo = new SemaphoreCreateInfo()
  34. {
  35. SType = StructureType.SemaphoreCreateInfo
  36. };
  37. gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _imageAvailableSemaphore).ThrowOnError();
  38. gd.Api.CreateSemaphore(device, semaphoreCreateInfo, null, out _renderFinishedSemaphore).ThrowOnError();
  39. }
  40. private void RecreateSwapchain()
  41. {
  42. _vsyncModeChanged = false;
  43. for (int i = 0; i < _swapchainImageViews.Length; i++)
  44. {
  45. _swapchainImageViews[i].Dispose();
  46. }
  47. CreateSwapchain();
  48. }
  49. private unsafe void CreateSwapchain()
  50. {
  51. _gd.SurfaceApi.GetPhysicalDeviceSurfaceCapabilities(_physicalDevice, _surface, out var capabilities);
  52. uint surfaceFormatsCount;
  53. _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, null);
  54. var surfaceFormats = new SurfaceFormatKHR[surfaceFormatsCount];
  55. fixed (SurfaceFormatKHR* pSurfaceFormats = surfaceFormats)
  56. {
  57. _gd.SurfaceApi.GetPhysicalDeviceSurfaceFormats(_physicalDevice, _surface, &surfaceFormatsCount, pSurfaceFormats);
  58. }
  59. uint presentModesCount;
  60. _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, null);
  61. var presentModes = new PresentModeKHR[presentModesCount];
  62. fixed (PresentModeKHR* pPresentModes = presentModes)
  63. {
  64. _gd.SurfaceApi.GetPhysicalDeviceSurfacePresentModes(_physicalDevice, _surface, &presentModesCount, pPresentModes);
  65. }
  66. uint imageCount = capabilities.MinImageCount + 1;
  67. if (capabilities.MaxImageCount > 0 && imageCount > capabilities.MaxImageCount)
  68. {
  69. imageCount = capabilities.MaxImageCount;
  70. }
  71. var surfaceFormat = ChooseSwapSurfaceFormat(surfaceFormats);
  72. var extent = ChooseSwapExtent(capabilities);
  73. _width = (int)extent.Width;
  74. _height = (int)extent.Height;
  75. _format = surfaceFormat.Format;
  76. var oldSwapchain = _swapchain;
  77. var swapchainCreateInfo = new SwapchainCreateInfoKHR()
  78. {
  79. SType = StructureType.SwapchainCreateInfoKhr,
  80. Surface = _surface,
  81. MinImageCount = imageCount,
  82. ImageFormat = surfaceFormat.Format,
  83. ImageColorSpace = surfaceFormat.ColorSpace,
  84. ImageExtent = extent,
  85. ImageUsage = ImageUsageFlags.ColorAttachmentBit | ImageUsageFlags.TransferDstBit,
  86. ImageSharingMode = SharingMode.Exclusive,
  87. ImageArrayLayers = 1,
  88. PreTransform = capabilities.CurrentTransform,
  89. CompositeAlpha = CompositeAlphaFlagsKHR.OpaqueBitKhr,
  90. PresentMode = ChooseSwapPresentMode(presentModes, _vsyncEnabled),
  91. Clipped = true,
  92. OldSwapchain = oldSwapchain
  93. };
  94. _gd.SwapchainApi.CreateSwapchain(_device, swapchainCreateInfo, null, out _swapchain).ThrowOnError();
  95. _gd.SwapchainApi.GetSwapchainImages(_device, _swapchain, &imageCount, null);
  96. _swapchainImages = new Image[imageCount];
  97. fixed (Image* pSwapchainImages = _swapchainImages)
  98. {
  99. _gd.SwapchainApi.GetSwapchainImages(_device, _swapchain, &imageCount, pSwapchainImages);
  100. }
  101. _swapchainImageViews = new Auto<DisposableImageView>[imageCount];
  102. for (int i = 0; i < imageCount; i++)
  103. {
  104. _swapchainImageViews[i] = CreateSwapchainImageView(_swapchainImages[i], surfaceFormat.Format);
  105. }
  106. }
  107. private unsafe Auto<DisposableImageView> CreateSwapchainImageView(Image swapchainImage, VkFormat format)
  108. {
  109. var componentMapping = new ComponentMapping(
  110. ComponentSwizzle.R,
  111. ComponentSwizzle.G,
  112. ComponentSwizzle.B,
  113. ComponentSwizzle.A);
  114. var aspectFlags = ImageAspectFlags.ColorBit;
  115. var subresourceRange = new ImageSubresourceRange(aspectFlags, 0, 1, 0, 1);
  116. var imageCreateInfo = new ImageViewCreateInfo()
  117. {
  118. SType = StructureType.ImageViewCreateInfo,
  119. Image = swapchainImage,
  120. ViewType = ImageViewType.Type2D,
  121. Format = format,
  122. Components = componentMapping,
  123. SubresourceRange = subresourceRange
  124. };
  125. _gd.Api.CreateImageView(_device, imageCreateInfo, null, out var imageView).ThrowOnError();
  126. return new Auto<DisposableImageView>(new DisposableImageView(_gd.Api, _device, imageView));
  127. }
  128. private static SurfaceFormatKHR ChooseSwapSurfaceFormat(SurfaceFormatKHR[] availableFormats)
  129. {
  130. if (availableFormats.Length == 1 && availableFormats[0].Format == VkFormat.Undefined)
  131. {
  132. return new SurfaceFormatKHR(VkFormat.B8G8R8A8Unorm, ColorSpaceKHR.PaceSrgbNonlinearKhr);
  133. }
  134. foreach (var format in availableFormats)
  135. {
  136. if (format.Format == VkFormat.B8G8R8A8Unorm && format.ColorSpace == ColorSpaceKHR.PaceSrgbNonlinearKhr)
  137. {
  138. return format;
  139. }
  140. }
  141. return availableFormats[0];
  142. }
  143. private static PresentModeKHR ChooseSwapPresentMode(PresentModeKHR[] availablePresentModes, bool vsyncEnabled)
  144. {
  145. if (!vsyncEnabled && availablePresentModes.Contains(PresentModeKHR.ImmediateKhr))
  146. {
  147. return PresentModeKHR.ImmediateKhr;
  148. }
  149. else if (availablePresentModes.Contains(PresentModeKHR.MailboxKhr))
  150. {
  151. return PresentModeKHR.MailboxKhr;
  152. }
  153. else if (availablePresentModes.Contains(PresentModeKHR.FifoKhr))
  154. {
  155. return PresentModeKHR.FifoKhr;
  156. }
  157. else
  158. {
  159. return PresentModeKHR.FifoKhr;
  160. }
  161. }
  162. public static Extent2D ChooseSwapExtent(SurfaceCapabilitiesKHR capabilities)
  163. {
  164. if (capabilities.CurrentExtent.Width != uint.MaxValue)
  165. {
  166. return capabilities.CurrentExtent;
  167. }
  168. else
  169. {
  170. uint width = Math.Max(capabilities.MinImageExtent.Width, Math.Min(capabilities.MaxImageExtent.Width, SurfaceWidth));
  171. uint height = Math.Max(capabilities.MinImageExtent.Height, Math.Min(capabilities.MaxImageExtent.Height, SurfaceHeight));
  172. return new Extent2D(width, height);
  173. }
  174. }
  175. public unsafe override void Present(ITexture texture, ImageCrop crop, Action swapBuffersCallback)
  176. {
  177. uint nextImage = 0;
  178. while (true)
  179. {
  180. var acquireResult = _gd.SwapchainApi.AcquireNextImage(
  181. _device,
  182. _swapchain,
  183. ulong.MaxValue,
  184. _imageAvailableSemaphore,
  185. new Fence(),
  186. ref nextImage);
  187. if (acquireResult == Result.ErrorOutOfDateKhr ||
  188. acquireResult == Result.SuboptimalKhr ||
  189. _vsyncModeChanged)
  190. {
  191. RecreateSwapchain();
  192. }
  193. else
  194. {
  195. acquireResult.ThrowOnError();
  196. break;
  197. }
  198. }
  199. var swapchainImage = _swapchainImages[nextImage];
  200. _gd.FlushAllCommands();
  201. var cbs = _gd.CommandBufferPool.Rent();
  202. Transition(
  203. cbs.CommandBuffer,
  204. swapchainImage,
  205. 0,
  206. AccessFlags.TransferWriteBit,
  207. ImageLayout.Undefined,
  208. ImageLayout.General);
  209. var view = (TextureView)texture;
  210. int srcX0, srcX1, srcY0, srcY1;
  211. float scale = view.ScaleFactor;
  212. if (crop.Left == 0 && crop.Right == 0)
  213. {
  214. srcX0 = 0;
  215. srcX1 = (int)(view.Width / scale);
  216. }
  217. else
  218. {
  219. srcX0 = crop.Left;
  220. srcX1 = crop.Right;
  221. }
  222. if (crop.Top == 0 && crop.Bottom == 0)
  223. {
  224. srcY0 = 0;
  225. srcY1 = (int)(view.Height / scale);
  226. }
  227. else
  228. {
  229. srcY0 = crop.Top;
  230. srcY1 = crop.Bottom;
  231. }
  232. if (scale != 1f)
  233. {
  234. srcX0 = (int)(srcX0 * scale);
  235. srcY0 = (int)(srcY0 * scale);
  236. srcX1 = (int)Math.Ceiling(srcX1 * scale);
  237. srcY1 = (int)Math.Ceiling(srcY1 * scale);
  238. }
  239. if (ScreenCaptureRequested)
  240. {
  241. CaptureFrame(view, srcX0, srcY0, srcX1 - srcX0, srcY1 - srcY0, view.Info.Format.IsBgr(), crop.FlipX, crop.FlipY);
  242. ScreenCaptureRequested = false;
  243. }
  244. float ratioX = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _height * crop.AspectRatioX / (_width * crop.AspectRatioY));
  245. float ratioY = crop.IsStretched ? 1.0f : MathF.Min(1.0f, _width * crop.AspectRatioY / (_height * crop.AspectRatioX));
  246. int dstWidth = (int)(_width * ratioX);
  247. int dstHeight = (int)(_height * ratioY);
  248. int dstPaddingX = (_width - dstWidth) / 2;
  249. int dstPaddingY = (_height - dstHeight) / 2;
  250. int dstX0 = crop.FlipX ? _width - dstPaddingX : dstPaddingX;
  251. int dstX1 = crop.FlipX ? dstPaddingX : _width - dstPaddingX;
  252. int dstY0 = crop.FlipY ? dstPaddingY : _height - dstPaddingY;
  253. int dstY1 = crop.FlipY ? _height - dstPaddingY : dstPaddingY;
  254. _gd.HelperShader.Blit(
  255. _gd,
  256. cbs,
  257. view,
  258. _swapchainImageViews[nextImage],
  259. _width,
  260. _height,
  261. _format,
  262. new Extents2D(srcX0, srcY0, srcX1, srcY1),
  263. new Extents2D(dstX0, dstY1, dstX1, dstY0),
  264. true,
  265. true);
  266. Transition(
  267. cbs.CommandBuffer,
  268. swapchainImage,
  269. 0,
  270. 0,
  271. ImageLayout.General,
  272. ImageLayout.PresentSrcKhr);
  273. _gd.CommandBufferPool.Return(
  274. cbs,
  275. stackalloc[] { _imageAvailableSemaphore },
  276. stackalloc[] { PipelineStageFlags.ColorAttachmentOutputBit },
  277. stackalloc[] { _renderFinishedSemaphore });
  278. // TODO: Present queue.
  279. var semaphore = _renderFinishedSemaphore;
  280. var swapchain = _swapchain;
  281. Result result;
  282. var presentInfo = new PresentInfoKHR()
  283. {
  284. SType = StructureType.PresentInfoKhr,
  285. WaitSemaphoreCount = 1,
  286. PWaitSemaphores = &semaphore,
  287. SwapchainCount = 1,
  288. PSwapchains = &swapchain,
  289. PImageIndices = &nextImage,
  290. PResults = &result
  291. };
  292. lock (_gd.QueueLock)
  293. {
  294. _gd.SwapchainApi.QueuePresent(_gd.Queue, presentInfo);
  295. }
  296. }
  297. private unsafe void Transition(
  298. CommandBuffer commandBuffer,
  299. Image image,
  300. AccessFlags srcAccess,
  301. AccessFlags dstAccess,
  302. ImageLayout srcLayout,
  303. ImageLayout dstLayout)
  304. {
  305. var subresourceRange = new ImageSubresourceRange(ImageAspectFlags.ColorBit, 0, 1, 0, 1);
  306. var barrier = new ImageMemoryBarrier()
  307. {
  308. SType = StructureType.ImageMemoryBarrier,
  309. SrcAccessMask = srcAccess,
  310. DstAccessMask = dstAccess,
  311. OldLayout = srcLayout,
  312. NewLayout = dstLayout,
  313. SrcQueueFamilyIndex = Vk.QueueFamilyIgnored,
  314. DstQueueFamilyIndex = Vk.QueueFamilyIgnored,
  315. Image = image,
  316. SubresourceRange = subresourceRange
  317. };
  318. _gd.Api.CmdPipelineBarrier(
  319. commandBuffer,
  320. PipelineStageFlags.TopOfPipeBit,
  321. PipelineStageFlags.AllCommandsBit,
  322. 0,
  323. 0,
  324. null,
  325. 0,
  326. null,
  327. 1,
  328. barrier);
  329. }
  330. private void CaptureFrame(TextureView texture, int x, int y, int width, int height, bool isBgra, bool flipX, bool flipY)
  331. {
  332. byte[] bitmap = texture.GetData(x, y, width, height);
  333. _gd.OnScreenCaptured(new ScreenCaptureImageInfo(width, height, isBgra, bitmap, flipX, flipY));
  334. }
  335. public override void SetSize(int width, int height)
  336. {
  337. // Not needed as we can get the size from the surface.
  338. }
  339. public override void ChangeVSyncMode(bool vsyncEnabled)
  340. {
  341. _vsyncEnabled = vsyncEnabled;
  342. _vsyncModeChanged = true;
  343. }
  344. protected virtual void Dispose(bool disposing)
  345. {
  346. if (disposing)
  347. {
  348. unsafe
  349. {
  350. _gd.Api.DestroySemaphore(_device, _renderFinishedSemaphore, null);
  351. _gd.Api.DestroySemaphore(_device, _imageAvailableSemaphore, null);
  352. for (int i = 0; i < _swapchainImageViews.Length; i++)
  353. {
  354. _swapchainImageViews[i].Dispose();
  355. }
  356. _gd.SwapchainApi.DestroySwapchain(_device, _swapchain, null);
  357. }
  358. }
  359. }
  360. public override void Dispose()
  361. {
  362. Dispose(true);
  363. }
  364. }
  365. }