| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173 | 
							- #include "StdInc.h"
 
- #include "Client.h"
 
- #include <SDL.h>
 
- #include "CMusicHandler.h"
 
- #include "../lib/mapping/CCampaignHandler.h"
 
- #include "../CCallback.h"
 
- #include "../lib/CConsoleHandler.h"
 
- #include "CGameInfo.h"
 
- #include "../lib/CGameState.h"
 
- #include "CPlayerInterface.h"
 
- #include "../lib/StartInfo.h"
 
- #include "../lib/BattleInfo.h"
 
- #include "../lib/CModHandler.h"
 
- #include "../lib/CArtHandler.h"
 
- #include "../lib/CGeneralTextHandler.h"
 
- #include "../lib/CHeroHandler.h"
 
- #include "../lib/CTownHandler.h"
 
- #include "../lib/CBuildingHandler.h"
 
- #include "../lib/spells/CSpellHandler.h"
 
- #include "../lib/serializer/CTypeList.h"
 
- #include "../lib/serializer/Connection.h"
 
- #include "../lib/serializer/CLoadIntegrityValidator.h"
 
- #ifndef VCMI_ANDROID
 
- #include "../lib/Interprocess.h"
 
- #endif
 
- #include "../lib/NetPacks.h"
 
- #include "../lib/VCMI_Lib.h"
 
- #include "../lib/VCMIDirs.h"
 
- #include "../lib/mapping/CMap.h"
 
- #include "../lib/JsonNode.h"
 
- #include "mapHandler.h"
 
- #include "../lib/CConfigHandler.h"
 
- #include "CPreGame.h"
 
- #include "battle/CBattleInterface.h"
 
- #include "../lib/CThreadHelper.h"
 
- #include "../lib/CScriptingModule.h"
 
- #include "../lib/registerTypes/RegisterTypes.h"
 
- #include "gui/CGuiHandler.h"
 
- #include "CMT.h"
 
- extern std::string NAME;
 
- #ifdef VCMI_ANDROID
 
- #include "lib/CAndroidVMHelper.h"
 
- #endif
 
- /*
 
-  * Client.cpp, part of VCMI engine
 
-  *
 
-  * Authors: listed in file AUTHORS in main folder
 
-  *
 
-  * License: GNU General Public License v2.0 or later
 
-  * Full text of license available in license.txt file, in main folder
 
-  *
 
-  */
 
- #ifdef VCMI_ANDROID
 
- std::atomic_bool androidTestServerReadyFlag;
 
- #endif
 
- template <typename T> class CApplyOnCL;
 
- class CBaseForCLApply
 
- {
 
- public:
 
- 	virtual void applyOnClAfter(CClient *cl, void *pack) const =0;
 
- 	virtual void applyOnClBefore(CClient *cl, void *pack) const =0;
 
- 	virtual ~CBaseForCLApply(){}
 
- 	template<typename U> static CBaseForCLApply *getApplier(const U * t=nullptr)
 
- 	{
 
- 		return new CApplyOnCL<U>;
 
- 	}
 
- };
 
- template <typename T> class CApplyOnCL : public CBaseForCLApply
 
- {
 
- public:
 
- 	void applyOnClAfter(CClient *cl, void *pack) const override
 
- 	{
 
- 		T *ptr = static_cast<T*>(pack);
 
- 		ptr->applyCl(cl);
 
- 	}
 
- 	void applyOnClBefore(CClient *cl, void *pack) const override
 
- 	{
 
- 		T *ptr = static_cast<T*>(pack);
 
- 		ptr->applyFirstCl(cl);
 
- 	}
 
- };
 
- template <> class CApplyOnCL<CPack> : public CBaseForCLApply
 
- {
 
- public:
 
- 	void applyOnClAfter(CClient *cl, void *pack) const override
 
- 	{
 
- 		logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
 
- 		assert(0);
 
- 	}
 
- 	void applyOnClBefore(CClient *cl, void *pack) const override
 
- 	{
 
- 		logGlobal->errorStream() << "Cannot apply on CL plain CPack!";
 
- 		assert(0);
 
- 	}
 
- };
 
- static CApplier<CBaseForCLApply> *applier = nullptr;
 
- void CClient::init()
 
- {
 
- 	hotSeat = false;
 
- 	connectionHandler = nullptr;
 
- 	pathInfo = nullptr;
 
- 	applier = new CApplier<CBaseForCLApply>;
 
- 	registerTypesClientPacks1(*applier);
 
- 	registerTypesClientPacks2(*applier);
 
- 	IObjectInterface::cb = this;
 
- 	serv = nullptr;
 
- 	gs = nullptr;
 
- 	erm = nullptr;
 
- 	terminate = false;
 
- }
 
- CClient::CClient(void)
 
- {
 
- 	init();
 
- }
 
- CClient::CClient(CConnection *con, StartInfo *si)
 
- {
 
- 	init();
 
- 	newGame(con,si);
 
- }
 
- CClient::~CClient(void)
 
- {
 
- 	delete applier;
 
- }
 
- void CClient::waitForMoveAndSend(PlayerColor color)
 
- {
 
- 	try
 
- 	{
 
- 		setThreadName("CClient::waitForMoveAndSend");
 
- 		assert(vstd::contains(battleints, color));
 
- 		BattleAction ba = battleints[color]->activeStack(gs->curB->battleGetStackByID(gs->curB->activeStack, false));
 
- 		if(ba.actionType != Battle::CANCEL)
 
- 		{
 
- 			logNetwork->traceStream() << "Send battle action to server: " << ba;
 
- 			MakeAction temp_action(ba);
 
- 			sendRequest(&temp_action, color);
 
- 		}
 
- 	}
 
- 	catch(boost::thread_interrupted&)
 
- 	{
 
- 		logNetwork->debugStream() << "Wait for move thread was interrupted and no action will be send. Was a battle ended by spell?";
 
- 	}
 
- 	catch(...)
 
- 	{
 
- 		handleException();
 
- 	}
 
- }
 
