GLRenderer.cs 20 KB

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