GLRenderer.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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.HOS.Services.Hid;
  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 (GetGraphicsMode(),
  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 static GraphicsMode GetGraphicsMode()
  61. {
  62. if (Environment.OSVersion.Platform == PlatformID.Unix)
  63. {
  64. return new GraphicsMode(new ColorFormat(24));
  65. }
  66. return new GraphicsMode(new ColorFormat());
  67. }
  68. private void GLRenderer_ShuttingDown(object sender, EventArgs args)
  69. {
  70. _device.DisposeGpu();
  71. }
  72. private void Parent_FocusOutEvent(object o, Gtk.FocusOutEventArgs args)
  73. {
  74. IsFocused = false;
  75. }
  76. private void Parent_FocusInEvent(object o, Gtk.FocusInEventArgs args)
  77. {
  78. IsFocused = true;
  79. }
  80. private void GLRenderer_Destroyed(object sender, EventArgs e)
  81. {
  82. Dispose();
  83. }
  84. protected void Renderer_Shown(object sender, EventArgs e)
  85. {
  86. IsFocused = this.ParentWindow.State.HasFlag(Gdk.WindowState.Focused);
  87. }
  88. public void HandleScreenState(KeyboardState keyboard)
  89. {
  90. bool toggleFullscreen = keyboard.IsKeyDown(OpenTK.Input.Key.F11)
  91. || ((keyboard.IsKeyDown(OpenTK.Input.Key.AltLeft)
  92. || keyboard.IsKeyDown(OpenTK.Input.Key.AltRight))
  93. && keyboard.IsKeyDown(OpenTK.Input.Key.Enter))
  94. || keyboard.IsKeyDown(OpenTK.Input.Key.Escape);
  95. bool fullScreenToggled = ParentWindow.State.HasFlag(Gdk.WindowState.Fullscreen);
  96. if (toggleFullscreen != _toggleFullscreen)
  97. {
  98. if (toggleFullscreen)
  99. {
  100. if (fullScreenToggled)
  101. {
  102. ParentWindow.Unfullscreen();
  103. (Toplevel as MainWindow)?.ToggleExtraWidgets(true);
  104. }
  105. else
  106. {
  107. if (keyboard.IsKeyDown(OpenTK.Input.Key.Escape))
  108. {
  109. if (GtkDialog.CreateExitDialog())
  110. {
  111. Exit();
  112. }
  113. }
  114. else
  115. {
  116. ParentWindow.Fullscreen();
  117. (Toplevel as MainWindow)?.ToggleExtraWidgets(false);
  118. }
  119. }
  120. }
  121. }
  122. _toggleFullscreen = toggleFullscreen;
  123. }
  124. private void GLRenderer_Initialized(object sender, EventArgs e)
  125. {
  126. // Release the GL exclusivity that OpenTK gave us as we aren't going to use it in GTK Thread.
  127. GraphicsContext.MakeCurrent(null);
  128. WaitEvent.Set();
  129. }
  130. protected override bool OnConfigureEvent(EventConfigure evnt)
  131. {
  132. var result = base.OnConfigureEvent(evnt);
  133. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  134. _renderer.Window.SetSize(evnt.Width * monitor.ScaleFactor, evnt.Height * monitor.ScaleFactor);
  135. return result;
  136. }
  137. public void Start()
  138. {
  139. IsRenderHandler = true;
  140. _chrono.Restart();
  141. IsActive = true;
  142. Gtk.Window parent = this.Toplevel as Gtk.Window;
  143. parent.FocusInEvent += Parent_FocusInEvent;
  144. parent.FocusOutEvent += Parent_FocusOutEvent;
  145. Gtk.Application.Invoke(delegate
  146. {
  147. parent.Present();
  148. string titleNameSection = string.IsNullOrWhiteSpace(_device.System.TitleName) ? string.Empty
  149. : $" - {_device.System.TitleName}";
  150. string titleVersionSection = string.IsNullOrWhiteSpace(_device.System.TitleVersionString) ? string.Empty
  151. : $" v{_device.System.TitleVersionString}";
  152. string titleIdSection = string.IsNullOrWhiteSpace(_device.System.TitleIdText) ? string.Empty
  153. : $" ({_device.System.TitleIdText.ToUpper()})";
  154. string titleArchSection = _device.System.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  155. parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  156. });
  157. Thread renderLoopThread = new Thread(Render)
  158. {
  159. Name = "GUI.RenderLoop"
  160. };
  161. renderLoopThread.Start();
  162. MainLoop();
  163. renderLoopThread.Join();
  164. Exit();
  165. }
  166. protected override bool OnButtonPressEvent(EventButton evnt)
  167. {
  168. _mouseX = evnt.X;
  169. _mouseY = evnt.Y;
  170. if (evnt.Button == 1)
  171. {
  172. _mousePressed = true;
  173. }
  174. return false;
  175. }
  176. protected override bool OnButtonReleaseEvent(EventButton evnt)
  177. {
  178. if (evnt.Button == 1)
  179. {
  180. _mousePressed = false;
  181. }
  182. return false;
  183. }
  184. protected override bool OnMotionNotifyEvent(EventMotion evnt)
  185. {
  186. if (evnt.Device.InputSource == InputSource.Mouse)
  187. {
  188. _mouseX = evnt.X;
  189. _mouseY = evnt.Y;
  190. }
  191. return false;
  192. }
  193. protected override void OnGetPreferredHeight(out int minimumHeight, out int naturalHeight)
  194. {
  195. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  196. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  197. if (monitor.Geometry.Height >= 1080)
  198. {
  199. minimumHeight = SwitchPanelHeight;
  200. }
  201. // Otherwise, we default minimal size to 480p 16:9.
  202. else
  203. {
  204. minimumHeight = 480;
  205. }
  206. naturalHeight = minimumHeight;
  207. }
  208. protected override void OnGetPreferredWidth(out int minimumWidth, out int naturalWidth)
  209. {
  210. Gdk.Monitor monitor = Display.GetMonitorAtWindow(Window);
  211. // If the monitor is at least 1080p, use the Switch panel size as minimal size.
  212. if (monitor.Geometry.Height >= 1080)
  213. {
  214. minimumWidth = SwitchPanelWidth;
  215. }
  216. // Otherwise, we default minimal size to 480p 16:9.
  217. else
  218. {
  219. minimumWidth = 854;
  220. }
  221. naturalWidth = minimumWidth;
  222. }
  223. public void Exit()
  224. {
  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 GLRenderer!");
  237. }
  238. _renderer = (Renderer)_device.Gpu.Renderer;
  239. }
  240. public void Render()
  241. {
  242. // First take exclusivity on the OpenGL context.
  243. GraphicsContext.MakeCurrent(WindowInfo);
  244. _renderer.Initialize();
  245. // Make sure the first frame is not transparent.
  246. GL.ClearColor(OpenTK.Color.Black);
  247. GL.Clear(ClearBufferMask.ColorBufferBit);
  248. SwapBuffers();
  249. while (IsActive)
  250. {
  251. if (IsStopped)
  252. {
  253. return;
  254. }
  255. _ticks += _chrono.ElapsedTicks;
  256. _chrono.Restart();
  257. if (_device.WaitFifo())
  258. {
  259. _device.ProcessFrame();
  260. }
  261. if (_ticks >= _ticksPerFrame)
  262. {
  263. _device.PresentFrame(SwapBuffers);
  264. _device.Statistics.RecordSystemFrameTime();
  265. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  266. _device.EnableDeviceVsync,
  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. HotkeyButtons currentHotkeyButtons = 0;
  298. ControllerKeys currentButton = 0;
  299. JoystickPosition leftJoystick;
  300. JoystickPosition rightJoystick;
  301. KeyboardInput? hidKeyboard = null;
  302. int leftJoystickDx = 0;
  303. int leftJoystickDy = 0;
  304. int rightJoystickDx = 0;
  305. int rightJoystickDy = 0;
  306. // OpenTK always captures keyboard events, even if out of focus, so check if window is focused.
  307. if (IsFocused)
  308. {
  309. KeyboardState keyboard = OpenTK.Input.Keyboard.GetState();
  310. Gtk.Application.Invoke(delegate
  311. {
  312. HandleScreenState(keyboard);
  313. });
  314. // Normal Input
  315. currentHotkeyButtons = KeyboardControls.GetHotkeyButtons(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  316. currentButton = KeyboardControls.GetButtons(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  317. if (ConfigurationState.Instance.Hid.EnableKeyboard)
  318. {
  319. hidKeyboard = KeyboardControls.GetKeysDown(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  320. }
  321. (leftJoystickDx, leftJoystickDy) = KeyboardControls.GetLeftStick(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  322. (rightJoystickDx, rightJoystickDy) = KeyboardControls.GetRightStick(ConfigurationState.Instance.Hid.KeyboardControls, keyboard);
  323. }
  324. if (!hidKeyboard.HasValue)
  325. {
  326. hidKeyboard = new KeyboardInput
  327. {
  328. Modifier = 0,
  329. Keys = new int[0x8]
  330. };
  331. }
  332. currentButton |= _primaryController.GetButtons();
  333. // Keyboard has priority stick-wise
  334. if (leftJoystickDx == 0 && leftJoystickDy == 0)
  335. {
  336. (leftJoystickDx, leftJoystickDy) = _primaryController.GetLeftStick();
  337. }
  338. if (rightJoystickDx == 0 && rightJoystickDy == 0)
  339. {
  340. (rightJoystickDx, rightJoystickDy) = _primaryController.GetRightStick();
  341. }
  342. leftJoystick = new JoystickPosition
  343. {
  344. Dx = leftJoystickDx,
  345. Dy = leftJoystickDy
  346. };
  347. rightJoystick = new JoystickPosition
  348. {
  349. Dx = rightJoystickDx,
  350. Dy = rightJoystickDy
  351. };
  352. currentButton |= _device.Hid.UpdateStickButtons(leftJoystick, rightJoystick);
  353. bool hasTouch = false;
  354. // Get screen touch position from left mouse click
  355. // OpenTK always captures mouse events, even if out of focus, so check if window is focused.
  356. if (IsFocused && _mousePressed)
  357. {
  358. int screenWidth = AllocatedWidth;
  359. int screenHeight = AllocatedHeight;
  360. if (AllocatedWidth > (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight)
  361. {
  362. screenWidth = (AllocatedHeight * SwitchPanelWidth) / SwitchPanelHeight;
  363. }
  364. else
  365. {
  366. screenHeight = (AllocatedWidth * SwitchPanelHeight) / SwitchPanelWidth;
  367. }
  368. int startX = (AllocatedWidth - screenWidth) >> 1;
  369. int startY = (AllocatedHeight - screenHeight) >> 1;
  370. int endX = startX + screenWidth;
  371. int endY = startY + screenHeight;
  372. if (_mouseX >= startX &&
  373. _mouseY >= startY &&
  374. _mouseX < endX &&
  375. _mouseY < endY)
  376. {
  377. int screenMouseX = (int)_mouseX - startX;
  378. int screenMouseY = (int)_mouseY - startY;
  379. int mX = (screenMouseX * SwitchPanelWidth) / screenWidth;
  380. int mY = (screenMouseY * SwitchPanelHeight) / screenHeight;
  381. TouchPoint currentPoint = new TouchPoint
  382. {
  383. X = (uint)mX,
  384. Y = (uint)mY,
  385. // Placeholder values till more data is acquired
  386. DiameterX = 10,
  387. DiameterY = 10,
  388. Angle = 90
  389. };
  390. hasTouch = true;
  391. _device.Hid.Touchscreen.Update(currentPoint);
  392. }
  393. }
  394. if (!hasTouch)
  395. {
  396. _device.Hid.Touchscreen.Update();
  397. }
  398. if (ConfigurationState.Instance.Hid.EnableKeyboard && hidKeyboard.HasValue)
  399. {
  400. _device.Hid.Keyboard.Update(hidKeyboard.Value);
  401. }
  402. _device.Hid.DebugPad.Update();
  403. _device.Hid.Npads.SetGamepadsInput(new GamepadInput
  404. {
  405. PlayerId = PlayerIndex.Auto,
  406. Buttons = currentButton,
  407. LStick = leftJoystick,
  408. RStick = rightJoystick
  409. });
  410. // Toggle vsync
  411. if (currentHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync) &&
  412. !_prevHotkeyButtons.HasFlag(HotkeyButtons.ToggleVSync))
  413. {
  414. _device.EnableDeviceVsync = !_device.EnableDeviceVsync;
  415. }
  416. _prevHotkeyButtons = currentHotkeyButtons;
  417. return true;
  418. }
  419. }
  420. }