- void CClient::run()
 
- {
 
- 	setThreadName("CClient::run");
 
- 	try
 
- 	{
 
- 		while(!terminate)
 
- 		{
 
- 			CPack *pack = serv->retreivePack(); //get the package from the server
 
- 			if (terminate)
 
- 			{
 
- 				vstd::clear_pointer(pack);
 
- 				break;
 
- 			}
 
- 			handlePack(pack);
 
- 		}
 
- 	}
 
- 	//catch only asio exceptions
 
- 	catch (const boost::system::system_error& e)
 
- 	{
 
- 		logNetwork->errorStream() << "Lost connection to server, ending listening thread!";
 
- 		logNetwork->errorStream() << e.what();
 
- 		if(!terminate) //rethrow (-> boom!) only if closing connection was unexpected
 
- 		{
 
- 			logNetwork->errorStream() << "Something wrong, lost connection while game is still ongoing...";
 
- 			throw;
 
- 		}
 
- 	}
 
- }
 
- void CClient::save(const std::string & fname)
 
- {
 
- 	if(gs->curB)
 
- 	{
 
- 		logNetwork->errorStream() << "Game cannot be saved during battle!";
 
- 		return;
 
- 	}
 
- 	SaveGame save_game(fname);
 
- 	sendRequest((CPackForClient*)&save_game, PlayerColor::NEUTRAL);
 
- }
 
- void CClient::endGame(bool closeConnection /*= true*/)
 
- {
 
- 	//suggest interfaces to finish their stuff (AI should interrupt any bg working threads)
 
- 	for (auto& i : playerint)
 
- 		i.second->finish();
 
- 	// Game is ending
 
- 	// Tell the network thread to reach a stable state
 
- 	if (closeConnection)
 
- 		stopConnection();
 
- 	logNetwork->infoStream() << "Closed connection.";
 
- 	GH.curInt = nullptr;
 
- 	{
 
- 		boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 
- 		logNetwork->infoStream() << "Ending current game!";
 
- 		if(GH.topInt())
 
- 		{
 
- 			GH.topInt()->deactivate();
 
- 		}
 
- 		GH.listInt.clear();
 
- 		GH.objsToBlit.clear();
 
- 		GH.statusbar = nullptr;
 
- 		logNetwork->infoStream() << "Removed GUI.";
 
- 		vstd::clear_pointer(const_cast<CGameInfo*>(CGI)->mh);
 
- 		vstd::clear_pointer(gs);
 
- 		logNetwork->infoStream() << "Deleted mapHandler and gameState.";
 
- 		LOCPLINT = nullptr;
 
- 	}
 
- 	playerint.clear();
 
- 	battleints.clear();
 
- 	callbacks.clear();
 
- 	battleCallbacks.clear();
 
- 	CGKeys::reset();
 
- 	CGMagi::reset();
 
- 	CGObelisk::reset();
 
- 	logNetwork->infoStream() << "Deleted playerInts.";
 
- 	logNetwork->infoStream() << "Client stopped.";
 
- }
 
- #if 1
 
- 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 ui16 port)
 
- {
 
- 	PlayerColor player(player_); //intentional shadowing
 
- 	logNetwork->infoStream() << "Loading procedure started!";
 
- 	CServerHandler sh;
 
- 	if(server)
 
- 		sh.startServer();
 
- 	else
 
- 		serv = sh.justConnectToServer(ipaddr, port);
 
- 	CStopWatch tmh;
 
- 	std::unique_ptr<CLoadFile> loader;
 
- 	try
 
- 	{
 
- 		boost::filesystem::path clientSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::CLIENT_SAVEGAME));
 
- 		boost::filesystem::path controlServerSaveName;
 
- 		if (CResourceHandler::get("local")->existsResource(ResourceID(fname, EResType::SERVER_SAVEGAME)))
 
- 		{
 
- 			controlServerSaveName = *CResourceHandler::get("local")->getResourceName(ResourceID(fname, EResType::SERVER_SAVEGAME));
 
- 		}
 
- 		else// create entry for server savegame. Triggered if save was made after launch and not yet present in res handler
 
- 		{
 
- 			controlServerSaveName = boost::filesystem::path(clientSaveName).replace_extension(".vsgm1");
 
- 			CResourceHandler::get("local")->createResource(controlServerSaveName.string(), true);
 
- 		}
 
- 		if(clientSaveName.empty())
 
- 			throw std::runtime_error("Cannot open client part of " + fname);
 
- 		if(controlServerSaveName.empty() || !boost::filesystem::exists(controlServerSaveName))
 
- 			throw std::runtime_error("Cannot open server part of " + fname);
 
- 		{
 
- 			CLoadIntegrityValidator checkingLoader(clientSaveName, controlServerSaveName, MINIMAL_SERIALIZATION_VERSION);
 
- 			loadCommonState(checkingLoader);
 
- 			loader = checkingLoader.decay();
 
- 		}
 
- 		logNetwork->infoStream() << "Loaded common part of save " << tmh.getDiff();
 
- 		const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
 
- 		const_cast<CGameInfo*>(CGI)->mh->map = gs->map;
 
- 		pathInfo = make_unique<CPathsInfo>(getMapSize());
 
- 		CGI->mh->init();
 
- 		logNetwork->infoStream() <<"Initing maphandler: "<<tmh.getDiff();
 
- 	}
 
- 	catch(std::exception &e)
 
- 	{
 
- 		logGlobal->errorStream() << "Cannot load game " << fname << ". Error: " << e.what();
 
- 		throw; //obviously we cannot continue here
 
- 	}
 
- /*
 
-     if(!server)
 
-          player = PlayerColor(player_);
 
- */
 
