GLRenderer.cs 19 KB

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