RendererWidgetBase.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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)
  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 = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyPictures), "Ryujinx");
  255. string path = System.IO.Path.Combine(directory, filename);
  256. Directory.CreateDirectory(directory);
  257. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  258. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  259. if (e.FlipX)
  260. {
  261. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  262. }
  263. if (e.FlipY)
  264. {
  265. image.Mutate(x => x.Flip(FlipMode.Vertical));
  266. }
  267. image.SaveAsPng(path, new PngEncoder()
  268. {
  269. ColorType = PngColorType.Rgb
  270. });
  271. image.Dispose();
  272. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  273. }
  274. });
  275. }
  276. }
  277. public void Render()
  278. {
  279. Gtk.Window parent = Toplevel as Gtk.Window;
  280. parent.Present();
  281. InitializeRenderer();
  282. Device.Gpu.Renderer.Initialize(_glLogLevel);
  283. _gpuVendorName = GetGpuVendorName();
  284. Device.Gpu.InitializeShaderCache();
  285. Translator.IsReadyForTranslation.Set();
  286. while (_isActive)
  287. {
  288. if (_isStopped)
  289. {
  290. return;
  291. }
  292. _ticks += _chrono.ElapsedTicks;
  293. _chrono.Restart();
  294. if (Device.WaitFifo())
  295. {
  296. Device.Statistics.RecordFifoStart();
  297. Device.ProcessFrame();
  298. Device.Statistics.RecordFifoEnd();
  299. }
  300. while (Device.ConsumeFrameAvailable())
  301. {
  302. Device.PresentFrame(SwapBuffers);
  303. }
  304. if (_ticks >= _ticksPerFrame)
  305. {
  306. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? "Docked" : "Handheld";
  307. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  308. if (scale != 1)
  309. {
  310. dockedMode += $" ({scale}x)";
  311. }
  312. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  313. Device.EnableDeviceVsync,
  314. dockedMode,
  315. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  316. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS",
  317. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  318. $"GPU: {_gpuVendorName}"));
  319. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  320. }
  321. }
  322. }
  323. public void Start()
  324. {
  325. _chrono.Restart();
  326. _isActive = true;
  327. Gtk.Window parent = Toplevel as Gtk.Window;
  328. Application.Invoke(delegate
  329. {
  330. parent.Present();
  331. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  332. : $" - {Device.Application.TitleName}";
  333. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  334. : $" v{Device.Application.DisplayVersion}";
  335. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  336. : $" ({Device.Application.TitleIdText.ToUpper()})";
  337. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  338. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  339. });
  340. Thread renderLoopThread = new Thread(Render)
  341. {
  342. Name = "GUI.RenderLoop"
  343. };
  344. renderLoopThread.Start();
  345. Thread nvStutterWorkaround = new Thread(NVStutterWorkaround)
  346. {
  347. Name = "GUI.NVStutterWorkaround"
  348. };
  349. nvStutterWorkaround.Start();
  350. MainLoop();
  351. renderLoopThread.Join();
  352. nvStutterWorkaround.Join();
  353. Exit();
  354. }
  355. public void Exit()
  356. {
  357. TouchScreenManager?.Dispose();
  358. NpadManager?.Dispose();
  359. if (_isStopped)
  360. {
  361. return;
  362. }
  363. _isStopped = true;
  364. _isActive = false;
  365. _exitEvent.WaitOne();
  366. _exitEvent.Dispose();
  367. }
  368. private void NVStutterWorkaround()
  369. {
  370. while (_isActive)
  371. {
  372. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  373. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  374. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  375. // This creates a new thread every second or so.
  376. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  377. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  378. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  379. // TODO: This should be removed when the issue with the GateThread is resolved.
  380. ThreadPool.QueueUserWorkItem((state) => { });
  381. Thread.Sleep(300);
  382. }
  383. }
  384. public void MainLoop()
  385. {
  386. while (_isActive)
  387. {
  388. UpdateFrame();
  389. // Polling becomes expensive if it's not slept
  390. Thread.Sleep(1);
  391. }
  392. _exitEvent.Set();
  393. }
  394. private bool UpdateFrame()
  395. {
  396. if (!_isActive)
  397. {
  398. return true;
  399. }
  400. if (_isStopped)
  401. {
  402. return false;
  403. }
  404. if ((Toplevel as MainWindow).IsFocused)
  405. {
  406. Application.Invoke(delegate
  407. {
  408. KeyboardStateSnapshot keyboard = _keyboardInterface.GetKeyboardStateSnapshot();
  409. HandleScreenState(keyboard);
  410. if (keyboard.IsPressed(Key.Delete))
  411. {
  412. if (!ParentWindow.State.HasFlag(WindowState.Fullscreen))
  413. {
  414. Ptc.Continue();
  415. }
  416. }
  417. });
  418. }
  419. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  420. if ((Toplevel as MainWindow).IsFocused)
  421. {
  422. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  423. if (currentHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync) &&
  424. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.ToggleVSync))
  425. {
  426. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  427. }
  428. if ((currentHotkeyState.HasFlag(KeyboardHotkeyState.Screenshot) &&
  429. !_prevHotkeyState.HasFlag(KeyboardHotkeyState.Screenshot)) || ScreenshotRequested)
  430. {
  431. ScreenshotRequested = false;
  432. Renderer.Screenshot();
  433. }
  434. _prevHotkeyState = currentHotkeyState;
  435. }
  436. // Touchscreen
  437. bool hasTouch = false;
  438. // Get screen touch position
  439. if ((Toplevel as MainWindow).IsFocused && !ConfigurationState.Instance.Hid.EnableMouse)
  440. {
  441. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as GTK3MouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  442. }
  443. if (!hasTouch)
  444. {
  445. TouchScreenManager.Update(false);
  446. }
  447. Device.Hid.DebugPad.Update();
  448. return true;
  449. }
  450. [Flags]
  451. private enum KeyboardHotkeyState
  452. {
  453. None,
  454. ToggleVSync,
  455. Screenshot
  456. }
  457. private KeyboardHotkeyState GetHotkeyState()
  458. {
  459. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  460. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  461. {
  462. state |= KeyboardHotkeyState.ToggleVSync;
  463. }
  464. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  465. {
  466. state |= KeyboardHotkeyState.Screenshot;
  467. }
  468. return state;
  469. }
  470. }
  471. }