- 	std::set<PlayerColor> clientPlayers;
 
- 	if(server)
 
- 	serv = sh.connectToServer();
 
-     //*loader >> *this;
 
- 	if(server)
 
- 	{
 
- 		tmh.update();
 
- 		ui8 pom8;
 
- 		*serv << ui8(3) << ui8(loadNumPlayers); //load game; one client if single-player
 
- 		*serv << fname;
 
- 		*serv >> pom8;
 
- 		if(pom8)
 
- 			throw std::runtime_error("Server cannot open the savegame!");
 
- 		else
 
- 			logNetwork->infoStream() << "Server opened savegame properly.";
 
- 	}
 
- 	if(server)
 
- 	{
 
- 		for(auto & elem : gs->scenarioOps->playerInfos)
 
- 		{
 
- 			if(!std::count(humanplayerindices.begin(),humanplayerindices.end(),elem.first.getNum()) || elem.first==player)
 
- 				clientPlayers.insert(elem.first);
 
- 		}
 
- 		clientPlayers.insert(PlayerColor::NEUTRAL);
 
- 	}
 
- 	else
 
- 	{
 
- 		clientPlayers.insert(player);
 
- 	}
 
- 	std::cout << "CLIENTPLAYERS:\n";
 
- 	for(auto x : clientPlayers)
 
- 		std::cout << x << std::endl;
 
- 	std::cout << "ENDCLIENTPLAYERS\n";
 
- 	serialize(loader->serializer,0,clientPlayers);
 
- 	*serv << ui32(clientPlayers.size());
 
- 	for(auto & elem : clientPlayers)
 
- 		*serv << ui8(elem.getNum());
 
- 	serv->addStdVecItems(gs); /*why is this here?*/
 
-     //*loader >> *this;
 
- 	logNetwork->infoStream() << "Loaded client part of save " << tmh.getDiff();
 
- 	logNetwork->infoStream() <<"Sent info to server: "<<tmh.getDiff();
 
-     //*serv << clientPlayers;
 
- 	serv->enableStackSendingByID();
 
- 	serv->disableSmartPointerSerialization();
 
- // 	logGlobal->traceStream() << "Objects:";
 
- // 	for(int i = 0; i < gs->map->objects.size(); i++)
 
- // 	{
 
- // 		auto o = gs->map->objects[i];
 
- // 		if(o)
 
- // 			logGlobal->traceStream() << boost::format("\tindex=%5d, id=%5d; address=%5d, pos=%s, name=%s") % i % o->id % (int)o.get() % o->pos % o->getHoverText();
 
- // 		else
 
- // 			logGlobal->traceStream() << boost::format("\tindex=%5d --- nullptr") % i;
 
- // 	}
 
- }
 
- #endif
 
- void CClient::newGame( CConnection *con, StartInfo *si )
 
- {
 
- 	enum {SINGLE, HOST, GUEST} networkMode = SINGLE;
 
- 	if (con == nullptr)
 
- 	{
 
- 		CServerHandler sh;
 
- 		serv = sh.connectToServer();
 
- 	}
 
- 	else
 
- 	{
 
- 		serv = con;
 
- 		networkMode = con->isHost() ? HOST : GUEST;
 
- 	}
 
- 	CConnection &c = *serv;
 
- 	////////////////////////////////////////////////////
 
- 	logNetwork->infoStream() <<"\tWill send info to server...";
 
- 	CStopWatch tmh;
 
- 	if(networkMode == SINGLE)
 
- 	{
 
- 		ui8 pom8;
 
- 		c << ui8(2) << ui8(1); //new game; one client
 
- 		c << *si;
 
- 		c >> pom8;
 
- 		if(pom8) throw std::runtime_error("Server cannot open the map!");
 
- 	}
 
- 	c >> si;
 
- 	logNetwork->infoStream() <<"\tSending/Getting info to/from the server: "<<tmh.getDiff();
 
- 	c.enableStackSendingByID();
 
- 	c.disableSmartPointerSerialization();
 
- 	// Initialize game state
 
- 	gs = new CGameState();
 
- 	logNetwork->info("\tCreating gamestate: %i",tmh.getDiff());
 
- 	gs->init(si, settings["general"]["saveRandomMaps"].Bool());
 
- 	logNetwork->infoStream() <<"Initializing GameState (together): "<<tmh.getDiff();
 
- 	// Now after possible random map gen, we know exact player count.
 
- 	// Inform server about how many players client handles
 
- 	std::set<PlayerColor> myPlayers;
 
- 	for(auto & elem : gs->scenarioOps->playerInfos)
 
- 	{
 
- 		if((networkMode == SINGLE)                                                      //single - one client has all player
 
- 		   || (networkMode != SINGLE && serv->connectionID == elem.second.playerID)      //multi - client has only "its players"
 
- 		   || (networkMode == HOST && elem.second.playerID == PlayerSettings::PLAYER_AI))//multi - host has all AI players
 
- 		{
 
- 			myPlayers.insert(elem.first); //add player
 
- 		}
 
- 	}
 
- 	if(networkMode != GUEST)
 
- 		myPlayers.insert(PlayerColor::NEUTRAL);
 
- 	c << myPlayers;
 
- 	// Init map handler
 
- 	if(gs->map)
 
- 	{
 
- 		if(!settings["session"]["headless"].Bool())
 
- 		{
 
- 			const_cast<CGameInfo*>(CGI)->mh = new CMapHandler();
 
- 			CGI->mh->map = gs->map;
 
- 			logNetwork->infoStream() << "Creating mapHandler: " << tmh.getDiff();
 
- 			CGI->mh->init();
 
- 		}
 
- 		pathInfo = make_unique<CPathsInfo>(getMapSize());
 
- 		logNetwork->infoStream() << "Initializing mapHandler (together): " << tmh.getDiff();
 
- 	}
 
- 	int humanPlayers = 0;
 
- 	for(auto & elem : gs->scenarioOps->playerInfos)//initializing interfaces for players
 
- 	{
 
- 		PlayerColor color = elem.first;
 
- 		gs->currentPlayer = color;
 
- 		if(!vstd::contains(myPlayers, color))
 
- 			continue;
 
- 		logNetwork->traceStream() << "Preparing interface for player " << color;
 
- 		if(si->mode != StartInfo::DUEL)
 
- 		{
 
- 			if(elem.second.playerID == PlayerSettings::PLAYER_AI)
 
- 			{
 
- 				auto AiToGive = aiNameForPlayer(elem.second, false);
 
- 				logNetwork->infoStream() << boost::format("Player %s will be lead by %s") % color % AiToGive;
 
- 				installNewPlayerInterface(CDynLibHandler::getNewAI(AiToGive), color);
 
- 			}
 
- 			else
 
- 			{
 
- 				installNewPlayerInterface(std::make_shared<CPlayerInterface>(color), color);
 
- 				humanPlayers++;
 
- 			}
 
- 		}
 
- 		else
 
- 		{
 
- 			std::string AItoGive = aiNameForPlayer(elem.second, true);
 
- 			installNewBattleInterface(CDynLibHandler::getNewBattleAI(AItoGive), color);
 
- 		}
 
- 	}
 
- 	if(si->mode == StartInfo::DUEL)
 
- 	{
 
- 		if(!settings["session"]["headless"].Bool())
 
- 		{
 
- 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 
- 			auto p = std::make_shared<CPlayerInterface>(PlayerColor::NEUTRAL);
 
- 			p->observerInDuelMode = true;
 
- 			installNewPlayerInterface(p, boost::none);
 
- 			GH.curInt = p.get();
 
- 		}
 
- 		battleStarted(gs->curB);
 
- 	}
 
- 	else
 
- 	{
 
- 		if(settings["session"]["spectate"].Bool())
 
- 		{
 
- 			installNewPlayerInterface(std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR), PlayerColor::SPECTATOR, true);
 
- 		}
 
- 		loadNeutralBattleAI();
 
- 	}
 
