RendererWidgetBase.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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.Configuration;
  8. using Ryujinx.Graphics.GAL;
  9. using Ryujinx.HLE.HOS.Services.Hid;
  10. using Ryujinx.Input;
  11. using Ryujinx.Input.GTK3;
  12. using Ryujinx.Input.HLE;
  13. using Ryujinx.Ui.Widgets;
  14. using System;
  15. using System.Diagnostics;
  16. using System.Linq;
  17. using System.Threading;
  18. namespace Ryujinx.Ui
  19. {
  20. using Key = Input.Key;
  21. using Switch = HLE.Switch;
  22. public abstract class RendererWidgetBase : DrawingArea
  23. {
  24. private const int SwitchPanelWidth = 1280;
  25. private const int SwitchPanelHeight = 720;
  26. private const int TargetFps = 60;
  27. public ManualResetEvent WaitEvent { get; set; }
  28. public NpadManager NpadManager { get; }
  29. public TouchScreenManager TouchScreenManager { get; }
  30. public Switch Device { get; private set; }
  31. public IRenderer Renderer { get; private set; }
  32. public static event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  33. private bool _isActive;
  34. private bool _isStopped;
  35. private bool _toggleFullscreen;
  36. private bool _toggleDockedMode;
  37. private readonly long _ticksPerFrame;
  38. private long _ticks = 0;
  39. private readonly Stopwatch _chrono;
  40. private KeyboardHotkeyState _prevHotkeyState;
  41. private readonly ManualResetEvent _exitEvent;
  42. // Hide Cursor
  43. const int CursorHideIdleTime = 8; // seconds
  44. private static readonly Cursor _invisibleCursor = new Cursor(Display.Default, CursorType.BlankCursor);
  45. private long _lastCursorMoveTime;
  46. private bool _hideCursorOnIdle;
  47. private InputManager _inputManager;
  48. private IKeyboard _keyboardInterface;
  49. private GraphicsDebugLevel _glLogLevel;
  50. private string _gpuVendorName;
  51. private int _windowHeight;
  52. private int _windowWidth;
  53. public RendererWidgetBase(InputManager inputManager, GraphicsDebugLevel glLogLevel)
  54. {
  55. var mouseDriver = new GTK3MouseDriver(this);
  56. _inputManager = inputManager;
  57. _inputManager.SetMouseDriver(mouseDriver);
  58. NpadManager = _inputManager.CreateNpadManager();
  59. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  60. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  61. WaitEvent = new ManualResetEvent(false);
  62. _glLogLevel = glLogLevel;
  63. Destroyed += Renderer_Destroyed;
  64. _chrono = new Stopwatch();
  65. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  66. AddEvents((int)(EventMask.ButtonPressMask
  67. | EventMask.ButtonReleaseMask
  68. | EventMask.PointerMotionMask
  69. | EventMask.KeyPressMask
  70. | EventMask.KeyReleaseMask));
  71. _exitEvent = new ManualResetEvent(false);
  72. _hideCursorOnIdle = ConfigurationState.Instance.HideCursorOnIdle;
  73. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  74. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorStateChanged;
  75. }
  76. public abstract void InitializeRenderer();
  77. public abstract void SwapBuffers();
  78. public abstract string GetGpuVendorName();
  79. private void HideCursorStateChanged(object sender, ReactiveEventArgs<bool> state)
  80. {
  81. Gtk.Application.Invoke(delegate
  82. {
  83. _hideCursorOnIdle = state.NewValue;
  84. if (_hideCursorOnIdle)
  85. {
  86. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  87. }
  88. else
  89. {
  90. Window.Cursor = null;
  91. }
  92. });
  93. }
  94. private void Renderer_Destroyed(object sender, EventArgs e)
  95. {
  96. ConfigurationState.Instance.HideCursorOnIdle.Event -= HideCursorStateChanged;
  97. NpadManager.Dispose();
  98. Dispose();
  99. }
  100. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  101. {
  102. if (_hideCursorOnIdle)
  103. {
  104. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  105. }
  106. return false;
  107. }
  108. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  109. {
  110. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  111. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  112. if (monitor.Geometry.Height >= 1080)
  113. {
  114. minimumHeight = SwitchPanelHeight;
  115. }
  116. // Otherwise, we default minimal size to 480p 16:9.
  117. else
  118. {
  119. minimumHeight = 480;
  120. }
  121. naturalHeight = minimumHeight;
  122. }
  123. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  124. {
  125. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  126. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  127. if (monitor.Geometry.Height >= 1080)
  128. {
  129. minimumWidth = SwitchPanelWidth;
  130. }
  131. // Otherwise, we default minimal size to 480p 16:9.
  132. else
  133. {
  134. minimumWidth = 854;
  135. }
  136. naturalWidth = minimumWidth;
  137. }
  138. protected override bool OnConfigureEvent(EventConfigure evnt)
  139. {
  140. bool result = base.OnConfigureEvent(evnt);
  141. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  142. _windowWidth = evnt.Width * monitor.ScaleFactor;
  143. _windowHeight = evnt.Height * monitor.ScaleFactor;
  144. Renderer?.Window.SetSize(_windowWidth, _windowHeight);
  145. return result;
  146. }
  147. private void HandleScreenState(KeyboardStateSnapshot keyboard)
  148. {
  149. bool toggleFullscreen = keyboard.IsPressed(Key.F11)
  150. || ((keyboard.IsPressed(Key.AltLeft)
  151. || keyboard.IsPressed(Key.AltRight))
  152. && keyboard.IsPressed(Key.Enter))
  153. || keyboard.IsPressed(Key.Escape);
  154. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  155. if (toggleFullscreen != _toggleFullscreen)
  156. {
  157. if (toggleFullscreen)
  158. {
  159. if (fullScreenToggled)
  160. {
  161. ParentWindow.Unfullscreen();
  162. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  163. }
  164. else
  165. {
  166. if (keyboard.IsPressed(Key.Escape))
  167. {
  168. if (!ConfigurationState.Instance.ShowConfirmExit || GtkDialog.CreateExitDialog())
  169. {
  170. Exit();
  171. }
  172. }
  173. else
  174. {
  175. ParentWindow.Fullscreen();
  176. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  177. }
  178. }
  179. }
  180. }
  181. _toggleFullscreen = toggleFullscreen;
  182. bool toggleDockedMode = keyboard.IsPressed(Key.F9);
  183. if (toggleDockedMode != _toggleDockedMode)
  184. {
  185. if (toggleDockedMode)
  186. {
  187. ConfigurationState.Instance.System.EnableDockedMode.Value =
  188. !ConfigurationState.Instance.System.EnableDockedMode.Value;
  189. }
  190. }
  191. _toggleDockedMode = toggleDockedMode;
  192. if (_hideCursorOnIdle)
  193. {
  194. long cursorMoveDelta = Stopwatch.GetTimestamp() - _lastCursorMoveTime;
  195. Window.Cursor = (cursorMoveDelta >= CursorHideIdleTime * Stopwatch.Frequency) ? _invisibleCursor : null;
  196. }
  197. }
  198. public void Initialize(Switch device)
  199. {
  200. Device = device;
  201. Renderer = Device.Gpu.Renderer;
  202. Renderer?.Window.SetSize(_windowWidth, _windowHeight);
  203. NpadManager.Initialize(device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard);
  204. TouchScreenManager.Initialize(device);
  205. }
  206. public void Render()
  207. {
  208. Gtk.Window parent = Toplevel as Gtk.Window;
  209. parent.Present();
  210. InitializeRenderer();
  211. Device.Gpu.Renderer.Initialize(_glLogLevel);
  212. _gpuVendorName = GetGpuVendorName();
  213. Device.Gpu.InitializeShaderCache();
  214. Translator.IsReadyForTranslation.Set();
  215. while (_isActive)
  216. {
  217. if (_isStopped)
  218. {
  219. return;
  220. }
  221. _ticks += _chrono.ElapsedTicks;
  222. _chrono.Restart();
  223. if (Device.WaitFifo())
  224. {
  225. Device.Statistics.RecordFifoStart();
  226. Device.ProcessFrame();
  227. Device.Statistics.RecordFifoEnd();
  228. }
  229. while (Device.ConsumeFrameAvailable())
  230. {
  231. Device.PresentFrame(SwapBuffers);
  232. }
  233. if (_ticks >= _ticksPerFrame)
  234. {
  235. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? "Docked" : "Handheld";
  236. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  237. if (scale != 1)
  238. {
  239. dockedMode += $" ({scale}x)";
  240. }
  241. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  242. Device.EnableDeviceVsync,
  243. dockedMode,
  244. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  245. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS",
  246. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  247. $"GPU: {_gpuVendorName}"));
  248. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  249. }
  250. }
  251. }
  252. public void Start()
  253. {
  254. _chrono.Restart();
  255. _isActive = true;
  256. Gtk.Window parent = Toplevel as Gtk.Window;
  257. Application.Invoke(delegate
  258. {
  259. parent.Present();
  260. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  261. : $" - {Device.Application.TitleName}";
  262. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  263. : $" v{Device.Application.DisplayVersion}";
  264. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  265. : $" ({Device.Application.TitleIdText.ToUpper()})";
  266. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  267. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  268. });
  269. Thread renderLoopThread = new Thread(Render)
  270. {
  271. Name = "GUI.RenderLoop"
  272. };
  273. renderLoopThread.Start();
  274. Thread nvStutterWorkaround = new Thread(NVStutterWorkaround)
  275. {
  276. Name = "GUI.NVStutterWorkaround"
  277. };
  278. nvStutterWorkaround.Start();
  279. MainLoop();
  280. renderLoopThread.Join();
  281. nvStutterWorkaround.Join();
  282. Exit();
  283. }
  284. public void Exit()
  285. {
  286. TouchScreenManager?.Dispose();
  287. NpadManager?.Dispose();
  288. if (_isStopped)
  289. {
  290. return;
  291. }
  292. _isStopped = true;
  293. _isActive = false;
  294. _exitEvent.WaitOne();
  295. _exitEvent.Dispose();
  296. }
  297. private void NVStutterWorkaround()
  298. {
  299. while (_isActive)
  300. {
  301. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  302. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  303. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  304. // This creates a new thread every second or so.
  305. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  306. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  307. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  308. // TODO: This should be removed when the issue with the GateThread is resolved.
  309. ThreadPool.QueueUserWorkItem((state) => { });
  310. Thread.Sleep(300);
  311. }
  312. }
  313. public void MainLoop()
  314. {
  315. while (_isActive)
  316. {
  317. UpdateFrame();
  318. // Polling becomes expensive if it's not slept
  319. Thread.Sleep(1);
  320. }
  321. _exitEvent.Set();
  322. }
  323. private bool UpdateFrame()
  324. {
  325. if (!_isActive)
  326. {
  327. return true;
  328. }
  329. if (_isStopped)
  330. {
  331. return false;
  332. }
  333. if ((Toplevel as MainWindow).IsFocused)
  334. {
  335. Application.Invoke(delegate
  336. {
  337. KeyboardStateSnapshot keyboard = _keyboardInterface.GetKeyboardStateSnapshot();
  338. HandleScreenState(keyboard);
  339. if (keyboard.IsPressed(Key.Delete))
  340. {
  341. if (!ParentWindow.State.HasFlag(WindowState.Fullscreen))
  342. {
  343. Ptc.Continue();
  344. }
  345. }
  346. });
  347. }
  348. NpadManager.Update();
  349. if ((Toplevel as MainWindow).IsFocused)
  350. {
  351. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  352. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync) &&
  353. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync))
  354. {
  355. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  356. }
  357. _prevHotkeyState = currentHotkeyState;
  358. }
  359. // Touchscreen
  360. bool hasTouch = false;
  361. // Get screen touch position
  362. if ((Toplevel as MainWindow).IsFocused)
  363. {
  364. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as GTK3MouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  365. }
  366. if (!hasTouch)
  367. {
  368. TouchScreenManager.Update(false);
  369. }
  370. Device.Hid.DebugPad.Update();
  371. return true;
  372. }
  373. [Flags]
  374. private enum KeyboardHotkeyState
  375. {
  376. None,
  377. ToggleVSync
  378. }
  379. private KeyboardHotkeyState GetHotkeyState()
  380. {
  381. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  382. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  383. {
  384. state |= KeyboardHotkeyState.ToggleVSync;
  385. }
  386. return state;
  387. }
  388. }
  389. }