Window.cs 15 KB

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