AppHost.cs 46 KB

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