GLRenderer.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  256. if (scale != 1)
  257. {
  258. dockedMode += $" ({scale}x)";
  259. }
  260. if (_ticks >= _ticksPerFrame)
  261. {
  262. _device.PresentFrame(SwapBuffers);
  263. _device.Statistics.RecordSystemFrameTime();
  264. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  265. _device.EnableDeviceVsync,
  266. dockedMode,
  267. $"Host: {_device.Statistics.GetSystemFrameRate():00.00} FPS",
  268. $"Game: {_device.Statistics.GetGameFrameRate():00.00} FPS",
  269. $"GPU: {_renderer.GpuVendor}"));
  270. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  271. }
  272. }
  273. }
  274. public void SwapBuffers()
  275. {
  276. OpenTK.Graphics.GraphicsContext.CurrentContext.SwapBuffers();
  277. }
  278. public void MainLoop()
  279. {
  280. while (IsActive)
  281. {
  282. UpdateFrame();
  283. // Polling becomes expensive if it's not slept
  284. Thread.Sleep(1);
  285. }
  286. }
  287. private bool UpdateFrame()
  288. {
  289. if (!IsActive)
  290. {
  291. return true;
  292. }
  293. if (IsStopped)
  294. {
  295. return false;
  296. }
  297. if (IsFocused)
  298. {
  299. Gtk.Application.Invoke(delegate
  300. {
  301. KeyboardState keyboard = OpenTK.Input.Keyboard.GetState();
  302. HandleScreenState(keyboard);
  303. if (keyboard.IsKeyDown(OpenTK.Input.Key.Delete))
  304. {
  305. if (!ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen))
  306. {
  307. Ptc.Continue();
  308. }
  309. }
  310. });
  311. }
  312. List<GamepadInput> gamepadInputs = new List<GamepadInput>();
  313. foreach (InputConfig inputConfig in ConfigurationState.Instance.Hid.InputConfig.Value.ToArray())
  314. {
  315. ControllerKeys currentButton = 0;
  316. JoystickPosition leftJoystick = new JoystickPosition();
  317. JoystickPosition rightJoystick = new JoystickPosition();
  318. KeyboardInput? hidKeyboard = null;
  319. int leftJoystickDx = 0;
  320. int leftJoystickDy = 0;
  321. int rightJoystickDx = 0;
  322. int rightJoystickDy = 0;
  323. if (inputConfig is KeyboardConfig keyboardConfig)
  324. {
  325. if (IsFocused)
  326. {
  327. // Keyboard Input
  328. KeyboardController keyboardController = new KeyboardController(keyboardConfig);
  329. currentButton = keyboardController.GetButtons();
  330. (leftJoystickDx, leftJoystickDy) = keyboardController.GetLeftStick();
  331. (rightJoystickDx, rightJoystickDy) = keyboardController.GetRightStick();
  332. leftJoystick = new JoystickPosition
  333. {
  334. Dx = leftJoystickDx,
  335. Dy = leftJoystickDy
  336. };
  337. rightJoystick = new JoystickPosition
  338. {
  339. Dx = rightJoystickDx,
  340. Dy = rightJoystickDy
  341. };
  342. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  343. {
  344. hidKeyboard = keyboardController.GetKeysDown();
  345. }
  346. if (!hidKeyboard.HasValue)
  347. {
  348. hidKeyboard = new KeyboardInput
  349. {
  350. Modifier = 0,
  351. Keys = new int[0x8]
  352. };
  353. }
  354. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  355. {
  356. _device.Hid.Keyboard.Update(hidKeyboard.Value);
  357. }
  358. }
  359. }
  360. else if (inputConfig is Common.Configuration.Hid.ControllerConfig controllerConfig)
  361. {
  362. // Controller Input
  363. JoystickController joystickController = new JoystickController(controllerConfig);
  364. currentButton |= joystickController.GetButtons();
  365. (leftJoystickDx, leftJoystickDy) = joystickController.GetLeftStick();
  366. (rightJoystickDx, rightJoystickDy) = joystickController.GetRightStick();
  367. leftJoystick = new JoystickPosition
  368. {
  369. Dx = controllerConfig.LeftJoycon.InvertStickX ? -leftJoystickDx : leftJoystickDx,
  370. Dy = controllerConfig.LeftJoycon.InvertStickY ? -leftJoystickDy : leftJoystickDy
  371. };
  372. rightJoystick = new JoystickPosition
  373. {
  374. Dx = controllerConfig.RightJoycon.InvertStickX ? -rightJoystickDx : rightJoystickDx,
  375. Dy = controllerConfig.RightJoycon.InvertStickY ? -rightJoystickDy : rightJoystickDy
  376. };
  377. }
  378. currentButton |= _device.Hid.UpdateStickButtons(leftJoystick, rightJoystick);
  379. gamepadInputs.Add(new GamepadInput
  380. {
  381. PlayerId = (HLE.HOS.Services.Hid.PlayerIndex)inputConfig.PlayerIndex,
  382. Buttons = currentButton,
  383. LStick = leftJoystick,
  384. RStick = rightJoystick
  385. });
  386. }
  387. _device.Hid.Npads.SetGamepadsInput(gamepadInputs.ToArray());
  388. // Hotkeys
  389. HotkeyButtons currentHotkeyButtons = KeyboardController.GetHotkeyButtons(OpenTK.Input.Keyboard.GetState());
  390. if (currentHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync) &&
  391. !_prevHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync))
  392. {
  393. _device.EnableDeviceVsync = !_device.EnableDeviceVsync;
  394. }
  395. _prevHotkeyButtons = currentHotkeyButtons;
  396. //Touchscreen
  397. bool hasTouch = false;
  398. // Get screen touch position from left mouse click
  399. // OpenTK always captures mouse events, even if out of focus, so check if window is focused.
  400. if (IsFocused && _mousePressed)
  401. {
  402. int screenWidth = AllocatedWidth;
  403. int screenHeight = AllocatedHeight;
  404. if (AllocatedWidth > (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight)
  405. {
  406. screenWidth = (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight;
  407. }
  408. else
  409. {
  410. screenHeight = (AllocatedWidth * SwitchPanelHeight) / SwitchPanelWidth;
  411. }
  412. int startX = (AllocatedWidth - screenWidth) >> 1;
  413. int startY = (AllocatedHeight - screenHeight) >> 1;
  414. int endX = startX + screenWidth;
  415. int endY = startY + screenHeight;
  416. if (_mouseX >= startX &&
  417. _mouseY >= startY &&
  418. _mouseX < endX &&
  419. _mouseY < endY)
  420. {
  421. int screenMouseX = (int)_mouseX - startX;
  422. int screenMouseY = (int)_mouseY - startY;
  423. int mX = (screenMouseX * SwitchPanelWidth) / screenWidth;
  424. int mY = (screenMouseY * SwitchPanelHeight) / screenHeight;
  425. TouchPoint currentPoint = new TouchPoint
  426. {
  427. X = (uint)mX,
  428. Y = (uint)mY,
  429. // Placeholder values till more data is acquired
  430. DiameterX = 10,
  431. DiameterY = 10,
  432. Angle = 90
  433. };
  434. hasTouch = true;
  435. _device.Hid.Touchscreen.Update(currentPoint);
  436. }
  437. }
  438. if (!hasTouch)
  439. {
  440. _device.Hid.Touchscreen.Update();
  441. }
  442. _device.Hid.DebugPad.Update();
  443. return true;
  444. }
  445. }
  446. }