GLRenderer.cs 16 KB

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