GLRenderer.cs 25 KB

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