RendererWidgetBase.cs 18 KB

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