EntryPoint.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. setThreadNameLoggingOnly("MainGUI");
  189. boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  190. if(vm.count("logLocation"))
  191. logPath = vm["logLocation"].as<std::string>() + "/VCMI_Client_log.txt";
  192. #ifndef VCMI_IOS
  193. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  194. {
  195. ClientCommandManager commandController;
  196. commandController.processCommand(buffer, calledFromIngameConsole);
  197. };
  198. CConsoleHandler console(callbackFunction);
  199. console.start();
  200. logConfig = new CBasicLogConfigurator(logPath, &console);
  201. #else
  202. logConfig = new CBasicLogConfigurator(logPath, nullptr);
  203. #endif
  204. logConfig->configureDefault();
  205. logGlobal->info("Starting client of '%s'", GameConstants::VCMI_VERSION);
  206. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  207. logGlobal->info("The log file will be saved to %s", logPath);
  208. // Init filesystem and settings
  209. try
  210. {
  211. preinitDLL(false);
  212. }
  213. catch (const DataLoadingException & e)
  214. {
  215. handleFatalError(e.what(), true);
  216. }
  217. Settings session = settings.write["session"];
  218. auto setSettingBool = [&](std::string key, std::string arg) {
  219. Settings s = settings.write(vstd::split(key, "/"));
  220. if(vm.count(arg))
  221. s->Bool() = true;
  222. else if(s->isNull())
  223. s->Bool() = false;
  224. };
  225. auto setSettingInteger = [&](std::string key, std::string arg, si64 defaultValue) {
  226. Settings s = settings.write(vstd::split(key, "/"));
  227. if(vm.count(arg))
  228. s->Integer() = vm[arg].as<si64>();
  229. else if(s->isNull())
  230. s->Integer() = defaultValue;
  231. };
  232. setSettingBool("session/onlyai", "onlyAI");
  233. setSettingBool("session/disableVideo", "disable-video");
  234. if(vm.count("headless"))
  235. {
  236. session["headless"].Bool() = true;
  237. session["onlyai"].Bool() = true;
  238. }
  239. else if(vm.count("spectate"))
  240. {
  241. session["spectate"].Bool() = true;
  242. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  243. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  244. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  245. if(vm.count("spectate-hero-speed"))
  246. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  247. if(vm.count("spectate-battle-speed"))
  248. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  249. }
  250. // Server settings
  251. setSettingBool("session/donotstartserver", "donotstartserver");
  252. // Init special testing settings
  253. setSettingInteger("session/serverport", "serverport", 0);
  254. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  255. // Initialize logging based on settings
  256. logConfig->configure();
  257. logGlobal->debug("settings = %s", settings.toJsonNode().toString());
  258. // Some basic data validation to produce better error messages in cases of incorrect install
  259. auto testFile = [](std::string filename, std::string message)
  260. {
  261. if (!CResourceHandler::get()->existsResource(ResourcePath(filename)))
  262. handleFatalError(message, false);
  263. };
  264. testFile("DATA/HELP.TXT", "VCMI requires Heroes III: Shadow of Death or Heroes III: Complete data files to run!");
  265. testFile("DATA/TENTCOLR.TXT", "Heroes III: Restoration of Erathia (including HD Edition) data files are not supported!");
  266. testFile("MODS/VCMI/MOD.JSON", "VCMI installation is corrupted! Built-in mod was not found!");
  267. testFile("DATA/PLAYERS.PAL", "Heroes III data files (Data/H3Bitmap.lod) are incomplete or corruped! Please reinstall them.");
  268. testFile("SPRITES/DEFAULT.DEF", "Heroes III data files (Data/H3Sprite.lod) are incomplete or corruped! Please reinstall them.");
  269. srand ( (unsigned int)time(nullptr) );
  270. ENGINE = std::make_unique<GameEngine>();
  271. if(!settings["session"]["headless"].Bool())
  272. ENGINE->init();
  273. GAME = std::make_unique<GameInstance>();
  274. ENGINE->setEngineUser(GAME.get());
  275. #ifndef VCMI_NO_THREADED_LOAD
  276. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  277. boost::thread loading([]()
  278. {
  279. setThreadName("initialize");
  280. init();
  281. });
  282. #else
  283. init();
  284. #endif
  285. #ifndef VCMI_NO_THREADED_LOAD
  286. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  287. {
  288. CAndroidVMHelper vmHelper;
  289. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  290. #endif // ANDROID
  291. loading.join();
  292. #ifdef VCMI_ANDROID
  293. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  294. }
  295. #endif // ANDROID
  296. #endif // THREADED
  297. if (criticalInitializationError.has_value())
  298. {
  299. handleFatalError(criticalInitializationError.value(), false);
  300. }
  301. if(!settings["session"]["headless"].Bool())
  302. {
  303. pomtime.getDiff();
  304. graphics = new Graphics(); // should be before curh
  305. ENGINE->renderHandler().onLibraryLoadingFinished(LIBRARY);
  306. CMessage::init();
  307. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  308. ENGINE->cursor().init();
  309. ENGINE->cursor().show();
  310. }
  311. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  312. session["autoSkip"].Bool() = vm.count("autoSkip");
  313. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  314. session["aiSolo"].Bool() = false;
  315. if(vm.count("testmap"))
  316. {
  317. session["testmap"].String() = vm["testmap"].as<std::string>();
  318. session["onlyai"].Bool() = true;
  319. boost::thread(&CServerHandler::debugStartTest, &GAME->server(), session["testmap"].String(), false);
  320. }
  321. else if(vm.count("testsave"))
  322. {
  323. session["testsave"].String() = vm["testsave"].as<std::string>();
  324. session["onlyai"].Bool() = true;
  325. boost::thread(&CServerHandler::debugStartTest, &GAME->server(), session["testsave"].String(), true);
  326. }
  327. else if (!settings["session"]["headless"].Bool())
  328. {
  329. GAME->mainmenu()->makeActiveInterface();
  330. bool playIntroVideo = !vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool();
  331. if(playIntroVideo)
  332. GAME->mainmenu()->playIntroVideos();
  333. else
  334. GAME->mainmenu()->playMusic();
  335. }
  336. std::vector<std::string> names;
  337. if(!settings["session"]["headless"].Bool())
  338. {
  339. checkForModLoadingFailure();
  340. mainLoop();
  341. }
  342. else
  343. {
  344. while(!headlessQuit)
  345. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  346. boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  347. quitApplication();
  348. }
  349. return 0;
  350. }
  351. static void mainLoop()
  352. {
  353. #ifndef VCMI_UNIX
  354. // on Linux, name of main thread is also name of our process. Which we don't want to change
  355. setThreadName("MainGUI");
  356. #endif
  357. while(1) //main SDL events loop
  358. {
  359. ENGINE->input().fetchEvents();
  360. ENGINE->renderFrame();
  361. }
  362. }
  363. [[noreturn]] static void quitApplicationImmediately(int error_code)
  364. {
  365. // Perform quick exit without executing static destructors and let OS cleanup anything that we did not
  366. // We generally don't care about them and this leads to numerous issues, e.g.
  367. // destruction of locked mutexes (fails an assertion), even in third-party libraries (as well as native libs on Android)
  368. // Android - std::quick_exit is available only starting from API level 21
  369. // Mingw, macOS and iOS - std::quick_exit is unavailable (at least in current version of CI)
  370. #if (defined(__ANDROID_API__) && __ANDROID_API__ < 21) || (defined(__MINGW32__)) || defined(VCMI_APPLE)
  371. ::exit(error_code);
  372. #else
  373. std::quick_exit(error_code);
  374. #endif
  375. }
  376. [[noreturn]] static void quitApplication()
  377. {
  378. GAME->server().endNetwork();
  379. if(!settings["session"]["headless"].Bool())
  380. {
  381. if(GAME->server().client)
  382. GAME->server().endGameplay();
  383. ENGINE->windows().clear();
  384. }
  385. GAME.reset();
  386. GAME->mainmenu().reset();
  387. if(!settings["session"]["headless"].Bool())
  388. {
  389. CMessage::dispose();
  390. vstd::clear_pointer(graphics);
  391. }
  392. vstd::clear_pointer(LIBRARY);
  393. // sometimes leads to a hang. TODO: investigate
  394. //vstd::clear_pointer(console);// should be removed after everything else since used by logging
  395. if(!settings["session"]["headless"].Bool())
  396. ENGINE->screenHandler().close();
  397. if(logConfig != nullptr)
  398. {
  399. logConfig->deconfigure();
  400. delete logConfig;
  401. logConfig = nullptr;
  402. }
  403. //ENGINE.reset();
  404. std::cout << "Ending...\n";
  405. quitApplicationImmediately(0);
  406. }
  407. void handleQuit(bool ask)
  408. {
  409. if(!ask)
  410. {
  411. if(settings["session"]["headless"].Bool())
  412. {
  413. headlessQuit = true;
  414. }
  415. else
  416. {
  417. quitApplication();
  418. }
  419. return;
  420. }
  421. if (GAME->interface())
  422. GAME->interface()->showYesNoDialog(LIBRARY->generaltexth->allTexts[69], quitApplication, nullptr);
  423. else
  424. CInfoWindow::showYesNoDialog(LIBRARY->generaltexth->allTexts[69], {}, quitApplication, {}, PlayerColor(1));
  425. }
  426. /// Notify user about encountered fatal error and terminate the game
  427. /// TODO: decide on better location for this method
  428. void handleFatalError(const std::string & message, bool terminate)
  429. {
  430. logGlobal->error("FATAL ERROR ENCOUNTERED, VCMI WILL NOW TERMINATE");
  431. logGlobal->error("Reason: %s", message);
  432. std::string messageToShow = "Fatal error! " + message;
  433. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal error!", messageToShow.c_str(), nullptr);
  434. if (terminate)
  435. throw std::runtime_error(message);
  436. else
  437. quitApplicationImmediately(1);
  438. }