EntryPoint.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 "Global.h"
  12. #include "StdInc.h"
  13. #include "client/CGameInfo.h"
  14. #include "client/mainmenu/CMainMenu.h"
  15. #include "media/CEmptyVideoPlayer.h"
  16. #include "media/CMusicHandler.h"
  17. #include "media/CSoundHandler.h"
  18. #include "media/CVideoHandler.h"
  19. #include "client/gui/CursorHandler.h"
  20. #include "client/eventsSDL/InputHandler.h"
  21. #include "client/gui/CGuiHandler.h"
  22. #include "client/CServerHandler.h"
  23. #include "client/ClientCommandManager.h"
  24. #include "client/windows/CMessage.h"
  25. #include "client/render/IRenderHandler.h"
  26. #include "client/render/IScreenHandler.h"
  27. #include "client/render/Graphics.h"
  28. #include "client/CMT.h"
  29. #include "../lib/CThreadHelper.h"
  30. #include "../lib/ExceptionsCommon.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. std::atomic<bool> headlessQuit = false;
  49. std::optional<std::string> criticalInitializationError;
  50. #ifndef VCMI_IOS
  51. void processCommand(const std::string &message);
  52. #endif
  53. void playIntro();
  54. static void mainLoop();
  55. CBasicLogConfigurator *logConfig;
  56. void init()
  57. {
  58. CStopWatch tmh;
  59. try
  60. {
  61. loadDLLClasses();
  62. CGI->setFromLib();
  63. }
  64. catch (const DataLoadingException & e)
  65. {
  66. criticalInitializationError = e.what();
  67. return;
  68. }
  69. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  70. // Debug code to load all maps on start
  71. //ClientCommandManager commandController;
  72. //commandController.processCommand("convert txt", false);
  73. }
  74. static void prog_version()
  75. {
  76. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  77. std::cout << VCMIDirs::get().genHelpString();
  78. }
  79. static void prog_help(const po::options_description &opts)
  80. {
  81. auto time = std::time(nullptr);
  82. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  83. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  84. printf("This is free software; see the source for copying conditions. There is NO\n");
  85. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  86. printf("\n");
  87. std::cout << opts;
  88. }
  89. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  90. int wmain(int argc, wchar_t* argv[])
  91. #elif defined(VCMI_MOBILE)
  92. int SDL_main(int argc, char *argv[])
  93. #else
  94. int main(int argc, char * argv[])
  95. #endif
  96. {
  97. #ifdef VCMI_ANDROID
  98. CAndroidVMHelper::initClassloader(SDL_AndroidGetJNIEnv());
  99. // boost will crash without this
  100. setenv("LANG", "C", 1);
  101. #endif
  102. #if !defined(VCMI_MOBILE)
  103. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  104. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  105. #endif
  106. std::cout << "Starting... " << std::endl;
  107. po::options_description opts("Allowed options");
  108. po::variables_map vm;
  109. opts.add_options()
  110. ("help,h", "display help and exit")
  111. ("version,v", "display version information and exit")
  112. ("testmap", po::value<std::string>(), "")
  113. ("testsave", po::value<std::string>(), "")
  114. ("spectate,s", "enable spectator interface for AI-only games")
  115. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  116. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  117. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  118. ("spectate-skip-battle", "skip battles in spectator view")
  119. ("spectate-skip-battle-result", "skip battle result window")
  120. ("onlyAI", "allow one to run without human player, all players will be default AI")
  121. ("headless", "runs without GUI, implies --onlyAI")
  122. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  123. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  124. ("autoSkip", "automatically skip turns in GUI")
  125. ("disable-video", "disable video player")
  126. ("nointro,i", "skips intro movies")
  127. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  128. ("serverport", po::value<si64>(), "override port specified in config file")
  129. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
  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(boost::program_options::error &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;
  162. CStopWatch 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. setThreadNameLoggingOnly("MainGUI");
  175. const boost::filesystem::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  176. logConfig = new CBasicLogConfigurator(logPath, console);
  177. logConfig->configureDefault();
  178. logGlobal->info("Starting client of '%s'", GameConstants::VCMI_VERSION);
  179. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  180. logGlobal->info("The log file will be saved to %s", logPath);
  181. // Init filesystem and settings
  182. try
  183. {
  184. preinitDLL(::console, false);
  185. }
  186. catch (const DataLoadingException & e)
  187. {
  188. handleFatalError(e.what(), true);
  189. }
  190. Settings session = settings.write["session"];
  191. auto setSettingBool = [&](std::string key, std::string arg) {
  192. Settings s = settings.write(vstd::split(key, "/"));
  193. if(vm.count(arg))
  194. s->Bool() = true;
  195. else if(s->isNull())
  196. s->Bool() = false;
  197. };
  198. auto setSettingInteger = [&](std::string key, std::string arg, si64 defaultValue) {
  199. Settings s = settings.write(vstd::split(key, "/"));
  200. if(vm.count(arg))
  201. s->Integer() = vm[arg].as<si64>();
  202. else if(s->isNull())
  203. s->Integer() = defaultValue;
  204. };
  205. setSettingBool("session/onlyai", "onlyAI");
  206. if(vm.count("headless"))
  207. {
  208. session["headless"].Bool() = true;
  209. session["onlyai"].Bool() = true;
  210. }
  211. else if(vm.count("spectate"))
  212. {
  213. session["spectate"].Bool() = true;
  214. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  215. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  216. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  217. if(vm.count("spectate-hero-speed"))
  218. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  219. if(vm.count("spectate-battle-speed"))
  220. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  221. }
  222. // Server settings
  223. setSettingBool("session/donotstartserver", "donotstartserver");
  224. // Init special testing settings
  225. setSettingInteger("session/serverport", "serverport", 0);
  226. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  227. // Initialize logging based on settings
  228. logConfig->configure();
  229. logGlobal->debug("settings = %s", settings.toJsonNode().toString());
  230. // Some basic data validation to produce better error messages in cases of incorrect install
  231. auto testFile = [](std::string filename, std::string message)
  232. {
  233. if (!CResourceHandler::get()->existsResource(ResourcePath(filename)))
  234. handleFatalError(message, false);
  235. };
  236. testFile("DATA/HELP.TXT", "VCMI requires Heroes III: Shadow of Death or Heroes III: Complete data files to run!");
  237. testFile("DATA/TENTCOLR.TXT", "Heroes III: Restoration of Erathia (including HD Edition) data files are not supported!");
  238. testFile("MODS/VCMI/MOD.JSON", "VCMI installation is corrupted! Built-in mod was not found!");
  239. testFile("DATA/PLAYERS.PAL", "Heroes III data files (Data/H3Bitmap.lod) are incomplete or corruped! Please reinstall them.");
  240. testFile("SPRITES/DEFAULT.DEF", "Heroes III data files (Data/H3Sprite.lod) are incomplete or corruped! Please reinstall them.");
  241. srand ( (unsigned int)time(nullptr) );
  242. if(!settings["session"]["headless"].Bool())
  243. GH.init();
  244. CCS = new CClientState();
  245. CGI = new CGameInfo(); //contains all global information about game (texts, lodHandlers, map handler etc.)
  246. CSH = new CServerHandler();
  247. // Initialize video
  248. #ifdef DISABLE_VIDEO
  249. CCS->videoh = new CEmptyVideoPlayer();
  250. #else
  251. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  252. CCS->videoh = new CVideoPlayer();
  253. else
  254. CCS->videoh = new CEmptyVideoPlayer();
  255. #endif
  256. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  257. if(!settings["session"]["headless"].Bool())
  258. {
  259. //initializing audio
  260. CCS->soundh = new CSoundHandler();
  261. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  262. CCS->musich = new CMusicHandler();
  263. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  264. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  265. }
  266. #ifndef VCMI_NO_THREADED_LOAD
  267. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  268. boost::thread loading([]()
  269. {
  270. setThreadName("initialize");
  271. init();
  272. });
  273. #else
  274. init();
  275. #endif
  276. if(!settings["session"]["headless"].Bool())
  277. {
  278. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  279. playIntro();
  280. GH.screenHandler().clearScreen();
  281. }
  282. #ifndef VCMI_NO_THREADED_LOAD
  283. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  284. {
  285. CAndroidVMHelper vmHelper;
  286. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  287. #endif // ANDROID
  288. loading.join();
  289. #ifdef VCMI_ANDROID
  290. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  291. }
  292. #endif // ANDROID
  293. #endif // THREADED
  294. if (criticalInitializationError.has_value())
  295. {
  296. handleFatalError(criticalInitializationError.value(), false);
  297. }
  298. if(!settings["session"]["headless"].Bool())
  299. {
  300. pomtime.getDiff();
  301. graphics = new Graphics(); // should be before curh
  302. GH.renderHandler().onLibraryLoadingFinished(CGI);
  303. CCS->curh = new CursorHandler();
  304. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  305. CMessage::init();
  306. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  307. CCS->curh->show();
  308. }
  309. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  310. session["autoSkip"].Bool() = vm.count("autoSkip");
  311. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  312. session["aiSolo"].Bool() = false;
  313. if(vm.count("testmap"))
  314. {
  315. session["testmap"].String() = vm["testmap"].as<std::string>();
  316. session["onlyai"].Bool() = true;
  317. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  318. }
  319. else if(vm.count("testsave"))
  320. {
  321. session["testsave"].String() = vm["testsave"].as<std::string>();
  322. session["onlyai"].Bool() = true;
  323. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  324. }
  325. else
  326. {
  327. auto mmenu = CMainMenu::create();
  328. GH.curInt = mmenu.get();
  329. }
  330. std::vector<std::string> names;
  331. if(!settings["session"]["headless"].Bool())
  332. {
  333. mainLoop();
  334. }
  335. else
  336. {
  337. while(!headlessQuit)
  338. boost::this_thread::sleep_for(boost::chrono::milliseconds(200));
  339. boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
  340. quitApplication();
  341. }
  342. return 0;
  343. }
  344. //plays intro, ends when intro is over or button has been pressed (handles events)
  345. void playIntro()
  346. {
  347. if(!CCS->videoh->playIntroVideo(VideoPath::builtin("3DOLOGO.SMK")))
  348. return;
  349. if (!CCS->videoh->playIntroVideo(VideoPath::builtin("NWCLOGO.SMK")))
  350. return;
  351. CCS->videoh->playIntroVideo(VideoPath::builtin("H3INTRO.SMK"));
  352. }
  353. static void mainLoop()
  354. {
  355. #ifndef VCMI_UNIX
  356. // on Linux, name of main thread is also name of our process. Which we don't want to change
  357. setThreadName("MainGUI");
  358. #endif
  359. while(1) //main SDL events loop
  360. {
  361. GH.input().fetchEvents();
  362. GH.renderFrame();
  363. }
  364. }