AppHost.cs 40 KB

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