EntryPoint.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. /*
  2. * EntryPoint.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. // EntryPoint.cpp : Defines the entry point for the console application.
  11. #include "StdInc.h"
  12. #include "../Global.h"
  13. #include "../client/ClientCommandManager.h"
  14. #include "../client/CMT.h"
  15. #include "../client/CPlayerInterface.h"
  16. #include "../client/CServerHandler.h"
  17. #include "../client/eventsSDL/InputHandler.h"
  18. #include "../client/GameEngine.h"
  19. #include "../client/GameInstance.h"
  20. #include "../client/gui/CursorHandler.h"
  21. #include "../client/gui/WindowHandler.h"
  22. #include "../client/mainmenu/CMainMenu.h"
  23. #include "../client/media/CEmptyVideoPlayer.h"
  24. #include "../client/media/CMusicHandler.h"
  25. #include "../client/media/CSoundHandler.h"
  26. #include "../client/media/CVideoHandler.h"
  27. #include "../client/render/Graphics.h"
  28. #include "../client/render/IRenderHandler.h"
  29. #include "../client/render/IScreenHandler.h"
  30. #include "../client/lobby/CBonusSelection.h"
  31. #include "../client/windows/CMessage.h"
  32. #include "../client/windows/InfoWindows.h"
  33. #include "../lib/CThreadHelper.h"
  34. #include "../lib/ExceptionsCommon.h"
  35. #include "../lib/filesystem/Filesystem.h"
  36. #include "../lib/logging/CBasicLogConfigurator.h"
  37. #include "../lib/modding/IdentifierStorage.h"
  38. #include "../lib/modding/CModHandler.h"
  39. #include "../lib/modding/ModDescription.h"
  40. #include "../lib/texts/CGeneralTextHandler.h"
  41. #include "../lib/texts/MetaString.h"
  42. #include "../lib/GameLibrary.h"
  43. #include "../lib/VCMIDirs.h"
  44. #include <boost/program_options.hpp>
  45. #include <vstd/StringUtils.h>
  46. #include <SDL_main.h>
  47. #include <SDL.h>
  48. #ifdef VCMI_ANDROID
  49. #include "../lib/CAndroidVMHelper.h"
  50. #include <SDL_system.h>
  51. #endif
  52. #if __MINGW32__
  53. #undef main
  54. #endif
  55. namespace po = boost::program_options;
  56. namespace po_style = boost::program_options::command_line_style;
  57. static std::atomic<bool> headlessQuit = false;
  58. static std::optional<std::string> criticalInitializationError;
  59. #ifndef VCMI_IOS
  60. void processCommand(const std::string &message);
  61. #endif
  62. [[noreturn]] static void quitApplication();
  63. static void mainLoop();
  64. static CBasicLogConfigurator *logConfig;
  65. static void init()
  66. {
  67. CStopWatch tmh;
  68. try
  69. {
  70. loadDLLClasses();
  71. }
  72. catch (const DataLoadingException & e)
  73. {
  74. criticalInitializationError = e.what();
  75. return;
  76. }
  77. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  78. // Debug code to load all maps on start
  79. //ClientCommandManager commandController;
  80. //commandController.processCommand("translate maps", false);
  81. }
  82. static void checkForModLoadingFailure()
  83. {
  84. const auto & brokenMods = LIBRARY->identifiersHandler->getModsWithFailedRequests();
  85. if (!brokenMods.empty())
  86. {
  87. MetaString messageText;
  88. messageText.appendTextID("vcmi.client.errors.modLoadingFailure");
  89. for (const auto & modID : brokenMods)
  90. {
  91. messageText.appendRawString(LIBRARY->modh->getModInfo(modID).getName());
  92. messageText.appendEOL();
  93. }
  94. CInfoWindow::showInfoDialog(messageText.toString(), {});
  95. }
  96. }
  97. static void prog_version()
  98. {
  99. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  100. std::cout << VCMIDirs::get().genHelpString();
  101. }
  102. static void prog_help(const po::options_description &opts)
  103. {
  104. auto time = std::time(nullptr);
  105. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  106. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  107. printf("This is free software; see the source for copying conditions. There is NO\n");
  108. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  109. printf("\n");
  110. std::cout << opts;
  111. }
  112. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  113. int wmain(int argc, wchar_t* argv[])
  114. #elif defined(VCMI_MOBILE)
  115. int SDL_main(int argc, char *argv[])
  116. #else
  117. int main(int argc, char * argv[])
  118. #endif
  119. {
  120. #ifdef VCMI_ANDROID
  121. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  122. // boost will crash without this
  123. setenv("LANG", "C", 1);
  124. #endif
  125. #if !defined(VCMI_MOBILE)
  126. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  127. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  128. #endif
  129. std::cout << "Starting... " << std::endl;
  130. po::options_description opts("Allowed options");
  131. po::variables_map vm;
  132. opts.add_options()
  133. ("help,h", "display help and exit")
  134. ("version,v", "display version information and exit")
  135. ("testmap", po::value<std::string>(), "")
  136. ("testsave", po::value<std::string>(), "")
  137. ("logLocation", po::value<std::string>(), "new location for log files")
  138. ("spectate,s", "enable spectator interface for AI-only games")
  139. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  140. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  141. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  142. ("spectate-skip-battle", "skip battles in spectator view")
  143. ("spectate-skip-battle-result", "skip battle result window")
  144. ("onlyAI", "allow one to run without human player, all players will be default AI")
  145. ("headless", "runs without GUI, implies --onlyAI")
  146. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  147. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  148. ("autoSkip", "automatically skip turns in GUI")
  149. ("disable-video", "disable video player")
  150. ("nointro,i", "skips intro movies")
  151. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  152. ("serverport", po::value<si64>(), "override port specified in config file")
  153. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
  154. if(argc > 1)
  155. {
  156. try
  157. {
  158. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  159. }
  160. catch(boost::program_options::error &e)
  161. {
  162. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  163. }
  164. }
  165. po::notify(vm);
  166. if(vm.count("help"))
  167. {
  168. prog_help(opts);
  169. #ifdef VCMI_IOS
  170. exit(0);
  171. #else
  172. return 0;
  173. #endif
  174. }
  175. if(vm.count("version"))
  176. {
  177. prog_version();
  178. #ifdef VCMI_IOS
  179. exit(0);
  180. #else
  181. return 0;
  182. #endif
  183. }
  184. // Init old logging system and new (temporary) logging system
  185. CStopWatch total;
  186. CStopWatch pomtime;
  187. std::cout.flags(std::ios::unitbuf);
  188. #ifndef VCMI_IOS
  189. console = new CConsoleHandler();
  190. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  191. {
  192. ClientCommandManager commandController;
  193. commandController.processCommand(buffer, calledFromIngameConsole);
  194. };
  195. *console->cb = callbackFunction;
  196. console->start();
  197. #endif
  198. setThreadNameLoggingOnly("MainGUI");
  199. boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  200. if(vm.count("logLocation"))
  201. logPath = vm["logLocation"].as<std::string>() + "/VCMI_Client_log.txt";
  202. logConfig = new CBasicLogConfigurator(logPath, console);
  203. logConfig->configureDefault();
  204. logGlobal->info("Starting client of '%s'", GameConstants::VCMI_VERSION);
  205. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  206. logGlobal->info("The log file will be saved to %s", logPath);
  207. // Init filesystem and settings
  208. try
  209. {
  210. preinitDLL(::console, false);
  211. }
  212. catch (const DataLoadingException & e)
  213. {
  214. handleFatalError(e.what(), true);
  215. }
  216. Settings session = settings.write["session"];
  217. auto setSettingBool = [&](std::string key, std::string arg) {
  218. Settings s = settings.write(vstd::split(key, "/"));
  219. if(vm.count(arg))
  220. s->Bool() = true;
  221. else if(s->isNull())
  222. s->Bool() = false;
  223. };
  224. auto setSettingInteger = [&](std::string key, std::string arg, si64 defaultValue) {
  225. Settings s = settings.write(vstd::split(key, "/"));
  226. if(vm.count(arg))
  227. s->Integer() = vm[arg].as<si64>();
  228. else if(s->isNull())
  229. s->Integer() = defaultValue;
  230. };
  231. setSettingBool("session/onlyai", "onlyAI");
  232. setSettingBool("session/disableVideo", "disable-video");
  233. if(vm.count("headless"))
  234. {
  235. session["headless"].Bool() = true;
  236. session["onlyai"].Bool() = true;
  237. }
  238. else if(vm.count("spectate"))
  239. {
  240. session["spectate"].Bool() = true;
  241. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  242. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  243. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  244. if(vm.count("spectate-hero-speed"))
  245. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  246. if(vm.count("spectate-battle-speed"))
  247. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  248. }
  249. // Server settings
  250. setSettingBool("session/donotstartserver", "donotstartserver");
  251. // Init special testing settings
  252. setSettingInteger("session/serverport", "serverport", 0);
  253. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  254. // Initialize logging based on settings
  255. logConfig->configure();
  256. logGlobal->debug("settings = %s", settings.toJsonNode().toString());
  257. // Some basic data validation to produce better error messages in cases of incorrect install
  258. auto testFile = [](std::string filename, std::string message)
  259. {
  260. if (!CResourceHandler::get()->existsResource(ResourcePath(filename)))
  261. handleFatalError(message, false);
  262. };
  263. testFile("DATA/HELP.TXT", "VCMI requires Heroes III: Shadow of Death or Heroes III: Complete data files to run!");
  264. testFile("DATA/TENTCOLR.TXT", "Heroes III: Restoration of Erathia (including HD Edition) data files are not supported!");
  265. testFile("MODS/VCMI/MOD.JSON", "VCMI installation is corrupted! Built-in mod was not found!");
  266. testFile("DATA/PLAYERS.PAL", "Heroes III data files (Data/H3Bitmap.lod) are incomplete or corruped! Please reinstall them.");
  267. testFile("SPRITES/DEFAULT.DEF", "Heroes III data files (Data/H3Sprite.lod) are incomplete or corruped! Please reinstall them.");
  268. srand ( (unsigned int)time(nullptr) );
  269. ENGINE = std::make_unique<GameEngine>();
  270. if(!settings["session"]["headless"].Bool())
  271. ENGINE->init();
  272. GAME = std::make_unique<GameInstance>();
  273. #ifndef VCMI_NO_THREADED_LOAD
  274. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  275. boost::thread loading([]()
  276. {
  277. setThreadName("initialize");
  278. init();
  279. });
  280. #else
  281. init();
  282. #endif
  283. #ifndef VCMI_NO_THREADED_LOAD
  284. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  285. {
  286. CAndroidVMHelper vmHelper;
  287. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  288. #endif // ANDROID
  289. loading.join();
  290. #ifdef VCMI_ANDROID
  291. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  292. }
  293. #endif // ANDROID
  294. #endif // THREADED
  295. if (criticalInitializationError.has_value())
  296. {
  297. handleFatalError(criticalInitializationError.value(), false);
  298. }
  299. if(!settings["session"]["headless"].Bool())
  300. {
  301. pomtime.getDiff();
  302. graphics = new Graphics(); // should be before curh
  303. ENGINE->renderHandler().onLibraryLoadingFinished(LIBRARY);
  304. CMessage::init();
  305. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  306. ENGINE->cursor().init();
  307. ENGINE->cursor().show();
  308. }
  309. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  310. session["autoSkip"].Bool() = vm.count("autoSkip");
  311. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  312. session["aiSolo"].Bool() = false;
  313. if(vm.count("testmap"))
  314. {
  315. session["testmap"].String() = vm["testmap"].as<std::string>();
  316. session["onlyai"].Bool() = true;
  317. boost::thread(&CServerHandler::debugStartTest, &GAME->server(), session["testmap"].String(), false);
  318. }
  319. else if(vm.count("testsave"))
  320. {
  321. session["testsave"].String() = vm["testsave"].as<std::string>();
  322. session["onlyai"].Bool() = true;
  323. boost::thread(&CServerHandler::debugStartTest, &GAME->server(), session["testsave"].String(), true);
  324. }
  325. else
  326. {
  327. auto mmenu = CMainMenu::create();
  328. ENGINE->curInt = mmenu.get();
  329. bool playIntroVideo = !settings["session"]["headless"].Bool() && !vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool();
  330. if(playIntroVideo)
  331. mmenu->playIntroVideos();
  332. else
  333. mmenu->playMusic();
  334. }
  335. std::vector<std::string> names;
  336. if(!settings["session"]["headless"].Bool())
  337. {
  338. checkForModLoadingFailure();
  339. mainLoop();
  340. }
  341. else
  342. {
  343. while(!headlessQuit)
  344. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  345. boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  346. quitApplication();
  347. }
  348. return 0;
  349. }
  350. static void mainLoop()
  351. {
  352. #ifndef VCMI_UNIX
  353. // on Linux, name of main thread is also name of our process. Which we don't want to change
  354. setThreadName("MainGUI");
  355. #endif
  356. while(1) //main SDL events loop
  357. {
  358. ENGINE->input().fetchEvents();
  359. ENGINE->renderFrame();
  360. }
  361. }
  362. [[noreturn]] static void quitApplicationImmediately(int error_code)
  363. {
  364. // Perform quick exit without executing static destructors and let OS cleanup anything that we did not
  365. // We generally don't care about them and this leads to numerous issues, e.g.
  366. // destruction of locked mutexes (fails an assertion), even in third-party libraries (as well as native libs on Android)
  367. // Android - std::quick_exit is available only starting from API level 21
  368. // Mingw, macOS and iOS - std::quick_exit is unavailable (at least in current version of CI)
  369. #if (defined(__ANDROID_API__) && __ANDROID_API__ < 21) || (defined(__MINGW32__)) || defined(VCMI_APPLE)
  370. ::exit(error_code);
  371. #else
  372. std::quick_exit(error_code);
  373. #endif
  374. }
  375. [[noreturn]] static void quitApplication()
  376. {
  377. GAME->server().endNetwork();
  378. if(!settings["session"]["headless"].Bool())
  379. {
  380. if(GAME->server().client)
  381. GAME->server().endGameplay();
  382. ENGINE->windows().clear();
  383. }
  384. GAME.reset();
  385. CMM.reset();
  386. if(!settings["session"]["headless"].Bool())
  387. {
  388. CMessage::dispose();
  389. vstd::clear_pointer(graphics);
  390. }
  391. vstd::clear_pointer(LIBRARY);
  392. // sometimes leads to a hang. TODO: investigate
  393. //vstd::clear_pointer(console);// should be removed after everything else since used by logging
  394. if(!settings["session"]["headless"].Bool())
  395. ENGINE->screenHandler().close();
  396. if(logConfig != nullptr)
  397. {
  398. logConfig->deconfigure();
  399. delete logConfig;
  400. logConfig = nullptr;
  401. }
  402. //ENGINE.reset();
  403. std::cout << "Ending...\n";
  404. quitApplicationImmediately(0);
  405. }
  406. void handleQuit(bool ask)
  407. {
  408. if(!ask)
  409. {
  410. if(settings["session"]["headless"].Bool())
  411. {
  412. headlessQuit = true;
  413. }
  414. else
  415. {
  416. quitApplication();
  417. }
  418. return;
  419. }
  420. if (GAME->interface())
  421. GAME->interface()->showYesNoDialog(LIBRARY->generaltexth->allTexts[69], quitApplication, nullptr);
  422. else
  423. CInfoWindow::showYesNoDialog(LIBRARY->generaltexth->allTexts[69], {}, quitApplication, {}, PlayerColor(1));
  424. }
  425. /// Notify user about encountered fatal error and terminate the game
  426. /// TODO: decide on better location for this method
  427. void handleFatalError(const std::string & message, bool terminate)
  428. {
  429. logGlobal->error("FATAL ERROR ENCOUNTERED, VCMI WILL NOW TERMINATE");
  430. logGlobal->error("Reason: %s", message);
  431. std::string messageToShow = "Fatal error! " + message;
  432. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal error!", messageToShow.c_str(), nullptr);
  433. if (terminate)
  434. throw std::runtime_error(message);
  435. else
  436. quitApplicationImmediately(1);
  437. }