Program.cs 24 KB

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