- 	serv->addStdVecItems(gs);
 
- 	hotSeat = (humanPlayers > 1);
 
- // 	std::vector<FileInfo> scriptModules;
 
- // 	CFileUtility::getFilesWithExt(scriptModules, LIB_DIR "/scripting", "." LIB_EXT);
 
- // 	for(FileInfo &m : scriptModules)
 
- // 	{
 
- // 		CScriptingModule * nm = CDynLibHandler::getNewScriptingModule(m.name);
 
- // 		privilagedGameEventReceivers.push_back(nm);
 
- // 		privilagedBattleEventReceivers.push_back(nm);
 
- // 		nm->giveActionCB(this);
 
- // 		nm->giveInfoCB(this);
 
- // 		nm->init();
 
- //
 
- // 		erm = nm; //something tells me that there'll at most one module and it'll be ERM
 
- // 	}
 
- }
 
- void CClient::serialize(BinarySerializer & h, const int version)
 
- {
 
- 	assert(h.saving);
 
- 	h & hotSeat;
 
- 	{
 
- 		ui8 players = playerint.size();
 
- 		h & players;
 
- 		for(auto i = playerint.begin(); i != playerint.end(); i++)
 
- 		{
 
- 			LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
 
- 			assert(i->first == i->second->playerID);
 
- 			h & i->first & i->second->dllName & i->second->human;
 
- 			i->second->saveGame(h, version);
 
- 		}
 
- 	}
 
- }
 
- void CClient::serialize(BinaryDeserializer & h, const int version)
 
- {
 
- 	assert(!h.saving);
 
- 	h & hotSeat;
 
- 	{
 
- 		ui8 players = 0; //fix for uninitialized warning
 
- 		h & players;
 
- 		for(int i=0; i < players; i++)
 
- 		{
 
- 			std::string dllname;
 
- 			PlayerColor pid;
 
- 			bool isHuman = false;
 
- 			h & pid & dllname & isHuman;
 
- 			LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
 
- 			std::shared_ptr<CGameInterface> nInt;
 
- 			if(dllname.length())
 
- 			{
 
- 				if(pid == PlayerColor::NEUTRAL)
 
- 				{
 
- 					installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
 
- 					//TODO? consider serialization
 
- 					continue;
 
- 				}
 
- 				else
 
- 				{
 
- 					assert(!isHuman);
 
- 					nInt = CDynLibHandler::getNewAI(dllname);
 
- 				}
 
- 			}
 
- 			else
 
- 			{
 
- 				assert(isHuman);
 
- 				nInt = std::make_shared<CPlayerInterface>(pid);
 
- 			}
 
- 			nInt->dllName = dllname;
 
- 			nInt->human = isHuman;
 
- 			nInt->playerID = pid;
 
- 			installNewPlayerInterface(nInt, pid);
 
- 			nInt->loadGame(h, version); //another evil cast, check above
 
- 		}
 
- 		if(!vstd::contains(battleints, PlayerColor::NEUTRAL))
 
- 			loadNeutralBattleAI();
 
- 	}
 
- }
 
- void CClient::serialize(BinarySerializer & h, const int version, const std::set<PlayerColor> & playerIDs)
 
- {
 
- 	assert(h.saving);
 
- 	h & hotSeat;
 
- 	{
 
- 		ui8 players = playerint.size();
 
- 		h & players;
 
- 		for(auto i = playerint.begin(); i != playerint.end(); i++)
 
- 		{
 
- 			LOG_TRACE_PARAMS(logGlobal, "Saving player %s interface", i->first);
 
- 			assert(i->first == i->second->playerID);
 
- 			h & i->first & i->second->dllName & i->second->human;
 
- 			i->second->saveGame(h, version);
 
- 		}
 
- 	}
 
- }
 
