GLRenderer.cs 18 KB

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