GLRenderer.cs 18 KB

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