- void CClient::serialize(BinaryDeserializer & h, const int version, const std::set<PlayerColor> & playerIDs)
 
- {
 
- 	assert(!h.saving);
 
- 	h & hotSeat;
 
- 	{
 
- 		ui8 players = 0; //fix for uninitialized warning
 
- 		h & players;
 
- 		for(int i=0; i < players; i++)
 
- 		{
 
- 			std::string dllname;
 
- 			PlayerColor pid;
 
- 			bool isHuman = false;
 
- 			h & pid & dllname & isHuman;
 
- 			LOG_TRACE_PARAMS(logGlobal, "Loading player %s interface", pid);
 
- 			std::shared_ptr<CGameInterface> nInt;
 
- 			if(dllname.length())
 
- 			{
 
- 				if(pid == PlayerColor::NEUTRAL)
 
- 				{
 
- 					if(playerIDs.count(pid))
 
- 						installNewBattleInterface(CDynLibHandler::getNewBattleAI(dllname), pid);
 
- 					//TODO? consider serialization
 
- 					continue;
 
- 				}
 
- 				else
 
- 				{
 
- 					assert(!isHuman);
 
- 					nInt = CDynLibHandler::getNewAI(dllname);
 
- 				}
 
- 			}
 
- 			else
 
- 			{
 
- 				assert(isHuman);
 
- 				nInt = std::make_shared<CPlayerInterface>(pid);
 
- 			}
 
- 			nInt->dllName = dllname;
 
- 			nInt->human = isHuman;
 
- 			nInt->playerID = pid;
 
- 			nInt->loadGame(h, version);
 
- 			if(settings["session"]["onlyai"].Bool() && isHuman)
 
- 			{
 
- 				removeGUI();
 
- 				nInt.reset();
 
- 				dllname = aiNameForPlayer(false);
 
- 				nInt = CDynLibHandler::getNewAI(dllname);
 
- 				nInt->dllName = dllname;
 
- 				nInt->human = false;
 
- 				nInt->playerID = pid;
 
- 				installNewPlayerInterface(nInt, pid);
 
- 				GH.totalRedraw();
 
- 			}
 
- 			else
 
- 			{
 
- 				if(playerIDs.count(pid))
 
- 					installNewPlayerInterface(nInt, pid);
 
- 			}
 
- 		}
 
- 		if(settings["session"]["spectate"].Bool())
 
- 		{
 
- 			removeGUI();
 
- 			auto p = std::make_shared<CPlayerInterface>(PlayerColor::SPECTATOR);
 
- 			installNewPlayerInterface(p, PlayerColor::SPECTATOR, true);
 
- 			GH.curInt = p.get();
 
- 			LOCPLINT->activateForSpectator();
 
- 			GH.totalRedraw();
 
- 		}
 
- 		if(playerIDs.count(PlayerColor::NEUTRAL))
 
- 			loadNeutralBattleAI();
 
- 	}
 
- }
 
- void CClient::handlePack( CPack * pack )
 
- {
 
- 	if(pack == nullptr)
 
- 	{
 
- 		logNetwork->error("Dropping nullptr CPack! You should check whether client and server ABI matches.");
 
- 		return;
 
- 	}
 
- 	CBaseForCLApply *apply = applier->getApplier(typeList.getTypeID(pack)); //find the applier
 
- 	if(apply)
 
- 	{
 
- 		boost::unique_lock<boost::recursive_mutex> guiLock(*CPlayerInterface::pim);
 
- 		apply->applyOnClBefore(this, pack);
 
- 		logNetwork->trace("\tMade first apply on cl");
 
- 		gs->apply(pack);
 
- 		logNetwork->trace("\tApplied on gs");
 
- 		apply->applyOnClAfter(this, pack);
 
- 		logNetwork->trace("\tMade second apply on cl");
 
- 	}
 
- 	else
 
- 	{
 
- 		logNetwork->error("Message %s cannot be applied, cannot find applier!", typeList.getTypeInfo(pack)->name());
 
- 	}
 
- 	delete pack;
 
- }
 
- void CClient::finishCampaign( std::shared_ptr<CCampaignState> camp )
 
- {
 
- }
 
- void CClient::proposeNextMission(std::shared_ptr<CCampaignState> camp)
 
- {
 
- 	GH.pushInt(new CBonusSelection(camp));
 
- }
 
- void CClient::stopConnection()
 
- {
 
- 	terminate = true;
 
- 	if(serv)
 
- 	{
 
- 		boost::unique_lock<boost::mutex>(*serv->wmx);
 
- 		if(serv->isHost()) //request closing connection
 
- 		{
 
- 			logNetwork->infoStream() << "Connection has been requested to be closed.";
 
- 			CloseServer close_server;
 
- 			sendRequest(&close_server, PlayerColor::NEUTRAL);
 
- 			logNetwork->infoStream() << "Sent closing signal to the server";
 
- 		}
 
- 		else
 
- 		{
 
- 			LeaveGame leave_Game;
 
- 			sendRequest(&leave_Game, PlayerColor::NEUTRAL);
 
- 			logNetwork->infoStream() << "Sent leaving signal to the server";
 
- 		}
 
- 	}
 
- 	if(connectionHandler)//end connection handler
 
- 	{
 
- 		if(connectionHandler->get_id() != boost::this_thread::get_id())
 
- 			connectionHandler->join();
 
- 		logNetwork->infoStream() << "Connection handler thread joined";
 
- 		vstd::clear_pointer(connectionHandler);
 
- 	}
 
- 	if (serv) //and delete connection
 
- 	{
 
- 		serv->close();
 
- 		vstd::clear_pointer(serv);
 
- 		logNetwork->warnStream() << "Our socket has been closed.";
 
- 	}
 
- }
 
