RendererWidgetBase.cs 21 KB

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