WindowBase.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. using ARMeilleure.Translation;
  2. using Ryujinx.Common.Configuration;
  3. using Ryujinx.Common.Configuration.Hid;
  4. using Ryujinx.Common.Logging;
  5. using Ryujinx.Graphics.GAL;
  6. using Ryujinx.Graphics.GAL.Multithreading;
  7. using Ryujinx.HLE.HOS.Applets;
  8. using Ryujinx.HLE.HOS.Services.Am.AppletOE.ApplicationProxyService.ApplicationProxy.Types;
  9. using Ryujinx.HLE.Ui;
  10. using Ryujinx.Input;
  11. using Ryujinx.Input.HLE;
  12. using Ryujinx.SDL2.Common;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Diagnostics;
  16. using System.Threading;
  17. using static SDL2.SDL;
  18. using Switch = Ryujinx.HLE.Switch;
  19. namespace Ryujinx.Headless.SDL2
  20. {
  21. abstract class WindowBase : IHostUiHandler, IDisposable
  22. {
  23. protected const int DefaultWidth = 1280;
  24. protected const int DefaultHeight = 720;
  25. private const SDL_WindowFlags DefaultFlags = SDL_WindowFlags.SDL_WINDOW_ALLOW_HIGHDPI | SDL_WindowFlags.SDL_WINDOW_RESIZABLE | SDL_WindowFlags.SDL_WINDOW_INPUT_FOCUS | SDL_WindowFlags.SDL_WINDOW_SHOWN;
  26. private const int TargetFps = 60;
  27. public NpadManager NpadManager { get; }
  28. public TouchScreenManager TouchScreenManager { get; }
  29. public Switch Device { get; private set; }
  30. public IRenderer Renderer { get; private set; }
  31. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  32. protected IntPtr WindowHandle { get; set; }
  33. public IHostUiTheme HostUiTheme { get; }
  34. public int Width { get; private set; }
  35. public int Height { get; private set; }
  36. protected SDL2MouseDriver MouseDriver;
  37. private InputManager _inputManager;
  38. private IKeyboard _keyboardInterface;
  39. private GraphicsDebugLevel _glLogLevel;
  40. private readonly Stopwatch _chrono;
  41. private readonly long _ticksPerFrame;
  42. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  43. private readonly ManualResetEvent _exitEvent;
  44. private long _ticks;
  45. private bool _isActive;
  46. private bool _isStopped;
  47. private uint _windowId;
  48. private string _gpuVendorName;
  49. private AspectRatio _aspectRatio;
  50. private bool _enableMouse;
  51. public WindowBase(InputManager inputManager, GraphicsDebugLevel glLogLevel, AspectRatio aspectRatio, bool enableMouse)
  52. {
  53. MouseDriver = new SDL2MouseDriver();
  54. _inputManager = inputManager;
  55. _inputManager.SetMouseDriver(MouseDriver);
  56. NpadManager = _inputManager.CreateNpadManager();
  57. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  58. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  59. _glLogLevel = glLogLevel;
  60. _chrono = new Stopwatch();
  61. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  62. _gpuCancellationTokenSource = new CancellationTokenSource();
  63. _exitEvent = new ManualResetEvent(false);
  64. _aspectRatio = aspectRatio;
  65. _enableMouse = enableMouse;
  66. HostUiTheme = new HeadlessHostUiTheme();
  67. SDL2Driver.Instance.Initialize();
  68. }
  69. public void Initialize(Switch device, List<InputConfig> inputConfigs, bool enableKeyboard, bool enableMouse)
  70. {
  71. Device = device;
  72. IRenderer renderer = Device.Gpu.Renderer;
  73. if (renderer is ThreadedRenderer tr)
  74. {
  75. renderer = tr.BaseRenderer;
  76. }
  77. Renderer = renderer;
  78. NpadManager.Initialize(device, inputConfigs, enableKeyboard, enableMouse);
  79. TouchScreenManager.Initialize(device);
  80. }
  81. private void InitializeWindow()
  82. {
  83. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName) ? string.Empty
  84. : $" - {Device.Application.TitleName}";
  85. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion) ? string.Empty
  86. : $" v{Device.Application.DisplayVersion}";
  87. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText) ? string.Empty
  88. : $" ({Device.Application.TitleIdText.ToUpper()})";
  89. string titleArchSection = Device.Application.TitleIs64Bit ? " (64-bit)" : " (32-bit)";
  90. WindowHandle = SDL_CreateWindow($"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DefaultWidth, DefaultHeight, DefaultFlags | GetWindowFlags());
  91. if (WindowHandle == IntPtr.Zero)
  92. {
  93. string errorMessage = $"SDL_CreateWindow failed with error \"{SDL_GetError()}\"";
  94. Logger.Error?.Print(LogClass.Application, errorMessage);
  95. throw new Exception(errorMessage);
  96. }
  97. _windowId = SDL_GetWindowID(WindowHandle);
  98. SDL2Driver.Instance.RegisterWindow(_windowId, HandleWindowEvent);
  99. Width = DefaultWidth;
  100. Height = DefaultHeight;
  101. }
  102. private void HandleWindowEvent(SDL_Event evnt)
  103. {
  104. if (evnt.type == SDL_EventType.SDL_WINDOWEVENT)
  105. {
  106. switch (evnt.window.windowEvent)
  107. {
  108. case SDL_WindowEventID.SDL_WINDOWEVENT_SIZE_CHANGED:
  109. Width = evnt.window.data1;
  110. Height = evnt.window.data2;
  111. Renderer?.Window.SetSize(Width, Height);
  112. MouseDriver.SetClientSize(Width, Height);
  113. break;
  114. case SDL_WindowEventID.SDL_WINDOWEVENT_CLOSE:
  115. Exit();
  116. break;
  117. default:
  118. break;
  119. }
  120. }
  121. else
  122. {
  123. MouseDriver.Update(evnt);
  124. }
  125. }
  126. protected abstract void InitializeRenderer();
  127. protected abstract void FinalizeRenderer();
  128. protected abstract void SwapBuffers(object image);
  129. protected abstract string GetGpuVendorName();
  130. public abstract SDL_WindowFlags GetWindowFlags();
  131. public void Render()
  132. {
  133. InitializeRenderer();
  134. Device.Gpu.Renderer.Initialize(_glLogLevel);
  135. _gpuVendorName = GetGpuVendorName();
  136. Device.Gpu.Renderer.RunLoop(() =>
  137. {
  138. Device.Gpu.SetGpuThread();
  139. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  140. Translator.IsReadyForTranslation.Set();
  141. while (_isActive)
  142. {
  143. if (_isStopped)
  144. {
  145. return;
  146. }
  147. _ticks += _chrono.ElapsedTicks;
  148. _chrono.Restart();
  149. if (Device.WaitFifo())
  150. {
  151. Device.Statistics.RecordFifoStart();
  152. Device.ProcessFrame();
  153. Device.Statistics.RecordFifoEnd();
  154. }
  155. while (Device.ConsumeFrameAvailable())
  156. {
  157. Device.PresentFrame((texture) => { SwapBuffers(texture); });
  158. }
  159. if (_ticks >= _ticksPerFrame)
  160. {
  161. string dockedMode = Device.System.State.DockedMode ? "Docked" : "Handheld";
  162. float scale = Graphics.Gpu.GraphicsConfig.ResScale;
  163. if (scale != 1)
  164. {
  165. dockedMode += $" ({scale}x)";
  166. }
  167. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  168. Device.EnableDeviceVsync,
  169. dockedMode,
  170. Device.Configuration.AspectRatio.ToText(),
  171. $"Game: {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  172. $"FIFO: {Device.Statistics.GetFifoPercent():0.00} %",
  173. $"GPU: {_gpuVendorName}"));
  174. _ticks = Math.Min(_ticks - _ticksPerFrame, _ticksPerFrame);
  175. }
  176. }
  177. });
  178. FinalizeRenderer();
  179. }
  180. public void Exit()
  181. {
  182. TouchScreenManager?.Dispose();
  183. NpadManager?.Dispose();
  184. if (_isStopped)
  185. {
  186. return;
  187. }
  188. _gpuCancellationTokenSource.Cancel();
  189. _isStopped = true;
  190. _isActive = false;
  191. _exitEvent.WaitOne();
  192. _exitEvent.Dispose();
  193. }
  194. public void MainLoop()
  195. {
  196. while (_isActive)
  197. {
  198. UpdateFrame();
  199. SDL_PumpEvents();
  200. // Polling becomes expensive if it's not slept
  201. Thread.Sleep(1);
  202. }
  203. _exitEvent.Set();
  204. }
  205. private void NVStutterWorkaround()
  206. {
  207. while (_isActive)
  208. {
  209. // When NVIDIA Threaded Optimization is on, the driver will snapshot all threads in the system whenever the application creates any new ones.
  210. // The ThreadPool has something called a "GateThread" which terminates itself after some inactivity.
  211. // However, it immediately starts up again, since the rules regarding when to terminate and when to start differ.
  212. // This creates a new thread every second or so.
  213. // The main problem with this is that the thread snapshot can take 70ms, is on the OpenGL thread and will delay rendering any graphics.
  214. // This is a little over budget on a frame time of 16ms, so creates a large stutter.
  215. // The solution is to keep the ThreadPool active so that it never has a reason to terminate the GateThread.
  216. // TODO: This should be removed when the issue with the GateThread is resolved.
  217. ThreadPool.QueueUserWorkItem((state) => { });
  218. Thread.Sleep(300);
  219. }
  220. }
  221. private bool UpdateFrame()
  222. {
  223. if (!_isActive)
  224. {
  225. return true;
  226. }
  227. if (_isStopped)
  228. {
  229. return false;
  230. }
  231. NpadManager.Update();
  232. // Touchscreen
  233. bool hasTouch = false;
  234. // Get screen touch position
  235. if (!_enableMouse)
  236. {
  237. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as SDL2MouseDriver).IsButtonPressed(MouseButton.Button1), _aspectRatio.ToFloat());
  238. }
  239. if (!hasTouch)
  240. {
  241. TouchScreenManager.Update(false);
  242. }
  243. Device.Hid.DebugPad.Update();
  244. return true;
  245. }
  246. public void Execute()
  247. {
  248. _chrono.Restart();
  249. _isActive = true;
  250. InitializeWindow();
  251. Thread renderLoopThread = new Thread(Render)
  252. {
  253. Name = "GUI.RenderLoop"
  254. };
  255. renderLoopThread.Start();
  256. Thread nvStutterWorkaround = null;
  257. if (Renderer is Graphics.OpenGL.Renderer)
  258. {
  259. nvStutterWorkaround = new Thread(NVStutterWorkaround)
  260. {
  261. Name = "GUI.NVStutterWorkaround"
  262. };
  263. nvStutterWorkaround.Start();
  264. }
  265. MainLoop();
  266. renderLoopThread.Join();
  267. nvStutterWorkaround?.Join();
  268. Exit();
  269. }
  270. public bool DisplayInputDialog(SoftwareKeyboardUiArgs args, out string userText)
  271. {
  272. // SDL2 doesn't support input dialogs
  273. userText = "Ryujinx";
  274. return true;
  275. }
  276. public bool DisplayMessageDialog(string title, string message)
  277. {
  278. SDL_ShowSimpleMessageBox(SDL_MessageBoxFlags.SDL_MESSAGEBOX_INFORMATION, title, message, WindowHandle);
  279. return true;
  280. }
  281. public bool DisplayMessageDialog(ControllerAppletUiArgs args)
  282. {
  283. string playerCount = args.PlayerCountMin == args.PlayerCountMax ? $"exactly {args.PlayerCountMin}" : $"{args.PlayerCountMin}-{args.PlayerCountMax}";
  284. string message = $"Application requests {playerCount} player(s) with:\n\n"
  285. + $"TYPES: {args.SupportedStyles}\n\n"
  286. + $"PLAYERS: {string.Join(", ", args.SupportedPlayers)}\n\n"
  287. + (args.IsDocked ? "Docked mode set. Handheld is also invalid.\n\n" : "")
  288. + "Please reconfigure Input now and then press OK.";
  289. return DisplayMessageDialog("Controller Applet", message);
  290. }
  291. public IDynamicTextInputHandler CreateDynamicTextInputHandler()
  292. {
  293. return new HeadlessDynamicTextInputHandler();
  294. }
  295. public void ExecuteProgram(Switch device, ProgramSpecifyKind kind, ulong value)
  296. {
  297. device.Configuration.UserChannelPersistence.ExecuteProgram(kind, value);
  298. Exit();
  299. }
  300. public bool DisplayErrorAppletDialog(string title, string message, string[] buttonsText)
  301. {
  302. SDL_MessageBoxData data = new SDL_MessageBoxData
  303. {
  304. title = title,
  305. message = message,
  306. buttons = new SDL_MessageBoxButtonData[buttonsText.Length],
  307. numbuttons = buttonsText.Length,
  308. window = WindowHandle
  309. };
  310. for (int i = 0; i < buttonsText.Length; i++)
  311. {
  312. data.buttons[i] = new SDL_MessageBoxButtonData
  313. {
  314. buttonid = i,
  315. text = buttonsText[i]
  316. };
  317. }
  318. SDL_ShowMessageBox(ref data, out int _);
  319. return true;
  320. }
  321. public void Dispose()
  322. {
  323. Dispose(true);
  324. }
  325. protected virtual void Dispose(bool disposing)
  326. {
  327. if (disposing)
  328. {
  329. _isActive = false;
  330. TouchScreenManager?.Dispose();
  331. NpadManager.Dispose();
  332. SDL2Driver.Instance.UnregisterWindow(_windowId);
  333. SDL_DestroyWindow(WindowHandle);
  334. SDL2Driver.Instance.Dispose();
  335. }
  336. }
  337. }
  338. }