- void CClient::battleStarted(const BattleInfo * info)
 
- {
 
- 	for(auto &battleCb : battleCallbacks)
 
- 	{
 
- 		if(vstd::contains_if(info->sides, [&](const SideInBattle& side) {return side.color == battleCb.first; })
 
- 			||  battleCb.first >= PlayerColor::PLAYER_LIMIT)
 
- 		{
 
- 			battleCb.second->setBattle(info);
 
- 		}
 
- 	}
 
- // 	for(ui8 side : info->sides)
 
- // 		if(battleCallbacks.count(side))
 
- // 			battleCallbacks[side]->setBattle(info);
 
- 	std::shared_ptr<CPlayerInterface> att, def;
 
- 	auto &leftSide = info->sides[0], &rightSide = info->sides[1];
 
- 	//If quick combat is not, do not prepare interfaces for battleint
 
- 	if(!settings["adventure"]["quickCombat"].Bool())
 
- 	{
 
- 		if(vstd::contains(playerint, leftSide.color) && playerint[leftSide.color]->human)
 
- 			att = std::dynamic_pointer_cast<CPlayerInterface>( playerint[leftSide.color] );
 
- 		if(vstd::contains(playerint, rightSide.color) && playerint[rightSide.color]->human)
 
- 			def = std::dynamic_pointer_cast<CPlayerInterface>( playerint[rightSide.color] );
 
- 	}
 
- 	if(!settings["session"]["headless"].Bool())
 
- 	{
 
- 		if(!!att || !!def || gs->scenarioOps->mode == StartInfo::DUEL)
 
- 		{
 
- 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 
- 			auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
 
- 				Rect((screen->w - 800)/2,
 
- 					 (screen->h - 600)/2, 800, 600), att, def);
 
- 			GH.pushInt(bi);
 
- 		}
 
- 		else if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
 
- 		{
 
- 			//TODO: This certainly need improvement
 
- 			auto spectratorInt = std::dynamic_pointer_cast<CPlayerInterface>(playerint[PlayerColor::SPECTATOR]);
 
- 			spectratorInt->cb->setBattle(info);
 
- 			boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 
- 			auto bi = new CBattleInterface(leftSide.armyObject, rightSide.armyObject, leftSide.hero, rightSide.hero,
 
- 				Rect((screen->w - 800)/2,
 
- 					 (screen->h - 600)/2, 800, 600), att, def, spectratorInt);
 
- 			GH.pushInt(bi);
 
- 		}
 
- 	}
 
- 	auto callBattleStart = [&](PlayerColor color, ui8 side){
 
- 		if(vstd::contains(battleints, color))
 
- 			battleints[color]->battleStart(leftSide.armyObject, rightSide.armyObject, info->tile, leftSide.hero, rightSide.hero, side);
 
- 	};
 
- 	callBattleStart(leftSide.color, 0);
 
- 	callBattleStart(rightSide.color, 1);
 
- 	callBattleStart(PlayerColor::UNFLAGGABLE, 1);
 
- 	if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
 
- 		callBattleStart(PlayerColor::SPECTATOR, 1);
 
- 	if(info->tacticDistance && vstd::contains(battleints,info->sides[info->tacticsSide].color))
 
- 	{
 
- 		boost::thread(&CClient::commenceTacticPhaseForInt, this, battleints[info->sides[info->tacticsSide].color]);
 
- 	}
 
- }
 
- void CClient::battleFinished()
 
- {
 
- 	for(auto & side : gs->curB->sides)
 
- 		if(battleCallbacks.count(side.color))
 
- 			battleCallbacks[side.color]->setBattle(nullptr);
 
- 	if(settings["session"]["spectate"].Bool() && !settings["session"]["spectate-skip-battle"].Bool())
 
- 		battleCallbacks[PlayerColor::SPECTATOR]->setBattle(nullptr);
 
- }
 
- void CClient::loadNeutralBattleAI()
 
- {
 
- 	installNewBattleInterface(CDynLibHandler::getNewBattleAI(settings["server"]["neutralAI"].String()), PlayerColor::NEUTRAL);
 
- }
 
- void CClient::commitPackage( CPackForClient *pack )
 
- {
 
- 	CommitPackage cp;
 
- 	cp.freePack = false;
 
- 	cp.packToCommit = pack;
 
- 	sendRequest(&cp, PlayerColor::NEUTRAL);
 
- }
 
- PlayerColor CClient::getLocalPlayer() const
 
- {
 
- 	if(LOCPLINT)
 
- 		return LOCPLINT->playerID;
 
- 	return getCurrentPlayer();
 
- }
 
- void CClient::commenceTacticPhaseForInt(std::shared_ptr<CBattleGameInterface> battleInt)
 
- {
 
- 	setThreadName("CClient::commenceTacticPhaseForInt");
 
- 	try
 
- 	{
 
- 		battleInt->yourTacticPhase(gs->curB->tacticDistance);
 
- 		if(gs && !!gs->curB && gs->curB->tacticDistance) //while awaiting for end of tactics phase, many things can happen (end of battle... or game)
 
- 		{
 
- 			MakeAction ma(BattleAction::makeEndOFTacticPhase(gs->curB->playerToSide(battleInt->playerID)));
 
- 			sendRequest(&ma, battleInt->playerID);
 
- 		}
 
- 	}
 
- 	catch(...)
 
- 	{
 
- 		handleException();
 
- 	}
 
- }
 
- void CClient::invalidatePaths()
 
- {
 
- 	// turn pathfinding info into invalid. It will be regenerated later
 
- 	boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
 
- 	pathInfo->hero = nullptr;
 
- }
 
- const CPathsInfo * CClient::getPathsInfo(const CGHeroInstance *h)
 
