CMT.cpp 17 KB

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