AppHost.cs 41 KB

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