- {
 
- 	assert(h);
 
- 	boost::unique_lock<boost::mutex> pathLock(pathInfo->pathMx);
 
- 	if (pathInfo->hero != h)
 
- 	{
 
- 		gs->calculatePaths(h, *pathInfo.get());
 
- 	}
 
- 	return pathInfo.get();
 
- }
 
- int CClient::sendRequest(const CPack *request, PlayerColor player)
 
- {
 
- 	static ui32 requestCounter = 0;
 
- 	ui32 requestID = requestCounter++;
 
- 	logNetwork->traceStream() << boost::format("Sending a request \"%s\". It'll have an ID=%d.")
 
- 				% typeid(*request).name() % requestID;
 
- 	waitingRequest.pushBack(requestID);
 
- 	serv->sendPackToServer(*request, player, requestID);
 
- 	if(vstd::contains(playerint, player))
 
- 		playerint[player]->requestSent(dynamic_cast<const CPackForServer*>(request), requestID);
 
- 	return requestID;
 
- }
 
- void CClient::campaignMapFinished( std::shared_ptr<CCampaignState> camp )
 
- {
 
- 	endGame(false);
 
- 	GH.curInt = CGPreGame::create();
 
- 	auto & epilogue = camp->camp->scenarios[camp->mapsConquered.back()].epilog;
 
- 	auto finisher = [=]()
 
- 	{
 
- 		if(camp->mapsRemaining.size())
 
- 			proposeNextMission(camp);
 
- 		else
 
- 			finishCampaign(camp);
 
- 	};
 
- 	if(epilogue.hasPrologEpilog)
 
- 	{
 
- 		GH.pushInt(new CPrologEpilogVideo(epilogue, finisher));
 
- 	}
 
- 	else
 
- 	{
 
- 		finisher();
 
- 	}
 
- }
 
- void CClient::installNewPlayerInterface(std::shared_ptr<CGameInterface> gameInterface, boost::optional<PlayerColor> color, bool battlecb)
 
- {
 
- 	boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 
- 	PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
 
- 	if(!color)
 
- 		privilagedGameEventReceivers.push_back(gameInterface);
 
- 	playerint[colorUsed] = gameInterface;
 
- 	logGlobal->traceStream() << boost::format("\tInitializing the interface for player %s") % colorUsed;
 
- 	auto cb = std::make_shared<CCallback>(gs, color, this);
 
- 	callbacks[colorUsed] = cb;
 
- 	battleCallbacks[colorUsed] = cb;
 
- 	gameInterface->init(cb);
 
- 	installNewBattleInterface(gameInterface, color, battlecb);
 
- }
 
- void CClient::installNewBattleInterface(std::shared_ptr<CBattleGameInterface> battleInterface, boost::optional<PlayerColor> color, bool needCallback /*= true*/)
 
- {
 
- 	boost::unique_lock<boost::recursive_mutex> un(*CPlayerInterface::pim);
 
- 	PlayerColor colorUsed = color.get_value_or(PlayerColor::UNFLAGGABLE);
 
- 	if(!color)
 
- 		privilagedBattleEventReceivers.push_back(battleInterface);
 
- 	battleints[colorUsed] = battleInterface;
 
- 	if(needCallback)
 
- 	{
 
- 		logGlobal->traceStream() << boost::format("\tInitializing the battle interface for player %s") % *color;
 
- 		auto cbc = std::make_shared<CBattleCallback>(gs, color, this);
 
- 		battleCallbacks[colorUsed] = cbc;
 
- 		battleInterface->init(cbc);
 
- 	}
 
- }
 
- std::string CClient::aiNameForPlayer(const PlayerSettings &ps, bool battleAI)
 
- {
 
- 	if(ps.name.size())
 
- 	{
 
- 		const boost::filesystem::path aiPath = VCMIDirs::get().fullLibraryPath("AI", ps.name);
 
- 		if (boost::filesystem::exists(aiPath))
 
- 			return ps.name;
 
- 	}
 
- 	return aiNameForPlayer(battleAI);
 
- }
 
- std::string CClient::aiNameForPlayer(bool battleAI)
 
- {
 
- 	const int sensibleAILimit = settings["session"]["oneGoodAI"].Bool() ? 1 : PlayerColor::PLAYER_LIMIT_I;
 
- 	std::string goodAI = battleAI ? settings["server"]["neutralAI"].String() : settings["server"]["playerAI"].String();
 
- 	std::string badAI = battleAI ? "StupidAI" : "EmptyAI";
 
- 	//TODO what about human players
 
- 	if(battleints.size() >= sensibleAILimit)
 
- 		return badAI;
 
- 	return goodAI;
 
- }
 
- void CServerHandler::startServer()
 
- {
 
- 	if(settings["session"]["donotstartserver"].Bool())
 
- 		return;
 
- 	th.update();
 
- #ifdef VCMI_ANDROID
 
- 	CAndroidVMHelper envHelper;
 
- 	envHelper.callStaticVoidMethod(CAndroidVMHelper::NATIVE_METHODS_DEFAULT_CLASS, "startServer", true);
 
- #else
 
- 	serverThread = new boost::thread(&CServerHandler::callServer, this); //runs server executable;
 
- #endif
 
- 	if(verbose)
 
- 		logNetwork->infoStream() << "Setting up thread calling server: " << th.getDiff();
 
- }
 
- void CServerHandler::waitForServer()
 
- {
 
- 	if(settings["session"]["donotstartserver"].Bool())
 
- 		return;
 
- 	if(!serverThread)
 
- 		startServer();
 
- 	th.update();
 
- #ifndef VCMI_ANDROID
 
- 	if(shared)
 
- 		shared->sr->waitTillReady();
 
- #else
 
- 	logNetwork->infoStream() << "waiting for server";
 
- 	while (!androidTestServerReadyFlag.load())
 
- 	{
 
- 		logNetwork->infoStream() << "still waiting...";
 
- 		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
 
- 	}
 
- 	logNetwork->infoStream() << "waiting for server finished...";
 
- 	androidTestServerReadyFlag = false;
 
- #endif
 
- 	if(verbose)
 
- 		logNetwork->infoStream() << "Waiting for server: " << th.getDiff();
 
- }
 
