Window.cs 15 KB

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