AppHost.cs 39 KB

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