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