CCallback.cpp 11 KB

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