CMT.cpp 15 KB

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