Program.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. using ARMeilleure.Translation;
  2. using ARMeilleure.Translation.PTC;
  3. using CommandLine;
  4. using LibHac.Tools.FsSystem;
  5. using Ryujinx.Audio.Backends.SDL2;
  6. using Ryujinx.Common;
  7. using Ryujinx.Common.Configuration;
  8. using Ryujinx.Common.Configuration.Hid;
  9. using Ryujinx.Common.Configuration.Hid.Controller;
  10. using Ryujinx.Common.Configuration.Hid.Controller.Motion;
  11. using Ryujinx.Common.Configuration.Hid.Keyboard;
  12. using Ryujinx.Common.Logging;
  13. using Ryujinx.Common.System;
  14. using Ryujinx.Common.Utilities;
  15. using Ryujinx.Graphics.GAL;
  16. using Ryujinx.Graphics.GAL.Multithreading;
  17. using Ryujinx.Graphics.Gpu;
  18. using Ryujinx.Graphics.Gpu.Shader;
  19. using Ryujinx.Graphics.OpenGL;
  20. using Ryujinx.Headless.SDL2.OpenGL;
  21. using Ryujinx.HLE;
  22. using Ryujinx.HLE.FileSystem;
  23. using Ryujinx.HLE.FileSystem.Content;
  24. using Ryujinx.HLE.HOS;
  25. using Ryujinx.HLE.HOS.Services.Account.Acc;
  26. using Ryujinx.Input;
  27. using Ryujinx.Input.HLE;
  28. using Ryujinx.Input.SDL2;
  29. using System;
  30. using System.Collections.Generic;
  31. using System.IO;
  32. using System.Reflection;
  33. using System.Text.Json;
  34. using System.Threading;
  35. using ConfigGamepadInputId = Ryujinx.Common.Configuration.Hid.Controller.GamepadInputId;
  36. using ConfigStickInputId = Ryujinx.Common.Configuration.Hid.Controller.StickInputId;
  37. using Key = Ryujinx.Common.Configuration.Hid.Key;
  38. namespace Ryujinx.Headless.SDL2
  39. {
  40. class Program
  41. {
  42. public static string Version { get; private set; }
  43. private static VirtualFileSystem _virtualFileSystem;
  44. private static ContentManager _contentManager;
  45. private static AccountManager _accountManager;
  46. private static LibHacHorizonManager _libHacHorizonManager;
  47. private static UserChannelPersistence _userChannelPersistence;
  48. private static InputManager _inputManager;
  49. private static Switch _emulationContext;
  50. private static WindowBase _window;
  51. private static WindowsMultimediaTimerResolution _windowsMultimediaTimerResolution;
  52. private static List<InputConfig> _inputConfiguration;
  53. private static bool _enableKeyboard;
  54. private static bool _enableMouse;
  55. static void Main(string[] args)
  56. {
  57. Version = ReleaseInformations.GetVersion();
  58. Console.Title = $"Ryujinx Console {Version} (Headless SDL2)";
  59. AppDataManager.Initialize(null);
  60. _virtualFileSystem = VirtualFileSystem.CreateInstance();
  61. _libHacHorizonManager = new LibHacHorizonManager();
  62. _libHacHorizonManager.InitializeFsServer(_virtualFileSystem);
  63. _libHacHorizonManager.InitializeArpServer();
  64. _libHacHorizonManager.InitializeBcatServer();
  65. _libHacHorizonManager.InitializeSystemClients();
  66. _contentManager = new ContentManager(_virtualFileSystem);
  67. _accountManager = new AccountManager(_libHacHorizonManager.RyujinxClient);
  68. _userChannelPersistence = new UserChannelPersistence();
  69. _inputManager = new InputManager(new SDL2KeyboardDriver(), new SDL2GamepadDriver());
  70. GraphicsConfig.EnableShaderCache = true;
  71. Parser.Default.ParseArguments<Options>(args)
  72. .WithParsed(options => Load(options))
  73. .WithNotParsed(errors => errors.Output());
  74. _inputManager.Dispose();
  75. }
  76. private static InputConfig HandlePlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  77. {
  78. if (inputId == null)
  79. {
  80. if (index == PlayerIndex.Player1)
  81. {
  82. Logger.Info?.Print(LogClass.Application, $"{index} not configured, defaulting to default keyboard.");
  83. // Default to keyboard
  84. inputId = "0";
  85. }
  86. else
  87. {
  88. Logger.Info?.Print(LogClass.Application, $"{index} not configured");
  89. return null;
  90. }
  91. }
  92. IGamepad gamepad;
  93. bool isKeyboard = true;
  94. gamepad = _inputManager.KeyboardDriver.GetGamepad(inputId);
  95. if (gamepad == null)
  96. {
  97. gamepad = _inputManager.GamepadDriver.GetGamepad(inputId);
  98. isKeyboard = false;
  99. if (gamepad == null)
  100. {
  101. Logger.Error?.Print(LogClass.Application, $"{index} gamepad not found (\"{inputId}\")");
  102. return null;
  103. }
  104. }
  105. string gamepadName = gamepad.Name;
  106. gamepad.Dispose();
  107. InputConfig config;
  108. if (inputProfileName == null || inputProfileName.Equals("default"))
  109. {
  110. if (isKeyboard)
  111. {
  112. config = new StandardKeyboardInputConfig
  113. {
  114. Version = InputConfig.CurrentVersion,
  115. Backend = InputBackendType.WindowKeyboard,
  116. Id = null,
  117. ControllerType = ControllerType.JoyconPair,
  118. LeftJoycon = new LeftJoyconCommonConfig<Key>
  119. {
  120. DpadUp = Key.Up,
  121. DpadDown = Key.Down,
  122. DpadLeft = Key.Left,
  123. DpadRight = Key.Right,
  124. ButtonMinus = Key.Minus,
  125. ButtonL = Key.E,
  126. ButtonZl = Key.Q,
  127. ButtonSl = Key.Unbound,
  128. ButtonSr = Key.Unbound
  129. },
  130. LeftJoyconStick = new JoyconConfigKeyboardStick<Key>
  131. {
  132. StickUp = Key.W,
  133. StickDown = Key.S,
  134. StickLeft = Key.A,
  135. StickRight = Key.D,
  136. StickButton = Key.F,
  137. },
  138. RightJoycon = new RightJoyconCommonConfig<Key>
  139. {
  140. ButtonA = Key.Z,
  141. ButtonB = Key.X,
  142. ButtonX = Key.C,
  143. ButtonY = Key.V,
  144. ButtonPlus = Key.Plus,
  145. ButtonR = Key.U,
  146. ButtonZr = Key.O,
  147. ButtonSl = Key.Unbound,
  148. ButtonSr = Key.Unbound
  149. },
  150. RightJoyconStick = new JoyconConfigKeyboardStick<Key>
  151. {
  152. StickUp = Key.I,
  153. StickDown = Key.K,
  154. StickLeft = Key.J,
  155. StickRight = Key.L,
  156. StickButton = Key.H,
  157. }
  158. };
  159. }
  160. else
  161. {
  162. bool isNintendoStyle = gamepadName.Contains("Nintendo");
  163. config = new StandardControllerInputConfig
  164. {
  165. Version = InputConfig.CurrentVersion,
  166. Backend = InputBackendType.GamepadSDL2,
  167. Id = null,
  168. ControllerType = ControllerType.JoyconPair,
  169. DeadzoneLeft = 0.1f,
  170. DeadzoneRight = 0.1f,
  171. RangeLeft = 1.0f,
  172. RangeRight = 1.0f,
  173. TriggerThreshold = 0.5f,
  174. LeftJoycon = new LeftJoyconCommonConfig<ConfigGamepadInputId>
  175. {
  176. DpadUp = ConfigGamepadInputId.DpadUp,
  177. DpadDown = ConfigGamepadInputId.DpadDown,
  178. DpadLeft = ConfigGamepadInputId.DpadLeft,
  179. DpadRight = ConfigGamepadInputId.DpadRight,
  180. ButtonMinus = ConfigGamepadInputId.Minus,
  181. ButtonL = ConfigGamepadInputId.LeftShoulder,
  182. ButtonZl = ConfigGamepadInputId.LeftTrigger,
  183. ButtonSl = ConfigGamepadInputId.Unbound,
  184. ButtonSr = ConfigGamepadInputId.Unbound,
  185. },
  186. LeftJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  187. {
  188. Joystick = ConfigStickInputId.Left,
  189. StickButton = ConfigGamepadInputId.LeftStick,
  190. InvertStickX = false,
  191. InvertStickY = false,
  192. Rotate90CW = false,
  193. },
  194. RightJoycon = new RightJoyconCommonConfig<ConfigGamepadInputId>
  195. {
  196. ButtonA = isNintendoStyle ? ConfigGamepadInputId.A : ConfigGamepadInputId.B,
  197. ButtonB = isNintendoStyle ? ConfigGamepadInputId.B : ConfigGamepadInputId.A,
  198. ButtonX = isNintendoStyle ? ConfigGamepadInputId.X : ConfigGamepadInputId.Y,
  199. ButtonY = isNintendoStyle ? ConfigGamepadInputId.Y : ConfigGamepadInputId.X,
  200. ButtonPlus = ConfigGamepadInputId.Plus,
  201. ButtonR = ConfigGamepadInputId.RightShoulder,
  202. ButtonZr = ConfigGamepadInputId.RightTrigger,
  203. ButtonSl = ConfigGamepadInputId.Unbound,
  204. ButtonSr = ConfigGamepadInputId.Unbound,
  205. },
  206. RightJoyconStick = new JoyconConfigControllerStick<ConfigGamepadInputId, ConfigStickInputId>
  207. {
  208. Joystick = ConfigStickInputId.Right,
  209. StickButton = ConfigGamepadInputId.RightStick,
  210. InvertStickX = false,
  211. InvertStickY = false,
  212. Rotate90CW = false,
  213. },
  214. Motion = new StandardMotionConfigController
  215. {
  216. MotionBackend = MotionInputBackendType.GamepadDriver,
  217. EnableMotion = true,
  218. Sensitivity = 100,
  219. GyroDeadzone = 1,
  220. },
  221. Rumble = new RumbleConfigController
  222. {
  223. StrongRumble = 1f,
  224. WeakRumble = 1f,
  225. EnableRumble = false
  226. }
  227. };
  228. }
  229. }
  230. else
  231. {
  232. string profileBasePath;
  233. if (isKeyboard)
  234. {
  235. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "keyboard");
  236. }
  237. else
  238. {
  239. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "controller");
  240. }
  241. string path = Path.Combine(profileBasePath, inputProfileName + ".json");
  242. if (!File.Exists(path))
  243. {
  244. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" not found for \"{inputId}\"");
  245. return null;
  246. }
  247. try
  248. {
  249. using (Stream stream = File.OpenRead(path))
  250. {
  251. config = JsonHelper.Deserialize<InputConfig>(stream);
  252. }
  253. }
  254. catch (JsonException)
  255. {
  256. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" parsing failed for \"{inputId}\"");
  257. return null;
  258. }
  259. }
  260. config.Id = inputId;
  261. config.PlayerIndex = index;
  262. string inputTypeName = isKeyboard ? "Keyboard" : "Gamepad";
  263. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} configured with {inputTypeName} \"{config.Id}\"");
  264. // If both stick ranges are 0 (usually indicative of an outdated profile load) then both sticks will be set to 1.0.
  265. if (config is StandardControllerInputConfig controllerConfig)
  266. {
  267. if (controllerConfig.RangeLeft <= 0.0f && controllerConfig.RangeRight <= 0.0f)
  268. {
  269. controllerConfig.RangeLeft = 1.0f;
  270. controllerConfig.RangeRight = 1.0f;
  271. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} stick range reset. Save the profile now to update your configuration");
  272. }
  273. }
  274. return config;
  275. }
  276. static void Load(Options option)
  277. {
  278. IGamepad gamepad;
  279. if (option.ListInputIds)
  280. {
  281. Logger.Info?.Print(LogClass.Application, "Input Ids:");
  282. foreach (string id in _inputManager.KeyboardDriver.GamepadsIds)
  283. {
  284. gamepad = _inputManager.KeyboardDriver.GetGamepad(id);
  285. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  286. gamepad.Dispose();
  287. }
  288. foreach (string id in _inputManager.GamepadDriver.GamepadsIds)
  289. {
  290. gamepad = _inputManager.GamepadDriver.GetGamepad(id);
  291. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  292. gamepad.Dispose();
  293. }
  294. return;
  295. }
  296. if (option.InputPath == null)
  297. {
  298. Logger.Error?.Print(LogClass.Application, "Please provide a file to load");
  299. return;
  300. }
  301. _inputConfiguration = new List<InputConfig>();
  302. _enableKeyboard = (bool)option.EnableKeyboard;
  303. _enableMouse = (bool)option.EnableMouse;
  304. void LoadPlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  305. {
  306. InputConfig inputConfig = HandlePlayerConfiguration(inputProfileName, inputId, index);
  307. if (inputConfig != null)
  308. {
  309. _inputConfiguration.Add(inputConfig);
  310. }
  311. }
  312. LoadPlayerConfiguration(option.InputProfile1Name, option.InputId1, PlayerIndex.Player1);
  313. LoadPlayerConfiguration(option.InputProfile2Name, option.InputId2, PlayerIndex.Player2);
  314. LoadPlayerConfiguration(option.InputProfile3Name, option.InputId3, PlayerIndex.Player3);
  315. LoadPlayerConfiguration(option.InputProfile4Name, option.InputId4, PlayerIndex.Player4);
  316. LoadPlayerConfiguration(option.InputProfile5Name, option.InputId5, PlayerIndex.Player5);
  317. LoadPlayerConfiguration(option.InputProfile6Name, option.InputId6, PlayerIndex.Player6);
  318. LoadPlayerConfiguration(option.InputProfile7Name, option.InputId7, PlayerIndex.Player7);
  319. LoadPlayerConfiguration(option.InputProfile8Name, option.InputId8, PlayerIndex.Player8);
  320. LoadPlayerConfiguration(option.InputProfileHandheldName, option.InputIdHandheld, PlayerIndex.Handheld);
  321. if (_inputConfiguration.Count == 0)
  322. {
  323. return;
  324. }
  325. // Setup logging level
  326. Logger.SetEnable(LogLevel.Debug, (bool)option.LoggingEnableDebug);
  327. Logger.SetEnable(LogLevel.Stub, (bool)option.LoggingEnableStub);
  328. Logger.SetEnable(LogLevel.Info, (bool)option.LoggingEnableInfo);
  329. Logger.SetEnable(LogLevel.Warning, (bool)option.LoggingEnableWarning);
  330. Logger.SetEnable(LogLevel.Error, (bool)option.LoggingEnableError);
  331. Logger.SetEnable(LogLevel.Trace, (bool)option.LoggingEnableTrace);
  332. Logger.SetEnable(LogLevel.Guest, (bool)option.LoggingEnableGuest);
  333. Logger.SetEnable(LogLevel.AccessLog, (bool)option.LoggingEnableFsAccessLog);
  334. if ((bool)option.EnableFileLog)
  335. {
  336. Logger.AddTarget(new AsyncLogTargetWrapper(
  337. new FileLogTarget(ReleaseInformations.GetBaseApplicationDirectory(), "file"),
  338. 1000,
  339. AsyncLogTargetOverflowAction.Block
  340. ));
  341. }
  342. // Setup graphics configuration
  343. GraphicsConfig.EnableShaderCache = (bool)option.EnableShaderCache;
  344. GraphicsConfig.ResScale = option.ResScale;
  345. GraphicsConfig.MaxAnisotropy = option.MaxAnisotropy;
  346. GraphicsConfig.ShadersDumpPath = option.GraphicsShadersDumpPath;
  347. while (true)
  348. {
  349. LoadApplication(option);
  350. if (_userChannelPersistence.PreviousIndex == -1 || !_userChannelPersistence.ShouldRestart)
  351. {
  352. break;
  353. }
  354. _userChannelPersistence.ShouldRestart = false;
  355. }
  356. }
  357. private static void SetupProgressHandler()
  358. {
  359. Ptc.PtcStateChanged -= ProgressHandler;
  360. Ptc.PtcStateChanged += ProgressHandler;
  361. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  362. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  363. }
  364. private static void ProgressHandler<T>(T state, int current, int total) where T : Enum
  365. {
  366. string label;
  367. switch (state)
  368. {
  369. case PtcLoadingState ptcState:
  370. label = $"PTC : {current}/{total}";
  371. break;
  372. case ShaderCacheState shaderCacheState:
  373. label = $"Shaders : {current}/{total}";
  374. break;
  375. default:
  376. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  377. }
  378. Logger.Info?.Print(LogClass.Application, label);
  379. }
  380. private static Switch InitializeEmulationContext(WindowBase window, Options options)
  381. {
  382. IRenderer renderer = new Renderer();
  383. BackendThreading threadingMode = options.BackendThreading;
  384. bool threadedGAL = threadingMode == BackendThreading.On || (threadingMode == BackendThreading.Auto && renderer.PreferThreading);
  385. if (threadedGAL)
  386. {
  387. renderer = new ThreadedRenderer(renderer);
  388. }
  389. HLEConfiguration configuration = new HLEConfiguration(_virtualFileSystem,
  390. _libHacHorizonManager,
  391. _contentManager,
  392. _accountManager,
  393. _userChannelPersistence,
  394. renderer,
  395. new SDL2HardwareDeviceDriver(),
  396. (bool)options.ExpandRam ? MemoryConfiguration.MemoryConfiguration6GB : MemoryConfiguration.MemoryConfiguration4GB,
  397. window,
  398. options.SystemLanguage,
  399. options.SystemRegion,
  400. (bool)options.EnableVsync,
  401. (bool)options.EnableDockedMode,
  402. (bool)options.EnablePtc,
  403. (bool)options.EnableInternetAccess,
  404. (bool)options.EnableFsIntegrityChecks ? IntegrityCheckLevel.ErrorOnInvalid : IntegrityCheckLevel.None,
  405. options.FsGlobalAccessLogMode,
  406. options.SystemTimeOffset,
  407. options.SystemTimeZone,
  408. options.MemoryManagerMode,
  409. (bool)options.IgnoreMissingServices,
  410. options.AspectRatio,
  411. options.AudioVolume);
  412. return new Switch(configuration);
  413. }
  414. private static void ExecutionEntrypoint()
  415. {
  416. if (OperatingSystem.IsWindows())
  417. {
  418. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  419. }
  420. DisplaySleep.Prevent();
  421. _window.Initialize(_emulationContext, _inputConfiguration, _enableKeyboard, _enableMouse);
  422. _window.Execute();
  423. Ptc.Close();
  424. PtcProfiler.Stop();
  425. _emulationContext.Dispose();
  426. _window.Dispose();
  427. if (OperatingSystem.IsWindows())
  428. {
  429. _windowsMultimediaTimerResolution?.Dispose();
  430. _windowsMultimediaTimerResolution = null;
  431. }
  432. }
  433. private static bool LoadApplication(Options options)
  434. {
  435. string path = options.InputPath;
  436. Logger.RestartTime();
  437. _window = new OpenGLWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, (bool)options.EnableMouse);
  438. _emulationContext = InitializeEmulationContext(_window, options);
  439. SetupProgressHandler();
  440. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  441. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  442. if (Directory.Exists(path))
  443. {
  444. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  445. if (romFsFiles.Length == 0)
  446. {
  447. romFsFiles = Directory.GetFiles(path, "*.romfs");
  448. }
  449. if (romFsFiles.Length > 0)
  450. {
  451. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  452. _emulationContext.LoadCart(path, romFsFiles[0]);
  453. }
  454. else
  455. {
  456. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  457. _emulationContext.LoadCart(path);
  458. }
  459. }
  460. else if (File.Exists(path))
  461. {
  462. switch (Path.GetExtension(path).ToLowerInvariant())
  463. {
  464. case ".xci":
  465. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  466. _emulationContext.LoadXci(path);
  467. break;
  468. case ".nca":
  469. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  470. _emulationContext.LoadNca(path);
  471. break;
  472. case ".nsp":
  473. case ".pfs0":
  474. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  475. _emulationContext.LoadNsp(path);
  476. break;
  477. default:
  478. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  479. try
  480. {
  481. _emulationContext.LoadProgram(path);
  482. }
  483. catch (ArgumentOutOfRangeException)
  484. {
  485. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  486. return false;
  487. }
  488. break;
  489. }
  490. }
  491. else
  492. {
  493. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  494. _emulationContext.Dispose();
  495. return false;
  496. }
  497. Translator.IsReadyForTranslation.Reset();
  498. Thread windowThread = new Thread(() =>
  499. {
  500. ExecutionEntrypoint();
  501. })
  502. {
  503. Name = "GUI.WindowThread"
  504. };
  505. windowThread.Start();
  506. windowThread.Join();
  507. return true;
  508. }
  509. }
  510. }