CCallback.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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/CArtHandler.h"
  21. #include "lib/GameConstants.h"
  22. #include "lib/CPlayerState.h"
  23. #include "lib/UnlockGuard.h"
  24. #include "lib/battle/BattleInfo.h"
  25. #include "lib/networkPacks/PacksForServer.h"
  26. #include "lib/networkPacks/SaveLocalState.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::sortBackpackArtifactsBySlot(const ObjectInstanceID hero)
  170. {
  171. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SORT_BY_SLOT);
  172. sendRequest(mba);
  173. }
  174. void CCallback::sortBackpackArtifactsByCost(const ObjectInstanceID hero)
  175. {
  176. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SORT_BY_COST);
  177. sendRequest(mba);
  178. }
  179. void CCallback::sortBackpackArtifactsByClass(const ObjectInstanceID hero)
  180. {
  181. ManageBackpackArtifacts mba(hero, ManageBackpackArtifacts::ManageCmd::SORT_BY_CLASS);
  182. sendRequest(mba);
  183. }
  184. void CCallback::manageHeroCostume(ObjectInstanceID hero, size_t costumeIndex, bool saveCostume)
  185. {
  186. ManageEquippedArtifacts mea(hero, costumeIndex, saveCostume);
  187. sendRequest(mea);
  188. }
  189. void CCallback::eraseArtifactByClient(const ArtifactLocation & al)
  190. {
  191. EraseArtifactByClient ea(al);
  192. sendRequest(ea);
  193. }
  194. bool CCallback::buildBuilding(const CGTownInstance *town, BuildingID buildingID)
  195. {
  196. if(town->tempOwner!=player)
  197. return false;
  198. if(canBuildStructure(town, buildingID) != EBuildingState::ALLOWED)
  199. return false;
  200. BuildStructure pack(town->id,buildingID);
  201. sendRequest(pack);
  202. return true;
  203. }
  204. bool CCallback::visitTownBuilding(const CGTownInstance *town, BuildingID buildingID)
  205. {
  206. if(town->tempOwner!=player)
  207. return false;
  208. VisitTownBuilding pack(town->id, buildingID);
  209. sendRequest(pack);
  210. return true;
  211. }
  212. void CBattleCallback::battleMakeSpellAction(const BattleID & battleID, const BattleAction & action)
  213. {
  214. assert(action.actionType == EActionType::HERO_SPELL);
  215. MakeAction mca(action);
  216. mca.battleID = battleID;
  217. sendRequest(mca);
  218. }
  219. int CBattleCallback::sendRequest(const CPackForServer & request)
  220. {
  221. int requestID = cl->sendRequest(request, *getPlayerID());
  222. if(waitTillRealize)
  223. {
  224. logGlobal->trace("We'll wait till request %d is answered.\n", requestID);
  225. auto gsUnlocker = vstd::makeUnlockSharedGuardIf(CGameState::mutex, unlockGsWhenWaiting);
  226. cl->waitingRequest.waitWhileContains(requestID);
  227. }
  228. return requestID;
  229. }
  230. void CCallback::spellResearch( const CGTownInstance *town, SpellID spellAtSlot, bool accepted )
  231. {
  232. SpellResearch pack(town->id, spellAtSlot, accepted);
  233. sendRequest(pack);
  234. }
  235. void CCallback::swapGarrisonHero( const CGTownInstance *town )
  236. {
  237. if(town->tempOwner == *player || (town->getGarrisonHero() && town->getGarrisonHero()->tempOwner == *player ))
  238. {
  239. GarrisonHeroSwap pack(town->id);
  240. sendRequest(pack);
  241. }
  242. }
  243. void CCallback::buyArtifact(const CGHeroInstance *hero, ArtifactID aid)
  244. {
  245. if(hero->tempOwner != *player) return;
  246. BuyArtifact pack(hero->id,aid);
  247. sendRequest(pack);
  248. }
  249. void CCallback::trade(const ObjectInstanceID marketId, EMarketMode mode, TradeItemSell id1, TradeItemBuy id2, ui32 val1, const CGHeroInstance * hero)
  250. {
  251. trade(marketId, mode, std::vector(1, id1), std::vector(1, id2), std::vector(1, val1), hero);
  252. }
  253. 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)
  254. {
  255. TradeOnMarketplace pack;
  256. pack.marketId = marketId;
  257. pack.heroId = hero ? hero->id : ObjectInstanceID();
  258. pack.mode = mode;
  259. pack.r1 = id1;
  260. pack.r2 = id2;
  261. pack.val = val1;
  262. sendRequest(pack);
  263. }
  264. void CCallback::setFormation(const CGHeroInstance * hero, EArmyFormation mode)
  265. {
  266. SetFormation pack(hero->id, mode);
  267. sendRequest(pack);
  268. }
  269. void CCallback::recruitHero(const CGObjectInstance *townOrTavern, const CGHeroInstance *hero, const HeroTypeID & nextHero)
  270. {
  271. assert(townOrTavern);
  272. assert(hero);
  273. HireHero pack(hero->getHeroTypeID(), townOrTavern->id, nextHero);
  274. pack.player = *player;
  275. sendRequest(pack);
  276. }
  277. void CCallback::saveLocalState(const JsonNode & data)
  278. {
  279. SaveLocalState state;
  280. state.data = data;
  281. state.player = *player;
  282. sendRequest(state);
  283. }
  284. void CCallback::save( const std::string &fname )
  285. {
  286. cl->save(fname);
  287. }
  288. void CCallback::gamePause(bool pause)
  289. {
  290. if(pause)
  291. {
  292. GamePause pack;
  293. pack.player = *player;
  294. sendRequest(pack);
  295. }
  296. else
  297. {
  298. sendQueryReply(0, QueryID::CLIENT);
  299. }
  300. }
  301. void CCallback::sendMessage(const std::string &mess, const CGObjectInstance * currentObject)
  302. {
  303. ASSERT_IF_CALLED_WITH_PLAYER
  304. PlayerMessage pm(mess, currentObject? currentObject->id : ObjectInstanceID(-1));
  305. if(player)
  306. pm.player = *player;
  307. sendRequest(pm);
  308. }
  309. void CCallback::buildBoat( const IShipyard *obj )
  310. {
  311. BuildBoat bb;
  312. bb.objid = dynamic_cast<const CGObjectInstance*>(obj)->id;
  313. sendRequest(bb);
  314. }
  315. CCallback::CCallback(std::shared_ptr<CGameState> gamestate, std::optional<PlayerColor> Player, CClient * C)
  316. : CBattleCallback(Player, C)
  317. , gamestate(gamestate)
  318. {
  319. waitTillRealize = false;
  320. unlockGsWhenWaiting = false;
  321. }
  322. CCallback::~CCallback() = default;
  323. bool CCallback::canMoveBetween(const int3 &a, const int3 &b)
  324. {
  325. //bidirectional
  326. return gameState().getMap().canMoveBetween(a, b);
  327. }
  328. std::optional<PlayerColor> CCallback::getPlayerID() const
  329. {
  330. return CBattleCallback::getPlayerID();
  331. }
  332. int3 CCallback::getGuardingCreaturePosition(int3 tile)
  333. {
  334. if (!gameState().getMap().isInTheMap(tile))
  335. return int3(-1,-1,-1);
  336. return gameState().getMap().guardingCreaturePositions[tile.z][tile.x][tile.y];
  337. }
  338. void CCallback::dig( const CGObjectInstance *hero )
  339. {
  340. DigWithHero dwh;
  341. dwh.id = hero->id;
  342. sendRequest(dwh);
  343. }
  344. void CCallback::castSpell(const CGHeroInstance *hero, SpellID spellID, const int3 &pos)
  345. {
  346. CastAdvSpell cas;
  347. cas.hid = hero->id;
  348. cas.sid = spellID;
  349. cas.pos = pos;
  350. sendRequest(cas);
  351. }
  352. int CCallback::mergeOrSwapStacks(const CArmedInstance *s1, const CArmedInstance *s2, SlotID p1, SlotID p2)
  353. {
  354. if(s1->getCreature(p1) == s2->getCreature(p2))
  355. return mergeStacks(s1, s2, p1, p2);
  356. else
  357. return swapCreatures(s1, s2, p1, p2);
  358. }
  359. void CCallback::registerBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  360. {
  361. cl->additionalBattleInts[*player].push_back(battleEvents);
  362. }
  363. void CCallback::unregisterBattleInterface(std::shared_ptr<IBattleEventsReceiver> battleEvents)
  364. {
  365. cl->additionalBattleInts[*player] -= battleEvents;
  366. }
  367. CBattleCallback::CBattleCallback(std::optional<PlayerColor> player, CClient * C):
  368. cl(C),
  369. player(player)
  370. {
  371. }
  372. void CBattleCallback::battleMakeUnitAction(const BattleID & battleID, const BattleAction & action)
  373. {
  374. MakeAction ma;
  375. ma.ba = action;
  376. ma.battleID = battleID;
  377. sendRequest(ma);
  378. }
  379. void CBattleCallback::battleMakeTacticAction(const BattleID & battleID, const BattleAction & action )
  380. {
  381. MakeAction ma;
  382. ma.ba = action;
  383. ma.battleID = battleID;
  384. sendRequest(ma);
  385. }
  386. std::optional<BattleAction> CBattleCallback::makeSurrenderRetreatDecision(const BattleID & battleID, const BattleStateInfoForRetreat & battleState)
  387. {
  388. return cl->playerint[getPlayerID().value()]->makeSurrenderRetreatDecision(battleID, battleState);
  389. }
  390. std::shared_ptr<CPlayerBattleCallback> CBattleCallback::getBattle(const BattleID & battleID)
  391. {
  392. if (activeBattles.count(battleID))
  393. return activeBattles.at(battleID);
  394. 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()));
  395. }
  396. std::optional<PlayerColor> CBattleCallback::getPlayerID() const
  397. {
  398. return player;
  399. }
  400. void CBattleCallback::onBattleStarted(const IBattleInfo * info)
  401. {
  402. if (activeBattles.count(info->getBattleID()) > 0)
  403. throw std::runtime_error("Player " + player->toString() + " is already engaged in battle " + std::to_string(info->getBattleID().getNum()));
  404. logGlobal->debug("Battle %d started for player %s", info->getBattleID(), player->toString());
  405. activeBattles[info->getBattleID()] = std::make_shared<CPlayerBattleCallback>(info, *getPlayerID());
  406. }
  407. void CBattleCallback::onBattleEnded(const BattleID & battleID)
  408. {
  409. if (activeBattles.count(battleID) == 0)
  410. throw std::runtime_error("Player " + player->toString() + " is not engaged in battle " + std::to_string(battleID.getNum()));
  411. logGlobal->debug("Battle %d ended for player %s", battleID, player->toString());
  412. activeBattles.erase(battleID);
  413. }