RendererWidgetBase.cs 21 KB

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