- CConnection * CServerHandler::connectToServer()
 
- {
 
- 	waitForServer();
 
- 	th.update(); //put breakpoint here to attach to server before it does something stupid
 
- #ifndef VCMI_ANDROID
 
- 	CConnection *ret = justConnectToServer(settings["server"]["server"].String(), shared ? shared->sr->port : 0);
 
- #else
 
- 	CConnection *ret = justConnectToServer(settings["server"]["server"].String());
 
- #endif
 
- 	if(verbose)
 
- 		logNetwork->infoStream()<<"\tConnecting to the server: "<<th.getDiff();
 
- 	return ret;
 
- }
 
- ui16 CServerHandler::getDefaultPort()
 
- {
 
- 	if(settings["session"]["serverport"].Integer())
 
- 		return settings["session"]["serverport"].Integer();
 
- 	else
 
- 		return settings["server"]["port"].Integer();
 
- }
 
- std::string CServerHandler::getDefaultPortStr()
 
- {
 
- 	return boost::lexical_cast<std::string>(getDefaultPort());
 
- }
 
- CServerHandler::CServerHandler(bool runServer /*= false*/)
 
- {
 
- 	serverThread = nullptr;
 
- 	shared = nullptr;
 
- 	verbose = true;
 
- 	uuid = boost::uuids::to_string(boost::uuids::random_generator()());
 
- #ifndef VCMI_ANDROID
 
- 	if(settings["session"]["donotstartserver"].Bool() || settings["session"]["disable-shm"].Bool())
 
- 		return;
 
- 	std::string sharedMemoryName = "vcmi_memory";
 
- 	if(settings["session"]["enable-shm-uuid"].Bool())
 
- 	{
 
- 		//used or automated testing when multiple clients start simultaneously
 
- 		sharedMemoryName += "_" + uuid;
 
- 	}
 
- 	try
 
- 	{
 
- 		shared = new SharedMemory(sharedMemoryName, true);
 
- 	}
 
- 	catch(...)
 
- 	{
 
- 		vstd::clear_pointer(shared);
 
- 		logNetwork->error("Cannot open interprocess memory.");
 
- 		handleException();
 
- 		throw;
 
- 	}
 
- #endif
 
- }
 
- CServerHandler::~CServerHandler()
 
- {
 
- 	delete shared;
 
- 	delete serverThread; //detaches, not kills thread
 
- }
 
- void CServerHandler::callServer()
 
- {
 
- #ifndef VCMI_ANDROID
 
- 	setThreadName("CServerHandler::callServer");
 
- 	const std::string logName = (VCMIDirs::get().userCachePath() / "server_log.txt").string();
 
- 	std::string comm = VCMIDirs::get().serverPath().string()
 
- 		+ " --port=" + getDefaultPortStr()
 
- 		+ " --run-by-client"
 
- 		+ " --uuid=" + uuid;
 
- 	if(shared)
 
- 	{
 
- 		comm += " --enable-shm";
 
- 		if(settings["session"]["enable-shm-uuid"].Bool())
 
- 			comm += " --enable-shm-uuid";
 
- 	}
 
- 	comm += " > \"" + logName + '\"';
 
- 	int result = std::system(comm.c_str());
 
- 	if (result == 0)
 
- 	{
 
- 		logNetwork->infoStream() << "Server closed correctly";
 
- 		serverAlive.setn(false);
 
- 	}
 
- 	else
 
- 	{
 
- 		logNetwork->errorStream() << "Error: server failed to close correctly or crashed!";
 
- 		logNetwork->errorStream() << "Check " << logName << " for more info";
 
- 		exit(1);// exit in case of error. Othervice without working server VCMI will hang
 
- 	}
 
- #endif
 
- }
 
- CConnection * CServerHandler::justConnectToServer(const std::string &host, const ui16 port)
 
- {
 
- 	CConnection *ret = nullptr;
 
- 	while(!ret)
 
- 	{
 
- 		try
 
- 		{
 
- 			logNetwork->infoStream() << "Establishing connection...";
 
- 			ret = new CConnection(	host.size() ? host : settings["server"]["server"].String(),
 
- 									port ? port : getDefaultPort(),
 
- 									NAME);
 
- 			ret->connectionID = 1; // TODO: Refactoring for the server so IDs set outside of CConnection
 
- 		}
 
- 		catch(...)
 
- 		{
 
- 			logNetwork->errorStream() << "\nCannot establish connection! Retrying within 2 seconds";
 
- 			SDL_Delay(2000);
 
- 		}
 
- 	}
 
- 	return ret;
 
- }
 
- #ifdef VCMI_ANDROID
 
- extern "C" JNIEXPORT void JNICALL Java_eu_vcmi_vcmi_NativeMethods_notifyServerReady(JNIEnv * env, jobject cls)
 
- {
 
- 	logNetwork->infoStream() << "Received server ready signal";
 
- 	androidTestServerReadyFlag.store(true);
 
- }
 
- extern "C" JNIEXPORT bool JNICALL Java_eu_vcmi_vcmi_NativeMethods_tryToSaveTheGame(JNIEnv * env, jobject cls)
 
- {
 
- 	logGlobal->infoStream() << "Received emergency save game request";
 
- 	if(!LOCPLINT || !LOCPLINT->cb)
 
- 	{
 
- 		return false;
 
- 	}
 
- 	LOCPLINT->cb->save("Saves/_Android_Autosave");
 
- 	return true;
 
- }
 
- #endif
 
 
  |