Client.cpp 29 KB

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