GLRenderer.cs 21 KB

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