CMT.cpp 16 KB

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