Program.cs 23 KB

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