AppHost.cs 43 KB

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