Program.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. };
  209. }
  210. }
  211. else
  212. {
  213. string profileBasePath;
  214. if (isKeyboard)
  215. {
  216. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "keyboard");
  217. }
  218. else
  219. {
  220. profileBasePath = Path.Combine(AppDataManager.ProfilesDirPath, "controller");
  221. }
  222. string path = Path.Combine(profileBasePath, inputProfileName + ".json");
  223. if (!File.Exists(path))
  224. {
  225. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" not found for \"{inputId}\"");
  226. return null;
  227. }
  228. try
  229. {
  230. using (Stream stream = File.OpenRead(path))
  231. {
  232. config = JsonHelper.Deserialize<InputConfig>(stream);
  233. }
  234. }
  235. catch (JsonException)
  236. {
  237. Logger.Error?.Print(LogClass.Application, $"Input profile \"{inputProfileName}\" parsing failed for \"{inputId}\"");
  238. return null;
  239. }
  240. }
  241. config.Id = inputId;
  242. config.PlayerIndex = index;
  243. string inputTypeName = isKeyboard ? "Keyboard" : "Gamepad";
  244. Logger.Info?.Print(LogClass.Application, $"{config.PlayerIndex} configured with {inputTypeName} \"{config.Id}\"");
  245. return config;
  246. }
  247. static void Load(Options option)
  248. {
  249. IGamepad gamepad;
  250. if (option.ListInputIds)
  251. {
  252. Logger.Info?.Print(LogClass.Application, "Input Ids:");
  253. foreach (string id in _inputManager.KeyboardDriver.GamepadsIds)
  254. {
  255. gamepad = _inputManager.KeyboardDriver.GetGamepad(id);
  256. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  257. gamepad.Dispose();
  258. }
  259. foreach (string id in _inputManager.GamepadDriver.GamepadsIds)
  260. {
  261. gamepad = _inputManager.GamepadDriver.GetGamepad(id);
  262. Logger.Info?.Print(LogClass.Application, $"- {id} (\"{gamepad.Name}\")");
  263. gamepad.Dispose();
  264. }
  265. return;
  266. }
  267. if (option.InputPath == null)
  268. {
  269. Logger.Error?.Print(LogClass.Application, "Please provide a file to load");
  270. return;
  271. }
  272. _inputConfiguration = new List<InputConfig>();
  273. _enableKeyboard = (bool)option.EnableKeyboard;
  274. _enableMouse = (bool)option.EnableMouse;
  275. void LoadPlayerConfiguration(string inputProfileName, string inputId, PlayerIndex index)
  276. {
  277. InputConfig inputConfig = HandlePlayerConfiguration(inputProfileName, inputId, index);
  278. if (inputConfig != null)
  279. {
  280. _inputConfiguration.Add(inputConfig);
  281. }
  282. }
  283. LoadPlayerConfiguration(option.InputProfile1Name, option.InputId1, PlayerIndex.Player1);
  284. LoadPlayerConfiguration(option.InputProfile2Name, option.InputId2, PlayerIndex.Player2);
  285. LoadPlayerConfiguration(option.InputProfile3Name, option.InputId3, PlayerIndex.Player3);
  286. LoadPlayerConfiguration(option.InputProfile4Name, option.InputId4, PlayerIndex.Player4);
  287. LoadPlayerConfiguration(option.InputProfile5Name, option.InputId5, PlayerIndex.Player5);
  288. LoadPlayerConfiguration(option.InputProfile6Name, option.InputId6, PlayerIndex.Player6);
  289. LoadPlayerConfiguration(option.InputProfile7Name, option.InputId7, PlayerIndex.Player7);
  290. LoadPlayerConfiguration(option.InputProfile8Name, option.InputId8, PlayerIndex.Player8);
  291. LoadPlayerConfiguration(option.InputProfileHandheldName, option.InputIdHandheld, PlayerIndex.Handheld);
  292. if (_inputConfiguration.Count == 0)
  293. {
  294. return;
  295. }
  296. // Setup logging level
  297. Logger.SetEnable(LogLevel.Debug, (bool)option.LoggingEnableDebug);
  298. Logger.SetEnable(LogLevel.Stub, (bool)option.LoggingEnableStub);
  299. Logger.SetEnable(LogLevel.Info, (bool)option.LoggingEnableInfo);
  300. Logger.SetEnable(LogLevel.Warning, (bool)option.LoggingEnableWarning);
  301. Logger.SetEnable(LogLevel.Error, (bool)option.LoggingEnableError);
  302. Logger.SetEnable(LogLevel.Guest, (bool)option.LoggingEnableGuest);
  303. Logger.SetEnable(LogLevel.AccessLog, (bool)option.LoggingEnableFsAccessLog);
  304. if ((bool)option.EnableFileLog)
  305. {
  306. Logger.AddTarget(new AsyncLogTargetWrapper(
  307. new FileLogTarget(AppDomain.CurrentDomain.BaseDirectory, "file"),
  308. 1000,
  309. AsyncLogTargetOverflowAction.Block
  310. ));
  311. }
  312. // Setup graphics configuration
  313. GraphicsConfig.EnableShaderCache = (bool)option.EnableShaderCache;
  314. GraphicsConfig.ResScale = option.ResScale;
  315. GraphicsConfig.MaxAnisotropy = option.MaxAnisotropy;
  316. GraphicsConfig.ShadersDumpPath = option.GraphicsShadersDumpPath;
  317. while (true)
  318. {
  319. LoadApplication(option);
  320. if (_userChannelPersistence.PreviousIndex == -1 || !_userChannelPersistence.ShouldRestart)
  321. {
  322. break;
  323. }
  324. _userChannelPersistence.ShouldRestart = false;
  325. }
  326. }
  327. private static void SetupProgressHandler()
  328. {
  329. Ptc.PtcStateChanged -= ProgressHandler;
  330. Ptc.PtcStateChanged += ProgressHandler;
  331. _emulationContext.Gpu.ShaderCacheStateChanged -= ProgressHandler;
  332. _emulationContext.Gpu.ShaderCacheStateChanged += ProgressHandler;
  333. }
  334. private static void ProgressHandler<T>(T state, int current, int total) where T : Enum
  335. {
  336. string label;
  337. switch (state)
  338. {
  339. case PtcLoadingState ptcState:
  340. label = $"PTC : {current}/{total}";
  341. break;
  342. case ShaderCacheState shaderCacheState:
  343. label = $"Shaders : {current}/{total}";
  344. break;
  345. default:
  346. throw new ArgumentException($"Unknown Progress Handler type {typeof(T)}");
  347. }
  348. Logger.Info?.Print(LogClass.Application, label);
  349. }
  350. private static Switch InitializeEmulationContext(WindowBase window, Options options)
  351. {
  352. HLEConfiguration configuration = new HLEConfiguration(_virtualFileSystem,
  353. _contentManager,
  354. _accountManager,
  355. _userChannelPersistence,
  356. new Renderer(),
  357. new SDL2HardwareDeviceDriver(),
  358. (bool)options.ExpandRam ? MemoryConfiguration.MemoryConfiguration6GB : MemoryConfiguration.MemoryConfiguration4GB,
  359. window,
  360. options.SystemLanguage,
  361. options.SystemRegion,
  362. (bool)options.EnableVsync,
  363. (bool)options.EnableDockedMode,
  364. (bool)options.EnablePtc,
  365. (bool)options.EnableFsIntegrityChecks ? LibHac.FsSystem.IntegrityCheckLevel.ErrorOnInvalid : LibHac.FsSystem.IntegrityCheckLevel.None,
  366. options.FsGlobalAccessLogMode,
  367. options.SystemTimeOffset,
  368. options.SystemTimeZone,
  369. options.MemoryManagerMode,
  370. (bool)options.IgnoreMissingServices,
  371. options.AspectRatio);
  372. return new Switch(configuration);
  373. }
  374. private static void ExecutionEntrypoint()
  375. {
  376. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  377. {
  378. _windowsMultimediaTimerResolution = new WindowsMultimediaTimerResolution(1);
  379. }
  380. DisplaySleep.Prevent();
  381. _window.Initialize(_emulationContext, _inputConfiguration, _enableKeyboard, _enableMouse);
  382. _window.Execute();
  383. Ptc.Close();
  384. PtcProfiler.Stop();
  385. _emulationContext.Dispose();
  386. _window.Dispose();
  387. _windowsMultimediaTimerResolution?.Dispose();
  388. _windowsMultimediaTimerResolution = null;
  389. }
  390. private static bool LoadApplication(Options options)
  391. {
  392. string path = options.InputPath;
  393. Logger.RestartTime();
  394. _window = new OpenGLWindow(_inputManager, options.LoggingGraphicsDebugLevel, options.AspectRatio, (bool)options.EnableMouse);
  395. _emulationContext = InitializeEmulationContext(_window, options);
  396. SetupProgressHandler();
  397. SystemVersion firmwareVersion = _contentManager.GetCurrentFirmwareVersion();
  398. Logger.Notice.Print(LogClass.Application, $"Using Firmware Version: {firmwareVersion?.VersionString}");
  399. if (Directory.Exists(path))
  400. {
  401. string[] romFsFiles = Directory.GetFiles(path, "*.istorage");
  402. if (romFsFiles.Length == 0)
  403. {
  404. romFsFiles = Directory.GetFiles(path, "*.romfs");
  405. }
  406. if (romFsFiles.Length > 0)
  407. {
  408. Logger.Info?.Print(LogClass.Application, "Loading as cart with RomFS.");
  409. _emulationContext.LoadCart(path, romFsFiles[0]);
  410. }
  411. else
  412. {
  413. Logger.Info?.Print(LogClass.Application, "Loading as cart WITHOUT RomFS.");
  414. _emulationContext.LoadCart(path);
  415. }
  416. }
  417. else if (File.Exists(path))
  418. {
  419. switch (Path.GetExtension(path).ToLowerInvariant())
  420. {
  421. case ".xci":
  422. Logger.Info?.Print(LogClass.Application, "Loading as XCI.");
  423. _emulationContext.LoadXci(path);
  424. break;
  425. case ".nca":
  426. Logger.Info?.Print(LogClass.Application, "Loading as NCA.");
  427. _emulationContext.LoadNca(path);
  428. break;
  429. case ".nsp":
  430. case ".pfs0":
  431. Logger.Info?.Print(LogClass.Application, "Loading as NSP.");
  432. _emulationContext.LoadNsp(path);
  433. break;
  434. default:
  435. Logger.Info?.Print(LogClass.Application, "Loading as Homebrew.");
  436. try
  437. {
  438. _emulationContext.LoadProgram(path);
  439. }
  440. catch (ArgumentOutOfRangeException)
  441. {
  442. Logger.Error?.Print(LogClass.Application, "The specified file is not supported by Ryujinx.");
  443. return false;
  444. }
  445. break;
  446. }
  447. }
  448. else
  449. {
  450. Logger.Warning?.Print(LogClass.Application, "Please specify a valid XCI/NCA/NSP/PFS0/NRO file.");
  451. _emulationContext.Dispose();
  452. return false;
  453. }
  454. Translator.IsReadyForTranslation.Reset();
  455. Thread windowThread = new Thread(() =>
  456. {
  457. ExecutionEntrypoint();
  458. })
  459. {
  460. Name = "GUI.WindowThread"
  461. };
  462. windowThread.Start();
  463. windowThread.Join();
  464. return true;
  465. }
  466. }
  467. }