Client.cpp 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. #include "StdInc.h"
  2. #include "Client.h"
  3. #include <SDL.h>
  4. #include "CMusicHandler.h"
  5. #include "../lib/mapping/CCampaignHandler.h"
  6. #include "../CCallback.h"
  7. #include "../lib/CConsoleHandler.h"
  8. #include "CGameInfo.h"
  9. #include "../lib/CGameState.h"
  10. #include "CPlayerInterface.h"
  11. #include "../lib/StartInfo.h"
  12. #include "../lib/BattleState.h"
  13. #include "../lib/CModHandler.h"
  14. #include "../lib/CArtHandler.h"
  15. #include "../lib/CGeneralTextHandler.h"
  16. #include "../lib/CHeroHandler.h"
  17. #include "../lib/CTownHandler.h"
  18. #include "../lib/CBuildingHandler.h"
  19. #include "../lib/spells/CSpellHandler.h"
  20. #include "../lib/Connection.h"
  21. #ifndef VCMI_ANDROID
  22. #include "../lib/Interprocess.h"
  23. #endif
  24. #include "../lib/NetPacks.h"
  25. #include "../lib/VCMI_Lib.h"
  26. #include "../lib/VCMIDirs.h"
  27. #include "../lib/mapping/CMap.h"
  28. #include "../lib/JsonNode.h"
  29. #include "mapHandler.h"
  30. #include "../lib/CConfigHandler.h"
  31. #include "Client.h"
  32. #include "CPreGame.h"
  33. #include "battle/CBattleInterface.h"
  34. #include "../lib/CThreadHelper.h"
  35. #include "../lib/CScriptingModule.h"
  36. #include "../lib/registerTypes/RegisterTypes.h"
  37. #include "gui/CGuiHandler.h"
  38. #include "CMT.h"
  39. extern std::string NAME;
  40. #ifndef VCMI_ANDROID
  41. namespace intpr = boost::interprocess;
  42. #endif
  43. /*
  44. * Client.cpp, part of VCMI engine
  45. *
  46. * Authors: listed in file AUTHORS in main folder
  47. *
  48. * License: GNU General Public License v2.0 or later
  49. * Full text of license available in license.txt file, in main folder
  50. *
  51. */
  52. template <typename T> class CApplyOnCL;
  53. class CBaseForCLApply
  54. {
  55. public:
  56. virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
  57. virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
  58. virtual ~CBaseForCLApply(){}
  59. template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
  60. {
  61. return new CApplyOnCL<U>;
  62. }
  63. };
  64. template <typename T> class CApplyOnCL : public CBaseForCLApply
  65. {
  66. public:
  67. void applyOnClAfter(CClient *cl, void *pack) const override
  68. {
  69. T *ptr = static_cast<T*>(pack);
  70. ptr->applyCl(cl);
  71. }
  72. void applyOnClBefore(CClient *cl, void *pack) const override
  73. {
  74. T *ptr = static_cast<T*>(pack);
  75. ptr->applyFirstCl(cl);
  76. }
  77. };
  78. template <> class CApplyOnCL<CPack> : public CBaseForCLApply
  79. {
  80. public:
  81. void applyOnClAfter(CClient *cl, void *pack) const override
  82. {
  83. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  84. assert(0);
  85. }
  86. void applyOnClBefore(CClient *cl, void *pack) const override
  87. {
  88. logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
  89. assert(0);
  90. }
  91. };
  92. static CApplier<CBaseForCLApply> *applier = nullptr;
  93. void CClient::init()
  94. {
  95. hotSeat = false;
  96. connectionHandler = nullptr;
  97. pathInfo = nullptr;
  98. applier = new CApplier<CBaseForCLApply>;
  99. registerTypesClientPacks1(*applier);
  100. registerTypesClientPacks2(*applier);
  101. IObjectInterface::cb = this;
  102. serv = nullptr;
  103. gs = nullptr;
  104. erm = nullptr;
  105. terminate = false;
  106. }
  107. CClient::CClient(void)
  108. {
  109. init();
  110. }
  111. CClient::CClient(CConnection *con, StartInfo *si)
  112. {
  113. init();
  114. newGame(con,si);
  115. }
  116. CClient::~CClient(void)
  117. {
  118. delete applier;
  119. }
  120. void CClient::waitForMoveAndSend(PlayerColor color)
  121. {
  122. try
  123. {
  124. setThreadName("CClient::waitForMoveAndSend");
  125. assert(vstd::contains(battleints, color));
  126. BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
  127. if(ba.actionType != Battle::CANCEL)
  128. {
  129. logNetwork->traceStream() << "Send battle action to server: " << ba;
  130. MakeAction temp_action(ba);
  131. sendRequest(&temp_action, color);
  132. }
  133. return;
  134. }
  135. catch(boost::thread_interrupted&)
  136. {
  137. logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
  138. return;
  139. }
  140. catch(...)
  141. {
  142. handleException();
  143. return;
  144. }
  145. logNetwork->errorStream() << "We should not be here!";
  146. }
  147. void CClient::run()
  148. {
  149. setThreadName("CClient::run");
  150. try
  151. {
  152. while(!terminate)
  153. {
  154. CPack *pack = serv->retreivePack(); //get the package from the server
  155. if (terminate)
  156. {
  157. vstd::clear_pointer(pack);
  158. break;
  159. }
  160. handlePack(pack);
  161. }
  162. }
  163. //catch only asio exceptions
  164. catch (const boost::system::system_error& e)
  165. {
  166. logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
  167. logNetwork->errorStream() << e.what();
  168. if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
  169. {
  170. logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
  171. throw;
  172. }
  173. }
  174. }
  175. void CClient::save(const std::string & fname)
  176. {
  177. if(gs->curB)
  178. {
  179. logNetwork->errorStream() << "Game cannot be saved during battle!";
  180. return;
  181. }
  182. SaveGame save_game(fname);
  183. sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
  184. }
  185. void CClient::endGame( bool closeConnection /*= true*/ )
  186. {
  187. //suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
  188. for(auto i : playerint)
  189. i.second->finish();
  190. // Game is ending
  191. // Tell the network thread to reach a stable state
  192. if(closeConnection)
  193. stopConnection();
  194. logNetwork->infoStream() << "Closed connection.";
  195. GH.curInt = nullptr;
  196. {
  197. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  198. logNetwork->infoStream() << "Ending current game!";
  199. if(GH.topInt())
  200. {
  201. GH.topInt()->deactivate();
  202. }
  203. GH.listInt.clear();
  204. GH.objsToBlit.clear();
  205. GH.statusbar = nullptr;
  206. logNetwork->infoStream() << "Removed GUI.";
  207. vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
  208. vstd::clear_pointer(gs);
  209. logNetwork->infoStream() << "Deleted mapHandler and gameState.";
  210. LOCPLINT = nullptr;
  211. }
  212. playerint.clear();
  213. battleints.clear();
  214. callbacks.clear();
  215. battleCallbacks.clear();
  216. CGObelisk::reset();
  217. logNetwork->infoStream() << "Deleted playerInts.";
  218. logNetwork->infoStream() << "Client stopped.";
  219. }
  220. #if 1
  221. void CClient::loadGame(const std::string & fname, const bool server, const std::vector<int>& humanplayerindices, const int loadNumPlayers, int player_, const std::string & ipaddr, const std::string & port)
  222. {
  223. PlayerColor player(player_); //intentional shadowing
  224. logNetwork->infoStream() << "Loading procedure started!";
  225. std::string realPort;
  226. if(settings["testing"]["enabled"].Bool())
  227. realPort = settings["testing"]["port"].String();
  228. else if(port.size())
  229. realPort = port;
  230. else
  231. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  232. CServerHandler sh;
  233. if(server)
  234. sh.startServer();
  235. else
  236. serv = sh.justConnectToServer(ipaddr, realPort);
  237. CStopWatch tmh;
  238. std::unique_ptr<CLoadFile> loader;
  239. try
  240. {
  241. boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
  242. boost::filesystem::path controlServerSaveName;
  243. if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
  244. {
  245. controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
  246. }
  247. else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
  248. {
  249. controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
  250. CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
  251. }
  252. if(clientSaveName.empty())
  253. throw std::runtime_error("Cannot open client part of " + fname);
  254. if(controlServerSaveName.empty())
  255. throw std::runtime_error("Cannot open server part of " + fname);
  256. {
  257. CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, minSupportedVersion);
  258. loadCommonState(checkingLoader);
  259. loader = checkingLoader.decay();
  260. }
  261. logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
  262. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  263. const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
  264. pathInfo = make_unique<CPathsInfo>(getMapSize());
  265. CGI->mh->init();
  266. logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
  267. }
  268. catch(std::exception &e)
  269. {
  270. logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
  271. throw; //obviously we cannot continue here
  272. }
  273. /*
  274. if(!server)
  275. player = PlayerColor(player_);
  276. */
  277. std::set<PlayerColor> clientPlayers;
  278. if(server)
  279. serv = sh.connectToServer();
  280. //*loader >> *this;
  281. if(server)
  282. {
  283. tmh.update();
  284. ui8 pom8;
  285. *serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player
  286. *serv << fname;
  287. *serv >> pom8;
  288. if(pom8)
  289. throw std::runtime_error("Server cannot open the savegame!");
  290. else
  291. logNetwork->infoStream() << "Server opened savegame properly.";
  292. }
  293. if(server)
  294. {
  295. for(auto & elem : gs->scenarioOps->playerInfos)
  296. {
  297. if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
  298. clientPlayers.insert(elem.first);
  299. }
  300. clientPlayers.insert(PlayerColor::NEUTRAL);
  301. }
  302. else
  303. {
  304. clientPlayers.insert(player);
  305. }
  306. std::cout << "CLIENTPLAYERS:\n";
  307. for(auto x : clientPlayers)
  308. std::cout << x << std::endl;
  309. std::cout << "ENDCLIENTPLAYERS\n";
  310. serialize(loader->serializer,0,clientPlayers);
  311. *serv << ui32(clientPlayers.size());
  312. for(auto & elem : clientPlayers)
  313. *serv << ui8(elem.getNum());
  314. serv->addStdVecItems(gs); /*why is this here?*/
  315. //*loader >> *this;
  316. logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
  317. logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
  318. //*serv << clientPlayers;
  319. serv->enableStackSendingByID();
  320. serv->disableSmartPointerSerialization();
  321. // logGlobal->traceStream() << "Objects:";
  322. // for(int i = 0; i < gs->map->objects.size(); i++)
  323. // {
  324. // auto o = gs->map->objects[i];
  325. // if(o)
  326. // logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
  327. // else
  328. // logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
  329. // }
  330. }
  331. #endif
  332. void CClient::newGame( CConnection *con, StartInfo *si )
  333. {
  334. enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
  335. if (con == nullptr)
  336. {
  337. CServerHandler sh;
  338. serv = sh.connectToServer();
  339. }
  340. else
  341. {
  342. serv = con;
  343. networkMode = (con->connectionID == 1) ? HOST : GUEST;
  344. }
  345. CConnection &c = *serv;
  346. ////////////////////////////////////////////////////
  347. logNetwork->infoStream() <<"\tWill send info to server...";
  348. CStopWatch tmh;
  349. if(networkMode == SINGLE)
  350. {
  351. ui8 pom8;
  352. c << ui8(2) << ui8(1); //new game; one client
  353. c << *si;
  354. c >> pom8;
  355. if(pom8) throw std::runtime_error("Server cannot open the map!");
  356. }
  357. c >> si;
  358. logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
  359. c.enableStackSendingByID();
  360. c.disableSmartPointerSerialization();
  361. // Initialize game state
  362. gs = new CGameState();
  363. logNetwork->infoStream() <<"\tCreating gamestate: "<<tmh.getDiff();
  364. gs->scenarioOps = si;
  365. gs->init(si);
  366. logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
  367. // Now after possible random map gen, we know exact player count.
  368. // Inform server about how many players client handles
  369. std::set<PlayerColor> myPlayers;
  370. for(auto & elem : gs->scenarioOps->playerInfos)
  371. {
  372. if((networkMode == SINGLE) //single - one client has all player
  373. || (networkMode != SINGLE && serv->connectionID == elem.second.playerID) //multi - client has only "its players"
  374. || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
  375. {
  376. myPlayers.insert(elem.first); //add player
  377. }
  378. }
  379. if(networkMode != GUEST)
  380. myPlayers.insert(PlayerColor::NEUTRAL);
  381. c << myPlayers;
  382. // Init map handler
  383. if(gs->map)
  384. {
  385. const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
  386. CGI->mh->map = gs->map;
  387. logNetwork->infoStream() << "Creating mapHandler: " << tmh.getDiff();
  388. CGI->mh->init();
  389. pathInfo = make_unique<CPathsInfo>(getMapSize());
  390. logNetwork->infoStream() << "Initializing mapHandler (together): " << tmh.getDiff();
  391. }
  392. int humanPlayers = 0;
  393. for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
  394. {
  395. PlayerColor color = elem.first;
  396. gs->currentPlayer = color;
  397. if(!vstd::contains(myPlayers, color))
  398. continue;
  399. logNetwork->traceStream() << "Preparing interface for player " << color;
  400. if(si->mode != StartInfo::DUEL)
  401. {
  402. if(elem.second.playerID == PlayerSettings::PLAYER_AI)
  403. {
  404. auto AiToGive = aiNameForPlayer(elem.second, false);
  405. logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
  406. installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
  407. }
  408. else
  409. {
  410. installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
  411. humanPlayers++;
  412. }
  413. }
  414. else
  415. {
  416. std::string AItoGive = aiNameForPlayer(elem.second, true);
  417. installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
  418. }
  419. }
  420. if(si->mode == StartInfo::DUEL)
  421. {
  422. if(!gNoGUI)
  423. {
  424. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  425. auto p = std::make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
  426. p->observerInDuelMode = true;
  427. installNewPlayerInterface(p, boost::none);
  428. GH.curInt = p.get();
  429. }
  430. battleStarted(gs->curB);
  431. }
  432. else
  433. {
  434. loadNeutralBattleAI();
  435. }
  436. serv->addStdVecItems(gs);
  437. hotSeat = (humanPlayers > 1);
  438. // std::vector<FileInfo> scriptModules;
  439. // CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
  440. // for(FileInfo &m : scriptModules)
  441. // {
  442. // CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
  443. // privilagedGameEventReceivers.push_back(nm);
  444. // privilagedBattleEventReceivers.push_back(nm);
  445. // nm->giveActionCB(this);
  446. // nm->giveInfoCB(this);
  447. // nm->init();
  448. //
  449. // erm = nm; //something tells me that there'll at most one module and it'll be ERM
  450. // }
  451. }
  452. void CClient::serialize(COSer & h, const int version)
  453. {
  454. assert(h.saving);
  455. h & hotSeat;
  456. {
  457. ui8 players = playerint.size();
  458. h & players;
  459. for(auto i = playerint.begin(); i != playerint.end(); i++)
  460. {
  461. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  462. assert(i->first == i->second->playerID);
  463. h & i->first & i->second->dllName & i->second->human;
  464. i->second->saveGame(h, version);
  465. }
  466. }
  467. }
  468. void CClient::serialize(CISer & h, const int version)
  469. {
  470. assert(!h.saving);
  471. h & hotSeat;
  472. {
  473. ui8 players = 0; //fix for uninitialized warning
  474. h & players;
  475. for(int i=0; i < players; i++)
  476. {
  477. std::string dllname;
  478. PlayerColor pid;
  479. bool isHuman = false;
  480. h & pid & dllname & isHuman;
  481. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  482. std::shared_ptr<CGameInterface> nInt;
  483. if(dllname.length())
  484. {
  485. if(pid == PlayerColor::NEUTRAL)
  486. {
  487. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  488. //TODO? consider serialization
  489. continue;
  490. }
  491. else
  492. {
  493. assert(!isHuman);
  494. nInt = CDynLibHandler::getNewAI(dllname);
  495. }
  496. }
  497. else
  498. {
  499. assert(isHuman);
  500. nInt = std::make_shared<CPlayerInterface>(pid);
  501. }
  502. nInt->dllName = dllname;
  503. nInt->human = isHuman;
  504. nInt->playerID = pid;
  505. installNewPlayerInterface(nInt, pid);
  506. nInt->loadGame(h, version); //another evil cast, check above
  507. }
  508. if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
  509. loadNeutralBattleAI();
  510. }
  511. }
  512. void CClient::serialize(COSer & h, const int version, const std::set<PlayerColor> & playerIDs)
  513. {
  514. assert(h.saving);
  515. h & hotSeat;
  516. {
  517. ui8 players = playerint.size();
  518. h & players;
  519. for(auto i = playerint.begin(); i != playerint.end(); i++)
  520. {
  521. LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
  522. assert(i->first == i->second->playerID);
  523. h & i->first & i->second->dllName & i->second->human;
  524. i->second->saveGame(h, version);
  525. }
  526. }
  527. }
  528. void CClient::serialize(CISer & h, const int version, const std::set<PlayerColor> & playerIDs)
  529. {
  530. assert(!h.saving);
  531. h & hotSeat;
  532. {
  533. ui8 players = 0; //fix for uninitialized warning
  534. h & players;
  535. for(int i=0; i < players; i++)
  536. {
  537. std::string dllname;
  538. PlayerColor pid;
  539. bool isHuman = false;
  540. h & pid & dllname & isHuman;
  541. LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
  542. std::shared_ptr<CGameInterface> nInt;
  543. if(dllname.length())
  544. {
  545. if(pid == PlayerColor::NEUTRAL)
  546. {
  547. if(playerIDs.count(pid))
  548. installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
  549. //TODO? consider serialization
  550. continue;
  551. }
  552. else
  553. {
  554. assert(!isHuman);
  555. nInt = CDynLibHandler::getNewAI(dllname);
  556. }
  557. }
  558. else
  559. {
  560. assert(isHuman);
  561. nInt = std::make_shared<CPlayerInterface>(pid);
  562. }
  563. nInt->dllName = dllname;
  564. nInt->human = isHuman;
  565. nInt->playerID = pid;
  566. if(playerIDs.count(pid))
  567. installNewPlayerInterface(nInt, pid);
  568. nInt->loadGame(h, version);
  569. }
  570. if(playerIDs.count(PlayerColor::NEUTRAL))
  571. loadNeutralBattleAI();
  572. }
  573. }
  574. void CClient::handlePack( CPack * pack )
  575. {
  576. CBaseForCLApply *apply = applier->apps[typeList.getTypeID(pack)]; //find the applier
  577. if(apply)
  578. {
  579. boost::unique_lock<boost::recursive_mutex> guiLock(*LOCPLINT->pim);
  580. apply->applyOnClBefore(this,pack);
  581. logNetwork->traceStream() << "\tMade first apply on cl";
  582. gs->apply(pack);
  583. logNetwork->traceStream() << "\tApplied on gs";
  584. apply->applyOnClAfter(this,pack);
  585. logNetwork->traceStream() << "\tMade second apply on cl";
  586. }
  587. else
  588. {
  589. logNetwork->errorStream() << "Message cannot be applied, cannot find applier! TypeID " << typeList.getTypeID(pack);
  590. }
  591. delete pack;
  592. }
  593. void CClient::finishCampaign( std::shared_ptr<CCampaignState> camp )
  594. {
  595. }
  596. void CClient::proposeNextMission(std::shared_ptr<CCampaignState> camp)
  597. {
  598. GH.pushInt(new CBonusSelection(camp));
  599. }
  600. void CClient::stopConnection()
  601. {
  602. terminate = true;
  603. if (serv) //request closing connection
  604. {
  605. logNetwork->infoStream() << "Connection has been requested to be closed.";
  606. boost::unique_lock<boost::mutex>(*serv->wmx);
  607. CloseServer close_server;
  608. sendRequest(&close_server, PlayerColor::NEUTRAL);
  609. logNetwork->infoStream() << "Sent closing signal to the server";
  610. }
  611. if(connectionHandler)//end connection handler
  612. {
  613. if(connectionHandler->get_id() != boost::this_thread::get_id())
  614. connectionHandler->join();
  615. logNetwork->infoStream() << "Connection handler thread joined";
  616. delete connectionHandler;
  617. connectionHandler = nullptr;
  618. }
  619. if (serv) //and delete connection
  620. {
  621. serv->close();
  622. delete serv;
  623. serv = nullptr;
  624. logNetwork->warnStream() << "Our socket has been closed.";
  625. }
  626. }
  627. void CClient::battleStarted(const BattleInfo * info)
  628. {
  629. for(auto &battleCb : battleCallbacks)
  630. {
  631. if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
  632. || battleCb.first >= PlayerColor::PLAYER_LIMIT)
  633. {
  634. battleCb.second->setBattle(info);
  635. }
  636. }
  637. // for(ui8 side : info->sides)
  638. // if(battleCallbacks.count(side))
  639. // battleCallbacks[side]->setBattle(info);
  640. std::shared_ptr<CPlayerInterface> att, def;
  641. auto &leftSide = info->sides[0], &rightSide = info->sides[1];
  642. //If quick combat is not, do not prepare interfaces for battleint
  643. if(!settings["adventure"]["quickCombat"].Bool())
  644. {
  645. if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
  646. att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
  647. if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
  648. def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
  649. }
  650. if(!gNoGUI && (!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL))
  651. {
  652. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  653. auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
  654. Rect((screen->w - 800)/2,
  655. (screen->h - 600)/2, 800, 600), att, def);
  656. GH.pushInt(bi);
  657. }
  658. auto callBattleStart = [&](PlayerColor color, ui8 side){
  659. if(vstd::contains(battleints, color))
  660. battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
  661. };
  662. callBattleStart(leftSide.color, 0);
  663. callBattleStart(rightSide.color, 1);
  664. callBattleStart(PlayerColor::UNFLAGGABLE, 1);
  665. if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
  666. {
  667. boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
  668. }
  669. }
  670. void CClient::battleFinished()
  671. {
  672. for(auto & side : gs->curB->sides)
  673. if(battleCallbacks.count(side.color))
  674. battleCallbacks[side.color]->setBattle(nullptr);
  675. }
  676. void CClient::loadNeutralBattleAI()
  677. {
  678. installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
  679. }
  680. void CClient::commitPackage( CPackForClient *pack )
  681. {
  682. CommitPackage cp;
  683. cp.freePack = false;
  684. cp.packToCommit = pack;
  685. sendRequest(&cp, PlayerColor::NEUTRAL);
  686. }
  687. PlayerColor CClient::getLocalPlayer() const
  688. {
  689. if(LOCPLINT)
  690. return LOCPLINT->playerID;
  691. return getCurrentPlayer();
  692. }
  693. void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
  694. {
  695. setThreadName("CClient::commenceTacticPhaseForInt");
  696. try
  697. {
  698. battleInt->yourTacticPhase(gs->curB->tacticDistance);
  699. if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
  700. {
  701. MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
  702. sendRequest(&ma, battleInt->playerID);
  703. }
  704. }
  705. catch(...)
  706. {
  707. handleException();
  708. }
  709. }
  710. void CClient::invalidatePaths()
  711. {
  712. // turn pathfinding info into invalid. It will be regenerated later
  713. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  714. pathInfo->hero = nullptr;
  715. }
  716. const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
  717. {
  718. assert(h);
  719. boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
  720. if (pathInfo->hero != h)
  721. {
  722. gs->calculatePaths(h, *pathInfo.get());
  723. }
  724. return pathInfo.get();
  725. }
  726. int CClient::sendRequest(const CPack *request, PlayerColor player)
  727. {
  728. static ui32 requestCounter = 0;
  729. ui32 requestID = requestCounter++;
  730. logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
  731. % typeid(*request).name() % requestID;
  732. waitingRequest.pushBack(requestID);
  733. serv->sendPackToServer(*request, player, requestID);
  734. if(vstd::contains(playerint, player))
  735. playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
  736. return requestID;
  737. }
  738. void CClient::campaignMapFinished( std::shared_ptr<CCampaignState> camp )
  739. {
  740. endGame(false);
  741. GH.curInt = CGPreGame::create();
  742. auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
  743. auto finisher = [=]()
  744. {
  745. if(camp->mapsRemaining.size())
  746. proposeNextMission(camp);
  747. else
  748. finishCampaign(camp);
  749. };
  750. if(epilogue.hasPrologEpilog)
  751. {
  752. GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
  753. }
  754. else
  755. {
  756. finisher();
  757. }
  758. }
  759. void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color)
  760. {
  761. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  762. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  763. if(!color)
  764. privilagedGameEventReceivers.push_back(gameInterface);
  765. playerint[colorUsed] = gameInterface;
  766. logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
  767. auto cb = std::make_shared<CCallback>(gs, color, this);
  768. callbacks[colorUsed] = cb;
  769. battleCallbacks[colorUsed] = cb;
  770. gameInterface->init(cb);
  771. installNewBattleInterface(gameInterface, color, false);
  772. }
  773. void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
  774. {
  775. boost::unique_lock<boost::recursive_mutex> un(*LOCPLINT->pim);
  776. PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
  777. if(!color)
  778. privilagedBattleEventReceivers.push_back(battleInterface);
  779. battleints[colorUsed] = battleInterface;
  780. if(needCallback)
  781. {
  782. logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
  783. auto cbc = std::make_shared<CBattleCallback>(gs, color, this);
  784. battleCallbacks[colorUsed] = cbc;
  785. battleInterface->init(cbc);
  786. }
  787. }
  788. std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
  789. {
  790. if(ps.name.size())
  791. {
  792. const boost::filesystem::path aiPath =
  793. VCMIDirs::get().libraryPath() / "AI" / VCMIDirs::get().libraryName(ps.name);
  794. if (boost::filesystem::exists(aiPath))
  795. return ps.name;
  796. }
  797. const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
  798. std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
  799. std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
  800. //TODO what about human players
  801. if(battleints.size() >= sensibleAILimit)
  802. return badAI;
  803. return goodAI;
  804. }
  805. void CServerHandler::startServer()
  806. {
  807. th.update();
  808. serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
  809. if(verbose)
  810. logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
  811. }
  812. void CServerHandler::waitForServer()
  813. {
  814. if(!serverThread)
  815. startServer();
  816. th.update();
  817. #ifndef VCMI_ANDROID
  818. intpr::scoped_lock<intpr::interprocess_mutex> slock(shared->sr->mutex);
  819. while(!shared->sr->ready)
  820. {
  821. shared->sr->cond.wait(slock);
  822. }
  823. #endif
  824. if(verbose)
  825. logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
  826. }
  827. CConnection * CServerHandler::connectToServer()
  828. {
  829. #ifndef VCMI_ANDROID
  830. if(!shared->sr->ready)
  831. waitForServer();
  832. #else
  833. waitForServer();
  834. #endif
  835. th.update(); //put breakpoint here to attach to server before it does something stupid
  836. CConnection *ret = justConnectToServer(settings["server"]["server"].String(), port);
  837. if(verbose)
  838. logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
  839. return ret;
  840. }
  841. CServerHandler::CServerHandler(bool runServer /*= false*/)
  842. {
  843. serverThread = nullptr;
  844. shared = nullptr;
  845. if(settings["testing"]["enabled"].Bool())
  846. port = settings["testing"]["port"].String();
  847. else
  848. port = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  849. verbose = true;
  850. #ifndef VCMI_ANDROID
  851. boost::interprocess::shared_memory_object::remove("vcmi_memory"); //if the application has previously crashed, the memory may not have been removed. to avoid problems - try to destroy it
  852. try
  853. {
  854. shared = new SharedMem();
  855. }
  856. catch(...)
  857. {
  858. logNetwork->error("Cannot open interprocess memory.");
  859. handleException();
  860. throw;
  861. }
  862. #endif
  863. }
  864. CServerHandler::~CServerHandler()
  865. {
  866. delete shared;
  867. delete serverThread; //detaches, not kills thread
  868. }
  869. void CServerHandler::callServer()
  870. {
  871. setThreadName("CServerHandler::callServer");
  872. const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
  873. const std::string comm = VCMIDirs::get().serverPath().string() + " --port=" + port + " > \"" + logName + '\"';
  874. int result = std::system(comm.c_str());
  875. if (result == 0)
  876. logNetwork->infoStream() << "Server closed correctly";
  877. else
  878. {
  879. logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
  880. logNetwork->errorStream() << "Check " << logName << " for more info";
  881. exit(1);// exit in case of error. Othervice without working server VCMI will hang
  882. }
  883. }
  884. CConnection * CServerHandler::justConnectToServer(const std::string &host, const std::string &port)
  885. {
  886. std::string realPort;
  887. if(settings["testing"]["enabled"].Bool())
  888. realPort = settings["testing"]["port"].String();
  889. else if(port.size())
  890. realPort = port;
  891. else
  892. realPort = boost::lexical_cast<std::string>(settings["server"]["port"].Float());
  893. CConnection *ret = nullptr;
  894. while(!ret)
  895. {
  896. try
  897. {
  898. logNetwork->infoStream() << "Establishing connection...";
  899. ret = new CConnection( host.size() ? host : settings["server"]["server"].String(),
  900. realPort,
  901. NAME);
  902. }
  903. catch(...)
  904. {
  905. logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
  906. SDL_Delay(2000);
  907. }
  908. }
  909. return ret;
  910. }