CMT.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551
  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. //
  12. #include "StdInc.h"
  13. #include <boost/program_options.hpp>
  14. #include <vcmi/scripting/Service.h>
  15. #include "gui/SDL_Extensions.h"
  16. #include "CGameInfo.h"
  17. #include "mapHandler.h"
  18. #include "../lib/filesystem/Filesystem.h"
  19. #include "../lib/filesystem/FileStream.h"
  20. #include "mainmenu/CMainMenu.h"
  21. #include "lobby/CSelectionBase.h"
  22. #include "windows/CCastleInterface.h"
  23. #include "../lib/CConsoleHandler.h"
  24. #include "gui/CCursorHandler.h"
  25. #include "../lib/CGameState.h"
  26. #include "../CCallback.h"
  27. #include "CPlayerInterface.h"
  28. #include "windows/CAdvmapInterface.h"
  29. #include "../lib/CBuildingHandler.h"
  30. #include "CVideoHandler.h"
  31. #include "../lib/CHeroHandler.h"
  32. #include "../lib/CCreatureHandler.h"
  33. #include "../lib/spells/CSpellHandler.h"
  34. #include "CMusicHandler.h"
  35. #include "../lib/CGeneralTextHandler.h"
  36. #include "Graphics.h"
  37. #include "Client.h"
  38. #include "../lib/CConfigHandler.h"
  39. #include "../lib/serializer/BinaryDeserializer.h"
  40. #include "../lib/serializer/BinarySerializer.h"
  41. #include "../lib/VCMI_Lib.h"
  42. #include "../lib/VCMIDirs.h"
  43. #include "../lib/NetPacks.h"
  44. #include "CMessage.h"
  45. #include "../lib/CModHandler.h"
  46. #include "../lib/ScriptHandler.h"
  47. #include "../lib/CTownHandler.h"
  48. #include "../lib/CArtHandler.h"
  49. #include "../lib/GameConstants.h"
  50. #include "gui/CGuiHandler.h"
  51. #include "../lib/logging/CBasicLogConfigurator.h"
  52. #include "../lib/StringConstants.h"
  53. #include "../lib/CPlayerState.h"
  54. #include "gui/CAnimation.h"
  55. #include "../lib/serializer/Connection.h"
  56. #include "CServerHandler.h"
  57. #include "gui/NotificationHandler.h"
  58. #include <boost/asio.hpp>
  59. #include "mainmenu/CPrologEpilogVideo.h"
  60. #include <vstd/StringUtils.h>
  61. #ifdef VCMI_WINDOWS
  62. #include "SDL_syswm.h"
  63. #endif
  64. #ifdef VCMI_ANDROID
  65. #include "lib/CAndroidVMHelper.h"
  66. #endif
  67. #include "../lib/UnlockGuard.h"
  68. #include "CMT.h"
  69. #if __MINGW32__
  70. #undef main
  71. #endif
  72. namespace po = boost::program_options;
  73. namespace po_style = boost::program_options::command_line_style;
  74. namespace bfs = boost::filesystem;
  75. std::string NAME_AFFIX = "client";
  76. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  77. CGuiHandler GH;
  78. int preferredDriverIndex = -1;
  79. SDL_Window * mainWindow = nullptr;
  80. SDL_Renderer * mainRenderer = nullptr;
  81. SDL_Texture * screenTexture = nullptr;
  82. extern boost::thread_specific_ptr<bool> inGuiThread;
  83. SDL_Surface *screen = nullptr, //main screen surface
  84. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  85. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  86. std::queue<SDL_Event> SDLEventsQueue;
  87. boost::mutex eventsM;
  88. static po::variables_map vm;
  89. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  90. #ifndef VCMI_IOS
  91. void processCommand(const std::string &message);
  92. #endif
  93. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
  94. void playIntro();
  95. static void mainLoop();
  96. static CBasicLogConfigurator *logConfig;
  97. #ifndef VCMI_WINDOWS
  98. #ifndef _GNU_SOURCE
  99. #define _GNU_SOURCE
  100. #endif
  101. #include <getopt.h>
  102. #endif
  103. void init()
  104. {
  105. CStopWatch tmh;
  106. loadDLLClasses();
  107. const_cast<CGameInfo*>(CGI)->setFromLib();
  108. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  109. }
  110. static void prog_version()
  111. {
  112. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  113. std::cout << VCMIDirs::get().genHelpString();
  114. }
  115. static void prog_help(const po::options_description &opts)
  116. {
  117. auto time = std::time(0);
  118. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  119. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  120. printf("This is free software; see the source for copying conditions. There is NO\n");
  121. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  122. printf("\n");
  123. std::cout << opts;
  124. }
  125. static void SDLLogCallback(void* userdata,
  126. int category,
  127. SDL_LogPriority priority,
  128. const char* message)
  129. {
  130. //todo: convert SDL log priority to vcmi log priority
  131. //todo: make separate log domain for SDL
  132. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  133. }
  134. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  135. int wmain(int argc, wchar_t* argv[])
  136. #elif defined(VCMI_IOS) || defined(VCMI_ANDROID)
  137. int SDL_main(int argc, char *argv[])
  138. #else
  139. int main(int argc, char * argv[])
  140. #endif
  141. {
  142. #ifdef VCMI_ANDROID
  143. // boost will crash without this
  144. setenv("LANG", "C", 1);
  145. #endif
  146. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  147. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  148. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  149. #endif
  150. std::cout << "Starting... " << std::endl;
  151. po::options_description opts("Allowed options");
  152. opts.add_options()
  153. ("help,h", "display help and exit")
  154. ("version,v", "display version information and exit")
  155. ("disable-shm", "force disable shared memory usage")
  156. ("enable-shm-uuid", "use UUID for shared memory identifier")
  157. ("testmap", po::value<std::string>(), "")
  158. ("testsave", po::value<std::string>(), "")
  159. ("spectate,s", "enable spectator interface for AI-only games")
  160. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  161. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  162. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  163. ("spectate-skip-battle", "skip battles in spectator view")
  164. ("spectate-skip-battle-result", "skip battle result window")
  165. ("onlyAI", "allow to run without human player, all players will be default AI")
  166. ("headless", "runs without GUI, implies --onlyAI")
  167. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  168. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  169. ("autoSkip", "automatically skip turns in GUI")
  170. ("disable-video", "disable video player")
  171. ("nointro,i", "skips intro movies")
  172. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  173. ("serverport", po::value<si64>(), "override port specified in config file")
  174. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  175. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
  176. if(argc > 1)
  177. {
  178. try
  179. {
  180. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  181. }
  182. catch(std::exception &e)
  183. {
  184. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  185. }
  186. }
  187. po::notify(vm);
  188. if(vm.count("help"))
  189. {
  190. prog_help(opts);
  191. #ifdef VCMI_IOS
  192. exit(0);
  193. #else
  194. return 0;
  195. #endif
  196. }
  197. if(vm.count("version"))
  198. {
  199. prog_version();
  200. #ifdef VCMI_IOS
  201. exit(0);
  202. #else
  203. return 0;
  204. #endif
  205. }
  206. // Init old logging system and new (temporary) logging system
  207. CStopWatch total, pomtime;
  208. std::cout.flags(std::ios::unitbuf);
  209. #ifndef VCMI_IOS
  210. console = new CConsoleHandler();
  211. *console->cb = processCommand;
  212. console->start();
  213. #endif
  214. const bfs::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  215. logConfig = new CBasicLogConfigurator(logPath, console);
  216. logConfig->configureDefault();
  217. logGlobal->info(NAME);
  218. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  219. logGlobal->info("The log file will be saved to %s", logPath);
  220. // Init filesystem and settings
  221. preinitDLL(::console);
  222. settings.init();
  223. Settings session = settings.write["session"];
  224. auto setSettingBool = [](std::string key, std::string arg) {
  225. Settings s = settings.write(vstd::split(key, "/"));
  226. if(::vm.count(arg))
  227. s->Bool() = true;
  228. else if(s->isNull())
  229. s->Bool() = false;
  230. };
  231. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  232. Settings s = settings.write(vstd::split(key, "/"));
  233. if(::vm.count(arg))
  234. s->Integer() = ::vm[arg].as<si64>();
  235. else if(s->isNull())
  236. s->Integer() = defaultValue;
  237. };
  238. auto setSettingString = [](std::string key, std::string arg, std::string defaultValue) {
  239. Settings s = settings.write(vstd::split(key, "/"));
  240. if(::vm.count(arg))
  241. s->String() = ::vm[arg].as<std::string>();
  242. else if(s->isNull())
  243. s->String() = defaultValue;
  244. };
  245. setSettingBool("session/onlyai", "onlyAI");
  246. if(vm.count("headless"))
  247. {
  248. session["headless"].Bool() = true;
  249. session["onlyai"].Bool() = true;
  250. }
  251. else if(vm.count("spectate"))
  252. {
  253. session["spectate"].Bool() = true;
  254. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  255. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  256. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  257. if(vm.count("spectate-hero-speed"))
  258. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  259. if(vm.count("spectate-battle-speed"))
  260. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  261. }
  262. // Server settings
  263. setSettingBool("session/donotstartserver", "donotstartserver");
  264. // Shared memory options
  265. setSettingBool("session/disable-shm", "disable-shm");
  266. setSettingBool("session/enable-shm-uuid", "enable-shm-uuid");
  267. // Init special testing settings
  268. setSettingInteger("session/serverport", "serverport", 0);
  269. setSettingString("session/saveprefix", "saveprefix", "");
  270. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  271. // Initialize logging based on settings
  272. logConfig->configure();
  273. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  274. // Some basic data validation to produce better error messages in cases of incorrect install
  275. auto testFile = [](std::string filename, std::string message) -> bool
  276. {
  277. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  278. return true;
  279. logGlobal->error("Error: %s was not found!", message);
  280. return false;
  281. };
  282. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  283. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  284. {
  285. exit(1); // These are unrecoverable errors
  286. }
  287. // these two are optional + some installs have them on CD and not in data directory
  288. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  289. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  290. conf.init();
  291. logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
  292. srand ( (unsigned int)time(nullptr) );
  293. const JsonNode& video = settings["video"];
  294. const JsonNode& res = video["screenRes"];
  295. //something is really wrong...
  296. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  297. {
  298. logGlobal->error("Fatal error: failed to load settings!");
  299. logGlobal->error("Possible reasons:");
  300. logGlobal->error("\tCorrupted local configuration file at %s/settings.json", VCMIDirs::get().userConfigPath());
  301. logGlobal->error("\tMissing or corrupted global configuration file at %s/schemas/settings.json", VCMIDirs::get().userConfigPath());
  302. logGlobal->error("VCMI will now exit...");
  303. exit(EXIT_FAILURE);
  304. }
  305. if(!settings["session"]["headless"].Bool())
  306. {
  307. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  308. {
  309. logGlobal->error("Something was wrong: %s", SDL_GetError());
  310. exit(-1);
  311. }
  312. #ifdef VCMI_ANDROID
  313. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  314. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  315. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  316. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  317. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  318. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  319. #endif // VCMI_ANDROID
  320. GH.mainFPSmng->init(); //(!)init here AFTER SDL_Init() while using SDL for FPS management
  321. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  322. int driversCount = SDL_GetNumRenderDrivers();
  323. std::string preferredDriverName = video["driver"].String();
  324. logGlobal->info("Found %d render drivers", driversCount);
  325. for(int it = 0; it < driversCount; it++)
  326. {
  327. SDL_RendererInfo info;
  328. SDL_GetRenderDriverInfo(it,&info);
  329. std::string driverName(info.name);
  330. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  331. {
  332. preferredDriverIndex = it;
  333. logGlobal->info("\t%s (active)", driverName);
  334. }
  335. else
  336. logGlobal->info("\t%s", driverName);
  337. }
  338. setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
  339. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  340. }
  341. CCS = new CClientState();
  342. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  343. CSH = new CServerHandler();
  344. // Initialize video
  345. #ifdef DISABLE_VIDEO
  346. CCS->videoh = new CEmptyVideoPlayer();
  347. #else
  348. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  349. CCS->videoh = new CVideoPlayer();
  350. else
  351. CCS->videoh = new CEmptyVideoPlayer();
  352. #endif
  353. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  354. if(!settings["session"]["headless"].Bool())
  355. {
  356. //initializing audio
  357. CCS->soundh = new CSoundHandler();
  358. CCS->soundh->init();
  359. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  360. CCS->musich = new CMusicHandler();
  361. CCS->musich->init();
  362. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  363. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  364. }
  365. #ifdef VCMI_MAC
  366. // Ctrl+click should be treated as a right click on Mac OS X
  367. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  368. #endif
  369. #ifndef VCMI_NO_THREADED_LOAD
  370. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  371. boost::thread loading(init);
  372. #else
  373. init();
  374. #endif
  375. if(!settings["session"]["headless"].Bool())
  376. {
  377. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  378. playIntro();
  379. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  380. SDL_RenderClear(mainRenderer);
  381. SDL_RenderPresent(mainRenderer);
  382. }
  383. #ifndef VCMI_NO_THREADED_LOAD
  384. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  385. {
  386. CAndroidVMHelper vmHelper;
  387. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  388. #endif // ANDROID
  389. loading.join();
  390. #ifdef VCMI_ANDROID
  391. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  392. }
  393. #endif // ANDROID
  394. #endif // THREADED
  395. if(!settings["session"]["headless"].Bool())
  396. {
  397. pomtime.getDiff();
  398. CCS->curh = new CCursorHandler();
  399. graphics = new Graphics(); // should be before curh->init()
  400. CCS->curh->initCursor();
  401. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  402. pomtime.getDiff();
  403. graphics->load();//must be after Content loading but should be in main thread
  404. logGlobal->info("Main graphics: %d ms", pomtime.getDiff());
  405. CMessage::init();
  406. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  407. CCS->curh->show();
  408. }
  409. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  410. session["autoSkip"].Bool() = vm.count("autoSkip");
  411. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  412. session["aiSolo"].Bool() = false;
  413. if(vm.count("testmap"))
  414. {
  415. session["testmap"].String() = vm["testmap"].as<std::string>();
  416. session["onlyai"].Bool() = true;
  417. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  418. }
  419. else if(vm.count("testsave"))
  420. {
  421. session["testsave"].String() = vm["testsave"].as<std::string>();
  422. session["onlyai"].Bool() = true;
  423. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  424. }
  425. else
  426. {
  427. GH.curInt = CMainMenu::create().get();
  428. }
  429. if(!settings["session"]["headless"].Bool())
  430. {
  431. mainLoop();
  432. }
  433. else
  434. {
  435. while(true)
  436. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  437. }
  438. return 0;
  439. }
  440. void printInfoAboutIntObject(const CIntObject *obj, int level)
  441. {
  442. std::stringstream sbuffer;
  443. sbuffer << std::string(level, '\t');
  444. sbuffer << typeid(*obj).name() << " *** ";
  445. if (obj->active)
  446. {
  447. #define PRINT(check, text) if (obj->active & CIntObject::check) sbuffer << text
  448. PRINT(LCLICK, 'L');
  449. PRINT(RCLICK, 'R');
  450. PRINT(HOVER, 'H');
  451. PRINT(MOVE, 'M');
  452. PRINT(KEYBOARD, 'K');
  453. PRINT(TIME, 'T');
  454. PRINT(GENERAL, 'A');
  455. PRINT(WHEEL, 'W');
  456. PRINT(DOUBLECLICK, 'D');
  457. #undef PRINT
  458. }
  459. else
  460. sbuffer << "inactive";
  461. sbuffer << " at " << obj->pos.x <<"x"<< obj->pos.y;
  462. sbuffer << " (" << obj->pos.w <<"x"<< obj->pos.h << ")";
  463. logGlobal->info(sbuffer.str());
  464. for(const CIntObject *child : obj->children)
  465. printInfoAboutIntObject(child, level+1);
  466. }
  467. void removeGUI()
  468. {
  469. // CClient::endGame
  470. GH.curInt = nullptr;
  471. if(GH.topInt())
  472. GH.topInt()->deactivate();
  473. GH.listInt.clear();
  474. GH.objsToBlit.clear();
  475. GH.statusbar = nullptr;
  476. logGlobal->info("Removed GUI.");
  477. LOCPLINT = nullptr;
  478. }
  479. #ifndef VCMI_IOS
  480. void processCommand(const std::string &message)
  481. {
  482. std::istringstream readed;
  483. readed.str(message);
  484. std::string cn; //command name
  485. readed >> cn;
  486. // Check mantis issue 2292 for details
  487. // if(LOCPLINT && LOCPLINT->cingconsole)
  488. // LOCPLINT->cingconsole->print(message);
  489. if(message==std::string("die, fool"))
  490. {
  491. exit(EXIT_SUCCESS);
  492. }
  493. else if(cn==std::string("activate"))
  494. {
  495. int what;
  496. readed >> what;
  497. switch (what)
  498. {
  499. case 0:
  500. GH.topInt()->activate();
  501. break;
  502. case 1:
  503. adventureInt->activate();
  504. break;
  505. case 2:
  506. LOCPLINT->castleInt->activate();
  507. break;
  508. }
  509. }
  510. else if(cn=="redraw")
  511. {
  512. GH.totalRedraw();
  513. }
  514. else if(cn=="screen")
  515. {
  516. std::cout << "Screenbuf points to ";
  517. if(screenBuf == screen)
  518. logGlobal->error("screen");
  519. else if(screenBuf == screen2)
  520. logGlobal->error("screen2");
  521. else
  522. logGlobal->error("?!?");
  523. SDL_SaveBMP(screen, "Screen_c.bmp");
  524. SDL_SaveBMP(screen2, "Screen2_c.bmp");
  525. }
  526. else if(cn=="save")
  527. {
  528. if(!CSH->client)
  529. {
  530. std::cout << "Game in not active";
  531. return;
  532. }
  533. std::string fname;
  534. readed >> fname;
  535. CSH->client->save(fname);
  536. }
  537. // else if(cn=="load")
  538. // {
  539. // // TODO: this code should end the running game and manage to call startGame instead
  540. // std::string fname;
  541. // readed >> fname;
  542. // CSH->client->loadGame(fname);
  543. // }
  544. else if(message=="convert txt")
  545. {
  546. std::cout << "Command accepted.\t";
  547. const bfs::path outPath =
  548. VCMIDirs::get().userCachePath() / "extracted";
  549. bfs::create_directories(outPath);
  550. auto extractVector = [=](const std::vector<std::string> & source, const std::string & name)
  551. {
  552. JsonNode data(JsonNode::JsonType::DATA_VECTOR);
  553. size_t index = 0;
  554. for(auto & line : source)
  555. {
  556. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  557. lineNode["text"].String() = line;
  558. lineNode["index"].Integer() = index++;
  559. data.Vector().push_back(lineNode);
  560. }
  561. const bfs::path filePath = outPath / (name + ".json");
  562. bfs::ofstream file(filePath);
  563. file << data.toJson();
  564. };
  565. extractVector(VLC->generaltexth->allTexts, "generalTexts");
  566. extractVector(VLC->generaltexth->jktexts, "jkTexts");
  567. extractVector(VLC->generaltexth->arraytxt, "arrayTexts");
  568. std::cout << "\rExtracting done :)\n";
  569. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  570. }
  571. else if(message=="get config")
  572. {
  573. std::cout << "Command accepted.\t";
  574. const bfs::path outPath =
  575. VCMIDirs::get().userCachePath() / "extracted" / "configuration";
  576. bfs::create_directories(outPath);
  577. const std::vector<std::string> contentNames = {"heroClasses", "artifacts", "creatures", "factions", "objects", "heroes", "spells", "skills"};
  578. for(auto contentName : contentNames)
  579. {
  580. auto & content = (*VLC->modh->content)[contentName];
  581. auto contentOutPath = outPath / contentName;
  582. bfs::create_directories(contentOutPath);
  583. for(auto & iter : content.modData)
  584. {
  585. const JsonNode & modData = iter.second.modData;
  586. for(auto & nameAndObject : modData.Struct())
  587. {
  588. const JsonNode & object = nameAndObject.second;
  589. std::string name = CModHandler::normalizeIdentifier(object.meta, "core", nameAndObject.first);
  590. boost::algorithm::replace_all(name,":","_");
  591. const bfs::path filePath = contentOutPath / (name + ".json");
  592. bfs::ofstream file(filePath);
  593. file << object.toJson();
  594. }
  595. }
  596. }
  597. std::cout << "\rExtracting done :)\n";
  598. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  599. }
  600. #if SCRIPTING_ENABLED
  601. else if(message=="get scripts")
  602. {
  603. std::cout << "Command accepted.\t";
  604. const bfs::path outPath =
  605. VCMIDirs::get().userCachePath() / "extracted" / "scripts";
  606. bfs::create_directories(outPath);
  607. for(auto & kv : VLC->scriptHandler->objects)
  608. {
  609. std::string name = kv.first;
  610. boost::algorithm::replace_all(name,":","_");
  611. const scripting::ScriptImpl * script = kv.second.get();
  612. bfs::path filePath = outPath / (name + ".lua");
  613. bfs::ofstream file(filePath);
  614. file << script->getSource();
  615. }
  616. std::cout << "\rExtracting done :)\n";
  617. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  618. }
  619. #endif
  620. else if(message=="get txt")
  621. {
  622. std::cout << "Command accepted.\t";
  623. const bfs::path outPath =
  624. VCMIDirs::get().userCachePath() / "extracted";
  625. auto list = CResourceHandler::get()->getFilteredFiles([](const ResourceID & ident)
  626. {
  627. return ident.getType() == EResType::TEXT && boost::algorithm::starts_with(ident.getName(), "DATA/");
  628. });
  629. for (auto & filename : list)
  630. {
  631. const bfs::path filePath = outPath / (filename.getName() + ".TXT");
  632. bfs::create_directories(filePath.parent_path());
  633. bfs::ofstream file(filePath);
  634. auto text = CResourceHandler::get()->load(filename)->readAll();
  635. file.write((char*)text.first.get(), text.second);
  636. }
  637. std::cout << "\rExtracting done :)\n";
  638. std::cout << " Extracted files can be found in " << outPath << " directory\n";
  639. }
  640. else if(cn=="crash")
  641. {
  642. int *ptr = nullptr;
  643. *ptr = 666;
  644. //disaster!
  645. }
  646. else if(cn == "mp" && adventureInt)
  647. {
  648. if(const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(adventureInt->selection))
  649. std::cout << h->movement << "; max: " << h->maxMovePoints(true) << "/" << h->maxMovePoints(false) << std::endl;
  650. }
  651. else if(cn == "bonuses")
  652. {
  653. bool jsonFormat = (message == "bonuses json");
  654. auto format = [jsonFormat](const BonusList & b) -> std::string
  655. {
  656. if(jsonFormat)
  657. return b.toJsonNode().toJson(true);
  658. std::ostringstream ss;
  659. ss << b;
  660. return ss.str();
  661. };
  662. std::cout << "Bonuses of " << adventureInt->selection->getObjectName() << std::endl
  663. << format(adventureInt->selection->getBonusList()) << std::endl;
  664. std::cout << "\nInherited bonuses:\n";
  665. TCNodes parents;
  666. adventureInt->selection->getParents(parents);
  667. for(const CBonusSystemNode *parent : parents)
  668. {
  669. std::cout << "\nBonuses from " << typeid(*parent).name() << std::endl << format(*parent->getAllBonuses(Selector::all, Selector::all)) << std::endl;
  670. }
  671. }
  672. else if(cn == "not dialog")
  673. {
  674. LOCPLINT->showingDialog->setn(false);
  675. }
  676. else if(cn == "gui")
  677. {
  678. for(auto & child : GH.listInt)
  679. {
  680. const auto childPtr = child.get();
  681. if(const CIntObject * obj = dynamic_cast<const CIntObject *>(childPtr))
  682. printInfoAboutIntObject(obj, 0);
  683. else
  684. std::cout << typeid(childPtr).name() << std::endl;
  685. }
  686. }
  687. else if(cn=="tell")
  688. {
  689. std::string what;
  690. int id1, id2;
  691. readed >> what >> id1 >> id2;
  692. if(what == "hs")
  693. {
  694. for(const CGHeroInstance *h : LOCPLINT->cb->getHeroesInfo())
  695. if(h->type->ID.getNum() == id1)
  696. if(const CArtifactInstance *a = h->getArt(ArtifactPosition(id2)))
  697. std::cout << a->nodeName();
  698. }
  699. }
  700. else if (cn == "set")
  701. {
  702. std::string what, value;
  703. readed >> what;
  704. Settings conf = settings.write["session"][what];
  705. readed >> value;
  706. if (value == "on")
  707. {
  708. conf->Bool() = true;
  709. logGlobal->info("Option %s enabled!", what);
  710. }
  711. else if (value == "off")
  712. {
  713. conf->Bool() = false;
  714. logGlobal->info("Option %s disabled!", what);
  715. }
  716. }
  717. else if(cn == "unlock")
  718. {
  719. std::string mxname;
  720. readed >> mxname;
  721. if(mxname == "pim" && LOCPLINT)
  722. LOCPLINT->pim->unlock();
  723. }
  724. else if(cn == "def2bmp")
  725. {
  726. std::string URI;
  727. readed >> URI;
  728. std::unique_ptr<CAnimation> anim = make_unique<CAnimation>(URI);
  729. anim->preload();
  730. anim->exportBitmaps(VCMIDirs::get().userCachePath() / "extracted");
  731. }
  732. else if(cn == "extract")
  733. {
  734. std::string URI;
  735. readed >> URI;
  736. if (CResourceHandler::get()->existsResource(ResourceID(URI)))
  737. {
  738. const bfs::path outPath = VCMIDirs::get().userCachePath() / "extracted" / URI;
  739. auto data = CResourceHandler::get()->load(ResourceID(URI))->readAll();
  740. bfs::create_directories(outPath.parent_path());
  741. bfs::ofstream outFile(outPath, bfs::ofstream::binary);
  742. outFile.write((char*)data.first.get(), data.second);
  743. }
  744. else
  745. logGlobal->error("File not found!");
  746. }
  747. else if(cn == "setBattleAI")
  748. {
  749. std::string fname;
  750. readed >> fname;
  751. std::cout << "Will try loading that AI to see if it is correct name...\n";
  752. try
  753. {
  754. if(auto ai = CDynLibHandler::getNewBattleAI(fname)) //test that given AI is indeed available... heavy but it is easy to make a typo and break the game
  755. {
  756. Settings neutralAI = settings.write["server"]["neutralAI"];
  757. neutralAI->String() = fname;
  758. std::cout << "Setting changed, from now the battle ai will be " << fname << "!\n";
  759. }
  760. }
  761. catch(std::exception &e)
  762. {
  763. logGlobal->warn("Failed opening %s: %s", fname, e.what());
  764. logGlobal->warn("Setting not changes, AI not found or invalid!");
  765. }
  766. }
  767. auto giveTurn = [&](PlayerColor player)
  768. {
  769. YourTurn yt;
  770. yt.player = player;
  771. yt.daysWithoutCastle = CSH->client->getPlayerState(player)->daysWithoutCastle;
  772. yt.applyCl(CSH->client);
  773. };
  774. Settings session = settings.write["session"];
  775. if(cn == "autoskip")
  776. {
  777. session["autoSkip"].Bool() = !session["autoSkip"].Bool();
  778. }
  779. else if(cn == "gosolo")
  780. {
  781. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  782. if(!CSH->client)
  783. {
  784. std::cout << "Game in not active";
  785. return;
  786. }
  787. PlayerColor color;
  788. if(session["aiSolo"].Bool())
  789. {
  790. for(auto & elem : CSH->client->gameState()->players)
  791. {
  792. if(elem.second.human)
  793. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  794. }
  795. }
  796. else
  797. {
  798. color = LOCPLINT->playerID;
  799. removeGUI();
  800. for(auto & elem : CSH->client->gameState()->players)
  801. {
  802. if(elem.second.human)
  803. {
  804. auto AiToGive = CSH->client->aiNameForPlayer(*CSH->client->getPlayerSettings(elem.first), false);
  805. logNetwork->info("Player %s will be lead by %s", elem.first, AiToGive);
  806. CSH->client->installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), elem.first);
  807. }
  808. }
  809. GH.totalRedraw();
  810. giveTurn(color);
  811. }
  812. session["aiSolo"].Bool() = !session["aiSolo"].Bool();
  813. }
  814. else if(cn == "controlai")
  815. {
  816. std::string colorName;
  817. readed >> colorName;
  818. boost::to_lower(colorName);
  819. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  820. if(!CSH->client)
  821. {
  822. std::cout << "Game in not active";
  823. return;
  824. }
  825. PlayerColor color;
  826. if(LOCPLINT)
  827. color = LOCPLINT->playerID;
  828. for(auto & elem : CSH->client->gameState()->players)
  829. {
  830. if(elem.second.human || (colorName.length() &&
  831. elem.first.getNum() != vstd::find_pos(GameConstants::PLAYER_COLOR_NAMES, colorName)))
  832. {
  833. continue;
  834. }
  835. removeGUI();
  836. CSH->client->installNewPlayerInterface(std::make_shared<CPlayerInterface>(elem.first), elem.first);
  837. }
  838. GH.totalRedraw();
  839. if(color != PlayerColor::NEUTRAL)
  840. giveTurn(color);
  841. }
  842. // Check mantis issue 2292 for details
  843. /* else if(client && client->serv && client->serv->connected && LOCPLINT) //send to server
  844. {
  845. boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
  846. LOCPLINT->cb->sendMessage(message);
  847. }*/
  848. }
  849. #endif
  850. //plays intro, ends when intro is over or button has been pressed (handles events)
  851. void playIntro()
  852. {
  853. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, true, true))
  854. {
  855. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, true, true);
  856. }
  857. }
  858. #ifndef VCMI_IOS
  859. static bool checkVideoMode(int monitorIndex, int w, int h)
  860. {
  861. //we only check that our desired window size fits on screen
  862. SDL_DisplayMode mode;
  863. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  864. {
  865. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  866. logGlobal->error(SDL_GetError());
  867. return false;
  868. }
  869. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  870. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  871. {
  872. return true;
  873. }
  874. return false;
  875. }
  876. #endif
  877. static void cleanupRenderer()
  878. {
  879. screenBuf = nullptr; //it`s a link - just nullify
  880. if(nullptr != screen2)
  881. {
  882. SDL_FreeSurface(screen2);
  883. screen2 = nullptr;
  884. }
  885. if(nullptr != screen)
  886. {
  887. SDL_FreeSurface(screen);
  888. screen = nullptr;
  889. }
  890. if(nullptr != screenTexture)
  891. {
  892. SDL_DestroyTexture(screenTexture);
  893. screenTexture = nullptr;
  894. }
  895. }
  896. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  897. {
  898. // VCMI will only work with 2 or 4 bytes per pixel
  899. vstd::amax(bpp, 16);
  900. vstd::amin(bpp, 32);
  901. if(bpp>16)
  902. bpp = 32;
  903. if(displayIndex < 0)
  904. {
  905. if (mainWindow != nullptr)
  906. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  907. if (displayIndex < 0)
  908. displayIndex = 0;
  909. }
  910. #ifdef VCMI_IOS
  911. SDL_GetWindowSize(mainWindow, &w, &h);
  912. #else
  913. if(!checkVideoMode(displayIndex, w, h))
  914. {
  915. logGlobal->error("Error: SDL says that %dx%d resolution is not available!", w, h);
  916. return false;
  917. }
  918. #endif
  919. bool bufOnScreen = (screenBuf == screen);
  920. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  921. /* match best rendering resolution */
  922. int renderWidth = 0, renderHeight = 0;
  923. auto aspectRatio = (float)w / (float)h;
  924. auto minDiff = 10.f;
  925. for (const auto& pair : conf.guiOptions)
  926. {
  927. int pWidth, pHeight;
  928. std::tie(pWidth, pHeight) = pair.first;
  929. /* filter out resolution which is larger than window */
  930. if (pWidth > w || pHeight > h)
  931. {
  932. continue;
  933. }
  934. auto ratio = (float)pWidth / (float)pHeight;
  935. auto diff = fabs(aspectRatio - ratio);
  936. /* select closest aspect ratio */
  937. if (diff < minDiff)
  938. {
  939. renderWidth = pWidth;
  940. renderHeight = pHeight;
  941. minDiff = diff;
  942. }
  943. /* select largest resolution meets prior conditions.
  944. * since there are resolutions like 1366x768(not exactly 16:9), a deviation of 0.005 is allowed. */
  945. else if (fabs(diff - minDiff) < 0.005f && pWidth > renderWidth)
  946. {
  947. renderWidth = pWidth;
  948. renderHeight = pHeight;
  949. }
  950. }
  951. if (renderWidth == 0)
  952. {
  953. // no matching resolution for upscaling - complain & fallback to default resolution.
  954. logGlobal->error("Failed to match rendering resolution for %dx%d!", w, h);
  955. Settings newRes = settings.write["video"]["screenRes"];
  956. std::tie(w, h) = conf.guiOptions.begin()->first;
  957. newRes["width"].Float() = w;
  958. newRes["height"].Float() = h;
  959. conf.SetResolution(w, h);
  960. logGlobal->error("Falling back to %dx%d", w, h);
  961. renderWidth = w;
  962. renderHeight = h;
  963. }
  964. else
  965. {
  966. logGlobal->info("Set logical rendering resolution to %dx%d", renderWidth, renderHeight);
  967. }
  968. cleanupRenderer();
  969. if(nullptr == mainWindow)
  970. {
  971. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  972. auto createWindow = [displayIndex](Uint32 extraFlags) -> bool {
  973. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN | extraFlags);
  974. return mainWindow != nullptr;
  975. };
  976. # ifdef VCMI_IOS
  977. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  978. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  979. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  980. Uint32 windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  981. if(!createWindow(windowFlags | SDL_WINDOW_METAL))
  982. {
  983. logGlobal->warn("Metal unavailable, using OpenGLES");
  984. createWindow(windowFlags);
  985. }
  986. # else
  987. createWindow(0);
  988. # endif // VCMI_IOS
  989. // SDL on mobile doesn't do proper letterboxing, and will show an annoying flickering in the blank space in case you're not using the full screen estate
  990. // That's why we need to make sure our width and height we'll use below have the same aspect ratio as the screen itself to ensure we fill the full screen estate
  991. SDL_Rect screenRect;
  992. if(SDL_GetDisplayBounds(0, &screenRect) == 0)
  993. {
  994. const auto screenWidth = screenRect.w;
  995. const auto screenHeight = screenRect.h;
  996. const auto aspect = static_cast<double>(screenWidth) / screenHeight;
  997. logGlobal->info("Screen size and aspect ratio: %dx%d (%lf)", screenWidth, screenHeight, aspect);
  998. if((double)w / aspect > (double)h)
  999. {
  1000. h = (int)round((double)w / aspect);
  1001. }
  1002. else
  1003. {
  1004. w = (int)round((double)h * aspect);
  1005. }
  1006. logGlobal->info("Changing logical screen size to %dx%d", w, h);
  1007. }
  1008. else
  1009. {
  1010. logGlobal->error("Can't fix aspect ratio for screen");
  1011. }
  1012. #else
  1013. if(fullscreen)
  1014. {
  1015. if(realFullscreen)
  1016. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), renderWidth, renderHeight, SDL_WINDOW_FULLSCREEN);
  1017. else //in windowed full-screen mode use desktop resolution
  1018. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  1019. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  1020. }
  1021. else
  1022. {
  1023. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  1024. }
  1025. #endif // defined(VCMI_ANDROID) || defined(VCMI_IOS)
  1026. if(nullptr == mainWindow)
  1027. {
  1028. throw std::runtime_error("Unable to create window\n");
  1029. }
  1030. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  1031. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  1032. if(nullptr == mainRenderer)
  1033. {
  1034. throw std::runtime_error("Unable to create renderer\n");
  1035. }
  1036. SDL_RendererInfo info;
  1037. SDL_GetRendererInfo(mainRenderer, &info);
  1038. logGlobal->info("Created renderer %s", info.name);
  1039. }
  1040. else
  1041. {
  1042. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  1043. if(fullscreen)
  1044. {
  1045. if(realFullscreen)
  1046. {
  1047. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  1048. SDL_DisplayMode mode;
  1049. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  1050. mode.w = renderWidth;
  1051. mode.h = renderHeight;
  1052. SDL_SetWindowDisplayMode(mainWindow, &mode);
  1053. }
  1054. else
  1055. {
  1056. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  1057. }
  1058. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  1059. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  1060. }
  1061. else
  1062. {
  1063. SDL_SetWindowFullscreen(mainWindow, 0);
  1064. SDL_SetWindowSize(mainWindow, w, h);
  1065. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  1066. }
  1067. #endif
  1068. }
  1069. if(!(fullscreen && realFullscreen))
  1070. {
  1071. SDL_RenderSetLogicalSize(mainRenderer, renderWidth, renderHeight);
  1072. //following line is bugged not only on android, do not re-enable without checking
  1073. //#ifndef VCMI_ANDROID
  1074. // // on android this stretches the game to fit the screen, not preserving aspect and apparently this also breaks coordinates scaling in mouse events
  1075. // SDL_RenderSetViewport(mainRenderer, nullptr);
  1076. //#endif
  1077. }
  1078. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  1079. int bmask = 0xff000000;
  1080. int gmask = 0x00ff0000;
  1081. int rmask = 0x0000ff00;
  1082. int amask = 0x000000ff;
  1083. #else
  1084. int bmask = 0x000000ff;
  1085. int gmask = 0x0000ff00;
  1086. int rmask = 0x00ff0000;
  1087. int amask = 0xFF000000;
  1088. #endif
  1089. screen = SDL_CreateRGBSurface(0,renderWidth,renderHeight,bpp,rmask,gmask,bmask,amask);
  1090. if(nullptr == screen)
  1091. {
  1092. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", renderWidth, renderHeight, bpp, SDL_GetError());
  1093. throw std::runtime_error("Unable to create surface");
  1094. }
  1095. //No blending for screen itself. Required for proper cursor rendering.
  1096. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  1097. screenTexture = SDL_CreateTexture(mainRenderer,
  1098. SDL_PIXELFORMAT_ARGB8888,
  1099. SDL_TEXTUREACCESS_STREAMING,
  1100. renderWidth, renderHeight);
  1101. if(nullptr == screenTexture)
  1102. {
  1103. logGlobal->error("Unable to create screen texture");
  1104. logGlobal->error(SDL_GetError());
  1105. throw std::runtime_error("Unable to create screen texture");
  1106. }
  1107. screen2 = CSDL_Ext::copySurface(screen);
  1108. if(nullptr == screen2)
  1109. {
  1110. throw std::runtime_error("Unable to copy surface\n");
  1111. }
  1112. screenBuf = bufOnScreen ? screen : screen2;
  1113. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  1114. SDL_RenderClear(mainRenderer);
  1115. SDL_RenderPresent(mainRenderer);
  1116. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  1117. {
  1118. NotificationHandler::init(mainWindow);
  1119. }
  1120. return true;
  1121. }
  1122. //used only once during initialization
  1123. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  1124. {
  1125. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  1126. {
  1127. throw std::runtime_error("Requested screen resolution is not available\n");
  1128. }
  1129. }
  1130. static void fullScreenChanged()
  1131. {
  1132. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  1133. Settings full = settings.write["video"]["fullscreen"];
  1134. const bool toFullscreen = full->Bool();
  1135. auto bitsPerPixel = screen->format->BitsPerPixel;
  1136. auto w = screen->w;
  1137. auto h = screen->h;
  1138. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  1139. {
  1140. //will return false and report error if video mode is not supported
  1141. return;
  1142. }
  1143. GH.totalRedraw();
  1144. }
  1145. static void handleEvent(SDL_Event & ev)
  1146. {
  1147. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  1148. {
  1149. #ifdef VCMI_ANDROID
  1150. handleQuit(false);
  1151. #else
  1152. handleQuit();
  1153. #endif
  1154. return;
  1155. }
  1156. #ifdef VCMI_ANDROID
  1157. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  1158. {
  1159. handleQuit(true);
  1160. }
  1161. #endif
  1162. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  1163. {
  1164. Settings full = settings.write["video"]["fullscreen"];
  1165. full->Bool() = !full->Bool();
  1166. return;
  1167. }
  1168. else if(ev.type == SDL_USEREVENT)
  1169. {
  1170. switch(ev.user.code)
  1171. {
  1172. case EUserEvent::FORCE_QUIT:
  1173. {
  1174. handleQuit(false);
  1175. return;
  1176. }
  1177. break;
  1178. case EUserEvent::RETURN_TO_MAIN_MENU:
  1179. {
  1180. CSH->endGameplay();
  1181. GH.defActionsDef = 63;
  1182. CMM->menu->switchToTab("main");
  1183. }
  1184. break;
  1185. case EUserEvent::RESTART_GAME:
  1186. {
  1187. CSH->sendStartGame();
  1188. }
  1189. break;
  1190. case EUserEvent::CAMPAIGN_START_SCENARIO:
  1191. {
  1192. CSH->campaignServerRestartLock.set(true);
  1193. CSH->endGameplay();
  1194. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  1195. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  1196. auto finisher = [=]()
  1197. {
  1198. if(ourCampaign->mapsRemaining.size())
  1199. {
  1200. CMM->openCampaignLobby(ourCampaign);
  1201. }
  1202. };
  1203. if(epilogue.hasPrologEpilog)
  1204. {
  1205. GH.pushIntT<CPrologEpilogVideo>(epilogue, finisher);
  1206. }
  1207. else
  1208. {
  1209. CSH->campaignServerRestartLock.waitUntil(false);
  1210. finisher();
  1211. }
  1212. }
  1213. break;
  1214. case EUserEvent::RETURN_TO_MENU_LOAD:
  1215. CSH->endGameplay();
  1216. GH.defActionsDef = 63;
  1217. CMM->menu->switchToTab("load");
  1218. break;
  1219. case EUserEvent::FULLSCREEN_TOGGLED:
  1220. fullScreenChanged();
  1221. break;
  1222. case EUserEvent::INTERFACE_CHANGED:
  1223. if(LOCPLINT)
  1224. LOCPLINT->updateAmbientSounds();
  1225. break;
  1226. default:
  1227. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  1228. break;
  1229. }
  1230. return;
  1231. }
  1232. else if(ev.type == SDL_WINDOWEVENT)
  1233. {
  1234. switch (ev.window.event) {
  1235. case SDL_WINDOWEVENT_RESTORED:
  1236. #ifndef VCMI_IOS
  1237. fullScreenChanged();
  1238. #endif
  1239. break;
  1240. }
  1241. return;
  1242. }
  1243. else if(ev.type == SDL_SYSWMEVENT)
  1244. {
  1245. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  1246. {
  1247. NotificationHandler::handleSdlEvent(ev);
  1248. }
  1249. }
  1250. //preprocessing
  1251. if(ev.type == SDL_MOUSEMOTION)
  1252. {
  1253. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  1254. }
  1255. {
  1256. boost::unique_lock<boost::mutex> lock(eventsM);
  1257. SDLEventsQueue.push(ev);
  1258. }
  1259. }
  1260. static void mainLoop()
  1261. {
  1262. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  1263. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::FULLSCREEN_TOGGLED); });
  1264. inGuiThread.reset(new bool(true));
  1265. GH.mainFPSmng->init();
  1266. while(1) //main SDL events loop
  1267. {
  1268. SDL_Event ev;
  1269. while(1 == SDL_PollEvent(&ev))
  1270. {
  1271. handleEvent(ev);
  1272. }
  1273. CSH->applyPacksOnLobbyScreen();
  1274. GH.renderFrame();
  1275. }
  1276. }
  1277. void handleQuit(bool ask)
  1278. {
  1279. auto quitApplication = []()
  1280. {
  1281. if(!settings["session"]["headless"].Bool())
  1282. {
  1283. if(CSH->client)
  1284. CSH->endGameplay();
  1285. }
  1286. GH.listInt.clear();
  1287. GH.objsToBlit.clear();
  1288. CMM.reset();
  1289. if(!settings["session"]["headless"].Bool())
  1290. {
  1291. // cleanup, mostly to remove false leaks from analyzer
  1292. if(CCS)
  1293. {
  1294. CCS->musich->release();
  1295. CCS->soundh->release();
  1296. vstd::clear_pointer(CCS);
  1297. }
  1298. CMessage::dispose();
  1299. vstd::clear_pointer(graphics);
  1300. }
  1301. vstd::clear_pointer(VLC);
  1302. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  1303. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  1304. if(!settings["session"]["headless"].Bool())
  1305. {
  1306. if(settings["general"]["notifications"].Bool())
  1307. {
  1308. NotificationHandler::destroy();
  1309. }
  1310. cleanupRenderer();
  1311. if(nullptr != mainRenderer)
  1312. {
  1313. SDL_DestroyRenderer(mainRenderer);
  1314. mainRenderer = nullptr;
  1315. }
  1316. if(nullptr != mainWindow)
  1317. {
  1318. SDL_DestroyWindow(mainWindow);
  1319. mainWindow = nullptr;
  1320. }
  1321. SDL_Quit();
  1322. }
  1323. if(logConfig != nullptr)
  1324. {
  1325. logConfig->deconfigure();
  1326. delete logConfig;
  1327. logConfig = nullptr;
  1328. }
  1329. std::cout << "Ending...\n";
  1330. exit(0);
  1331. };
  1332. if(CSH->client && LOCPLINT && ask)
  1333. {
  1334. CCS->curh->changeGraphic(ECursor::ADVENTURE, 0);
  1335. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], quitApplication, nullptr);
  1336. }
  1337. else
  1338. {
  1339. quitApplication();
  1340. }
  1341. }