AppHost.cs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092
  1. using ARMeilleure.Translation;
  2. using Avalonia.Input;
  3. using Avalonia.Threading;
  4. using LibHac.Tools.FsSystem;
  5. using Ryujinx.Audio.Backends.Dummy;
  6. using Ryujinx.Audio.Backends.OpenAL;
  7. using Ryujinx.Audio.Backends.SDL2;
  8. using Ryujinx.Audio.Backends.SoundIo;
  9. using Ryujinx.Audio.Integration;
  10. using Ryujinx.Ava.Common;
  11. using Ryujinx.Ava.Common.Locale;
  12. using Ryujinx.Ava.Input;
  13. using Ryujinx.Ava.UI.Controls;
  14. using Ryujinx.Ava.UI.Helpers;
  15. using Ryujinx.Ava.UI.Models;
  16. using Ryujinx.Ava.UI.Windows;
  17. using Ryujinx.Common;
  18. using Ryujinx.Common.Configuration;
  19. using Ryujinx.Common.Logging;
  20. using Ryujinx.Common.SystemInterop;
  21. using Ryujinx.Graphics.GAL;
  22. using Ryujinx.Graphics.GAL.Multithreading;
  23. using Ryujinx.Graphics.Gpu;
  24. using Ryujinx.Graphics.OpenGL;
  25. using Ryujinx.Graphics.Vulkan;
  26. using Ryujinx.HLE.FileSystem;
  27. using Ryujinx.HLE.HOS;
  28. using Ryujinx.HLE.HOS.Services.Account.Acc;
  29. using Ryujinx.HLE.HOS.SystemState;
  30. using Ryujinx.Input;
  31. using Ryujinx.Input.HLE;
  32. using Ryujinx.Ui.Common;
  33. using Ryujinx.Ui.Common.Configuration;
  34. using Ryujinx.Ui.Common.Helper;
  35. using SixLabors.ImageSharp;
  36. using SixLabors.ImageSharp.Formats.Png;
  37. using SixLabors.ImageSharp.PixelFormats;
  38. using SixLabors.ImageSharp.Processing;
  39. using SPB.Graphics.Vulkan;
  40. using System;
  41. using System.Diagnostics;
  42. using System.IO;
  43. using System.Threading;
  44. using System.Threading.Tasks;
  45. using InputManager = Ryujinx.Input.HLE.InputManager;
  46. using Key = Ryujinx.Input.Key;
  47. using MouseButton = Ryujinx.Input.MouseButton;
  48. using Size = Avalonia.Size;
  49. using Switch = Ryujinx.HLE.Switch;
  50. using WindowState = Avalonia.Controls.WindowState;
  51. namespace Ryujinx.Ava
  52. {
  53. internal class AppHost
  54. {
  55. private const int CursorHideIdleTime = 8; // Hide Cursor seconds
  56. private const float MaxResolutionScale = 4.0f; // Max resolution hotkeys can scale to before wrapping.
  57. private const int TargetFps = 60;
  58. private const float VolumeDelta = 0.05f;
  59. private static readonly Cursor InvisibleCursor = new Cursor(StandardCursorType.None);
  60. private readonly long _ticksPerFrame;
  61. private readonly Stopwatch _chrono;
  62. private readonly AccountManager _accountManager;
  63. private readonly UserChannelPersistence _userChannelPersistence;
  64. private readonly InputManager _inputManager;
  65. private readonly MainWindow _parent;
  66. private readonly IKeyboard _keyboardInterface;
  67. private readonly GraphicsDebugLevel _glLogLevel;
  68. private bool _hideCursorOnIdle;
  69. private bool _isStopped;
  70. private bool _isActive;
  71. private long _lastCursorMoveTime;
  72. private float _newVolume;
  73. private long _ticks = 0;
  74. private KeyboardHotkeyState _prevHotkeyState;
  75. private IRenderer _renderer;
  76. private readonly Thread _renderingThread;
  77. private bool _isMouseInRenderer;
  78. private bool _renderingStarted;
  79. private bool _dialogShown;
  80. private WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  81. private readonly CancellationTokenSource _gpuCancellationTokenSource;
  82. public event EventHandler AppExit;
  83. public event EventHandler<StatusUpdatedEventArgs> StatusUpdatedEvent;
  84. public RendererHost Renderer { get; }
  85. public VirtualFileSystem VirtualFileSystem { get; }
  86. public ContentManager ContentManager { get; }
  87. public Switch Device { get; set; }
  88. public NpadManager NpadManager { get; }
  89. public TouchScreenManager TouchScreenManager { get; }
  90. public int Width { get; private set; }
  91. public int Height { get; private set; }
  92. public string ApplicationPath { get; private set; }
  93. private bool _isFirmwareTitle;
  94. public bool ScreenshotRequested { get; set; }
  95. private object _lockObject = new();
  96. public AppHost(
  97. RendererHost renderer,
  98. InputManager inputManager,
  99. string applicationPath,
  100. VirtualFileSystem virtualFileSystem,
  101. ContentManager contentManager,
  102. AccountManager accountManager,
  103. UserChannelPersistence userChannelPersistence,
  104. MainWindow parent)
  105. {
  106. _parent = parent;
  107. _inputManager = inputManager;
  108. _accountManager = accountManager;
  109. _userChannelPersistence = userChannelPersistence;
  110. _renderingThread = new Thread(RenderLoop, 1 * 1024 * 1024) { Name = "GUI.RenderThread" };
  111. _hideCursorOnIdle = ConfigurationState.Instance.HideCursorOnIdle;
  112. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  113. _glLogLevel = ConfigurationState.Instance.Logger.GraphicsDebugLevel;
  114. _inputManager.SetMouseDriver(new AvaloniaMouseDriver(_parent, renderer));
  115. _keyboardInterface = (IKeyboard)_inputManager.KeyboardDriver.GetGamepad("0");
  116. NpadManager = _inputManager.CreateNpadManager();
  117. TouchScreenManager = _inputManager.CreateTouchScreenManager();
  118. Renderer = renderer;
  119. ApplicationPath = applicationPath;
  120. VirtualFileSystem = virtualFileSystem;
  121. ContentManager = contentManager;
  122. _chrono = new Stopwatch();
  123. _ticksPerFrame = Stopwatch.Frequency / TargetFps;
  124. if (ApplicationPath.StartsWith("@SystemContent"))
  125. {
  126. ApplicationPath = _parent.VirtualFileSystem.SwitchPathToSystemPath(ApplicationPath);
  127. _isFirmwareTitle = true;
  128. }
  129. ConfigurationState.Instance.HideCursorOnIdle.Event += HideCursorState_Changed;
  130. _parent.PointerLeave += Parent_PointerLeft;
  131. _parent.PointerMoved += Parent_PointerMoved;
  132. ConfigurationState.Instance.System.IgnoreMissingServices.Event += UpdateIgnoreMissingServicesState;
  133. ConfigurationState.Instance.Graphics.AspectRatio.Event += UpdateAspectRatioState;
  134. ConfigurationState.Instance.System.EnableDockedMode.Event += UpdateDockedModeState;
  135. ConfigurationState.Instance.System.AudioVolume.Event += UpdateAudioVolumeState;
  136. _gpuCancellationTokenSource = new CancellationTokenSource();
  137. }
  138. private void Parent_PointerMoved(object sender, PointerEventArgs e)
  139. {
  140. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  141. var p = e.GetCurrentPoint(_parent).Position;
  142. var r = _parent.InputHitTest(p);
  143. _isMouseInRenderer = r == Renderer;
  144. }
  145. private void Parent_PointerLeft(object sender, PointerEventArgs e)
  146. {
  147. _isMouseInRenderer = false;
  148. _parent.Cursor = Cursor.Default;
  149. }
  150. private void SetRendererWindowSize(Size size)
  151. {
  152. if (_renderer != null)
  153. {
  154. double scale = _parent.PlatformImpl.RenderScaling;
  155. _renderer.Window?.SetSize((int)(size.Width * scale), (int)(size.Height * scale));
  156. }
  157. }
  158. private unsafe void Renderer_ScreenCaptured(object sender, ScreenCaptureImageInfo e)
  159. {
  160. if (e.Data.Length > 0 && e.Height > 0 && e.Width > 0)
  161. {
  162. Task.Run(() =>
  163. {
  164. lock (_lockObject)
  165. {
  166. var currentTime = DateTime.Now;
  167. string filename = $"ryujinx_capture_{currentTime.Year}-{currentTime.Month:D2}-{currentTime.Day:D2}_{currentTime.Hour:D2}-{currentTime.Minute:D2}-{currentTime.Second:D2}.png";
  168. string directory = AppDataManager.Mode switch
  169. {
  170. AppDataManager.LaunchMode.Portable => Path.Combine(AppDataManager.BaseDirPath, "screenshots"),
  171. _ => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "Ryujinx")
  172. };
  173. string path = Path.Combine(directory, filename);
  174. try
  175. {
  176. Directory.CreateDirectory(directory);
  177. }
  178. catch (Exception ex)
  179. {
  180. Logger.Error?.Print(LogClass.Application, $"Failed to create directory at path {directory}. Error : {ex.GetType().Name}", "Screenshot");
  181. return;
  182. }
  183. Image image = e.IsBgra ? Image.LoadPixelData<Bgra32>(e.Data, e.Width, e.Height)
  184. : Image.LoadPixelData<Rgba32>(e.Data, e.Width, e.Height);
  185. if (e.FlipX)
  186. {
  187. image.Mutate(x => x.Flip(FlipMode.Horizontal));
  188. }
  189. if (e.FlipY)
  190. {
  191. image.Mutate(x => x.Flip(FlipMode.Vertical));
  192. }
  193. image.SaveAsPng(path, new PngEncoder()
  194. {
  195. ColorType = PngColorType.Rgb
  196. });
  197. image.Dispose();
  198. Logger.Notice.Print(LogClass.Application, $"Screenshot saved to {path}", "Screenshot");
  199. }
  200. });
  201. }
  202. else
  203. {
  204. Logger.Error?.Print(LogClass.Application, $"Screenshot is empty. Size : {e.Data.Length} bytes. Resolution : {e.Width}x{e.Height}", "Screenshot");
  205. }
  206. }
  207. public void Start()
  208. {
  209. if (OperatingSystem.IsWindows())
  210. {
  211. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  212. }
  213. DisplaySleep.Prevent();
  214. NpadManager.Initialize(Device, ConfigurationState.Instance.Hid.InputConfig, ConfigurationState.Instance.Hid.EnableKeyboard, ConfigurationState.Instance.Hid.EnableMouse);
  215. TouchScreenManager.Initialize(Device);
  216. _parent.ViewModel.IsGameRunning = true;
  217. string titleNameSection = string.IsNullOrWhiteSpace(Device.Application.TitleName)
  218. ? string.Empty
  219. : $" - {Device.Application.TitleName}";
  220. string titleVersionSection = string.IsNullOrWhiteSpace(Device.Application.DisplayVersion)
  221. ? string.Empty
  222. : $" v{Device.Application.DisplayVersion}";
  223. string titleIdSection = string.IsNullOrWhiteSpace(Device.Application.TitleIdText)
  224. ? string.Empty
  225. : $" ({Device.Application.TitleIdText.ToUpper()})";
  226. string titleArchSection = Device.Application.TitleIs64Bit
  227. ? " (64-bit)"
  228. : " (32-bit)";
  229. Dispatcher.UIThread.InvokeAsync(() =>
  230. {
  231. _parent.Title = $"Ryujinx {Program.Version}{titleNameSection}{titleVersionSection}{titleIdSection}{titleArchSection}";
  232. });
  233. _parent.ViewModel.SetUiProgressHandlers(Device);
  234. Renderer.SizeChanged += Window_SizeChanged;
  235. _isActive = true;
  236. _renderingThread.Start();
  237. _parent.ViewModel.Volume = ConfigurationState.Instance.System.AudioVolume.Value;
  238. MainLoop();
  239. Exit();
  240. }
  241. private void UpdateIgnoreMissingServicesState(object sender, ReactiveEventArgs<bool> args)
  242. {
  243. if (Device != null)
  244. {
  245. Device.Configuration.IgnoreMissingServices = args.NewValue;
  246. }
  247. }
  248. private void UpdateAspectRatioState(object sender, ReactiveEventArgs<AspectRatio> args)
  249. {
  250. if (Device != null)
  251. {
  252. Device.Configuration.AspectRatio = args.NewValue;
  253. }
  254. }
  255. private void UpdateDockedModeState(object sender, ReactiveEventArgs<bool> e)
  256. {
  257. Device?.System.ChangeDockedModeState(e.NewValue);
  258. }
  259. private void UpdateAudioVolumeState(object sender, ReactiveEventArgs<float> e)
  260. {
  261. Device?.SetVolume(e.NewValue);
  262. Dispatcher.UIThread.Post(() =>
  263. {
  264. var value = e.NewValue;
  265. _parent.ViewModel.Volume = e.NewValue;
  266. });
  267. }
  268. public void Stop()
  269. {
  270. _isActive = false;
  271. }
  272. private void Exit()
  273. {
  274. (_keyboardInterface as AvaloniaKeyboard)?.Clear();
  275. if (_isStopped)
  276. {
  277. return;
  278. }
  279. _isStopped = true;
  280. _isActive = false;
  281. }
  282. public void DisposeContext()
  283. {
  284. Dispose();
  285. _isActive = false;
  286. if (_renderingThread.IsAlive)
  287. {
  288. _renderingThread.Join();
  289. }
  290. DisplaySleep.Restore();
  291. NpadManager.Dispose();
  292. TouchScreenManager.Dispose();
  293. Device.Dispose();
  294. DisposeGpu();
  295. AppExit?.Invoke(this, EventArgs.Empty);
  296. }
  297. private void Dispose()
  298. {
  299. if (Device.Application != null)
  300. {
  301. _parent.UpdateGameMetadata(Device.Application.TitleIdText);
  302. }
  303. ConfigurationState.Instance.System.IgnoreMissingServices.Event -= UpdateIgnoreMissingServicesState;
  304. ConfigurationState.Instance.Graphics.AspectRatio.Event -= UpdateAspectRatioState;
  305. ConfigurationState.Instance.System.EnableDockedMode.Event -= UpdateDockedModeState;
  306. ConfigurationState.Instance.System.AudioVolume.Event -= UpdateAudioVolumeState;
  307. _gpuCancellationTokenSource.Cancel();
  308. _gpuCancellationTokenSource.Dispose();
  309. _chrono.Stop();
  310. }
  311. public void DisposeGpu()
  312. {
  313. if (OperatingSystem.IsWindows())
  314. {
  315. _windowsMultimediaTimerResolution?.Dispose();
  316. _windowsMultimediaTimerResolution = null;
  317. }
  318. Renderer?.MakeCurrent();
  319. Device.DisposeGpu();
  320. Renderer?.MakeCurrent(null);
  321. }
  322. private void HideCursorState_Changed(object sender, ReactiveEventArgs<bool> state)
  323. {
  324. Dispatcher.UIThread.InvokeAsync(delegate
  325. {
  326. _hideCursorOnIdle = state.NewValue;
  327. if (_hideCursorOnIdle)
  328. {
  329. _lastCursorMoveTime = Stopwatch.GetTimestamp();
  330. }
  331. else
  332. {
  333. _parent.Cursor = Cursor.Default;
  334. }
  335. });
  336. }
  337. public async Task<bool> LoadGuestApplication()
  338. {
  339. InitializeSwitchInstance();
  340. MainWindow.UpdateGraphicsConfig();
  341. SystemVersion firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  342. if (!SetupValidator.CanStartApplication(ContentManager, ApplicationPath, out UserError userError))
  343. {
  344. if (SetupValidator.CanFixStartApplication(ContentManager, ApplicationPath, userError, out firmwareVersion))
  345. {
  346. if (userError == UserError.NoFirmware)
  347. {
  348. UserResult result = await ContentDialogHelper.CreateConfirmationDialog(
  349. LocaleManager.Instance[LocaleKeys.DialogFirmwareNoFirmwareInstalledMessage],
  350. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallEmbeddedMessage], firmwareVersion.VersionString),
  351. LocaleManager.Instance[LocaleKeys.InputDialogYes],
  352. LocaleManager.Instance[LocaleKeys.InputDialogNo],
  353. "");
  354. if (result != UserResult.Yes)
  355. {
  356. await UserErrorDialog.ShowUserErrorDialog(userError, _parent);
  357. Device.Dispose();
  358. return false;
  359. }
  360. }
  361. if (!SetupValidator.TryFixStartApplication(ContentManager, ApplicationPath, userError, out _))
  362. {
  363. await UserErrorDialog.ShowUserErrorDialog(userError, _parent);
  364. Device.Dispose();
  365. return false;
  366. }
  367. // Tell the user that we installed a firmware for them.
  368. if (userError == UserError.NoFirmware)
  369. {
  370. firmwareVersion = ContentManager.GetCurrentFirmwareVersion();
  371. _parent.RefreshFirmwareStatus();
  372. await ContentDialogHelper.CreateInfoDialog(
  373. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstalledMessage], firmwareVersion.VersionString),
  374. string.Format(LocaleManager.Instance[LocaleKeys.DialogFirmwareInstallEmbeddedSuccessMessage], firmwareVersion.VersionString),
  375. LocaleManager.Instance[LocaleKeys.InputDialogOk],
  376. "",
  377. LocaleManager.Instance[LocaleKeys.RyujinxInfo]);
  378. }
  379. }
  380. else
  381. {
  382. await UserErrorDialog.ShowUserErrorDialog(userError, _parent);
  383. Device.Dispose();
  384. return false;
  385. }
  386. }
  387. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  388. if (_isFirmwareTitle)
  389. {
  390. Logger.Info?.Print(LogClass.Application, "Loading as Firmware Title (NCA).");
  391. Device.LoadNca(ApplicationPath);
  392. }
  393. else if (Directory.Exists(ApplicationPath))
  394. {
  395. string[] romFsFiles = Directory.GetFiles(ApplicationPath, "*.istorage");
  396. if (romFsFiles.Length == 0)
  397. {
  398. romFsFiles = Directory.GetFiles(ApplicationPath, "*.romfs");
  399. }
  400. if (romFsFiles.Length > 0)
  401. {
  402. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  403. Device.LoadCart(ApplicationPath, romFsFiles[0]);
  404. }
  405. else
  406. {
  407. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  408. Device.LoadCart(ApplicationPath);
  409. }
  410. }
  411. else if (File.Exists(ApplicationPath))
  412. {
  413. switch (Path.GetExtension(ApplicationPath).ToLowerInvariant())
  414. {
  415. case ".xci":
  416. {
  417. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  418. Device.LoadXci(ApplicationPath);
  419. break;
  420. }
  421. case ".nca":
  422. {
  423. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  424. Device.LoadNca(ApplicationPath);
  425. break;
  426. }
  427. case ".nsp":
  428. case ".pfs0":
  429. {
  430. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  431. Device.LoadNsp(ApplicationPath);
  432. break;
  433. }
  434. default:
  435. {
  436. Logger.Info?.Print(LogClass.Application, "Loading as homebrew.");
  437. try
  438. {
  439. Device.LoadProgram(ApplicationPath);
  440. }
  441. catch (ArgumentOutOfRangeException)
  442. {
  443. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  444. Dispose();
  445. return false;
  446. }
  447. break;
  448. }
  449. }
  450. }
  451. else
  452. {
  453. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  454. Dispose();
  455. return false;
  456. }
  457. DiscordIntegrationModule.SwitchToPlayingState(Device.Application.TitleIdText, Device.Application.TitleName);
  458. _parent.ApplicationLibrary.LoadAndSaveMetaData(Device.Application.TitleIdText, appMetadata =>
  459. {
  460. appMetadata.LastPlayed = DateTime.UtcNow.ToString();
  461. });
  462. return true;
  463. }
  464. internal void Resume()
  465. {
  466. Device?.System.TogglePauseEmulation(false);
  467. _parent.ViewModel.IsPaused = false;
  468. }
  469. internal void Pause()
  470. {
  471. Device?.System.TogglePauseEmulation(true);
  472. _parent.ViewModel.IsPaused = true;
  473. }
  474. private void InitializeSwitchInstance()
  475. {
  476. VirtualFileSystem.ReloadKeySet();
  477. IRenderer renderer;
  478. if (Renderer.IsVulkan)
  479. {
  480. string preferredGpu = ConfigurationState.Instance.Graphics.PreferredGpu.Value;
  481. renderer = new VulkanRenderer(Renderer.CreateVulkanSurface, VulkanHelper.GetRequiredInstanceExtensions, preferredGpu);
  482. }
  483. else
  484. {
  485. renderer = new OpenGLRenderer();
  486. }
  487. IHardwareDeviceDriver deviceDriver = new DummyHardwareDeviceDriver();
  488. BackendThreading threadingMode = ConfigurationState.Instance.Graphics.BackendThreading;
  489. var isGALthreaded = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  490. if (isGALthreaded)
  491. {
  492. renderer = new ThreadedRenderer(renderer);
  493. }
  494. Logger.Info?.PrintMsg(LogClass.Gpu, $"Backend Threading ({threadingMode}): {isGALthreaded}");
  495. if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SDL2)
  496. {
  497. if (SDL2HardwareDeviceDriver.IsSupported)
  498. {
  499. deviceDriver = new SDL2HardwareDeviceDriver();
  500. }
  501. else
  502. {
  503. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  504. if (OpenALHardwareDeviceDriver.IsSupported)
  505. {
  506. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  507. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  508. MainWindow.SaveConfig();
  509. deviceDriver = new OpenALHardwareDeviceDriver();
  510. }
  511. else
  512. {
  513. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SoundIO.");
  514. if (SoundIoHardwareDeviceDriver.IsSupported)
  515. {
  516. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  517. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  518. MainWindow.SaveConfig();
  519. deviceDriver = new SoundIoHardwareDeviceDriver();
  520. }
  521. else
  522. {
  523. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  524. }
  525. }
  526. }
  527. }
  528. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.SoundIo)
  529. {
  530. if (SoundIoHardwareDeviceDriver.IsSupported)
  531. {
  532. deviceDriver = new SoundIoHardwareDeviceDriver();
  533. }
  534. else
  535. {
  536. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, trying to fall back to SDL2.");
  537. if (SDL2HardwareDeviceDriver.IsSupported)
  538. {
  539. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  540. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  541. MainWindow.SaveConfig();
  542. deviceDriver = new SDL2HardwareDeviceDriver();
  543. }
  544. else
  545. {
  546. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to OpenAL.");
  547. if (OpenALHardwareDeviceDriver.IsSupported)
  548. {
  549. Logger.Warning?.Print(LogClass.Audio, "Found OpenAL, changing configuration.");
  550. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.OpenAl;
  551. MainWindow.SaveConfig();
  552. deviceDriver = new OpenALHardwareDeviceDriver();
  553. }
  554. else
  555. {
  556. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, falling back to dummy audio out.");
  557. }
  558. }
  559. }
  560. }
  561. else if (ConfigurationState.Instance.System.AudioBackend.Value == AudioBackend.OpenAl)
  562. {
  563. if (OpenALHardwareDeviceDriver.IsSupported)
  564. {
  565. deviceDriver = new OpenALHardwareDeviceDriver();
  566. }
  567. else
  568. {
  569. Logger.Warning?.Print(LogClass.Audio, "OpenAL is not supported, trying to fall back to SDL2.");
  570. if (SDL2HardwareDeviceDriver.IsSupported)
  571. {
  572. Logger.Warning?.Print(LogClass.Audio, "Found SDL2, changing configuration.");
  573. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SDL2;
  574. MainWindow.SaveConfig();
  575. deviceDriver = new SDL2HardwareDeviceDriver();
  576. }
  577. else
  578. {
  579. Logger.Warning?.Print(LogClass.Audio, "SDL2 is not supported, trying to fall back to SoundIO.");
  580. if (SoundIoHardwareDeviceDriver.IsSupported)
  581. {
  582. Logger.Warning?.Print(LogClass.Audio, "Found SoundIO, changing configuration.");
  583. ConfigurationState.Instance.System.AudioBackend.Value = AudioBackend.SoundIo;
  584. MainWindow.SaveConfig();
  585. deviceDriver = new SoundIoHardwareDeviceDriver();
  586. }
  587. else
  588. {
  589. Logger.Warning?.Print(LogClass.Audio, "SoundIO is not supported, falling back to dummy audio out.");
  590. }
  591. }
  592. }
  593. }
  594. var memoryConfiguration = ConfigurationState.Instance.System.ExpandRam.Value ? HLE.MemoryConfiguration.MemoryConfiguration6GiB : HLE.MemoryConfiguration.MemoryConfiguration4GiB;
  595. IntegrityCheckLevel fsIntegrityCheckLevel = ConfigurationState.Instance.System.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None;
  596. HLE.HLEConfiguration configuration = new HLE.HLEConfiguration(VirtualFileSystem,
  597. _parent.LibHacHorizonManager,
  598. ContentManager,
  599. _accountManager,
  600. _userChannelPersistence,
  601. renderer,
  602. deviceDriver,
  603. memoryConfiguration,
  604. _parent.UiHandler,
  605. (SystemLanguage)ConfigurationState.Instance.System.Language.Value,
  606. (RegionCode)ConfigurationState.Instance.System.Region.Value,
  607. ConfigurationState.Instance.Graphics.EnableVsync,
  608. ConfigurationState.Instance.System.EnableDockedMode,
  609. ConfigurationState.Instance.System.EnablePtc,
  610. ConfigurationState.Instance.System.EnableInternetAccess,
  611. fsIntegrityCheckLevel,
  612. ConfigurationState.Instance.System.FsGlobalAccessLogMode,
  613. ConfigurationState.Instance.System.SystemTimeOffset,
  614. ConfigurationState.Instance.System.TimeZone,
  615. ConfigurationState.Instance.System.MemoryManagerMode,
  616. ConfigurationState.Instance.System.IgnoreMissingServices,
  617. ConfigurationState.Instance.Graphics.AspectRatio,
  618. ConfigurationState.Instance.System.AudioVolume);
  619. Device = new Switch(configuration);
  620. }
  621. private void Window_SizeChanged(object sender, Size e)
  622. {
  623. Width = (int)e.Width;
  624. Height = (int)e.Height;
  625. SetRendererWindowSize(e);
  626. }
  627. private void MainLoop()
  628. {
  629. while (_isActive)
  630. {
  631. UpdateFrame();
  632. // Polling becomes expensive if it's not slept
  633. Thread.Sleep(1);
  634. }
  635. }
  636. private unsafe void RenderLoop()
  637. {
  638. Dispatcher.UIThread.InvokeAsync(() =>
  639. {
  640. if (_parent.ViewModel.StartGamesInFullscreen)
  641. {
  642. _parent.WindowState = WindowState.FullScreen;
  643. }
  644. if (_parent.WindowState == WindowState.FullScreen)
  645. {
  646. _parent.ViewModel.ShowMenuAndStatusBar = false;
  647. }
  648. });
  649. IRenderer renderer = Device.Gpu.Renderer;
  650. if (renderer is ThreadedRenderer tr)
  651. {
  652. renderer = tr.BaseRenderer;
  653. }
  654. _renderer = renderer;
  655. _renderer.ScreenCaptured += Renderer_ScreenCaptured;
  656. (_renderer as OpenGLRenderer)?.InitializeBackgroundContext(SPBOpenGLContext.CreateBackgroundContext(Renderer.GetContext()));
  657. Renderer.MakeCurrent();
  658. Device.Gpu.Renderer.Initialize(_glLogLevel);
  659. Width = (int)Renderer.Bounds.Width;
  660. Height = (int)Renderer.Bounds.Height;
  661. _renderer.Window.SetSize((int)(Width * _parent.PlatformImpl.RenderScaling), (int)(Height * _parent.PlatformImpl.RenderScaling));
  662. _chrono.Start();
  663. Device.Gpu.Renderer.RunLoop(() =>
  664. {
  665. Device.Gpu.SetGpuThread();
  666. Device.Gpu.InitializeShaderCache(_gpuCancellationTokenSource.Token);
  667. Translator.IsReadyForTranslation.Set();
  668. while (_isActive)
  669. {
  670. _ticks += _chrono.ElapsedTicks;
  671. _chrono.Restart();
  672. if (Device.WaitFifo())
  673. {
  674. Device.Statistics.RecordFifoStart();
  675. Device.ProcessFrame();
  676. Device.Statistics.RecordFifoEnd();
  677. }
  678. while (Device.ConsumeFrameAvailable())
  679. {
  680. if (!_renderingStarted)
  681. {
  682. _renderingStarted = true;
  683. _parent.SwitchToGameControl();
  684. }
  685. Device.PresentFrame(() => Renderer?.SwapBuffers());
  686. }
  687. if (_ticks >= _ticksPerFrame)
  688. {
  689. UpdateStatus();
  690. }
  691. }
  692. });
  693. Renderer?.MakeCurrent(null);
  694. }
  695. public void UpdateStatus()
  696. {
  697. // Run a status update only when a frame is to be drawn. This prevents from updating the ui and wasting a render when no frame is queued
  698. string dockedMode = ConfigurationState.Instance.System.EnableDockedMode ? LocaleManager.Instance[LocaleKeys.Docked] : LocaleManager.Instance[LocaleKeys.Handheld];
  699. float scale = GraphicsConfig.ResScale;
  700. if (scale != 1)
  701. {
  702. dockedMode += $" ({scale}x)";
  703. }
  704. StatusUpdatedEvent?.Invoke(this, new StatusUpdatedEventArgs(
  705. Device.EnableDeviceVsync,
  706. LocaleManager.Instance[LocaleKeys.VolumeShort] + $": {(int)(Device.GetVolume() * 100)}%",
  707. Renderer.IsVulkan ? "Vulkan" : "OpenGL",
  708. dockedMode,
  709. ConfigurationState.Instance.Graphics.AspectRatio.Value.ToText(),
  710. LocaleManager.Instance[LocaleKeys.Game] + $": {Device.Statistics.GetGameFrameRate():00.00} FPS ({Device.Statistics.GetGameFrameTime():00.00} ms)",
  711. $"FIFO: {Device.Statistics.GetFifoPercent():00.00} %",
  712. $"GPU: {_renderer.GetHardwareInfo().GpuVendor}"));
  713. }
  714. public async Task ShowExitPrompt()
  715. {
  716. bool shouldExit = !ConfigurationState.Instance.ShowConfirmExit;
  717. if (!shouldExit)
  718. {
  719. if (_dialogShown)
  720. {
  721. return;
  722. }
  723. _dialogShown = true;
  724. shouldExit = await ContentDialogHelper.CreateStopEmulationDialog();
  725. _dialogShown = false;
  726. }
  727. if (shouldExit)
  728. {
  729. Stop();
  730. }
  731. }
  732. private void HandleScreenState()
  733. {
  734. if (ConfigurationState.Instance.Hid.EnableMouse)
  735. {
  736. Dispatcher.UIThread.Post(() =>
  737. {
  738. _parent.Cursor = _isMouseInRenderer ? InvisibleCursor : Cursor.Default;
  739. });
  740. }
  741. else
  742. {
  743. if (_hideCursorOnIdle)
  744. {
  745. long cursorMoveDelta = Stopwatch.GetTimestamp() - _lastCursorMoveTime;
  746. Dispatcher.UIThread.Post(() =>
  747. {
  748. _parent.Cursor = cursorMoveDelta >= CursorHideIdleTime * Stopwatch.Frequency ? InvisibleCursor : Cursor.Default;
  749. });
  750. }
  751. }
  752. }
  753. private bool UpdateFrame()
  754. {
  755. if (!_isActive)
  756. {
  757. return false;
  758. }
  759. if (_parent.IsActive)
  760. {
  761. Dispatcher.UIThread.Post(() =>
  762. {
  763. HandleScreenState();
  764. if (_keyboardInterface.GetKeyboardStateSnapshot().IsPressed(Key.Delete) && _parent.WindowState != WindowState.FullScreen)
  765. {
  766. Device.Application.DiskCacheLoadState?.Cancel();
  767. }
  768. });
  769. }
  770. NpadManager.Update(ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  771. if (_parent.IsActive)
  772. {
  773. KeyboardHotkeyState currentHotkeyState = GetHotkeyState();
  774. if (currentHotkeyState != _prevHotkeyState)
  775. {
  776. switch (currentHotkeyState)
  777. {
  778. case KeyboardHotkeyState.ToggleVSync:
  779. Device.EnableDeviceVsync = !Device.EnableDeviceVsync;
  780. break;
  781. case KeyboardHotkeyState.Screenshot:
  782. ScreenshotRequested = true;
  783. break;
  784. case KeyboardHotkeyState.ShowUi:
  785. _parent.ViewModel.ShowMenuAndStatusBar = true;
  786. break;
  787. case KeyboardHotkeyState.Pause:
  788. if (_parent.ViewModel.IsPaused)
  789. {
  790. Resume();
  791. }
  792. else
  793. {
  794. Pause();
  795. }
  796. break;
  797. case KeyboardHotkeyState.ToggleMute:
  798. if (Device.IsAudioMuted())
  799. {
  800. Device.SetVolume(ConfigurationState.Instance.System.AudioVolume);
  801. }
  802. else
  803. {
  804. Device.SetVolume(0);
  805. }
  806. _parent.ViewModel.Volume = Device.GetVolume();
  807. break;
  808. case KeyboardHotkeyState.ResScaleUp:
  809. GraphicsConfig.ResScale = GraphicsConfig.ResScale % MaxResolutionScale + 1;
  810. break;
  811. case KeyboardHotkeyState.ResScaleDown:
  812. GraphicsConfig.ResScale =
  813. (MaxResolutionScale + GraphicsConfig.ResScale - 2) % MaxResolutionScale + 1;
  814. break;
  815. case KeyboardHotkeyState.VolumeUp:
  816. _newVolume = MathF.Round((Device.GetVolume() + VolumeDelta), 2);
  817. Device.SetVolume(_newVolume);
  818. _parent.ViewModel.Volume = Device.GetVolume();
  819. break;
  820. case KeyboardHotkeyState.VolumeDown:
  821. _newVolume = MathF.Round((Device.GetVolume() - VolumeDelta), 2);
  822. Device.SetVolume(_newVolume);
  823. _parent.ViewModel.Volume = Device.GetVolume();
  824. break;
  825. case KeyboardHotkeyState.None:
  826. (_keyboardInterface as AvaloniaKeyboard).Clear();
  827. break;
  828. }
  829. }
  830. _prevHotkeyState = currentHotkeyState;
  831. if (ScreenshotRequested)
  832. {
  833. ScreenshotRequested = false;
  834. _renderer.Screenshot();
  835. }
  836. }
  837. // Touchscreen
  838. bool hasTouch = false;
  839. if (_parent.IsActive && !ConfigurationState.Instance.Hid.EnableMouse)
  840. {
  841. hasTouch = TouchScreenManager.Update(true, (_inputManager.MouseDriver as AvaloniaMouseDriver).IsButtonPressed(MouseButton.Button1), ConfigurationState.Instance.Graphics.AspectRatio.Value.ToFloat());
  842. }
  843. if (!hasTouch)
  844. {
  845. Device.Hid.Touchscreen.Update();
  846. }
  847. Device.Hid.DebugPad.Update();
  848. return true;
  849. }
  850. private KeyboardHotkeyState GetHotkeyState()
  851. {
  852. KeyboardHotkeyState state = KeyboardHotkeyState.None;
  853. if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleVsync))
  854. {
  855. state = KeyboardHotkeyState.ToggleVSync;
  856. }
  857. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Screenshot))
  858. {
  859. state = KeyboardHotkeyState.Screenshot;
  860. }
  861. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ShowUi))
  862. {
  863. state = KeyboardHotkeyState.ShowUi;
  864. }
  865. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.Pause))
  866. {
  867. state = KeyboardHotkeyState.Pause;
  868. }
  869. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ToggleMute))
  870. {
  871. state = KeyboardHotkeyState.ToggleMute;
  872. }
  873. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleUp))
  874. {
  875. state = KeyboardHotkeyState.ResScaleUp;
  876. }
  877. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.ResScaleDown))
  878. {
  879. state = KeyboardHotkeyState.ResScaleDown;
  880. }
  881. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeUp))
  882. {
  883. state = KeyboardHotkeyState.VolumeUp;
  884. }
  885. else if (_keyboardInterface.IsPressed((Key)ConfigurationState.Instance.Hid.Hotkeys.Value.VolumeDown))
  886. {
  887. state = KeyboardHotkeyState.VolumeDown;
  888. }
  889. return state;
  890. }
  891. }
  892. }