EntryPoint.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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/CGameInfo.h"
  14. #include "../client/ClientCommandManager.h"
  15. #include "../client/CMT.h"
  16. #include "../client/CPlayerInterface.h"
  17. #include "../client/CServerHandler.h"
  18. #include "../client/eventsSDL/InputHandler.h"
  19. #include "../client/gui/CGuiHandler.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/VCMI_Lib.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. CGI->setFromLib();
  72. }
  73. catch (const DataLoadingException & e)
  74. {
  75. criticalInitializationError = e.what();
  76. return;
  77. }
  78. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  79. // Debug code to load all maps on start
  80. //ClientCommandManager commandController;
  81. //commandController.processCommand("translate maps", false);
  82. }
  83. static void checkForModLoadingFailure()
  84. {
  85. const auto & brokenMods = VLC->identifiersHandler->getModsWithFailedRequests();
  86. if (!brokenMods.empty())
  87. {
  88. MetaString messageText;
  89. messageText.appendTextID("vcmi.client.errors.modLoadingFailure");
  90. for (const auto & modID : brokenMods)
  91. {
  92. messageText.appendRawString(VLC->modh->getModInfo(modID).getName());
  93. messageText.appendEOL();
  94. }
  95. CInfoWindow::showInfoDialog(messageText.toString(), {});
  96. }
  97. }
  98. static void prog_version()
  99. {
  100. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  101. std::cout << VCMIDirs::get().genHelpString();
  102. }
  103. static void prog_help(const po::options_description &opts)
  104. {
  105. auto time = std::time(nullptr);
  106. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  107. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  108. printf("This is free software; see the source for copying conditions. There is NO\n");
  109. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  110. printf("\n");
  111. std::cout << opts;
  112. }
  113. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  114. int wmain(int argc, wchar_t* argv[])
  115. #elif defined(VCMI_MOBILE)
  116. int SDL_main(int argc, char *argv[])
  117. #else
  118. int main(int argc, char * argv[])
  119. #endif
  120. {
  121. #ifdef VCMI_ANDROID
  122. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  123. // boost will crash without this
  124. setenv("LANG", "C", 1);
  125. #endif
  126. #if !defined(VCMI_MOBILE)
  127. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  128. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  129. #endif
  130. std::cout << "Starting... " << std::endl;
  131. po::options_description opts("Allowed options");
  132. po::variables_map vm;
  133. opts.add_options()
  134. ("help,h", "display help and exit")
  135. ("version,v", "display version information and exit")
  136. ("testmap", po::value<std::string>(), "")
  137. ("testsave", po::value<std::string>(), "")
  138. ("logLocation", po::value<std::string>(), "new location for log files")
  139. ("spectate,s", "enable spectator interface for AI-only games")
  140. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  141. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  142. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  143. ("spectate-skip-battle", "skip battles in spectator view")
  144. ("spectate-skip-battle-result", "skip battle result window")
  145. ("onlyAI", "allow one to run without human player, all players will be default AI")
  146. ("headless", "runs without GUI, implies --onlyAI")
  147. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  148. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  149. ("autoSkip", "automatically skip turns in GUI")
  150. ("disable-video", "disable video player")
  151. ("nointro,i", "skips intro movies")
  152. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  153. ("serverport", po::value<si64>(), "override port specified in config file")
  154. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
  155. if(argc > 1)
  156. {
  157. try
  158. {
  159. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  160. }
  161. catch(boost::program_options::error &e)
  162. {
  163. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  164. }
  165. }
  166. po::notify(vm);
  167. if(vm.count("help"))
  168. {
  169. prog_help(opts);
  170. #ifdef VCMI_IOS
  171. exit(0);
  172. #else
  173. return 0;
  174. #endif
  175. }
  176. if(vm.count("version"))
  177. {
  178. prog_version();
  179. #ifdef VCMI_IOS
  180. exit(0);
  181. #else
  182. return 0;
  183. #endif
  184. }
  185. // Init old logging system and new (temporary) logging system
  186. CStopWatch total;
  187. CStopWatch pomtime;
  188. std::cout.flags(std::ios::unitbuf);
  189. #ifndef VCMI_IOS
  190. console = new CConsoleHandler();
  191. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  192. {
  193. ClientCommandManager commandController;
  194. commandController.processCommand(buffer, calledFromIngameConsole);
  195. };
  196. *console->cb = callbackFunction;
  197. console->start();
  198. #endif
  199. setThreadNameLoggingOnly("MainGUI");
  200. boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  201. if(vm.count("logLocation"))
  202. logPath = vm["logLocation"].as<std::string>() + "/VCMI_Client_log.txt";
  203. logConfig = new CBasicLogConfigurator(logPath, console);
  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(::console, 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. 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!\nBuilt-in mod was not found!");
  266. testFile("DATA/NOTOSERIF-MEDIUM.TTF", "VCMI installation is corrupted!\nBuilt-in font was not found!\nManually deleting '" + VCMIDirs::get().userDataPath().string() + "/Mods/VCMI' directory (if it exists)\nor clearing app data and reimporting Heroes III files may fix this problem.");
  267. testFile("DATA/PLAYERS.PAL", "Heroes III data files (Data/H3Bitmap.lod) are incomplete or corruped!\n Please reinstall them.");
  268. testFile("SPRITES/DEFAULT.DEF", "Heroes III data files (Data/H3Sprite.lod) are incomplete or corruped!\n Please reinstall them.");
  269. srand ( (unsigned int)time(nullptr) );
  270. if(!settings["session"]["headless"].Bool())
  271. GH.init();
  272. CCS = new CClientState();
  273. CGI = new CGameInfo(); //contains all global information about game (texts, lodHandlers, map handler etc.)
  274. CSH = new CServerHandler();
  275. // Initialize video
  276. #ifndef ENABLE_VIDEO
  277. CCS->videoh = new CEmptyVideoPlayer();
  278. #else
  279. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  280. CCS->videoh = new CVideoPlayer();
  281. else
  282. CCS->videoh = new CEmptyVideoPlayer();
  283. #endif
  284. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  285. if(!settings["session"]["headless"].Bool())
  286. {
  287. //initializing audio
  288. CCS->soundh = new CSoundHandler();
  289. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  290. CCS->musich = new CMusicHandler();
  291. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  292. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  293. }
  294. #ifndef VCMI_NO_THREADED_LOAD
  295. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  296. boost::thread loading([]()
  297. {
  298. setThreadName("initialize");
  299. init();
  300. });
  301. #else
  302. init();
  303. #endif
  304. #ifndef VCMI_NO_THREADED_LOAD
  305. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  306. {
  307. CAndroidVMHelper vmHelper;
  308. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  309. #endif // ANDROID
  310. loading.join();
  311. #ifdef VCMI_ANDROID
  312. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  313. }
  314. #endif // ANDROID
  315. #endif // THREADED
  316. if (criticalInitializationError.has_value())
  317. {
  318. handleFatalError(criticalInitializationError.value(), false);
  319. }
  320. if(!settings["session"]["headless"].Bool())
  321. {
  322. pomtime.getDiff();
  323. graphics = new Graphics(); // should be before curh
  324. GH.renderHandler().onLibraryLoadingFinished(CGI);
  325. CCS->curh = new CursorHandler();
  326. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  327. CMessage::init();
  328. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  329. CCS->curh->show();
  330. }
  331. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  332. session["autoSkip"].Bool() = vm.count("autoSkip");
  333. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  334. session["aiSolo"].Bool() = false;
  335. if(vm.count("testmap"))
  336. {
  337. session["testmap"].String() = vm["testmap"].as<std::string>();
  338. session["onlyai"].Bool() = true;
  339. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  340. }
  341. else if(vm.count("testsave"))
  342. {
  343. session["testsave"].String() = vm["testsave"].as<std::string>();
  344. session["onlyai"].Bool() = true;
  345. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  346. }
  347. else
  348. {
  349. auto mmenu = CMainMenu::create();
  350. GH.curInt = mmenu.get();
  351. bool playIntroVideo = !settings["session"]["headless"].Bool() && !vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool();
  352. if(playIntroVideo)
  353. mmenu->playIntroVideos();
  354. else
  355. mmenu->playMusic();
  356. }
  357. std::vector<std::string> names;
  358. if(!settings["session"]["headless"].Bool())
  359. {
  360. checkForModLoadingFailure();
  361. mainLoop();
  362. }
  363. else
  364. {
  365. while(!headlessQuit)
  366. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  367. boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  368. quitApplication();
  369. }
  370. return 0;
  371. }
  372. static void mainLoop()
  373. {
  374. #ifndef VCMI_UNIX
  375. // on Linux, name of main thread is also name of our process. Which we don't want to change
  376. setThreadName("MainGUI");
  377. #endif
  378. while(1) //main SDL events loop
  379. {
  380. GH.input().fetchEvents();
  381. GH.renderFrame();
  382. }
  383. }
  384. [[noreturn]] static void quitApplicationImmediately(int error_code)
  385. {
  386. // Perform quick exit without executing static destructors and let OS cleanup anything that we did not
  387. // We generally don't care about them and this leads to numerous issues, e.g.
  388. // destruction of locked mutexes (fails an assertion), even in third-party libraries (as well as native libs on Android)
  389. // Android - std::quick_exit is available only starting from API level 21
  390. // Mingw, macOS and iOS - std::quick_exit is unavailable (at least in current version of CI)
  391. #if (defined(__ANDROID_API__) && __ANDROID_API__ < 21) || (defined(__MINGW32__)) || defined(VCMI_APPLE)
  392. ::exit(error_code);
  393. #else
  394. std::quick_exit(error_code);
  395. #endif
  396. }
  397. [[noreturn]] static void quitApplication()
  398. {
  399. CSH->endNetwork();
  400. if(!settings["session"]["headless"].Bool())
  401. {
  402. if(CSH->client)
  403. CSH->endGameplay();
  404. GH.windows().clear();
  405. }
  406. vstd::clear_pointer(CSH);
  407. CMM.reset();
  408. if(!settings["session"]["headless"].Bool())
  409. {
  410. // cleanup, mostly to remove false leaks from analyzer
  411. if(CCS)
  412. {
  413. delete CCS->consoleh;
  414. delete CCS->curh;
  415. delete CCS->videoh;
  416. delete CCS->musich;
  417. delete CCS->soundh;
  418. vstd::clear_pointer(CCS);
  419. }
  420. CMessage::dispose();
  421. vstd::clear_pointer(graphics);
  422. }
  423. vstd::clear_pointer(VLC);
  424. // sometimes leads to a hang. TODO: investigate
  425. //vstd::clear_pointer(console);// should be removed after everything else since used by logging
  426. if(!settings["session"]["headless"].Bool())
  427. GH.screenHandler().close();
  428. if(logConfig != nullptr)
  429. {
  430. logConfig->deconfigure();
  431. delete logConfig;
  432. logConfig = nullptr;
  433. }
  434. std::cout << "Ending...\n";
  435. quitApplicationImmediately(0);
  436. }
  437. void handleQuit(bool ask)
  438. {
  439. if(!ask)
  440. {
  441. if(settings["session"]["headless"].Bool())
  442. {
  443. headlessQuit = true;
  444. }
  445. else
  446. {
  447. quitApplication();
  448. }
  449. return;
  450. }
  451. // FIXME: avoids crash if player attempts to close game while opening is still playing
  452. // use cursor handler as indicator that loading is not done yet
  453. // proper solution would be to abort init thread (or wait for it to finish)
  454. if (!CCS->curh)
  455. {
  456. quitApplicationImmediately(0);
  457. }
  458. if (LOCPLINT)
  459. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, nullptr);
  460. else
  461. CInfoWindow::showYesNoDialog(CGI->generaltexth->allTexts[69], {}, quitApplication, {}, PlayerColor(1));
  462. }
  463. /// Notify user about encountered fatal error and terminate the game
  464. /// TODO: decide on better location for this method
  465. void handleFatalError(const std::string & message, bool terminate)
  466. {
  467. logGlobal->error("FATAL ERROR ENCOUNTERED, VCMI WILL NOW TERMINATE");
  468. logGlobal->error("Reason: %s", message);
  469. std::string messageToShow = "Fatal error! " + message;
  470. SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Fatal error!", messageToShow.c_str(), nullptr);
  471. if (terminate)
  472. throw std::runtime_error(message);
  473. else
  474. quitApplicationImmediately(1);
  475. }