AppHost.cs 41 KB

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