GLRenderer.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  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.Common.Configuration;
  9. using Ryujinx.Common.Configuration.Hid;
  10. using Ryujinx.Configuration;
  11. using Ryujinx.Graphics.OpenGL;
  12. using Ryujinx.HLE;
  13. using Ryujinx.HLE.HOS.Services.Hid;
  14. using Ryujinx.Motion;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Threading;
  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. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  327. $"Game: {_device.Statistics.GetGameFrameRate():00.00} FPS",
  328. $"FIFO: {_device.Statistics.GetFifoPercent():0.00} %",
  329. $"GPU: {_renderer.GpuVendor}"));
  330. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  331. }
  332. }
  333. }
  334. public void SwapBuffers()
  335. {
  336. OpenTK.Graphics.GraphicsContext.CurrentContext.SwapBuffers();
  337. }
  338. public void MainLoop()
  339. {
  340. while (_isActive)
  341. {
  342. UpdateFrame();
  343. // Polling becomes expensive if it's not slept
  344. Thread.Sleep(1);
  345. }
  346. _exitEvent.Set();
  347. }
  348. private bool UpdateFrame()
  349. {
  350. if (!_isActive)
  351. {
  352. return true;
  353. }
  354. if (_isStopped)
  355. {
  356. return false;
  357. }
  358. if (_isFocused)
  359. {
  360. Gtk.Application.Invoke(delegate
  361. {
  362. KeyboardState keyboard = OpenTK.Input.Keyboard.GetState();
  363. HandleScreenState(keyboard);
  364. if (keyboard.IsKeyDown(OpenTK.Input.Key.Delete))
  365. {
  366. if (!ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen))
  367. {
  368. Ptc.Continue();
  369. }
  370. }
  371. });
  372. }
  373. List<GamepadInput> gamepadInputs = new List<GamepadInput>(NpadDevices.MaxControllers);
  374. List<SixAxisInput> motionInputs = new List<SixAxisInput>(NpadDevices.MaxControllers);
  375. MotionDevice motionDevice = new MotionDevice(_dsuClient);
  376. foreach (InputConfig inputConfig in ConfigurationState.Instance.Hid.InputConfig.Value)
  377. {
  378. ControllerKeys currentButton = 0;
  379. JoystickPosition leftJoystick = new JoystickPosition();
  380. JoystickPosition rightJoystick = new JoystickPosition();
  381. KeyboardInput? hidKeyboard = null;
  382. int leftJoystickDx = 0;
  383. int leftJoystickDy = 0;
  384. int rightJoystickDx = 0;
  385. int rightJoystickDy = 0;
  386. if (inputConfig.EnableMotion)
  387. {
  388. motionDevice.RegisterController(inputConfig.PlayerIndex);
  389. }
  390. if (inputConfig is KeyboardConfig keyboardConfig)
  391. {
  392. if (_isFocused)
  393. {
  394. // Keyboard Input
  395. KeyboardController keyboardController = new KeyboardController(keyboardConfig);
  396. currentButton = keyboardController.GetButtons();
  397. (leftJoystickDx, leftJoystickDy) = keyboardController.GetLeftStick();
  398. (rightJoystickDx, rightJoystickDy) = keyboardController.GetRightStick();
  399. leftJoystick = new JoystickPosition
  400. {
  401. Dx = leftJoystickDx,
  402. Dy = leftJoystickDy
  403. };
  404. rightJoystick = new JoystickPosition
  405. {
  406. Dx = rightJoystickDx,
  407. Dy = rightJoystickDy
  408. };
  409. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  410. {
  411. hidKeyboard = keyboardController.GetKeysDown();
  412. }
  413. if (!hidKeyboard.HasValue)
  414. {
  415. hidKeyboard = new KeyboardInput
  416. {
  417. Modifier = 0,
  418. Keys = new int[0x8]
  419. };
  420. }
  421. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  422. {
  423. _device.Hid.Keyboard.Update(hidKeyboard.Value);
  424. }
  425. }
  426. }
  427. else if (inputConfig is Common.Configuration.Hid.ControllerConfig controllerConfig)
  428. {
  429. // Controller Input
  430. JoystickController joystickController = new JoystickController(controllerConfig);
  431. currentButton |= joystickController.GetButtons();
  432. (leftJoystickDx, leftJoystickDy) = joystickController.GetLeftStick();
  433. (rightJoystickDx, rightJoystickDy) = joystickController.GetRightStick();
  434. leftJoystick = new JoystickPosition
  435. {
  436. Dx = controllerConfig.LeftJoycon.InvertStickX ? -leftJoystickDx : leftJoystickDx,
  437. Dy = controllerConfig.LeftJoycon.InvertStickY ? -leftJoystickDy : leftJoystickDy
  438. };
  439. rightJoystick = new JoystickPosition
  440. {
  441. Dx = controllerConfig.RightJoycon.InvertStickX ? -rightJoystickDx : rightJoystickDx,
  442. Dy = controllerConfig.RightJoycon.InvertStickY ? -rightJoystickDy : rightJoystickDy
  443. };
  444. }
  445. currentButton |= _device.Hid.UpdateStickButtons(leftJoystick, rightJoystick);
  446. motionDevice.Poll(inputConfig, inputConfig.Slot);
  447. SixAxisInput sixAxisInput = new SixAxisInput()
  448. {
  449. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  450. Accelerometer = motionDevice.Accelerometer,
  451. Gyroscope = motionDevice.Gyroscope,
  452. Rotation = motionDevice.Rotation,
  453. Orientation = motionDevice.Orientation
  454. };
  455. motionInputs.Add(sixAxisInput);
  456. gamepadInputs.Add(new GamepadInput
  457. {
  458. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  459. Buttons = currentButton,
  460. LStick = leftJoystick,
  461. RStick = rightJoystick
  462. });
  463. if (inputConfig.ControllerType == Common.Configuration.Hid.ControllerType.JoyconPair)
  464. {
  465. if (!inputConfig.MirrorInput)
  466. {
  467. motionDevice.Poll(inputConfig, inputConfig.AltSlot);
  468. sixAxisInput = new SixAxisInput()
  469. {
  470. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  471. Accelerometer = motionDevice.Accelerometer,
  472. Gyroscope = motionDevice.Gyroscope,
  473. Rotation = motionDevice.Rotation,
  474. Orientation = motionDevice.Orientation
  475. };
  476. }
  477. motionInputs.Add(sixAxisInput);
  478. }
  479. }
  480. _device.Hid.Npads.Update(gamepadInputs);
  481. _device.Hid.Npads.UpdateSixAxis(motionInputs);
  482. if(_isFocused)
  483. {
  484. // Hotkeys
  485. HotkeyButtons currentHotkeyButtons = KeyboardController.GetHotkeyButtons(OpenTK.Input.Keyboard.GetState());
  486. if (currentHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync) &&
  487. !_prevHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync))
  488. {
  489. _device.EnableDeviceVsync = !_device.EnableDeviceVsync;
  490. }
  491. _prevHotkeyButtons = currentHotkeyButtons;
  492. }
  493. //Touchscreen
  494. bool hasTouch = false;
  495. // Get screen touch position from left mouse click
  496. // OpenTK always captures mouse events, even if out of focus, so check if window is focused.
  497. if (_isFocused && _mousePressed)
  498. {
  499. float aspectWidth = SwitchPanelHeight * ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat();
  500. int screenWidth = AllocatedWidth;
  501. int screenHeight = AllocatedHeight;
  502. if (AllocatedWidth > AllocatedHeight * aspectWidth / SwitchPanelHeight)
  503. {
  504. screenWidth = (int)(AllocatedHeight * aspectWidth) / SwitchPanelHeight;
  505. }
  506. else
  507. {
  508. screenHeight = (AllocatedWidth * SwitchPanelHeight) / (int)aspectWidth;
  509. }
  510. int startX = (AllocatedWidth - screenWidth) >> 1;
  511. int startY = (AllocatedHeight - screenHeight) >> 1;
  512. int endX = startX + screenWidth;
  513. int endY = startY + screenHeight;
  514. if (_mouseX >= startX &&
  515. _mouseY >= startY &&
  516. _mouseX < endX &&
  517. _mouseY < endY)
  518. {
  519. int screenMouseX = (int)_mouseX - startX;
  520. int screenMouseY = (int)_mouseY - startY;
  521. int mX = (screenMouseX * (int)aspectWidth) / screenWidth;
  522. int mY = (screenMouseY * SwitchPanelHeight) / screenHeight;
  523. TouchPoint currentPoint = new TouchPoint
  524. {
  525. X = (uint)mX,
  526. Y = (uint)mY,
  527. // Placeholder values till more data is acquired
  528. DiameterX = 10,
  529. DiameterY = 10,
  530. Angle = 90
  531. };
  532. hasTouch = true;
  533. _device.Hid.Touchscreen.Update(currentPoint);
  534. }
  535. }
  536. if (!hasTouch)
  537. {
  538. _device.Hid.Touchscreen.Update();
  539. }
  540. _device.Hid.DebugPad.Update();
  541. return true;
  542. }
  543. }
  544. }