GLRenderer.cs 20 KB

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