CCallback.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. #include "StdInc.h"
  2. #include "CCallback.h"
  3. #include "lib/CCreatureHandler.h"
  4. #include "client/CGameInfo.h"
  5. #include "lib/CGameState.h"
  6. #include "lib/BattleState.h"
  7. #include "client/CPlayerInterface.h"
  8. #include "client/Client.h"
  9. #include "lib/mapping/CMap.h"
  10. #include "lib/CBuildingHandler.h"
  11. #include "lib/mapObjects/CObjectClassesHandler.h"
  12. #include "lib/CGeneralTextHandler.h"
  13. #include "lib/CHeroHandler.h"
  14. #include "lib/Connection.h"
  15. #include "lib/NetPacks.h"
  16. #include "client/mapHandler.h"
  17. #include "lib/CSpellHandler.h"
  18. #include "lib/CArtHandler.h"
  19. #include "lib/GameConstants.h"
  20. #ifdef min
  21. #undef min
  22. #endif
  23. #ifdef max
  24. #undef max
  25. #endif
  26. #include "lib/UnlockGuard.h"
  27. /*
  28. * CCallback.cpp, part of VCMI engine
  29. *
  30. * Authors: listed in file AUTHORS in main folder
  31. *
  32. * License: GNU General Public License v2.0 or later
  33. * Full text of license available in license.txt file, in main folder
  34. *
  35. */
  36. template <ui16 N> bool isType(CPack *pack)
  37. {
  38. return pack->getType() == N;
  39. }
  40. bool CCallback::teleportHero(const CGHeroInstance *who, const CGTownInstance *where)
  41. {
  42. CastleTeleportHero pack(who->id, where->id, 1);
  43. sendRequest(&pack);
  44. return true;
  45. }
  46. bool CCallback::moveHero(const CGHeroInstance *h, int3 dst)
  47. {
  48. MoveHero pack(dst,h->id);
  49. sendRequest(&pack);
  50. return true;
  51. }
  52. int CCallback::selectionMade(int selection, QueryID queryID)
  53. {
  54. ASSERT_IF_CALLED_WITH_PLAYER
  55. if(queryID == QueryID(-1))
  56. {
  57. logGlobal->errorStream() << "Cannot answer the query -1!";
  58. return false;
  59. }
  60. QueryReply pack(queryID,selection);
  61. pack.player = *player;
  62. return sendRequest(&pack);
  63. }
  64. void CCallback::recruitCreatures(const CGObjectInstance *obj, CreatureID ID, ui32 amount, si32 level/*=-1*/)
  65. {
  66. if(player!=obj->tempOwner && obj->ID != Obj::WAR_MACHINE_FACTORY)
  67. return;
  68. RecruitCreatures pack(obj->id,ID,amount,level);
  69. sendRequest(&pack);
  70. }
  71. bool CCallback::dismissCreature(const CArmedInstance *obj, SlotID stackPos)
  72. {
  73. if(((player>=0) && obj->tempOwner != player) || (obj->stacksCount()<2 && obj->needsLastStack()))
  74. return false;
  75. DisbandCreature pack(stackPos,obj->id);
  76. sendRequest(&pack);
  77. return true;
  78. }
  79. bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID)
  80. {
  81. UpgradeCreature pack(stackPos,obj->id,newID);
  82. sendRequest(&pack);
  83. return false;
  84. }
  85. void CCallback::endTurn()
  86. {
  87. logGlobal->traceStream() << "Player " << *player << " ended his turn.";
  88. EndTurn pack;
  89. sendRequest(&pack); //report that we ended turn
  90. }
  91. int CCallback::swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  92. {
  93. ArrangeStacks pack(1,p1,p2,s1->id,s2->id,0);
  94. sendRequest(&pack);
  95. return 0;
  96. }
  97. int CCallback::mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  98. {
  99. ArrangeStacks pack(2,p1,p2,s1->id,s2->id,0);
  100. sendRequest(&pack);
  101. return 0;
  102. }
  103. int CCallback::splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val)
  104. {
  105. ArrangeStacks pack(3,p1,p2,s1->id,s2->id,val);
  106. sendRequest(&pack);
  107. return 0;
  108. }
  109. bool CCallback::dismissHero(const CGHeroInstance *hero)
  110. {
  111. if(player!=hero->tempOwner) return false;
  112. DismissHero pack(hero->id);
  113. sendRequest(&pack);
  114. return true;
  115. }
  116. // int CCallback::getMySerial() const
  117. // {
  118. // boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
  119. // return gs->players[player].serial;
  120. // }
  121. bool CCallback::swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2)
  122. {
  123. ExchangeArtifacts ea;
  124. ea.src = l1;
  125. ea.dst = l2;
  126. sendRequest(&ea);
  127. return true;
  128. }
  129. /**
  130. * Assembles or disassembles a combination artifact.
  131. * @param hero Hero holding the artifact(s).
  132. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  133. * @param assemble True for assembly operation, false for disassembly.
  134. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  135. * artifact to assemble to. Otherwise it's not used.
  136. */
  137. bool CCallback::assembleArtifacts (const CGHeroInstance * hero, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  138. {
  139. if (player != hero->tempOwner)
  140. return false;
  141. AssembleArtifacts aa(hero->id, artifactSlot, assemble, assembleTo);
  142. sendRequest(&aa);
  143. return true;
  144. }
  145. bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
  146. {
  147. if(town->tempOwner!=player)
  148. return false;
  149. if(!canBuildStructure(town, buildingID))
  150. return false;
  151. BuildStructure pack(town->id,buildingID);
  152. sendRequest(&pack);
  153. return true;
  154. }
  155. int CBattleCallback::battleMakeAction(BattleAction* action)
  156. {
  157. assert(action->actionType == Battle::HERO_SPELL);
  158. MakeCustomAction mca(*action);
  159. sendRequest(&mca);
  160. return 0;
  161. }
  162. int CBattleCallback::sendRequest(const CPack *request)
  163. {
  164. int requestID = cl->sendRequest(request, *player);
  165. if(waitTillRealize)
  166. {
  167. logGlobal->traceStream() << boost::format("We'll wait till request %d is answered.\n") % requestID;
  168. auto gsUnlocker = vstd::makeUnlockSharedGuardIf(getGsMutex(), unlockGsWhenWaiting);
  169. cl->waitingRequest.waitWhileContains(requestID);
  170. }
  171. boost::this_thread::interruption_point();
  172. return requestID;
  173. }
  174. void CCallback::swapGarrisonHero( const CGTownInstance *town )
  175. {
  176. if(town->tempOwner == *player
  177. || (town->garrisonHero && town->garrisonHero->tempOwner == *player ))
  178. {
  179. GarrisonHeroSwap pack(town->id);
  180. sendRequest(&pack);
  181. }
  182. }
  183. void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
  184. {
  185. if(hero->tempOwner != player) return;
  186. BuyArtifact pack(hero->id,aid);
  187. sendRequest(&pack);
  188. }
  189. void CCallback::trade(const CGObjectInstance *market, EMarketMode::EMarketMode mode, int id1, int id2, int val1, const CGHeroInstance *hero/* = nullptr*/)
  190. {
  191. TradeOnMarketplace pack;
  192. pack.market = market;
  193. pack.hero = hero;
  194. pack.mode = mode;
  195. pack.r1 = id1;
  196. pack.r2 = id2;
  197. pack.val = val1;
  198. sendRequest(&pack);
  199. }
  200. void CCallback::setFormation(const CGHeroInstance * hero, bool tight)
  201. {
  202. const_cast<CGHeroInstance*>(hero)-> formation = tight;
  203. SetFormation pack(hero->id,tight);
  204. sendRequest(&pack);
  205. }
  206. void CCallback::setSelection(const CArmedInstance * obj)
  207. {
  208. if(!player || obj->getOwner() != *player)
  209. {
  210. logGlobal->errorStream() << boost::format("Cannot set selection to the object that is not owned. Object owner is %s, callback player %s") % obj->getOwner() % player;
  211. return;
  212. }
  213. SetSelection ss;
  214. ss.player = *player;
  215. ss.id = obj->id;
  216. sendRequest(&(CPackForClient&)ss);
  217. if(obj->getOwner() != *player)
  218. {
  219. // Cf. bug #1679 http://bugs.vcmi.eu/view.php?id=1679
  220. logGlobal->warnStream() << "The selection request became invalid because of event that occurred after it was made. Object owner is now " << obj->getOwner();
  221. throw std::runtime_error("setSelection not allowed");
  222. }
  223. if(obj->ID == Obj::HERO)
  224. {
  225. if(cl->pathInfo->hero != obj) //calculate new paths only if we selected a different hero
  226. cl->calculatePaths(static_cast<const CGHeroInstance *>(obj));
  227. //nasty workaround. TODO: nice workaround
  228. cl->gs->getPlayer(*player)->currentSelection = obj->id;
  229. }
  230. }
  231. void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero)
  232. {
  233. assert(townOrTavern);
  234. assert(hero);
  235. ui8 i=0;
  236. for(; i<gs->players[*player].availableHeroes.size(); i++)
  237. {
  238. if(gs->players[*player].availableHeroes[i] == hero)
  239. {
  240. HireHero pack(i, townOrTavern->id);
  241. pack.player = *player;
  242. sendRequest(&pack);
  243. return;
  244. }
  245. }
  246. }
  247. void CCallback::save( const std::string &fname )
  248. {
  249. cl->save(fname);
  250. }
  251. void CCallback::sendMessage(const std::string &mess)
  252. {
  253. ASSERT_IF_CALLED_WITH_PLAYER
  254. PlayerMessage pm(*player, mess);
  255. sendRequest(&(CPackForClient&)pm);
  256. }
  257. void CCallback::buildBoat( const IShipyard *obj )
  258. {
  259. BuildBoat bb;
  260. bb.objid = obj->o->id;
  261. sendRequest(&bb);
  262. }
  263. CCallback::CCallback( CGameState * GS, boost::optional<PlayerColor> Player, CClient *C )
  264. :CBattleCallback(GS, Player, C)
  265. {
  266. waitTillRealize = false;
  267. unlockGsWhenWaiting = false;
  268. }
  269. CCallback::~CCallback()
  270. {
  271. //trivial, but required. Don`t remove.
  272. }
  273. const CGPathNode * CCallback::getPathInfo( int3 tile )
  274. {
  275. if (!gs->map->isInTheMap(tile))
  276. return nullptr;
  277. validatePaths();
  278. return &cl->pathInfo->nodes[tile.x][tile.y][tile.z];
  279. }
  280. int CCallback::getDistance( int3 tile )
  281. {
  282. CGPath ret;
  283. if (getPath2 (tile, ret))
  284. return ret.nodes.size();
  285. else
  286. return 255;
  287. }
  288. bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
  289. {
  290. //TODO: merge with Pathfinder::canMoveBetween
  291. return gs->checkForVisitableDir(a, b) && gs->checkForVisitableDir(b, a);
  292. }
  293. bool CCallback::getPath2( int3 dest, CGPath &ret )
  294. {
  295. if (!gs->map->isInTheMap(dest))
  296. return false;
  297. validatePaths();
  298. boost::unique_lock<boost::mutex> pathLock(cl->pathMx);
  299. return cl->pathInfo->getPath(dest, ret);
  300. }
  301. int CCallback::getMovementCost(const CGHeroInstance * hero, int3 dest)
  302. {
  303. return gs->getMovementCost(hero, hero->visitablePos(), dest, hero->hasBonusOfType (Bonus::FLYING_MOVEMENT), hero->movement);
  304. }
  305. int3 CCallback::getGuardingCreaturePosition(int3 tile)
  306. {
  307. if (!gs->map->isInTheMap(tile))
  308. return int3(-1,-1,-1);
  309. validatePaths();
  310. boost::unique_lock<boost::mutex> pathLock(cl->pathMx);
  311. return gs->map->guardingCreaturePositions[tile.x][tile.y][tile.z];
  312. }
  313. void CCallback::recalculatePaths()
  314. {
  315. cl->calculatePaths(cl->IGameCallback::getSelectedHero(*player));
  316. }
  317. void CCallback::calculatePaths( const CGHeroInstance *hero, CPathsInfo &out, int3 src /*= int3(-1,-1,-1)*/, int movement /*= -1*/ )
  318. {
  319. gs->calculatePaths(hero, out, src, movement);
  320. }
  321. void CCallback::dig( const CGObjectInstance *hero )
  322. {
  323. DigWithHero dwh;
  324. dwh.id = hero->id;
  325. sendRequest(&dwh);
  326. }
  327. void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos)
  328. {
  329. CastAdvSpell cas;
  330. cas.hid = hero->id;
  331. cas.sid = spellID;
  332. cas.pos = pos;
  333. sendRequest(&cas);
  334. }
  335. void CCallback::unregisterAllInterfaces()
  336. {
  337. cl->playerint.clear();
  338. cl->battleints.clear();
  339. }
  340. void CCallback::validatePaths()
  341. {
  342. ASSERT_IF_CALLED_WITH_PLAYER
  343. const CGHeroInstance *h = cl->IGameCallback::getSelectedHero(*player);
  344. if(h && ( cl->pathInfo->hero != h //wrong hero
  345. || cl->pathInfo->hpos != h->getPosition(false) //wrong hero position
  346. || !cl->pathInfo->isValid)) //paths invalidated by game event
  347. {
  348. recalculatePaths();
  349. }
  350. }
  351. int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  352. {
  353. if(s1->getCreature(p1) == s2->getCreature(p2))
  354. return mergeStacks(s1, s2, p1, p2);
  355. else
  356. return swapCreatures(s1, s2, p1, p2);
  357. }
  358. void CCallback::registerGameInterface(shared_ptr<IGameEventsReceiver> gameEvents)
  359. {
  360. cl->additionalPlayerInts[*player].push_back(gameEvents);
  361. }
  362. void CCallback::registerBattleInterface(shared_ptr<IBattleEventsReceiver> battleEvents)
  363. {
  364. cl->additionalBattleInts[*player].push_back(battleEvents);
  365. }
  366. void CCallback::unregisterGameInterface(shared_ptr<IGameEventsReceiver> gameEvents)
  367. {
  368. cl->additionalPlayerInts[*player] -= gameEvents;
  369. }
  370. void CCallback::unregisterBattleInterface(shared_ptr<IBattleEventsReceiver> battleEvents)
  371. {
  372. cl->additionalBattleInts[*player] -= battleEvents;
  373. }
  374. CBattleCallback::CBattleCallback(CGameState *GS, boost::optional<PlayerColor> Player, CClient *C )
  375. {
  376. gs = GS;
  377. player = Player;
  378. cl = C;
  379. }
  380. bool CBattleCallback::battleMakeTacticAction( BattleAction * action )
  381. {
  382. assert(cl->gs->curB->tacticDistance);
  383. MakeAction ma;
  384. ma.ba = *action;
  385. sendRequest(&ma);
  386. return true;
  387. }