yuzu.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <chrono>
  4. #include <iostream>
  5. #include <memory>
  6. #include <regex>
  7. #include <string>
  8. #include <thread>
  9. #include <fmt/ostream.h>
  10. #include "common/detached_tasks.h"
  11. #include "common/logging/backend.h"
  12. #include "common/logging/log.h"
  13. #include "common/microprofile.h"
  14. #include "common/nvidia_flags.h"
  15. #include "common/scm_rev.h"
  16. #include "common/scope_exit.h"
  17. #include "common/settings.h"
  18. #include "common/string_util.h"
  19. #include "common/telemetry.h"
  20. #include "core/core.h"
  21. #include "core/core_timing.h"
  22. #include "core/cpu_manager.h"
  23. #include "core/crypto/key_manager.h"
  24. #include "core/file_sys/registered_cache.h"
  25. #include "core/file_sys/vfs/vfs_real.h"
  26. #include "core/hle/service/filesystem/filesystem.h"
  27. #include "core/loader/loader.h"
  28. #include "core/telemetry_session.h"
  29. #include "frontend_common/config.h"
  30. #include "input_common/main.h"
  31. #include "network/network.h"
  32. #include "sdl_config.h"
  33. #include "video_core/renderer_base.h"
  34. #include "yuzu_cmd/emu_window/emu_window_sdl2.h"
  35. #include "yuzu_cmd/emu_window/emu_window_sdl2_gl.h"
  36. #include "yuzu_cmd/emu_window/emu_window_sdl2_null.h"
  37. #include "yuzu_cmd/emu_window/emu_window_sdl2_vk.h"
  38. #ifdef _WIN32
  39. // windows.h needs to be included before shellapi.h
  40. #include <windows.h>
  41. #include <shellapi.h>
  42. #include "common/windows/timer_resolution.h"
  43. #endif
  44. #undef _UNICODE
  45. #include <getopt.h>
  46. #ifndef _MSC_VER
  47. #include <unistd.h>
  48. #endif
  49. #ifdef _WIN32
  50. extern "C" {
  51. // tells Nvidia and AMD drivers to use the dedicated GPU by default on laptops with switchable
  52. // graphics
  53. __declspec(dllexport) unsigned long NvOptimusEnablement = 0x00000001;
  54. __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  55. }
  56. #endif
  57. #ifdef __unix__
  58. #include "common/linux/gamemode.h"
  59. #endif
  60. static void PrintHelp(const char* argv0) {
  61. std::cout << "Usage: " << argv0
  62. << " [options] <filename>\n"
  63. "-c, --config Load the specified configuration file\n"
  64. "-f, --fullscreen Start in fullscreen mode\n"
  65. "-g, --game File path of the game to load\n"
  66. "-h, --help Display this help and exit\n"
  67. "-m, --multiplayer=nick:password@address:port"
  68. " Nickname, password, address and port for multiplayer\n"
  69. "-p, --program Pass following string as arguments to executable\n"
  70. "-u, --user Select a specific user profile from 0 to 7\n"
  71. "-v, --version Output version information and exit\n";
  72. }
  73. static void PrintVersion() {
  74. std::cout << "yuzu " << Common::g_scm_branch << " " << Common::g_scm_desc << std::endl;
  75. }
  76. static void OnStateChanged(const Network::RoomMember::State& state) {
  77. switch (state) {
  78. case Network::RoomMember::State::Idle:
  79. LOG_DEBUG(Network, "Network is idle");
  80. break;
  81. case Network::RoomMember::State::Joining:
  82. LOG_DEBUG(Network, "Connection sequence to room started");
  83. break;
  84. case Network::RoomMember::State::Joined:
  85. LOG_DEBUG(Network, "Successfully joined to the room");
  86. break;
  87. case Network::RoomMember::State::Moderator:
  88. LOG_DEBUG(Network, "Successfully joined the room as a moderator");
  89. break;
  90. default:
  91. break;
  92. }
  93. }
  94. static void OnNetworkError(const Network::RoomMember::Error& error) {
  95. switch (error) {
  96. case Network::RoomMember::Error::LostConnection:
  97. LOG_DEBUG(Network, "Lost connection to the room");
  98. break;
  99. case Network::RoomMember::Error::CouldNotConnect:
  100. LOG_ERROR(Network, "Error: Could not connect");
  101. exit(1);
  102. break;
  103. case Network::RoomMember::Error::NameCollision:
  104. LOG_ERROR(
  105. Network,
  106. "You tried to use the same nickname as another user that is connected to the Room");
  107. exit(1);
  108. break;
  109. case Network::RoomMember::Error::IpCollision:
  110. LOG_ERROR(Network, "You tried to use the same fake IP-Address as another user that is "
  111. "connected to the Room");
  112. exit(1);
  113. break;
  114. case Network::RoomMember::Error::WrongPassword:
  115. LOG_ERROR(Network, "Room replied with: Wrong password");
  116. exit(1);
  117. break;
  118. case Network::RoomMember::Error::WrongVersion:
  119. LOG_ERROR(Network,
  120. "You are using a different version than the room you are trying to connect to");
  121. exit(1);
  122. break;
  123. case Network::RoomMember::Error::RoomIsFull:
  124. LOG_ERROR(Network, "The room is full");
  125. exit(1);
  126. break;
  127. case Network::RoomMember::Error::HostKicked:
  128. LOG_ERROR(Network, "You have been kicked by the host");
  129. break;
  130. case Network::RoomMember::Error::HostBanned:
  131. LOG_ERROR(Network, "You have been banned by the host");
  132. break;
  133. case Network::RoomMember::Error::UnknownError:
  134. LOG_ERROR(Network, "UnknownError");
  135. break;
  136. case Network::RoomMember::Error::PermissionDenied:
  137. LOG_ERROR(Network, "PermissionDenied");
  138. break;
  139. case Network::RoomMember::Error::NoSuchUser:
  140. LOG_ERROR(Network, "NoSuchUser");
  141. break;
  142. }
  143. }
  144. static void OnMessageReceived(const Network::ChatEntry& msg) {
  145. std::cout << std::endl << msg.nickname << ": " << msg.message << std::endl << std::endl;
  146. }
  147. static void OnStatusMessageReceived(const Network::StatusMessageEntry& msg) {
  148. std::string message;
  149. switch (msg.type) {
  150. case Network::IdMemberJoin:
  151. message = fmt::format("{} has joined", msg.nickname);
  152. break;
  153. case Network::IdMemberLeave:
  154. message = fmt::format("{} has left", msg.nickname);
  155. break;
  156. case Network::IdMemberKicked:
  157. message = fmt::format("{} has been kicked", msg.nickname);
  158. break;
  159. case Network::IdMemberBanned:
  160. message = fmt::format("{} has been banned", msg.nickname);
  161. break;
  162. case Network::IdAddressUnbanned:
  163. message = fmt::format("{} has been unbanned", msg.nickname);
  164. break;
  165. }
  166. if (!message.empty())
  167. std::cout << std::endl << "* " << message << std::endl << std::endl;
  168. }
  169. /// Application entry point
  170. int main(int argc, char** argv) {
  171. #ifdef _WIN32
  172. if (AttachConsole(ATTACH_PARENT_PROCESS)) {
  173. freopen("CONOUT$", "wb", stdout);
  174. freopen("CONOUT$", "wb", stderr);
  175. }
  176. #endif
  177. Common::Log::Initialize();
  178. Common::Log::SetColorConsoleBackendEnabled(true);
  179. Common::Log::Start();
  180. Common::DetachedTasks detached_tasks;
  181. int option_index = 0;
  182. #ifdef _WIN32
  183. int argc_w;
  184. auto argv_w = CommandLineToArgvW(GetCommandLineW(), &argc_w);
  185. if (argv_w == nullptr) {
  186. LOG_CRITICAL(Frontend, "Failed to get command line arguments");
  187. return -1;
  188. }
  189. #endif
  190. std::string filepath;
  191. std::optional<std::string> config_path;
  192. std::string program_args;
  193. std::optional<int> selected_user;
  194. bool use_multiplayer = false;
  195. bool fullscreen = false;
  196. std::string nickname{};
  197. std::string password{};
  198. std::string address{};
  199. u16 port = Network::DefaultRoomPort;
  200. static struct option long_options[] = {
  201. // clang-format off
  202. {"config", required_argument, 0, 'c'},
  203. {"fullscreen", no_argument, 0, 'f'},
  204. {"help", no_argument, 0, 'h'},
  205. {"game", required_argument, 0, 'g'},
  206. {"multiplayer", required_argument, 0, 'm'},
  207. {"program", optional_argument, 0, 'p'},
  208. {"user", required_argument, 0, 'u'},
  209. {"version", no_argument, 0, 'v'},
  210. {0, 0, 0, 0},
  211. // clang-format on
  212. };
  213. while (optind < argc) {
  214. int arg = getopt_long(argc, argv, "g:fhvp::c:u:", long_options, &option_index);
  215. if (arg != -1) {
  216. switch (static_cast<char>(arg)) {
  217. case 'c':
  218. config_path = optarg;
  219. break;
  220. case 'f':
  221. fullscreen = true;
  222. LOG_INFO(Frontend, "Starting in fullscreen mode...");
  223. break;
  224. case 'h':
  225. PrintHelp(argv[0]);
  226. return 0;
  227. case 'g': {
  228. const std::string str_arg(optarg);
  229. filepath = str_arg;
  230. break;
  231. }
  232. case 'm': {
  233. use_multiplayer = true;
  234. const std::string str_arg(optarg);
  235. // regex to check if the format is nickname:password@ip:port
  236. // with optional :password
  237. const std::regex re("^([^:]+)(?::(.+))?@([^:]+)(?::([0-9]+))?$");
  238. if (!std::regex_match(str_arg, re)) {
  239. std::cout << "Wrong format for option --multiplayer\n";
  240. PrintHelp(argv[0]);
  241. return 0;
  242. }
  243. std::smatch match;
  244. std::regex_search(str_arg, match, re);
  245. ASSERT(match.size() == 5);
  246. nickname = match[1];
  247. password = match[2];
  248. address = match[3];
  249. if (!match[4].str().empty()) {
  250. port = static_cast<u16>(std::strtoul(match[4].str().c_str(), nullptr, 0));
  251. }
  252. std::regex nickname_re("^[a-zA-Z0-9._\\- ]+$");
  253. if (!std::regex_match(nickname, nickname_re)) {
  254. std::cout
  255. << "Nickname is not valid. Must be 4 to 20 alphanumeric characters.\n";
  256. return 0;
  257. }
  258. if (address.empty()) {
  259. std::cout << "Address to room must not be empty.\n";
  260. return 0;
  261. }
  262. break;
  263. }
  264. case 'p':
  265. program_args = argv[optind];
  266. ++optind;
  267. break;
  268. case 'u':
  269. selected_user = atoi(optarg);
  270. break;
  271. case 'v':
  272. PrintVersion();
  273. return 0;
  274. }
  275. } else {
  276. #ifdef _WIN32
  277. filepath = Common::UTF16ToUTF8(argv_w[optind]);
  278. #else
  279. filepath = argv[optind];
  280. #endif
  281. optind++;
  282. }
  283. }
  284. SdlConfig config{config_path};
  285. // apply the log_filter setting
  286. // the logger was initialized before and doesn't pick up the filter on its own
  287. Common::Log::Filter filter;
  288. filter.ParseFilterString(Settings::values.log_filter.GetValue());
  289. Common::Log::SetGlobalFilter(filter);
  290. if (!program_args.empty()) {
  291. Settings::values.program_args = program_args;
  292. }
  293. if (selected_user.has_value()) {
  294. Settings::values.current_user = std::clamp(*selected_user, 0, 7);
  295. }
  296. #ifdef _WIN32
  297. LocalFree(argv_w);
  298. #endif
  299. MicroProfileOnThreadCreate("EmuThread");
  300. SCOPE_EXIT({ MicroProfileShutdown(); });
  301. Common::ConfigureNvidiaEnvironmentFlags();
  302. if (filepath.empty()) {
  303. LOG_CRITICAL(Frontend, "Failed to load ROM: No ROM specified");
  304. return -1;
  305. }
  306. Core::System system{};
  307. system.Initialize();
  308. InputCommon::InputSubsystem input_subsystem{};
  309. // Apply the command line arguments
  310. system.ApplySettings();
  311. std::unique_ptr<EmuWindow_SDL2> emu_window;
  312. switch (Settings::values.renderer_backend.GetValue()) {
  313. case Settings::RendererBackend::OpenGL:
  314. emu_window = std::make_unique<EmuWindow_SDL2_GL>(&input_subsystem, system, fullscreen);
  315. break;
  316. case Settings::RendererBackend::Vulkan:
  317. emu_window = std::make_unique<EmuWindow_SDL2_VK>(&input_subsystem, system, fullscreen);
  318. break;
  319. case Settings::RendererBackend::Null:
  320. emu_window = std::make_unique<EmuWindow_SDL2_Null>(&input_subsystem, system, fullscreen);
  321. break;
  322. }
  323. #ifdef _WIN32
  324. Common::Windows::SetCurrentTimerResolutionToMaximum();
  325. system.CoreTiming().SetTimerResolutionNs(Common::Windows::GetCurrentTimerResolution());
  326. #endif
  327. system.SetContentProvider(std::make_unique<FileSys::ContentProviderUnion>());
  328. system.SetFilesystem(std::make_shared<FileSys::RealVfsFilesystem>());
  329. system.GetFileSystemController().CreateFactories(*system.GetFilesystem());
  330. system.GetUserChannel().clear();
  331. const Core::SystemResultStatus load_result{system.Load(*emu_window, filepath)};
  332. switch (load_result) {
  333. case Core::SystemResultStatus::ErrorGetLoader:
  334. LOG_CRITICAL(Frontend, "Failed to obtain loader for {}!", filepath);
  335. return -1;
  336. case Core::SystemResultStatus::ErrorLoader:
  337. LOG_CRITICAL(Frontend, "Failed to load ROM!");
  338. return -1;
  339. case Core::SystemResultStatus::ErrorNotInitialized:
  340. LOG_CRITICAL(Frontend, "CPUCore not initialized");
  341. return -1;
  342. case Core::SystemResultStatus::ErrorVideoCore:
  343. LOG_CRITICAL(Frontend, "Failed to initialize VideoCore!");
  344. return -1;
  345. case Core::SystemResultStatus::Success:
  346. break; // Expected case
  347. default:
  348. if (static_cast<u32>(load_result) >
  349. static_cast<u32>(Core::SystemResultStatus::ErrorLoader)) {
  350. const u16 loader_id = static_cast<u16>(Core::SystemResultStatus::ErrorLoader);
  351. const u16 error_id = static_cast<u16>(load_result) - loader_id;
  352. LOG_CRITICAL(Frontend,
  353. "While attempting to load the ROM requested, an error occurred. Please "
  354. "refer to the yuzu wiki for more information or the yuzu discord for "
  355. "additional help.\n\nError Code: {:04X}-{:04X}\nError Description: {}",
  356. loader_id, error_id, static_cast<Loader::ResultStatus>(error_id));
  357. }
  358. break;
  359. }
  360. system.TelemetrySession().AddField(Common::Telemetry::FieldType::App, "Frontend", "SDL");
  361. if (use_multiplayer) {
  362. if (auto member = system.GetRoomNetwork().GetRoomMember().lock()) {
  363. member->BindOnChatMessageReceived(OnMessageReceived);
  364. member->BindOnStatusMessageReceived(OnStatusMessageReceived);
  365. member->BindOnStateChanged(OnStateChanged);
  366. member->BindOnError(OnNetworkError);
  367. LOG_DEBUG(Network, "Start connection to {}:{} with nickname {}", address, port,
  368. nickname);
  369. member->Join(nickname, address.c_str(), port, 0, Network::NoPreferredIP, password);
  370. } else {
  371. LOG_ERROR(Network, "Could not access RoomMember");
  372. return 0;
  373. }
  374. }
  375. // Core is loaded, start the GPU (makes the GPU contexts current to this thread)
  376. system.GPU().Start();
  377. system.GetCpuManager().OnGpuReady();
  378. if (Settings::values.use_disk_shader_cache.GetValue()) {
  379. system.Renderer().ReadRasterizer()->LoadDiskResources(
  380. system.GetApplicationProcessProgramID(), std::stop_token{},
  381. [](VideoCore::LoadCallbackStage, size_t value, size_t total) {});
  382. }
  383. system.RegisterExitCallback([&] {
  384. // Just exit right away.
  385. exit(0);
  386. });
  387. #ifdef __unix__
  388. Common::Linux::StartGamemode();
  389. #endif
  390. void(system.Run());
  391. if (system.DebuggerEnabled()) {
  392. system.InitializeDebugger();
  393. }
  394. while (emu_window->IsOpen()) {
  395. emu_window->WaitEvent();
  396. }
  397. system.DetachDebugger();
  398. void(system.Pause());
  399. system.ShutdownMainProcess();
  400. #ifdef __unix__
  401. Common::Linux::StopGamemode();
  402. #endif
  403. detached_tasks.WaitForAllTasks();
  404. return 0;
  405. }