CCallback.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /*
  2. * CCallback.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CCallback.h"
  12. #include "lib/CCreatureHandler.h"
  13. #include "lib/gameState/CGameState.h"
  14. #include "client/CPlayerInterface.h"
  15. #include "client/Client.h"
  16. #include "lib/mapping/CMap.h"
  17. #include "lib/mapObjects/CGHeroInstance.h"
  18. #include "lib/mapObjects/CGTownInstance.h"
  19. #include "lib/texts/CGeneralTextHandler.h"
  20. #include "lib/CHeroHandler.h"
  21. #include "lib/CArtHandler.h"
  22. #include "lib/GameConstants.h"
  23. #include "lib/CPlayerState.h"
  24. #include "lib/UnlockGuard.h"
  25. #include "lib/battle/BattleInfo.h"
  26. #include "lib/networkPacks/PacksForServer.h"
  27. bool CCallback::teleportHero(const CGHeroInstance *who, const CGTownInstance *where)
  28. {
  29. CastleTeleportHero pack(who->id, where->id, 1);
  30. sendRequest(&pack);
  31. return true;
  32. }
  33. void CCallback::moveHero(const CGHeroInstance *h, const int3 & destination, bool transit)
  34. {
  35. MoveHero pack({destination}, h->id, transit);
  36. sendRequest(&pack);
  37. }
  38. void CCallback::moveHero(const CGHeroInstance *h, const std::vector<int3> & path, bool transit)
  39. {
  40. MoveHero pack(path, h->id, transit);
  41. sendRequest(&pack);
  42. }
  43. int CCallback::selectionMade(int selection, QueryID queryID)
  44. {
  45. return sendQueryReply(selection, queryID);
  46. }
  47. int CCallback::sendQueryReply(std::optional<int32_t> reply, QueryID queryID)
  48. {
  49. ASSERT_IF_CALLED_WITH_PLAYER
  50. if(queryID == QueryID(-1))
  51. {
  52. logGlobal->error("Cannot answer the query -1!");
  53. return -1;
  54. }
  55. QueryReply pack(queryID, reply);
  56. pack.player = *player;
  57. return sendRequest(&pack);
  58. }
  59. void CCallback::recruitCreatures(const CGDwelling * obj, const CArmedInstance * dst, CreatureID ID, ui32 amount, si32 level)
  60. {
  61. // TODO exception for neutral dwellings shouldn't be hardcoded
  62. if(player != obj->tempOwner && obj->ID != Obj::WAR_MACHINE_FACTORY && obj->ID != Obj::REFUGEE_CAMP)
  63. return;
  64. RecruitCreatures pack(obj->id, dst->id, ID, amount, level);
  65. sendRequest(&pack);
  66. }
  67. bool CCallback::dismissCreature(const CArmedInstance *obj, SlotID stackPos)
  68. {
  69. if((player && obj->tempOwner != player) || (obj->stacksCount()<2 && obj->needsLastStack()))
  70. return false;
  71. DisbandCreature pack(stackPos,obj->id);
  72. sendRequest(&pack);
  73. return true;
  74. }
  75. bool CCallback::upgradeCreature(const CArmedInstance *obj, SlotID stackPos, CreatureID newID)
  76. {
  77. UpgradeCreature pack(stackPos,obj->id,newID);
  78. sendRequest(&pack);
  79. return false;
  80. }
  81. void CCallback::endTurn()
  82. {
  83. logGlobal->trace("Player %d ended his turn.", player->getNum());
  84. EndTurn pack;
  85. sendRequest(&pack);
  86. }
  87. int CCallback::swapCreatures(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  88. {
  89. ArrangeStacks pack(1,p1,p2,s1->id,s2->id,0);
  90. sendRequest(&pack);
  91. return 0;
  92. }
  93. int CCallback::mergeStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  94. {
  95. ArrangeStacks pack(2,p1,p2,s1->id,s2->id,0);
  96. sendRequest(&pack);
  97. return 0;
  98. }
  99. int CCallback::splitStack(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2, int val)
  100. {
  101. ArrangeStacks pack(3,p1,p2,s1->id,s2->id,val);
  102. sendRequest(&pack);
  103. return 0;
  104. }
  105. int CCallback::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  106. {
  107. BulkMoveArmy pack(srcArmy, destArmy, srcSlot);
  108. sendRequest(&pack);
  109. return 0;
  110. }
  111. int CCallback::bulkSplitStack(ObjectInstanceID armyId, SlotID srcSlot, int howMany)
  112. {
  113. BulkSplitStack pack(armyId, srcSlot, howMany);
  114. sendRequest(&pack);
  115. return 0;
  116. }
  117. int CCallback::bulkSmartSplitStack(ObjectInstanceID armyId, SlotID srcSlot)
  118. {
  119. BulkSmartSplitStack pack(armyId, srcSlot);
  120. sendRequest(&pack);
  121. return 0;
  122. }
  123. int CCallback::bulkMergeStacks(ObjectInstanceID armyId, SlotID srcSlot)
  124. {
  125. BulkMergeStacks pack(armyId, srcSlot);
  126. sendRequest(&pack);
  127. return 0;
  128. }
  129. bool CCallback::dismissHero(const CGHeroInstance *hero)
  130. {
  131. if(player!=hero->tempOwner) return false;
  132. DismissHero pack(hero->id);
  133. sendRequest(&pack);
  134. return true;
  135. }
  136. bool CCallback::swapArtifacts(const ArtifactLocation &l1, const ArtifactLocation &l2)
  137. {
  138. ExchangeArtifacts ea;
  139. ea.src = l1;
  140. ea.dst = l2;
  141. sendRequest(&ea);
  142. return true;
  143. }
  144. /**
  145. * Assembles or disassembles a combination artifact.
  146. * @param hero Hero holding the artifact(s).
  147. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  148. * @param assemble True for assembly operation, false for disassembly.
  149. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  150. * artifact to assemble to. Otherwise it's not used.
  151. */
  152. void CCallback::assembleArtifacts(const ObjectInstanceID & heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  153. {
  154. AssembleArtifacts aa(heroID, artifactSlot, assemble, assembleTo);
  155. sendRequest(&aa);
  156. }
  157. void CCallback::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap, bool equipped, bool backpack)
  158. {
  159. BulkExchangeArtifacts bma(srcHero, dstHero, swap, equipped, backpack);
  160. sendRequest(&bma);
  161. }
  162. void CCallback::scrollBackpackArtifacts(ObjectInstanceID hero, bool left)
  163. {
  164. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SCROLL_RIGHT);
  165. if(left)
  166. mba.cmd = ManageBackpackArtifacts::ManageCmd::SCROLL_LEFT;
  167. sendRequest(&mba);
  168. }
  169. void CCallback::manageHeroCostume(ObjectInstanceID hero, size_t costumeIndex, bool saveCostume)
  170. {
  171. ManageEquippedArtifacts mea(hero, costumeIndex, saveCostume);
  172. sendRequest(&mea);
  173. }
  174. void CCallback::eraseArtifactByClient(const ArtifactLocation & al)
  175. {
  176. EraseArtifactByClient ea(al);
  177. sendRequest(&ea);
  178. }
  179. bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
  180. {
  181. if(town->tempOwner!=player)
  182. return false;
  183. if(canBuildStructure(town, buildingID) != EBuildingState::ALLOWED)
  184. return false;
  185. BuildStructure pack(town->id,buildingID);
  186. sendRequest(&pack);
  187. return true;
  188. }
  189. bool CCallback::visitTownBuilding(const CGTownInstance *town, BuildingID buildingID)
  190. {
  191. if(town->tempOwner!=player)
  192. return false;
  193. VisitTownBuilding pack(town->id, buildingID);
  194. sendRequest(&pack);
  195. return true;
  196. }
  197. void CBattleCallback::battleMakeSpellAction(const BattleID & battleID, const BattleAction & action)
  198. {
  199. assert(action.actionType == EActionType::HERO_SPELL);
  200. MakeAction mca(action);
  201. mca.battleID = battleID;
  202. sendRequest(&mca);
  203. }
  204. int CBattleCallback::sendRequest(const CPackForServer * request)
  205. {
  206. int requestID = cl->sendRequest(request, *getPlayerID());
  207. if(waitTillRealize)
  208. {
  209. logGlobal->trace("We'll wait till request %d is answered.\n", requestID);
  210. auto gsUnlocker = vstd::makeUnlockSharedGuardIf(CGameState::mutex, unlockGsWhenWaiting);
  211. CClient::waitingRequest.waitWhileContains(requestID);
  212. }
  213. boost::this_thread::interruption_point();
  214. return requestID;
  215. }
  216. void CCallback::spellResearch( const CGTownInstance *town, SpellID spellAtSlot )
  217. {
  218. SpellResearch pack(town->id, spellAtSlot);
  219. sendRequest(&pack);
  220. }
  221. void CCallback::swapGarrisonHero( const CGTownInstance *town )
  222. {
  223. if(town->tempOwner == *player || (town->garrisonHero && town->garrisonHero->tempOwner == *player ))
  224. {
  225. GarrisonHeroSwap pack(town->id);
  226. sendRequest(&pack);
  227. }
  228. }
  229. void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
  230. {
  231. if(hero->tempOwner != *player) return;
  232. BuyArtifact pack(hero->id,aid);
  233. sendRequest(&pack);
  234. }
  235. void CCallback::trade(const ObjectInstanceID marketId, EMarketMode mode, TradeItemSell id1, TradeItemBuy id2, ui32 val1, const CGHeroInstance * hero)
  236. {
  237. trade(marketId, mode, std::vector(1, id1), std::vector(1, id2), std::vector(1, val1), hero);
  238. }
  239. void CCallback::trade(const ObjectInstanceID marketId, EMarketMode mode, const std::vector<TradeItemSell> & id1, const std::vector<TradeItemBuy> & id2, const std::vector<ui32> & val1, const CGHeroInstance * hero)
  240. {
  241. TradeOnMarketplace pack;
  242. pack.marketId = marketId;
  243. pack.heroId = hero ? hero->id : ObjectInstanceID();
  244. pack.mode = mode;
  245. pack.r1 = id1;
  246. pack.r2 = id2;
  247. pack.val = val1;
  248. sendRequest(&pack);
  249. }
  250. void CCallback::setFormation(const CGHeroInstance * hero, EArmyFormation mode)
  251. {
  252. SetFormation pack(hero->id, mode);
  253. sendRequest(&pack);
  254. }
  255. void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero, const HeroTypeID & nextHero)
  256. {
  257. assert(townOrTavern);
  258. assert(hero);
  259. HireHero pack(hero->getHeroType(), townOrTavern->id, nextHero);
  260. pack.player = *player;
  261. sendRequest(&pack);
  262. }
  263. void CCallback::save( const std::string &fname )
  264. {
  265. cl->save(fname);
  266. }
  267. void CCallback::gamePause(bool pause)
  268. {
  269. if(pause)
  270. {
  271. GamePause pack;
  272. pack.player = *player;
  273. sendRequest(&pack);
  274. }
  275. else
  276. {
  277. sendQueryReply(0, QueryID::CLIENT);
  278. }
  279. }
  280. void CCallback::sendMessage(const std::string &mess, const CGObjectInstance * currentObject)
  281. {
  282. ASSERT_IF_CALLED_WITH_PLAYER
  283. PlayerMessage pm(mess, currentObject? currentObject->id : ObjectInstanceID(-1));
  284. if(player)
  285. pm.player = *player;
  286. sendRequest(&pm);
  287. }
  288. void CCallback::buildBoat( const IShipyard *obj )
  289. {
  290. BuildBoat bb;
  291. bb.objid = dynamic_cast<const CGObjectInstance*>(obj)->id;
  292. sendRequest(&bb);
  293. }
  294. CCallback::CCallback(CGameState * GS, std::optional<PlayerColor> Player, CClient * C)
  295. : CBattleCallback(Player, C)
  296. {
  297. gs = GS;
  298. waitTillRealize = false;
  299. unlockGsWhenWaiting = false;
  300. }
  301. CCallback::~CCallback() = default;
  302. bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
  303. {
  304. //bidirectional
  305. return gs->map->canMoveBetween(a, b);
  306. }
  307. std::shared_ptr<const CPathsInfo> CCallback::getPathsInfo(const CGHeroInstance * h)
  308. {
  309. return cl->getPathsInfo(h);
  310. }
  311. std::optional<PlayerColor> CCallback::getPlayerID() const
  312. {
  313. return CBattleCallback::getPlayerID();
  314. }
  315. int3 CCallback::getGuardingCreaturePosition(int3 tile)
  316. {
  317. if (!gs->map->isInTheMap(tile))
  318. return int3(-1,-1,-1);
  319. return gs->map->guardingCreaturePositions[tile.z][tile.x][tile.y];
  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. int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  336. {
  337. if(s1->getCreature(p1) == s2->getCreature(p2))
  338. return mergeStacks(s1, s2, p1, p2);
  339. else
  340. return swapCreatures(s1, s2, p1, p2);
  341. }
  342. void CCallback::registerBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  343. {
  344. cl->additionalBattleInts[*player].push_back(battleEvents);
  345. }
  346. void CCallback::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  347. {
  348. cl->additionalBattleInts[*player] -= battleEvents;
  349. }
  350. CBattleCallback::CBattleCallback(std::optional<PlayerColor> player, CClient * C):
  351. cl(C),
  352. player(player)
  353. {
  354. }
  355. void CBattleCallback::battleMakeUnitAction(const BattleID & battleID, const BattleAction & action)
  356. {
  357. assert(!cl->gs->getBattle(battleID)->tacticDistance);
  358. MakeAction ma;
  359. ma.ba = action;
  360. ma.battleID = battleID;
  361. sendRequest(&ma);
  362. }
  363. void CBattleCallback::battleMakeTacticAction(const BattleID & battleID, const BattleAction & action )
  364. {
  365. assert(cl->gs->getBattle(battleID)->tacticDistance);
  366. MakeAction ma;
  367. ma.ba = action;
  368. ma.battleID = battleID;
  369. sendRequest(&ma);
  370. }
  371. std::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  372. {
  373. return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleID, battleState);
  374. }
  375. std::shared_ptr<CPlayerBattleCallback> CBattleCallback::getBattle(const BattleID & battleID)
  376. {
  377. if (activeBattles.count(battleID))
  378. return activeBattles.at(battleID);
  379. throw std::runtime_error("Failed to find battle " + std::to_string(battleID.getNum()) + " of player " + player->toString() + ". Number of ongoing battles: " + std::to_string(activeBattles.size()));
  380. }
  381. std::optional<PlayerColor> CBattleCallback::getPlayerID() const
  382. {
  383. return player;
  384. }
  385. void CBattleCallback::onBattleStarted(const IBattleInfo * info)
  386. {
  387. if (activeBattles.count(info->getBattleID()) > 0)
  388. throw std::runtime_error("Player " + player->toString() + " is already engaged in battle " + std::to_string(info->getBattleID().getNum()));
  389. logGlobal->debug("Battle %d started for player %s", info->getBattleID(), player->toString());
  390. activeBattles[info->getBattleID()] = std::make_shared<CPlayerBattleCallback>(info, *getPlayerID());
  391. }
  392. void CBattleCallback::onBattleEnded(const BattleID & battleID)
  393. {
  394. if (activeBattles.count(battleID) == 0)
  395. throw std::runtime_error("Player " + player->toString() + " is not engaged in battle " + std::to_string(battleID.getNum()));
  396. logGlobal->debug("Battle %d ended for player %s", battleID, player->toString());
  397. activeBattles.erase(battleID);
  398. }