CMT.cpp 43 KB

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