GLRenderer.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using Gdk;
  4. using OpenTK;
  5. using OpenTK.Graphics;
  6. using OpenTK.Graphics.OpenGL;
  7. using OpenTK.Input;
  8. using Ryujinx.Configuration;
  9. using Ryujinx.Common.Configuration;
  10. using Ryujinx.Common.Configuration.Hid;
  11. using Ryujinx.Graphics.OpenGL;
  12. using Ryujinx.HLE;
  13. using Ryujinx.HLE.HOS.Services.Hid;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Threading;
  17. using Ryujinx.Motion;
  18. namespace Ryujinx.Ui
  19. {
  20. public class GlRenderer : GLWidget
  21. {
  22. static GlRenderer()
  23. {
  24. OpenTK.Graphics.GraphicsContext.ShareContexts = true;
  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 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 System.Diagnostics.Stopwatch _chrono;
  42. private readonly Switch _device;
  43. private Renderer _renderer;
  44. private HotkeyButtons _prevHotkeyButtons;
  45. private Client _dsuClient;
  46. private GraphicsDebugLevel _glLogLevel;
  47. private readonly ManualResetEvent _exitEvent;
  48. public GlRenderer(Switch device, GraphicsDebugLevel glLogLevel)
  49. : base (GetGraphicsMode(),
  50. 3, 3,
  51. glLogLevel == GraphicsDebugLevel.None
  52. ? GraphicsContextFlags.ForwardCompatible
  53. : GraphicsContextFlags.ForwardCompatible | GraphicsContextFlags.Debug)
  54. {
  55. WaitEvent = new ManualResetEvent(false);
  56. _device = device;
  57. this.Initialized += GLRenderer_Initialized;
  58. this.Destroyed += GLRenderer_Destroyed;
  59. this.ShuttingDown += GLRenderer_ShuttingDown;
  60. Initialize();
  61. _chrono = new System.Diagnostics.Stopwatch();
  62. _ticksPerFrame = System.Diagnostics.Stopwatch.Frequency / TargetFps;
  63. AddEvents((int)(EventMask.ButtonPressMask
  64. | EventMask.ButtonReleaseMask
  65. | EventMask.PointerMotionMask
  66. | EventMask.KeyPressMask
  67. | EventMask.KeyReleaseMask));
  68. this.Shown += Renderer_Shown;
  69. _dsuClient = new Client();
  70. _glLogLevel = glLogLevel;
  71. _exitEvent = new ManualResetEvent(false);
  72. }
  73. private static GraphicsMode GetGraphicsMode()
  74. {
  75. return Environment.OSVersion.Platform == PlatformID.Unix ? new GraphicsMode(new ColorFormat(24)) : new GraphicsMode(new ColorFormat());
  76. }
  77. private void GLRenderer_ShuttingDown(object sender, EventArgs args)
  78. {
  79. _device.DisposeGpu();
  80. _dsuClient?.Dispose();
  81. }
  82. private void Parent_FocusOutEvent(object o, Gtk.FocusOutEventArgs args)
  83. {
  84. _isFocused = false;
  85. }
  86. private void Parent_FocusInEvent(object o, Gtk.FocusInEventArgs args)
  87. {
  88. _isFocused = true;
  89. }
  90. private void GLRenderer_Destroyed(object sender, EventArgs e)
  91. {
  92. _dsuClient?.Dispose();
  93. Dispose();
  94. }
  95. protected void Renderer_Shown(object sender, EventArgs e)
  96. {
  97. _isFocused = this.ParentWindow.State.HasFlag(Gdk.WindowState.Focused);
  98. }
  99. public void HandleScreenState(KeyboardState keyboard)
  100. {
  101. bool toggleFullscreen = keyboard.IsKeyDown(OpenTK.Input.Key.F11)
  102. || ((keyboard.IsKeyDown(OpenTK.Input.Key.AltLeft)
  103. || keyboard.IsKeyDown(OpenTK.Input.Key.AltRight))
  104. && keyboard.IsKeyDown(OpenTK.Input.Key.Enter))
  105. || keyboard.IsKeyDown(OpenTK.Input.Key.Escape);
  106. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  107. if (toggleFullscreen != _toggleFullscreen)
  108. {
  109. if (toggleFullscreen)
  110. {
  111. if (fullScreenToggled)
  112. {
  113. ParentWindow.Unfullscreen();
  114. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  115. }
  116. else
  117. {
  118. if (keyboard.IsKeyDown(OpenTK.Input.Key.Escape))
  119. {
  120. if (GtkDialog.CreateExitDialog())
  121. {
  122. Exit();
  123. }
  124. }
  125. else
  126. {
  127. ParentWindow.Fullscreen();
  128. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  129. }
  130. }
  131. }
  132. }
  133. _toggleFullscreen = toggleFullscreen;
  134. bool toggleDockedMode = keyboard.IsKeyDown(OpenTK.Input.Key.F9);
  135. if (toggleDockedMode != _toggleDockedMode)
  136. {
  137. if (toggleDockedMode)
  138. {
  139. ConfigurationState.Instance.System.EnableDockedMode.Value =
  140. !ConfigurationState.Instance.System.EnableDockedMode.Value;
  141. }
  142. }
  143. _toggleDockedMode = toggleDockedMode;
  144. }
  145. private void GLRenderer_Initialized(object sender, EventArgs e)
  146. {
  147. // Release the GL exclusivity that OpenTK gave us as we aren't going to use it in GTK Thread.
  148. GraphicsContext.MakeCurrent(null);
  149. WaitEvent.Set();
  150. }
  151. protected override bool OnConfigureEvent(EventConfigure evnt)
  152. {
  153. bool result = base.OnConfigureEvent(evnt);
  154. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  155. _renderer.Window.SetSize(evnt.Width * monitor.ScaleFactor, evnt.Height * monitor.ScaleFactor);
  156. return result;
  157. }
  158. public void Start()
  159. {
  160. IsRenderHandler = true;
  161. _chrono.Restart();
  162. _isActive = true;
  163. Gtk.Window parent = this.Toplevel as Gtk.Window;
  164. parent.FocusInEvent += Parent_FocusInEvent;
  165. parent.FocusOutEvent += Parent_FocusOutEvent;
  166. Gtk.Application.Invoke(delegate
  167. {
  168. parent.Present();
  169. string titleNameSection = string.IsNullOrWhiteSpace(_device.Application.TitleName) ? string.Empty
  170. : $" - {_device.Application.TitleName}";
  171. string titleVersionSection = string.IsNullOrWhiteSpace(_device.Application.DisplayVersion) ? string.Empty
  172. : $" v{_device.Application.DisplayVersion}";
  173. string titleIdSection = string.IsNullOrWhiteSpace(_device.Application.TitleIdText) ? string.Empty
  174. : $" ({_device.Application.TitleIdText.ToUpper()})";
  175. string titleArchSection = _device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  176. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  177. });
  178. Thread renderLoopThread = new Thread(Render)
  179. {
  180. Name = "GUI.RenderLoop"
  181. };
  182. renderLoopThread.Start();
  183. Thread nvStutterWorkaround = new Thread(NVStutterWorkaround)
  184. {
  185. Name = "GUI.NVStutterWorkaround"
  186. };
  187. nvStutterWorkaround.Start();
  188. MainLoop();
  189. renderLoopThread.Join();
  190. nvStutterWorkaround.Join();
  191. Exit();
  192. }
  193. private void NVStutterWorkaround()
  194. {
  195. while (_isActive)
  196. {
  197. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  198. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  199. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  200. // This creates a new thread every second or so.
  201. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  202. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  203. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  204. // TODO: This should be removed when the issue with the GateThread is resolved.
  205. ThreadPool.QueueUserWorkItem((state) => { });
  206. Thread.Sleep(300);
  207. }
  208. }
  209. protected override bool OnButtonPressEvent(EventButton evnt)
  210. {
  211. _mouseX = evnt.X;
  212. _mouseY = evnt.Y;
  213. if (evnt.Button == 1)
  214. {
  215. _mousePressed = true;
  216. }
  217. return false;
  218. }
  219. protected override bool OnButtonReleaseEvent(EventButton evnt)
  220. {
  221. if (evnt.Button == 1)
  222. {
  223. _mousePressed = false;
  224. }
  225. return false;
  226. }
  227. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  228. {
  229. if (evnt.Device.InputSource == InputSource.Mouse)
  230. {
  231. _mouseX = evnt.X;
  232. _mouseY = evnt.Y;
  233. }
  234. return false;
  235. }
  236. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  237. {
  238. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  239. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  240. if (monitor.Geometry.Height >= 1080)
  241. {
  242. minimumHeight = SwitchPanelHeight;
  243. }
  244. // Otherwise, we default minimal size to 480p 16:9.
  245. else
  246. {
  247. minimumHeight = 480;
  248. }
  249. naturalHeight = minimumHeight;
  250. }
  251. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  252. {
  253. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  254. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  255. if (monitor.Geometry.Height >= 1080)
  256. {
  257. minimumWidth = SwitchPanelWidth;
  258. }
  259. // Otherwise, we default minimal size to 480p 16:9.
  260. else
  261. {
  262. minimumWidth = 854;
  263. }
  264. naturalWidth = minimumWidth;
  265. }
  266. public void Exit()
  267. {
  268. _dsuClient?.Dispose();
  269. if (_isStopped)
  270. {
  271. return;
  272. }
  273. _isStopped = true;
  274. _isActive = false;
  275. _exitEvent.WaitOne();
  276. _exitEvent.Dispose();
  277. }
  278. public void Initialize()
  279. {
  280. if (!(_device.Gpu.Renderer is Renderer))
  281. {
  282. throw new NotSupportedException($"GPU renderer must be an OpenGL renderer when using {typeof(Renderer).Name}!");
  283. }
  284. _renderer = (Renderer)_device.Gpu.Renderer;
  285. }
  286. public void Render()
  287. {
  288. // First take exclusivity on the OpenGL context.
  289. _renderer.InitializeBackgroundContext(GraphicsContext);
  290. Gtk.Window parent = Toplevel as Gtk.Window;
  291. parent.Present();
  292. GraphicsContext.MakeCurrent(WindowInfo);
  293. _device.Gpu.Renderer.Initialize(_glLogLevel);
  294. // Make sure the first frame is not transparent.
  295. GL.ClearColor(OpenTK.Color.Black);
  296. GL.Clear(ClearBufferMask.ColorBufferBit);
  297. SwapBuffers();
  298. _device.Gpu.InitializeShaderCache();
  299. Translator.IsReadyForTranslation.Set();
  300. while (_isActive)
  301. {
  302. if (_isStopped)
  303. {
  304. return;
  305. }
  306. _ticks += _chrono.ElapsedTicks;
  307. _chrono.Restart();
  308. if (_device.WaitFifo())
  309. {
  310. _device.Statistics.RecordFifoStart();
  311. _device.ProcessFrame();
  312. _device.Statistics.RecordFifoEnd();
  313. }
  314. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? "Docked" : "Handheld";
  315. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  316. if (scale != 1)
  317. {
  318. dockedMode += $" ({scale}x)";
  319. }
  320. if (_ticks >= _ticksPerFrame)
  321. {
  322. _device.PresentFrame(SwapBuffers);
  323. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  324. _device.EnableDeviceVsync,
  325. dockedMode,
  326. $"Game: {_device.Statistics.GetGameFrameRate():00.00} FPS",
  327. $"FIFO: {_device.Statistics.GetFifoPercent():0.00} %",
  328. $"GPU: {_renderer.GpuVendor}"));
  329. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  330. }
  331. }
  332. }
  333. public void SwapBuffers()
  334. {
  335. OpenTK.Graphics.GraphicsContext.CurrentContext.SwapBuffers();
  336. }
  337. public void MainLoop()
  338. {
  339. while (_isActive)
  340. {
  341. UpdateFrame();
  342. // Polling becomes expensive if it's not slept
  343. Thread.Sleep(1);
  344. }
  345. _exitEvent.Set();
  346. }
  347. private bool UpdateFrame()
  348. {
  349. if (!_isActive)
  350. {
  351. return true;
  352. }
  353. if (_isStopped)
  354. {
  355. return false;
  356. }
  357. if (_isFocused)
  358. {
  359. Gtk.Application.Invoke(delegate
  360. {
  361. KeyboardState keyboard = OpenTK.Input.Keyboard.GetState();
  362. HandleScreenState(keyboard);
  363. if (keyboard.IsKeyDown(OpenTK.Input.Key.Delete))
  364. {
  365. if (!ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen))
  366. {
  367. Ptc.Continue();
  368. }
  369. }
  370. });
  371. }
  372. List<GamepadInput> gamepadInputs = new List<GamepadInput>(NpadDevices.MaxControllers);
  373. List<SixAxisInput> motionInputs = new List<SixAxisInput>(NpadDevices.MaxControllers);
  374. MotionDevice motionDevice = new MotionDevice(_dsuClient);
  375. foreach (InputConfig inputConfig in ConfigurationState.Instance.Hid.InputConfig.Value)
  376. {
  377. ControllerKeys currentButton = 0;
  378. JoystickPosition leftJoystick = new JoystickPosition();
  379. JoystickPosition rightJoystick = new JoystickPosition();
  380. KeyboardInput? hidKeyboard = null;
  381. int leftJoystickDx = 0;
  382. int leftJoystickDy = 0;
  383. int rightJoystickDx = 0;
  384. int rightJoystickDy = 0;
  385. if (inputConfig.EnableMotion)
  386. {
  387. motionDevice.RegisterController(inputConfig.PlayerIndex);
  388. }
  389. if (inputConfig is KeyboardConfig keyboardConfig)
  390. {
  391. if (_isFocused)
  392. {
  393. // Keyboard Input
  394. KeyboardController keyboardController = new KeyboardController(keyboardConfig);
  395. currentButton = keyboardController.GetButtons();
  396. (leftJoystickDx, leftJoystickDy) = keyboardController.GetLeftStick();
  397. (rightJoystickDx, rightJoystickDy) = keyboardController.GetRightStick();
  398. leftJoystick = new JoystickPosition
  399. {
  400. Dx = leftJoystickDx,
  401. Dy = leftJoystickDy
  402. };
  403. rightJoystick = new JoystickPosition
  404. {
  405. Dx = rightJoystickDx,
  406. Dy = rightJoystickDy
  407. };
  408. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  409. {
  410. hidKeyboard = keyboardController.GetKeysDown();
  411. }
  412. if (!hidKeyboard.HasValue)
  413. {
  414. hidKeyboard = new KeyboardInput
  415. {
  416. Modifier = 0,
  417. Keys = new int[0x8]
  418. };
  419. }
  420. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  421. {
  422. _device.Hid.Keyboard.Update(hidKeyboard.Value);
  423. }
  424. }
  425. }
  426. else if (inputConfig is Common.Configuration.Hid.ControllerConfig controllerConfig)
  427. {
  428. // Controller Input
  429. JoystickController joystickController = new JoystickController(controllerConfig);
  430. currentButton |= joystickController.GetButtons();
  431. (leftJoystickDx, leftJoystickDy) = joystickController.GetLeftStick();
  432. (rightJoystickDx, rightJoystickDy) = joystickController.GetRightStick();
  433. leftJoystick = new JoystickPosition
  434. {
  435. Dx = controllerConfig.LeftJoycon.InvertStickX ? -leftJoystickDx : leftJoystickDx,
  436. Dy = controllerConfig.LeftJoycon.InvertStickY ? -leftJoystickDy : leftJoystickDy
  437. };
  438. rightJoystick = new JoystickPosition
  439. {
  440. Dx = controllerConfig.RightJoycon.InvertStickX ? -rightJoystickDx : rightJoystickDx,
  441. Dy = controllerConfig.RightJoycon.InvertStickY ? -rightJoystickDy : rightJoystickDy
  442. };
  443. }
  444. currentButton |= _device.Hid.UpdateStickButtons(leftJoystick, rightJoystick);
  445. motionDevice.Poll(inputConfig, inputConfig.Slot);
  446. SixAxisInput sixAxisInput = new SixAxisInput()
  447. {
  448. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  449. Accelerometer = motionDevice.Accelerometer,
  450. Gyroscope = motionDevice.Gyroscope,
  451. Rotation = motionDevice.Rotation,
  452. Orientation = motionDevice.Orientation
  453. };
  454. motionInputs.Add(sixAxisInput);
  455. gamepadInputs.Add(new GamepadInput
  456. {
  457. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  458. Buttons = currentButton,
  459. LStick = leftJoystick,
  460. RStick = rightJoystick
  461. });
  462. if (inputConfig.ControllerType == Common.Configuration.Hid.ControllerType.JoyconPair)
  463. {
  464. if (!inputConfig.MirrorInput)
  465. {
  466. motionDevice.Poll(inputConfig, inputConfig.AltSlot);
  467. sixAxisInput = new SixAxisInput()
  468. {
  469. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  470. Accelerometer = motionDevice.Accelerometer,
  471. Gyroscope = motionDevice.Gyroscope,
  472. Rotation = motionDevice.Rotation,
  473. Orientation = motionDevice.Orientation
  474. };
  475. }
  476. motionInputs.Add(sixAxisInput);
  477. }
  478. }
  479. _device.Hid.Npads.Update(gamepadInputs);
  480. _device.Hid.Npads.UpdateSixAxis(motionInputs);
  481. if(_isFocused)
  482. {
  483. // Hotkeys
  484. HotkeyButtons currentHotkeyButtons = KeyboardController.GetHotkeyButtons(OpenTK.Input.Keyboard.GetState());
  485. if (currentHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync) &&
  486. !_prevHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync))
  487. {
  488. _device.EnableDeviceVsync = !_device.EnableDeviceVsync;
  489. }
  490. _prevHotkeyButtons = currentHotkeyButtons;
  491. }
  492. //Touchscreen
  493. bool hasTouch = false;
  494. // Get screen touch position from left mouse click
  495. // OpenTK always captures mouse events, even if out of focus, so check if window is focused.
  496. if (_isFocused && _mousePressed)
  497. {
  498. int screenWidth = AllocatedWidth;
  499. int screenHeight = AllocatedHeight;
  500. if (AllocatedWidth > (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight)
  501. {
  502. screenWidth = (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight;
  503. }
  504. else
  505. {
  506. screenHeight = (AllocatedWidth * SwitchPanelHeight) / SwitchPanelWidth;
  507. }
  508. int startX = (AllocatedWidth - screenWidth) >> 1;
  509. int startY = (AllocatedHeight - screenHeight) >> 1;
  510. int endX = startX + screenWidth;
  511. int endY = startY + screenHeight;
  512. if (_mouseX >= startX &&
  513. _mouseY >= startY &&
  514. _mouseX < endX &&
  515. _mouseY < endY)
  516. {
  517. int screenMouseX = (int)_mouseX - startX;
  518. int screenMouseY = (int)_mouseY - startY;
  519. int mX = (screenMouseX * SwitchPanelWidth) / screenWidth;
  520. int mY = (screenMouseY * SwitchPanelHeight) / screenHeight;
  521. TouchPoint currentPoint = new TouchPoint
  522. {
  523. X = (uint)mX,
  524. Y = (uint)mY,
  525. // Placeholder values till more data is acquired
  526. DiameterX = 10,
  527. DiameterY = 10,
  528. Angle = 90
  529. };
  530. hasTouch = true;
  531. _device.Hid.Touchscreen.Update(currentPoint);
  532. }
  533. }
  534. if (!hasTouch)
  535. {
  536. _device.Hid.Touchscreen.Update();
  537. }
  538. _device.Hid.DebugPad.Update();
  539. return true;
  540. }
  541. }
  542. }