RendererWidgetBase.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using Gdk;
  4. using Gtk;
  5. using Ryujinx.Common;
  6. using Ryujinx.Common.Configuration;
  7. using Ryujinx.Common.Logging;
  8. using Ryujinx.Configuration;
  9. using Ryujinx.Graphics.GAL;
  10. using Ryujinx.Graphics.GAL.Multithreading;
  11. using Ryujinx.Input;
  12. using Ryujinx.Input.GTK3;
  13. using Ryujinx.Input.HLE;
  14. using Ryujinx.Ui.Widgets;
  15. using SixLabors.ImageSharp;
  16. using SixLabors.ImageSharp.Formats.Png;
  17. using SixLabors.ImageSharp.PixelFormats;
  18. using SixLabors.ImageSharp.Processing;
  19. using System;
  20. using System.Diagnostics;
  21. using System.IO;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. namespace Ryujinx.Ui
  25. {
  26. using Image = SixLabors.ImageSharp.Image;
  27. using Key = Input.Key;
  28. using Switch = HLE.Switch;
  29. public abstract class RendererWidgetBase : DrawingArea
  30. {
  31. private const int SwitchPanelWidth = 1280;
  32. private const int SwitchPanelHeight = 720;
  33. private const int TargetFps = 60;
  34. public ManualResetEvent WaitEvent { get; set; }
  35. public NpadManager NpadManager { get; }
  36. public TouchScreenManager TouchScreenManager { get; }
  37. public Switch Device { get; private set; }
  38. public IRenderer Renderer { get; private set; }
  39. public bool ScreenshotRequested { get; set; }
  40. public static event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  41. private bool _isActive;
  42. private bool _isStopped;
  43. private bool _toggleFullscreen;
  44. private bool _toggleDockedMode;
  45. private readonly long _ticksPerFrame;
  46. private long _ticks = 0;
  47. private readonly Stopwatch _chrono;
  48. private KeyboardHotkeyState _prevHotkeyState;
  49. private readonly ManualResetEvent _exitEvent;
  50. // Hide Cursor
  51. const int CursorHideIdleTime = 8; // seconds
  52. private static readonly Cursor _invisibleCursor = new Cursor(Display.Default, CursorType.BlankCursor);
  53. private long _lastCursorMoveTime;
  54. private bool _hideCursorOnIdle;
  55. private InputManager _inputManager;
  56. private IKeyboard _keyboardInterface;
  57. private GraphicsDebugLevel _glLogLevel;
  58. private string _gpuVendorName;
  59. private int _windowHeight;
  60. private int _windowWidth;
  61. private bool _isMouseInClient;
  62. public RendererWidgetBase(InputManager inputManager, GraphicsDebugLevel glLogLevel)
  63. {
  64. var mouseDriver = new GTK3MouseDriver(this);
  65. _inputManager = inputManager;
  66. _inputManager.SetMouseDriver(mouseDriver);
  67. NpadManager = _inputManager.CreateNpadManager();
  68. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  69. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  70. WaitEvent = new ManualResetEvent(false);
  71. _glLogLevel = glLogLevel;
  72. Destroyed += Renderer_Destroyed;
  73. _chrono = new Stopwatch();
  74. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  75. AddEvents((int)(EventMask.ButtonPressMask
  76. | EventMask.ButtonReleaseMask
  77. | EventMask.PointerMotionMask
  78. | EventMask.ScrollMask
  79. | EventMask.EnterNotifyMask
  80. | EventMask.LeaveNotifyMask
  81. | EventMask.KeyPressMask
  82. | EventMask.KeyReleaseMask));
  83. _exitEvent = new ManualResetEvent(false);
  84. _hideCursorOnIdle = ConfigurationState.Instance.HideCursorOnIdle;
  85. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  86. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorStateChanged;
  87. }
  88. public abstract void InitializeRenderer();
  89. public abstract void SwapBuffers();
  90. public abstract string GetGpuVendorName();
  91. private void HideCursorStateChanged(object sender, ReactiveEventArgs<bool> state)
  92. {
  93. Gtk.Application.Invoke(delegate
  94. {
  95. _hideCursorOnIdle = state.NewValue;
  96. if (_hideCursorOnIdle)
  97. {
  98. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  99. }
  100. else
  101. {
  102. Window.Cursor = null;
  103. }
  104. });
  105. }
  106. private void Renderer_Destroyed(object sender, EventArgs e)
  107. {
  108. ConfigurationState.Instance.HideCursorOnIdle.Event -= HideCursorStateChanged;
  109. NpadManager.Dispose();
  110. Dispose();
  111. }
  112. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  113. {
  114. if (_hideCursorOnIdle)
  115. {
  116. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  117. }
  118. if (ConfigurationState.Instance.Hid.EnableMouse)
  119. {
  120. Window.Cursor = _invisibleCursor;
  121. }
  122. _isMouseInClient = true;
  123. return false;
  124. }
  125. protected override bool OnEnterNotifyEvent(EventCrossing evnt)
  126. {
  127. Window.Cursor = ConfigurationState.Instance.Hid.EnableMouse ? _invisibleCursor : null;
  128. _isMouseInClient = true;
  129. return base.OnEnterNotifyEvent(evnt);
  130. }
  131. protected override bool OnLeaveNotifyEvent(EventCrossing evnt)
  132. {
  133. Window.Cursor = null;
  134. _isMouseInClient = false;
  135. return base.OnLeaveNotifyEvent(evnt);
  136. }
  137. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  138. {
  139. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  140. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  141. if (monitor.Geometry.Height >= 1080)
  142. {
  143. minimumHeight = SwitchPanelHeight;
  144. }
  145. // Otherwise, we default minimal size to 480p 16:9.
  146. else
  147. {
  148. minimumHeight = 480;
  149. }
  150. naturalHeight = minimumHeight;
  151. }
  152. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  153. {
  154. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  155. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  156. if (monitor.Geometry.Height >= 1080)
  157. {
  158. minimumWidth = SwitchPanelWidth;
  159. }
  160. // Otherwise, we default minimal size to 480p 16:9.
  161. else
  162. {
  163. minimumWidth = 854;
  164. }
  165. naturalWidth = minimumWidth;
  166. }
  167. protected override bool OnConfigureEvent(EventConfigure evnt)
  168. {
  169. bool result = base.OnConfigureEvent(evnt);
  170. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  171. _windowWidth = evnt.Width * monitor.ScaleFactor;
  172. _windowHeight = evnt.Height * monitor.ScaleFactor;
  173. Renderer?.Window.SetSize(_windowWidth, _windowHeight);
  174. return result;
  175. }
  176. private void HandleScreenState(KeyboardStateSnapshot keyboard)
  177. {
  178. bool toggleFullscreen = keyboard.IsPressed(Key.F11)
  179. || ((keyboard.IsPressed(Key.AltLeft)
  180. || keyboard.IsPressed(Key.AltRight))
  181. && keyboard.IsPressed(Key.Enter))
  182. || keyboard.IsPressed(Key.Escape);
  183. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  184. if (toggleFullscreen != _toggleFullscreen)
  185. {
  186. if (toggleFullscreen)
  187. {
  188. if (fullScreenToggled)
  189. {
  190. ParentWindow.Unfullscreen();
  191. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  192. }
  193. else
  194. {
  195. if (keyboard.IsPressed(Key.Escape))
  196. {
  197. if (!ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  198. {
  199. Exit();
  200. }
  201. }
  202. else
  203. {
  204. ParentWindow.Fullscreen();
  205. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  206. }
  207. }
  208. }
  209. }
  210. _toggleFullscreen = toggleFullscreen;
  211. bool toggleDockedMode = keyboard.IsPressed(Key.F9);
  212. if (toggleDockedMode != _toggleDockedMode)
  213. {
  214. if (toggleDockedMode)
  215. {
  216. ConfigurationState.Instance.System.EnableDockedMode.Value =
  217. !ConfigurationState.Instance.System.EnableDockedMode.Value;
  218. }
  219. }
  220. _toggleDockedMode = toggleDockedMode;
  221. if (_hideCursorOnIdle && !ConfigurationState.Instance.Hid.EnableMouse)
  222. {
  223. long cursorMoveDelta = Stopwatch.GetTimestamp() - _lastCursorMoveTime;
  224. Window.Cursor = (cursorMoveDelta >= CursorHideIdleTime * Stopwatch.Frequency) ? _invisibleCursor : null;
  225. }
  226. if(ConfigurationState.Instance.Hid.EnableMouse && _isMouseInClient)
  227. {
  228. Window.Cursor = _invisibleCursor;
  229. }
  230. }
  231. public void Initialize(Switch device)
  232. {
  233. Device = device;
  234. IRenderer renderer = Device.Gpu.Renderer;
  235. if (renderer is ThreadedRenderer tr)
  236. {
  237. renderer = tr.BaseRenderer;
  238. }
  239. Renderer = renderer;
  240. Renderer?.Window.SetSize(_windowWidth, _windowHeight);
  241. if (Renderer != null)
  242. {
  243. Renderer.ScreenCaptured += Renderer_ScreenCaptured;
  244. }
  245. NpadManager.Initialize(device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  246. TouchScreenManager.Initialize(device);
  247. }
  248. private unsafe void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  249. {
  250. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  251. {
  252. Task.Run(() =>
  253. {
  254. lock (this)
  255. {
  256. var currentTime = DateTime.Now;
  257. string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png";
  258. string directory = AppDataManager.Mode switch
  259. {
  260. AppDataManager.LaunchMode.Portable => System.IO.Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  261. _ => System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures), "Ryujinx")
  262. };
  263. string path = System.IO.Path.Combine(directory, filename);
  264. try
  265. {
  266. Directory.CreateDirectory(directory);
  267. }
  268. catch (Exception ex)
  269. {
  270. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  271. return;
  272. }
  273. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  274. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  275. if (e.FlipX)
  276. {
  277. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  278. }
  279. if (e.FlipY)
  280. {
  281. image.Mutate(x => x.Flip(FlipMode.Vertical));
  282. }
  283. image.SaveAsPng(path, new PngEncoder()
  284. {
  285. ColorType = PngColorType.Rgb
  286. });
  287. image.Dispose();
  288. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  289. }
  290. });
  291. }
  292. else
  293. {
  294. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  295. }
  296. }
  297. public void Render()
  298. {
  299. Gtk.Window parent = Toplevel as Gtk.Window;
  300. parent.Present();
  301. InitializeRenderer();
  302. Device.Gpu.Renderer.Initialize(_glLogLevel);
  303. _gpuVendorName = GetGpuVendorName();
  304. Device.Gpu.Renderer.RunLoop(() =>
  305. {
  306. Device.Gpu.InitializeShaderCache();
  307. Translator.IsReadyForTranslation.Set();
  308. (Toplevel as MainWindow)?.ActivatePauseMenu();
  309. while (_isActive)
  310. {
  311. if (_isStopped)
  312. {
  313. return;
  314. }
  315. _ticks += _chrono.ElapsedTicks;
  316. _chrono.Restart();
  317. if (Device.WaitFifo())
  318. {
  319. Device.Statistics.RecordFifoStart();
  320. Device.ProcessFrame();
  321. Device.Statistics.RecordFifoEnd();
  322. }
  323. while (Device.ConsumeFrameAvailable())
  324. {
  325. Device.PresentFrame(SwapBuffers);
  326. }
  327. if (_ticks >= _ticksPerFrame)
  328. {
  329. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? "Docked" : "Handheld";
  330. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  331. if (scale != 1)
  332. {
  333. dockedMode += $" ({scale}x)";
  334. }
  335. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  336. Device.EnableDeviceVsync,
  337. dockedMode,
  338. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  339. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  340. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  341. $"GPU: {_gpuVendorName}"));
  342. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  343. }
  344. }
  345. });
  346. }
  347. public void Start()
  348. {
  349. _chrono.Restart();
  350. _isActive = true;
  351. Gtk.Window parent = Toplevel as Gtk.Window;
  352. Application.Invoke(delegate
  353. {
  354. parent.Present();
  355. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  356. : $" - {Device.Application.TitleName}";
  357. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  358. : $" v{Device.Application.DisplayVersion}";
  359. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  360. : $" ({Device.Application.TitleIdText.ToUpper()})";
  361. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  362. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  363. });
  364. Thread renderLoopThread = new Thread(Render)
  365. {
  366. Name = "GUI.RenderLoop"
  367. };
  368. renderLoopThread.Start();
  369. Thread nvStutterWorkaround = null;
  370. if (Renderer is Graphics.OpenGL.Renderer)
  371. {
  372. nvStutterWorkaround = new Thread(NVStutterWorkaround)
  373. {
  374. Name = "GUI.NVStutterWorkaround"
  375. };
  376. nvStutterWorkaround.Start();
  377. }
  378. MainLoop();
  379. renderLoopThread.Join();
  380. nvStutterWorkaround?.Join();
  381. Exit();
  382. }
  383. public void Exit()
  384. {
  385. TouchScreenManager?.Dispose();
  386. NpadManager?.Dispose();
  387. if (_isStopped)
  388. {
  389. return;
  390. }
  391. _isStopped = true;
  392. _isActive = false;
  393. _exitEvent.WaitOne();
  394. _exitEvent.Dispose();
  395. }
  396. private void NVStutterWorkaround()
  397. {
  398. while (_isActive)
  399. {
  400. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  401. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  402. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  403. // This creates a new thread every second or so.
  404. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  405. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  406. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  407. // TODO: This should be removed when the issue with the GateThread is resolved.
  408. ThreadPool.QueueUserWorkItem((state) => { });
  409. Thread.Sleep(300);
  410. }
  411. }
  412. public void MainLoop()
  413. {
  414. while (_isActive)
  415. {
  416. UpdateFrame();
  417. // Polling becomes expensive if it's not slept
  418. Thread.Sleep(1);
  419. }
  420. _exitEvent.Set();
  421. }
  422. private bool UpdateFrame()
  423. {
  424. if (!_isActive)
  425. {
  426. return true;
  427. }
  428. if (_isStopped)
  429. {
  430. return false;
  431. }
  432. if ((Toplevel as MainWindow).IsFocused)
  433. {
  434. Application.Invoke(delegate
  435. {
  436. KeyboardStateSnapshot keyboard = _keyboardInterface.GetKeyboardStateSnapshot();
  437. HandleScreenState(keyboard);
  438. if (keyboard.IsPressed(Key.Delete))
  439. {
  440. if (!ParentWindow.State.HasFlag(WindowState.Fullscreen))
  441. {
  442. Ptc.Continue();
  443. }
  444. }
  445. });
  446. }
  447. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  448. if ((Toplevel as MainWindow).IsFocused)
  449. {
  450. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  451. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync) &&
  452. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync))
  453. {
  454. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  455. }
  456. if ((currentHotkeyState.HasFlag(KeyboardHotkeyState.Screenshot) &&
  457. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.Screenshot)) || ScreenshotRequested)
  458. {
  459. ScreenshotRequested = false;
  460. Renderer.Screenshot();
  461. }
  462. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ShowUi) &&
  463. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ShowUi))
  464. {
  465. (Toplevel as MainWindow).ToggleExtraWidgets(true);
  466. }
  467. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.Pause) &&
  468. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.Pause))
  469. {
  470. (Toplevel as MainWindow)?.TogglePause();
  471. }
  472. _prevHotkeyState = currentHotkeyState;
  473. }
  474. // Touchscreen
  475. bool hasTouch = false;
  476. // Get screen touch position
  477. if ((Toplevel as MainWindow).IsFocused && !ConfigurationState.Instance.Hid.EnableMouse)
  478. {
  479. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as GTK3MouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  480. }
  481. if (!hasTouch)
  482. {
  483. TouchScreenManager.Update(false);
  484. }
  485. Device.Hid.DebugPad.Update();
  486. return true;
  487. }
  488. [Flags]
  489. private enum KeyboardHotkeyState
  490. {
  491. None = 0,
  492. ToggleVSync = 1 << 0,
  493. Screenshot = 1 << 1,
  494. ShowUi = 1 << 2,
  495. Pause = 1 << 3
  496. }
  497. private KeyboardHotkeyState GetHotkeyState()
  498. {
  499. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  500. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  501. {
  502. state |= KeyboardHotkeyState.ToggleVSync;
  503. }
  504. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  505. {
  506. state |= KeyboardHotkeyState.Screenshot;
  507. }
  508. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi))
  509. {
  510. state |= KeyboardHotkeyState.ShowUi;
  511. }
  512. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  513. {
  514. state |= KeyboardHotkeyState.Pause;
  515. }
  516. return state;
  517. }
  518. }
  519. }