CMT.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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 "gui/SDL_Extensions.h"
  15. #include "CGameInfo.h"
  16. #include "mapHandler.h"
  17. #include "../lib/filesystem/Filesystem.h"
  18. #include "../lib/filesystem/FileStream.h"
  19. #include "mainmenu/CMainMenu.h"
  20. #include "lobby/CSelectionBase.h"
  21. #include "windows/CCastleInterface.h"
  22. #include "../lib/CConsoleHandler.h"
  23. #include "gui/CursorHandler.h"
  24. #include "../lib/CGameState.h"
  25. #include "../CCallback.h"
  26. #include "CPlayerInterface.h"
  27. #include "windows/CAdvmapInterface.h"
  28. #include "../lib/CBuildingHandler.h"
  29. #include "CVideoHandler.h"
  30. #include "../lib/CHeroHandler.h"
  31. #include "../lib/spells/CSpellHandler.h"
  32. #include "CMusicHandler.h"
  33. #include "../lib/CGeneralTextHandler.h"
  34. #include "Graphics.h"
  35. #include "Client.h"
  36. #include "../lib/serializer/BinaryDeserializer.h"
  37. #include "../lib/serializer/BinarySerializer.h"
  38. #include "../lib/VCMIDirs.h"
  39. #include "../lib/NetPacks.h"
  40. #include "CMessage.h"
  41. #include "../lib/CModHandler.h"
  42. #include "../lib/CTownHandler.h"
  43. #include "gui/CGuiHandler.h"
  44. #include "../lib/logging/CBasicLogConfigurator.h"
  45. #include "../lib/CPlayerState.h"
  46. #include "gui/CAnimation.h"
  47. #include "../lib/serializer/Connection.h"
  48. #include "CServerHandler.h"
  49. #include "gui/NotificationHandler.h"
  50. #include "ClientCommandManager.h"
  51. #include <boost/asio.hpp>
  52. #include "mainmenu/CPrologEpilogVideo.h"
  53. #include <vstd/StringUtils.h>
  54. #include <SDL.h>
  55. #ifdef VCMI_WINDOWS
  56. #include "SDL_syswm.h"
  57. #endif
  58. #ifdef VCMI_ANDROID
  59. #include "lib/CAndroidVMHelper.h"
  60. #endif
  61. #include "CMT.h"
  62. #if __MINGW32__
  63. #undef main
  64. #endif
  65. namespace po = boost::program_options;
  66. namespace po_style = boost::program_options::command_line_style;
  67. namespace bfs = boost::filesystem;
  68. std::string NAME_AFFIX = "client";
  69. std::string NAME = GameConstants::VCMI_VERSION + std::string(" (") + NAME_AFFIX + ')'; //application name
  70. CGuiHandler GH;
  71. int preferredDriverIndex = -1;
  72. SDL_Window * mainWindow = nullptr;
  73. SDL_Renderer * mainRenderer = nullptr;
  74. SDL_Texture * screenTexture = nullptr;
  75. extern boost::thread_specific_ptr<bool> inGuiThread;
  76. SDL_Surface *screen = nullptr, //main screen surface
  77. *screen2 = nullptr, //and hlp surface (used to store not-active interfaces layer)
  78. *screenBuf = screen; //points to screen (if only advmapint is present) or screen2 (else) - should be used when updating controls which are not regularly redrawed
  79. std::queue<SDL_Event> SDLEventsQueue;
  80. boost::mutex eventsM;
  81. static po::variables_map vm;
  82. //static bool setResolution = false; //set by event handling thread after resolution is adjusted
  83. #ifndef VCMI_IOS
  84. void processCommand(const std::string &message);
  85. #endif
  86. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo=true);
  87. void playIntro();
  88. static void mainLoop();
  89. static CBasicLogConfigurator *logConfig;
  90. #ifndef VCMI_WINDOWS
  91. #ifndef _GNU_SOURCE
  92. #define _GNU_SOURCE
  93. #endif
  94. #include <getopt.h>
  95. #endif
  96. void init()
  97. {
  98. CStopWatch tmh;
  99. loadDLLClasses();
  100. const_cast<CGameInfo*>(CGI)->setFromLib();
  101. logGlobal->info("Initializing VCMI_Lib: %d ms", tmh.getDiff());
  102. }
  103. static void prog_version()
  104. {
  105. printf("%s\n", GameConstants::VCMI_VERSION.c_str());
  106. std::cout << VCMIDirs::get().genHelpString();
  107. }
  108. static void prog_help(const po::options_description &opts)
  109. {
  110. auto time = std::time(0);
  111. printf("%s - A Heroes of Might and Magic 3 clone\n", GameConstants::VCMI_VERSION.c_str());
  112. printf("Copyright (C) 2007-%d VCMI dev team - see AUTHORS file\n", std::localtime(&time)->tm_year + 1900);
  113. printf("This is free software; see the source for copying conditions. There is NO\n");
  114. printf("warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n");
  115. printf("\n");
  116. std::cout << opts;
  117. }
  118. static void SDLLogCallback(void* userdata,
  119. int category,
  120. SDL_LogPriority priority,
  121. const char* message)
  122. {
  123. //todo: convert SDL log priority to vcmi log priority
  124. //todo: make separate log domain for SDL
  125. logGlobal->debug("SDL(category %d; priority %d) %s", category, priority, message);
  126. }
  127. #if defined(VCMI_WINDOWS) && !defined(__GNUC__) && defined(VCMI_WITH_DEBUG_CONSOLE)
  128. int wmain(int argc, wchar_t* argv[])
  129. #elif defined(VCMI_IOS) || defined(VCMI_ANDROID)
  130. int SDL_main(int argc, char *argv[])
  131. #else
  132. int main(int argc, char * argv[])
  133. #endif
  134. {
  135. #ifdef VCMI_ANDROID
  136. // boost will crash without this
  137. setenv("LANG", "C", 1);
  138. #endif
  139. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  140. // Correct working dir executable folder (not bundle folder) so we can use executable relative paths
  141. boost::filesystem::current_path(boost::filesystem::system_complete(argv[0]).parent_path());
  142. #endif
  143. std::cout << "Starting... " << std::endl;
  144. po::options_description opts("Allowed options");
  145. opts.add_options()
  146. ("help,h", "display help and exit")
  147. ("version,v", "display version information and exit")
  148. ("disable-shm", "force disable shared memory usage")
  149. ("enable-shm-uuid", "use UUID for shared memory identifier")
  150. ("testmap", po::value<std::string>(), "")
  151. ("testsave", po::value<std::string>(), "")
  152. ("spectate,s", "enable spectator interface for AI-only games")
  153. ("spectate-ignore-hero", "wont follow heroes on adventure map")
  154. ("spectate-hero-speed", po::value<int>(), "hero movement speed on adventure map")
  155. ("spectate-battle-speed", po::value<int>(), "battle animation speed for spectator")
  156. ("spectate-skip-battle", "skip battles in spectator view")
  157. ("spectate-skip-battle-result", "skip battle result window")
  158. ("onlyAI", "allow to run without human player, all players will be default AI")
  159. ("headless", "runs without GUI, implies --onlyAI")
  160. ("ai", po::value<std::vector<std::string>>(), "AI to be used for the player, can be specified several times for the consecutive players")
  161. ("oneGoodAI", "puts one default AI and the rest will be EmptyAI")
  162. ("autoSkip", "automatically skip turns in GUI")
  163. ("disable-video", "disable video player")
  164. ("nointro,i", "skips intro movies")
  165. ("donotstartserver,d","do not attempt to start server and just connect to it instead server")
  166. ("serverport", po::value<si64>(), "override port specified in config file")
  167. ("saveprefix", po::value<std::string>(), "prefix for auto save files")
  168. ("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
  169. ("lobby", "parameters address, port, uuid to connect ro remote lobby session")
  170. ("lobby-address", po::value<std::string>(), "address to remote lobby")
  171. ("lobby-port", po::value<ui16>(), "port to remote lobby")
  172. ("lobby-host", "if this client hosts session")
  173. ("lobby-uuid", po::value<std::string>(), "uuid to the server")
  174. ("lobby-connections", po::value<ui16>(), "connections of server")
  175. ("lobby-username", po::value<std::string>(), "player name")
  176. ("lobby-gamemode", po::value<ui16>(), "use 0 for new game and 1 for load game")
  177. ("uuid", po::value<std::string>(), "uuid for the client");
  178. if(argc > 1)
  179. {
  180. try
  181. {
  182. po::store(po::parse_command_line(argc, argv, opts, po_style::unix_style|po_style::case_insensitive), vm);
  183. }
  184. catch(std::exception &e)
  185. {
  186. std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
  187. }
  188. }
  189. po::notify(vm);
  190. if(vm.count("help"))
  191. {
  192. prog_help(opts);
  193. #ifdef VCMI_IOS
  194. exit(0);
  195. #else
  196. return 0;
  197. #endif
  198. }
  199. if(vm.count("version"))
  200. {
  201. prog_version();
  202. #ifdef VCMI_IOS
  203. exit(0);
  204. #else
  205. return 0;
  206. #endif
  207. }
  208. // Init old logging system and new (temporary) logging system
  209. CStopWatch total, pomtime;
  210. std::cout.flags(std::ios::unitbuf);
  211. #ifndef VCMI_IOS
  212. console = new CConsoleHandler();
  213. auto callbackFunction = [](std::string buffer, bool calledFromIngameConsole)
  214. {
  215. ClientCommandManager commandController;
  216. commandController.processCommand(buffer, calledFromIngameConsole);
  217. };
  218. *console->cb = callbackFunction;
  219. console->start();
  220. #endif
  221. const bfs::path logPath = VCMIDirs::get().userLogsPath() / "VCMI_Client_log.txt";
  222. logConfig = new CBasicLogConfigurator(logPath, console);
  223. logConfig->configureDefault();
  224. logGlobal->info(NAME);
  225. logGlobal->info("Creating console and configuring logger: %d ms", pomtime.getDiff());
  226. logGlobal->info("The log file will be saved to %s", logPath);
  227. // Init filesystem and settings
  228. preinitDLL(::console);
  229. settings.init();
  230. Settings session = settings.write["session"];
  231. auto setSettingBool = [](std::string key, std::string arg) {
  232. Settings s = settings.write(vstd::split(key, "/"));
  233. if(::vm.count(arg))
  234. s->Bool() = true;
  235. else if(s->isNull())
  236. s->Bool() = false;
  237. };
  238. auto setSettingInteger = [](std::string key, std::string arg, si64 defaultValue) {
  239. Settings s = settings.write(vstd::split(key, "/"));
  240. if(::vm.count(arg))
  241. s->Integer() = ::vm[arg].as<si64>();
  242. else if(s->isNull())
  243. s->Integer() = defaultValue;
  244. };
  245. auto setSettingString = [](std::string key, std::string arg, std::string defaultValue) {
  246. Settings s = settings.write(vstd::split(key, "/"));
  247. if(::vm.count(arg))
  248. s->String() = ::vm[arg].as<std::string>();
  249. else if(s->isNull())
  250. s->String() = defaultValue;
  251. };
  252. setSettingBool("session/onlyai", "onlyAI");
  253. if(vm.count("headless"))
  254. {
  255. session["headless"].Bool() = true;
  256. session["onlyai"].Bool() = true;
  257. }
  258. else if(vm.count("spectate"))
  259. {
  260. session["spectate"].Bool() = true;
  261. session["spectate-ignore-hero"].Bool() = vm.count("spectate-ignore-hero");
  262. session["spectate-skip-battle"].Bool() = vm.count("spectate-skip-battle");
  263. session["spectate-skip-battle-result"].Bool() = vm.count("spectate-skip-battle-result");
  264. if(vm.count("spectate-hero-speed"))
  265. session["spectate-hero-speed"].Integer() = vm["spectate-hero-speed"].as<int>();
  266. if(vm.count("spectate-battle-speed"))
  267. session["spectate-battle-speed"].Float() = vm["spectate-battle-speed"].as<int>();
  268. }
  269. // Server settings
  270. setSettingBool("session/donotstartserver", "donotstartserver");
  271. // Shared memory options
  272. setSettingBool("session/disable-shm", "disable-shm");
  273. setSettingBool("session/enable-shm-uuid", "enable-shm-uuid");
  274. // Init special testing settings
  275. setSettingInteger("session/serverport", "serverport", 0);
  276. setSettingString("session/saveprefix", "saveprefix", "");
  277. setSettingInteger("general/saveFrequency", "savefrequency", 1);
  278. // Initialize logging based on settings
  279. logConfig->configure();
  280. logGlobal->debug("settings = %s", settings.toJsonNode().toJson());
  281. // Some basic data validation to produce better error messages in cases of incorrect install
  282. auto testFile = [](std::string filename, std::string message) -> bool
  283. {
  284. if (CResourceHandler::get()->existsResource(ResourceID(filename)))
  285. return true;
  286. logGlobal->error("Error: %s was not found!", message);
  287. return false;
  288. };
  289. if (!testFile("DATA/HELP.TXT", "Heroes III data") ||
  290. !testFile("MODS/VCMI/MOD.JSON", "VCMI data"))
  291. {
  292. exit(1); // These are unrecoverable errors
  293. }
  294. // these two are optional + some installs have them on CD and not in data directory
  295. testFile("VIDEO/GOOD1A.SMK", "campaign movies");
  296. testFile("SOUNDS/G1A.WAV", "campaign music"); //technically not a music but voiced intro sounds
  297. conf.init();
  298. logGlobal->info("Loading settings: %d ms", pomtime.getDiff());
  299. srand ( (unsigned int)time(nullptr) );
  300. const JsonNode& video = settings["video"];
  301. const JsonNode& res = video["screenRes"];
  302. //something is really wrong...
  303. if (res["width"].Float() < 100 || res["height"].Float() < 100)
  304. {
  305. logGlobal->error("Fatal error: failed to load settings!");
  306. logGlobal->error("Possible reasons:");
  307. logGlobal->error("\tCorrupted local configuration file at %s/settings.json", VCMIDirs::get().userConfigPath());
  308. logGlobal->error("\tMissing or corrupted global configuration file at %s/schemas/settings.json", VCMIDirs::get().userConfigPath());
  309. logGlobal->error("VCMI will now exit...");
  310. exit(EXIT_FAILURE);
  311. }
  312. if(!settings["session"]["headless"].Bool())
  313. {
  314. if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO|SDL_INIT_NOPARACHUTE))
  315. {
  316. logGlobal->error("Something was wrong: %s", SDL_GetError());
  317. exit(-1);
  318. }
  319. #ifdef VCMI_ANDROID
  320. // manually setting egl pixel format, as a possible solution for sdl2<->android problem
  321. // https://bugzilla.libsdl.org/show_bug.cgi?id=2291
  322. SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
  323. SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 6);
  324. SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
  325. SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 0);
  326. #endif // VCMI_ANDROID
  327. GH.mainFPSmng->init(); //(!)init here AFTER SDL_Init() while using SDL for FPS management
  328. SDL_LogSetOutputFunction(&SDLLogCallback, nullptr);
  329. int driversCount = SDL_GetNumRenderDrivers();
  330. std::string preferredDriverName = video["driver"].String();
  331. logGlobal->info("Found %d render drivers", driversCount);
  332. for(int it = 0; it < driversCount; it++)
  333. {
  334. SDL_RendererInfo info;
  335. SDL_GetRenderDriverInfo(it,&info);
  336. std::string driverName(info.name);
  337. if(!preferredDriverName.empty() && driverName == preferredDriverName)
  338. {
  339. preferredDriverIndex = it;
  340. logGlobal->info("\t%s (active)", driverName);
  341. }
  342. else
  343. logGlobal->info("\t%s", driverName);
  344. }
  345. setScreenRes((int)res["width"].Float(), (int)res["height"].Float(), (int)video["bitsPerPixel"].Float(), video["fullscreen"].Bool(), (int)video["displayIndex"].Float());
  346. logGlobal->info("\tInitializing screen: %d ms", pomtime.getDiff());
  347. }
  348. CCS = new CClientState();
  349. CGI = new CGameInfo(); //contains all global informations about game (texts, lodHandlers, map handler etc.)
  350. CSH = new CServerHandler();
  351. // Initialize video
  352. #ifdef DISABLE_VIDEO
  353. CCS->videoh = new CEmptyVideoPlayer();
  354. #else
  355. if (!settings["session"]["headless"].Bool() && !vm.count("disable-video"))
  356. CCS->videoh = new CVideoPlayer();
  357. else
  358. CCS->videoh = new CEmptyVideoPlayer();
  359. #endif
  360. logGlobal->info("\tInitializing video: %d ms", pomtime.getDiff());
  361. if(!settings["session"]["headless"].Bool())
  362. {
  363. //initializing audio
  364. CCS->soundh = new CSoundHandler();
  365. CCS->soundh->init();
  366. CCS->soundh->setVolume((ui32)settings["general"]["sound"].Float());
  367. CCS->musich = new CMusicHandler();
  368. CCS->musich->init();
  369. CCS->musich->setVolume((ui32)settings["general"]["music"].Float());
  370. logGlobal->info("Initializing screen and sound handling: %d ms", pomtime.getDiff());
  371. }
  372. #ifdef VCMI_MAC
  373. // Ctrl+click should be treated as a right click on Mac OS X
  374. SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, "1");
  375. #endif
  376. #ifndef VCMI_NO_THREADED_LOAD
  377. //we can properly play intro only in the main thread, so we have to move loading to the separate thread
  378. boost::thread loading(init);
  379. #else
  380. init();
  381. #endif
  382. if(!settings["session"]["headless"].Bool())
  383. {
  384. if(!vm.count("battle") && !vm.count("nointro") && settings["video"]["showIntro"].Bool())
  385. playIntro();
  386. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 255);
  387. SDL_RenderClear(mainRenderer);
  388. SDL_RenderPresent(mainRenderer);
  389. }
  390. #ifndef VCMI_NO_THREADED_LOAD
  391. #ifdef VCMI_ANDROID // android loads the data quite slowly so we display native progressbar to prevent having only black screen for few seconds
  392. {
  393. CAndroidVMHelper vmHelper;
  394. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "showProgress");
  395. #endif // ANDROID
  396. loading.join();
  397. #ifdef VCMI_ANDROID
  398. vmHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "hideProgress");
  399. }
  400. #endif // ANDROID
  401. #endif // THREADED
  402. if(!settings["session"]["headless"].Bool())
  403. {
  404. pomtime.getDiff();
  405. graphics = new Graphics(); // should be before curh
  406. CCS->curh = new CursorHandler();
  407. logGlobal->info("Screen handler: %d ms", pomtime.getDiff());
  408. pomtime.getDiff();
  409. graphics->load();//must be after Content loading but should be in main thread
  410. logGlobal->info("Main graphics: %d ms", pomtime.getDiff());
  411. CMessage::init();
  412. logGlobal->info("Message handler: %d ms", pomtime.getDiff());
  413. CCS->curh->show();
  414. }
  415. logGlobal->info("Initialization of VCMI (together): %d ms", total.getDiff());
  416. session["autoSkip"].Bool() = vm.count("autoSkip");
  417. session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
  418. session["aiSolo"].Bool() = false;
  419. std::shared_ptr<CMainMenu> mmenu;
  420. if(vm.count("testmap"))
  421. {
  422. session["testmap"].String() = vm["testmap"].as<std::string>();
  423. session["onlyai"].Bool() = true;
  424. boost::thread(&CServerHandler::debugStartTest, CSH, session["testmap"].String(), false);
  425. }
  426. else if(vm.count("testsave"))
  427. {
  428. session["testsave"].String() = vm["testsave"].as<std::string>();
  429. session["onlyai"].Bool() = true;
  430. boost::thread(&CServerHandler::debugStartTest, CSH, session["testsave"].String(), true);
  431. }
  432. else
  433. {
  434. mmenu = CMainMenu::create();
  435. GH.curInt = mmenu.get();
  436. }
  437. std::vector<std::string> names;
  438. session["lobby"].Bool() = false;
  439. if(vm.count("lobby"))
  440. {
  441. session["lobby"].Bool() = true;
  442. session["host"].Bool() = false;
  443. session["address"].String() = vm["lobby-address"].as<std::string>();
  444. if(vm.count("lobby-username"))
  445. session["username"].String() = vm["lobby-username"].as<std::string>();
  446. else
  447. session["username"].String() = settings["launcher"]["lobbyUsername"].String();
  448. if(vm.count("lobby-gamemode"))
  449. session["gamemode"].Integer() = vm["lobby-gamemode"].as<ui16>();
  450. else
  451. session["gamemode"].Integer() = 0;
  452. CSH->uuid = vm["uuid"].as<std::string>();
  453. session["port"].Integer() = vm["lobby-port"].as<ui16>();
  454. logGlobal->info("Remote lobby mode at %s:%d, uuid is %s", session["address"].String(), session["port"].Integer(), CSH->uuid);
  455. if(vm.count("lobby-host"))
  456. {
  457. session["host"].Bool() = true;
  458. session["hostConnections"].String() = std::to_string(vm["lobby-connections"].as<ui16>());
  459. session["hostUuid"].String() = vm["lobby-uuid"].as<std::string>();
  460. logGlobal->info("This client will host session, server uuid is %s", session["hostUuid"].String());
  461. }
  462. //we should not reconnect to previous game in online mode
  463. Settings saveSession = settings.write["server"]["reconnect"];
  464. saveSession->Bool() = false;
  465. //start lobby immediately
  466. names.push_back(session["username"].String());
  467. ESelectionScreen sscreen = session["gamemode"].Integer() == 0 ? ESelectionScreen::newGame : ESelectionScreen::loadGame;
  468. mmenu->openLobby(sscreen, session["host"].Bool(), &names, ELoadMode::MULTI);
  469. }
  470. // Restore remote session - start game immediately
  471. if(settings["server"]["reconnect"].Bool())
  472. {
  473. CSH->restoreLastSession();
  474. }
  475. if(!settings["session"]["headless"].Bool())
  476. {
  477. mainLoop();
  478. }
  479. else
  480. {
  481. while(true)
  482. boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
  483. }
  484. return 0;
  485. }
  486. //plays intro, ends when intro is over or button has been pressed (handles events)
  487. void playIntro()
  488. {
  489. if(CCS->videoh->openAndPlayVideo("3DOLOGO.SMK", 0, 1, true, true))
  490. {
  491. CCS->videoh->openAndPlayVideo("AZVS.SMK", 0, 1, true, true);
  492. }
  493. }
  494. #ifndef VCMI_IOS
  495. static bool checkVideoMode(int monitorIndex, int w, int h)
  496. {
  497. //we only check that our desired window size fits on screen
  498. SDL_DisplayMode mode;
  499. if (0 != SDL_GetDesktopDisplayMode(monitorIndex, &mode))
  500. {
  501. logGlobal->error("SDL_GetDesktopDisplayMode failed");
  502. logGlobal->error(SDL_GetError());
  503. return false;
  504. }
  505. logGlobal->info("Check display mode: requested %d x %d; available up to %d x %d ", w, h, mode.w, mode.h);
  506. if (!mode.w || !mode.h || (w <= mode.w && h <= mode.h))
  507. {
  508. return true;
  509. }
  510. return false;
  511. }
  512. #endif
  513. static void cleanupRenderer()
  514. {
  515. screenBuf = nullptr; //it`s a link - just nullify
  516. if(nullptr != screen2)
  517. {
  518. SDL_FreeSurface(screen2);
  519. screen2 = nullptr;
  520. }
  521. if(nullptr != screen)
  522. {
  523. SDL_FreeSurface(screen);
  524. screen = nullptr;
  525. }
  526. if(nullptr != screenTexture)
  527. {
  528. SDL_DestroyTexture(screenTexture);
  529. screenTexture = nullptr;
  530. }
  531. }
  532. static bool recreateWindow(int w, int h, int bpp, bool fullscreen, int displayIndex)
  533. {
  534. // VCMI will only work with 2 or 4 bytes per pixel
  535. vstd::amax(bpp, 16);
  536. vstd::amin(bpp, 32);
  537. if(bpp>16)
  538. bpp = 32;
  539. if(displayIndex < 0)
  540. {
  541. if (mainWindow != nullptr)
  542. displayIndex = SDL_GetWindowDisplayIndex(mainWindow);
  543. if (displayIndex < 0)
  544. displayIndex = 0;
  545. }
  546. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  547. SDL_GetWindowSize(mainWindow, &w, &h);
  548. #else
  549. if(!checkVideoMode(displayIndex, w, h))
  550. {
  551. logGlobal->error("Error: SDL says that %dx%d resolution is not available!", w, h);
  552. }
  553. #endif
  554. bool bufOnScreen = (screenBuf == screen);
  555. bool realFullscreen = settings["video"]["realFullscreen"].Bool();
  556. /* match best rendering resolution */
  557. int renderWidth = 0, renderHeight = 0;
  558. auto aspectRatio = (float)w / (float)h;
  559. auto minDiff = 10.f;
  560. for (const auto& pair : conf.guiOptions)
  561. {
  562. int pWidth, pHeight;
  563. std::tie(pWidth, pHeight) = pair.first;
  564. /* filter out resolution which is larger than window */
  565. if (pWidth > w || pHeight > h)
  566. {
  567. continue;
  568. }
  569. auto ratio = (float)pWidth / (float)pHeight;
  570. auto diff = fabs(aspectRatio - ratio);
  571. /* select closest aspect ratio */
  572. if (diff < minDiff)
  573. {
  574. renderWidth = pWidth;
  575. renderHeight = pHeight;
  576. minDiff = diff;
  577. }
  578. /* select largest resolution meets prior conditions.
  579. * since there are resolutions like 1366x768(not exactly 16:9), a deviation of 0.005 is allowed. */
  580. else if (fabs(diff - minDiff) < 0.005f && pWidth > renderWidth)
  581. {
  582. renderWidth = pWidth;
  583. renderHeight = pHeight;
  584. }
  585. }
  586. if (renderWidth == 0)
  587. {
  588. // no matching resolution for upscaling - complain & fallback to default resolution.
  589. logGlobal->error("Failed to match rendering resolution for %dx%d!", w, h);
  590. Settings newRes = settings.write["video"]["screenRes"];
  591. std::tie(w, h) = conf.guiOptions.begin()->first;
  592. newRes["width"].Float() = w;
  593. newRes["height"].Float() = h;
  594. conf.SetResolution(w, h);
  595. logGlobal->error("Falling back to %dx%d", w, h);
  596. renderWidth = w;
  597. renderHeight = h;
  598. }
  599. else
  600. {
  601. logGlobal->info("Set logical rendering resolution to %dx%d", renderWidth, renderHeight);
  602. }
  603. cleanupRenderer();
  604. if(nullptr == mainWindow)
  605. {
  606. #if defined(VCMI_ANDROID) || defined(VCMI_IOS)
  607. auto createWindow = [displayIndex](Uint32 extraFlags) -> bool {
  608. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN | extraFlags);
  609. return mainWindow != nullptr;
  610. };
  611. # ifdef VCMI_IOS
  612. SDL_SetHint(SDL_HINT_IOS_HIDE_HOME_INDICATOR, "1");
  613. SDL_SetHint(SDL_HINT_RETURN_KEY_HIDES_IME, "1");
  614. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  615. Uint32 windowFlags = SDL_WINDOW_BORDERLESS | SDL_WINDOW_ALLOW_HIGHDPI;
  616. if(!createWindow(windowFlags | SDL_WINDOW_METAL))
  617. {
  618. logGlobal->warn("Metal unavailable, using OpenGLES");
  619. createWindow(windowFlags);
  620. }
  621. # else
  622. createWindow(0);
  623. # endif // VCMI_IOS
  624. // 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
  625. // 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
  626. SDL_Rect screenRect;
  627. if(SDL_GetDisplayBounds(0, &screenRect) == 0)
  628. {
  629. const auto screenWidth = screenRect.w;
  630. const auto screenHeight = screenRect.h;
  631. const auto aspect = static_cast<double>(screenWidth) / screenHeight;
  632. logGlobal->info("Screen size and aspect ratio: %dx%d (%lf)", screenWidth, screenHeight, aspect);
  633. if((double)w / aspect > (double)h)
  634. {
  635. h = (int)round((double)w / aspect);
  636. }
  637. else
  638. {
  639. w = (int)round((double)h * aspect);
  640. }
  641. logGlobal->info("Changing logical screen size to %dx%d", w, h);
  642. }
  643. else
  644. {
  645. logGlobal->error("Can't fix aspect ratio for screen");
  646. }
  647. #else
  648. if(fullscreen)
  649. {
  650. if(realFullscreen)
  651. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), renderWidth, renderHeight, SDL_WINDOW_FULLSCREEN);
  652. else //in windowed full-screen mode use desktop resolution
  653. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), 0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP);
  654. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  655. }
  656. else
  657. {
  658. mainWindow = SDL_CreateWindow(NAME.c_str(), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), w, h, 0);
  659. }
  660. #endif // defined(VCMI_ANDROID) || defined(VCMI_IOS)
  661. if(nullptr == mainWindow)
  662. {
  663. throw std::runtime_error("Unable to create window\n");
  664. }
  665. //create first available renderer if preferred not set. Use no flags, so HW accelerated will be preferred but SW renderer also will possible
  666. mainRenderer = SDL_CreateRenderer(mainWindow,preferredDriverIndex,0);
  667. if(nullptr == mainRenderer)
  668. {
  669. throw std::runtime_error("Unable to create renderer\n");
  670. }
  671. SDL_RendererInfo info;
  672. SDL_GetRendererInfo(mainRenderer, &info);
  673. logGlobal->info("Created renderer %s", info.name);
  674. }
  675. else
  676. {
  677. #if !defined(VCMI_ANDROID) && !defined(VCMI_IOS)
  678. if(fullscreen)
  679. {
  680. if(realFullscreen)
  681. {
  682. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN);
  683. SDL_DisplayMode mode;
  684. SDL_GetDesktopDisplayMode(displayIndex, &mode);
  685. mode.w = renderWidth;
  686. mode.h = renderHeight;
  687. SDL_SetWindowDisplayMode(mainWindow, &mode);
  688. }
  689. else
  690. {
  691. SDL_SetWindowFullscreen(mainWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
  692. }
  693. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex));
  694. SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
  695. }
  696. else
  697. {
  698. SDL_SetWindowFullscreen(mainWindow, 0);
  699. SDL_SetWindowSize(mainWindow, w, h);
  700. SDL_SetWindowPosition(mainWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex), SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex));
  701. }
  702. #endif
  703. }
  704. if(!(fullscreen && realFullscreen))
  705. {
  706. SDL_RenderSetLogicalSize(mainRenderer, renderWidth, renderHeight);
  707. //following line is bugged not only on android, do not re-enable without checking
  708. //#ifndef VCMI_ANDROID
  709. // // on android this stretches the game to fit the screen, not preserving aspect and apparently this also breaks coordinates scaling in mouse events
  710. // SDL_RenderSetViewport(mainRenderer, nullptr);
  711. //#endif
  712. }
  713. #if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
  714. int bmask = 0xff000000;
  715. int gmask = 0x00ff0000;
  716. int rmask = 0x0000ff00;
  717. int amask = 0x000000ff;
  718. #else
  719. int bmask = 0x000000ff;
  720. int gmask = 0x0000ff00;
  721. int rmask = 0x00ff0000;
  722. int amask = 0xFF000000;
  723. #endif
  724. screen = SDL_CreateRGBSurface(0,renderWidth,renderHeight,bpp,rmask,gmask,bmask,amask);
  725. if(nullptr == screen)
  726. {
  727. logGlobal->error("Unable to create surface %dx%d with %d bpp: %s", renderWidth, renderHeight, bpp, SDL_GetError());
  728. throw std::runtime_error("Unable to create surface");
  729. }
  730. //No blending for screen itself. Required for proper cursor rendering.
  731. SDL_SetSurfaceBlendMode(screen, SDL_BLENDMODE_NONE);
  732. screenTexture = SDL_CreateTexture(mainRenderer,
  733. SDL_PIXELFORMAT_ARGB8888,
  734. SDL_TEXTUREACCESS_STREAMING,
  735. renderWidth, renderHeight);
  736. if(nullptr == screenTexture)
  737. {
  738. logGlobal->error("Unable to create screen texture");
  739. logGlobal->error(SDL_GetError());
  740. throw std::runtime_error("Unable to create screen texture");
  741. }
  742. screen2 = CSDL_Ext::copySurface(screen);
  743. if(nullptr == screen2)
  744. {
  745. throw std::runtime_error("Unable to copy surface\n");
  746. }
  747. screenBuf = bufOnScreen ? screen : screen2;
  748. SDL_SetRenderDrawColor(mainRenderer, 0, 0, 0, 0);
  749. SDL_RenderClear(mainRenderer);
  750. SDL_RenderPresent(mainRenderer);
  751. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  752. {
  753. NotificationHandler::init(mainWindow);
  754. }
  755. return true;
  756. }
  757. //used only once during initialization
  758. static void setScreenRes(int w, int h, int bpp, bool fullscreen, int displayIndex, bool resetVideo)
  759. {
  760. if(!recreateWindow(w, h, bpp, fullscreen, displayIndex))
  761. {
  762. throw std::runtime_error("Requested screen resolution is not available\n");
  763. }
  764. }
  765. static void fullScreenChanged()
  766. {
  767. boost::unique_lock<boost::recursive_mutex> lock(*CPlayerInterface::pim);
  768. Settings full = settings.write["video"]["fullscreen"];
  769. const bool toFullscreen = full->Bool();
  770. auto bitsPerPixel = screen->format->BitsPerPixel;
  771. auto w = screen->w;
  772. auto h = screen->h;
  773. if(!recreateWindow(w, h, bitsPerPixel, toFullscreen, -1))
  774. {
  775. //will return false and report error if video mode is not supported
  776. return;
  777. }
  778. GH.totalRedraw();
  779. }
  780. static void handleEvent(SDL_Event & ev)
  781. {
  782. if((ev.type==SDL_QUIT) ||(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4 && (ev.key.keysym.mod & KMOD_ALT)))
  783. {
  784. #ifdef VCMI_ANDROID
  785. handleQuit(false);
  786. #else
  787. handleQuit();
  788. #endif
  789. return;
  790. }
  791. #ifdef VCMI_ANDROID
  792. else if (ev.type == SDL_KEYDOWN && ev.key.keysym.scancode == SDL_SCANCODE_AC_BACK)
  793. {
  794. handleQuit(true);
  795. }
  796. #endif
  797. else if(ev.type == SDL_KEYDOWN && ev.key.keysym.sym==SDLK_F4)
  798. {
  799. Settings full = settings.write["video"]["fullscreen"];
  800. full->Bool() = !full->Bool();
  801. return;
  802. }
  803. else if(ev.type == SDL_USEREVENT)
  804. {
  805. switch(ev.user.code)
  806. {
  807. case EUserEvent::FORCE_QUIT:
  808. {
  809. handleQuit(false);
  810. return;
  811. }
  812. break;
  813. case EUserEvent::RETURN_TO_MAIN_MENU:
  814. {
  815. CSH->endGameplay();
  816. GH.defActionsDef = 63;
  817. CMM->menu->switchToTab("main");
  818. }
  819. break;
  820. case EUserEvent::RESTART_GAME:
  821. {
  822. CSH->sendRestartGame();
  823. }
  824. break;
  825. case EUserEvent::CAMPAIGN_START_SCENARIO:
  826. {
  827. CSH->campaignServerRestartLock.set(true);
  828. CSH->endGameplay();
  829. auto ourCampaign = std::shared_ptr<CCampaignState>(reinterpret_cast<CCampaignState *>(ev.user.data1));
  830. auto & epilogue = ourCampaign->camp->scenarios[ourCampaign->mapsConquered.back()].epilog;
  831. auto finisher = [=]()
  832. {
  833. if(ourCampaign->mapsRemaining.size())
  834. {
  835. GH.pushInt(CMM);
  836. GH.pushInt(CMM->menu);
  837. CMM->openCampaignLobby(ourCampaign);
  838. }
  839. };
  840. if(epilogue.hasPrologEpilog)
  841. {
  842. GH.pushIntT<CPrologEpilogVideo>(epilogue, finisher);
  843. }
  844. else
  845. {
  846. CSH->campaignServerRestartLock.waitUntil(false);
  847. finisher();
  848. }
  849. }
  850. break;
  851. case EUserEvent::RETURN_TO_MENU_LOAD:
  852. CSH->endGameplay();
  853. GH.defActionsDef = 63;
  854. CMM->menu->switchToTab("load");
  855. break;
  856. case EUserEvent::FULLSCREEN_TOGGLED:
  857. fullScreenChanged();
  858. break;
  859. case EUserEvent::INTERFACE_CHANGED:
  860. if(LOCPLINT)
  861. LOCPLINT->updateAmbientSounds();
  862. break;
  863. default:
  864. logGlobal->error("Unknown user event. Code %d", ev.user.code);
  865. break;
  866. }
  867. return;
  868. }
  869. else if(ev.type == SDL_WINDOWEVENT)
  870. {
  871. switch (ev.window.event) {
  872. case SDL_WINDOWEVENT_RESTORED:
  873. #ifndef VCMI_IOS
  874. fullScreenChanged();
  875. #endif
  876. break;
  877. }
  878. return;
  879. }
  880. else if(ev.type == SDL_SYSWMEVENT)
  881. {
  882. if(!settings["session"]["headless"].Bool() && settings["general"]["notifications"].Bool())
  883. {
  884. NotificationHandler::handleSdlEvent(ev);
  885. }
  886. }
  887. //preprocessing
  888. if(ev.type == SDL_MOUSEMOTION)
  889. {
  890. CCS->curh->cursorMove(ev.motion.x, ev.motion.y);
  891. }
  892. {
  893. boost::unique_lock<boost::mutex> lock(eventsM);
  894. SDLEventsQueue.push(ev);
  895. }
  896. }
  897. static void mainLoop()
  898. {
  899. SettingsListener resChanged = settings.listen["video"]["fullscreen"];
  900. resChanged([](const JsonNode &newState){ CGuiHandler::pushSDLEvent(SDL_USEREVENT, EUserEvent::FULLSCREEN_TOGGLED); });
  901. inGuiThread.reset(new bool(true));
  902. GH.mainFPSmng->init();
  903. while(1) //main SDL events loop
  904. {
  905. SDL_Event ev;
  906. while(1 == SDL_PollEvent(&ev))
  907. {
  908. handleEvent(ev);
  909. }
  910. CSH->applyPacksOnLobbyScreen();
  911. GH.renderFrame();
  912. }
  913. }
  914. static void quitApplication()
  915. {
  916. if(!settings["session"]["headless"].Bool())
  917. {
  918. if(CSH->client)
  919. CSH->endGameplay();
  920. }
  921. GH.listInt.clear();
  922. GH.objsToBlit.clear();
  923. CMM.reset();
  924. if(!settings["session"]["headless"].Bool())
  925. {
  926. // cleanup, mostly to remove false leaks from analyzer
  927. if(CCS)
  928. {
  929. CCS->musich->release();
  930. CCS->soundh->release();
  931. vstd::clear_pointer(CCS);
  932. }
  933. CMessage::dispose();
  934. vstd::clear_pointer(graphics);
  935. }
  936. vstd::clear_pointer(VLC);
  937. vstd::clear_pointer(console);// should be removed after everything else since used by logging
  938. boost::this_thread::sleep(boost::posix_time::milliseconds(750));//???
  939. if(!settings["session"]["headless"].Bool())
  940. {
  941. if(settings["general"]["notifications"].Bool())
  942. {
  943. NotificationHandler::destroy();
  944. }
  945. cleanupRenderer();
  946. if(nullptr != mainRenderer)
  947. {
  948. SDL_DestroyRenderer(mainRenderer);
  949. mainRenderer = nullptr;
  950. }
  951. if(nullptr != mainWindow)
  952. {
  953. SDL_DestroyWindow(mainWindow);
  954. mainWindow = nullptr;
  955. }
  956. SDL_Quit();
  957. }
  958. if(logConfig != nullptr)
  959. {
  960. logConfig->deconfigure();
  961. delete logConfig;
  962. logConfig = nullptr;
  963. }
  964. std::cout << "Ending...\n";
  965. exit(0);
  966. }
  967. void handleQuit(bool ask)
  968. {
  969. if(CSH->client && LOCPLINT && ask)
  970. {
  971. CCS->curh->set(Cursor::Map::POINTER);
  972. LOCPLINT->showYesNoDialog(CGI->generaltexth->allTexts[69], [](){
  973. // Workaround for assertion failure on exit:
  974. // handleQuit() is alway called during SDL event processing
  975. // during which, eventsM is kept locked
  976. // this leads to assertion failure if boost::mutex is in locked state
  977. eventsM.unlock();
  978. quitApplication();
  979. }, nullptr);
  980. }
  981. else
  982. {
  983. quitApplication();
  984. }
  985. }