yuzu.cpp 14 KB

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