CGameHandler.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. /*
  2. * CGameHandler.h, 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. #pragma once
  11. #include <vcmi/Environment.h>
  12. #include "../lib/FunctionList.h"
  13. #include "../lib/IGameCallback.h"
  14. #include "../lib/battle/CBattleInfoCallback.h"
  15. #include "../lib/battle/BattleAction.h"
  16. #include "../lib/ScriptHandler.h"
  17. #include "CQuery.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. class CGameState;
  20. struct StartInfo;
  21. struct BattleResult;
  22. struct BattleAttack;
  23. struct BattleStackAttacked;
  24. struct CPack;
  25. struct Query;
  26. struct SetResources;
  27. struct NewStructures;
  28. class CGHeroInstance;
  29. class IMarket;
  30. class SpellCastEnvironment;
  31. #if SCRIPTING_ENABLED
  32. namespace scripting
  33. {
  34. class PoolImpl;
  35. }
  36. #endif
  37. template<typename T> class CApplier;
  38. VCMI_LIB_NAMESPACE_END
  39. class CGameHandler;
  40. class CVCMIServer;
  41. class CBaseForGHApply;
  42. struct PlayerStatus
  43. {
  44. bool makingTurn;
  45. PlayerStatus():makingTurn(false){};
  46. template <typename Handler> void serialize(Handler &h, const int version)
  47. {
  48. h & makingTurn;
  49. }
  50. };
  51. class PlayerStatuses
  52. {
  53. public:
  54. std::map<PlayerColor,PlayerStatus> players;
  55. boost::mutex mx;
  56. boost::condition_variable cv; //notifies when any changes are made
  57. void addPlayer(PlayerColor player);
  58. PlayerStatus operator[](PlayerColor player);
  59. bool checkFlag(PlayerColor player, bool PlayerStatus::*flag);
  60. void setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val);
  61. template <typename Handler> void serialize(Handler &h, const int version)
  62. {
  63. h & players;
  64. }
  65. };
  66. struct CasualtiesAfterBattle
  67. {
  68. typedef std::pair<StackLocation, int> TStackAndItsNewCount;
  69. typedef std::map<CreatureID, TQuantity> TSummoned;
  70. enum {ERASE = -1};
  71. const CArmedInstance * army;
  72. std::vector<TStackAndItsNewCount> newStackCounts;
  73. std::vector<ArtifactLocation> removedWarMachines;
  74. TSummoned summoned;
  75. ObjectInstanceID heroWithDeadCommander; //TODO: unify stack locations
  76. CasualtiesAfterBattle(const CArmedInstance * _army, BattleInfo *bat);
  77. void updateArmy(CGameHandler *gh);
  78. };
  79. class CGameHandler : public IGameCallback, public CBattleInfoCallback, public Environment
  80. {
  81. CVCMIServer * lobby;
  82. std::shared_ptr<CApplier<CBaseForGHApply>> applier;
  83. public:
  84. using FireShieldInfo = std::vector<std::pair<const CStack *, int64_t>>;
  85. //use enums as parameters, because doMove(sth, true, false, true) is not readable
  86. enum EGuardLook {CHECK_FOR_GUARDS, IGNORE_GUARDS};
  87. enum EVisitDest {VISIT_DEST, DONT_VISIT_DEST};
  88. enum ELEaveTile {LEAVING_TILE, REMAINING_ON_TILE};
  89. std::map<PlayerColor, std::set<std::shared_ptr<CConnection>>> connections; //player color -> connection to client with interface of that player
  90. PlayerStatuses states; //player color -> player state
  91. //queries stuff
  92. boost::recursive_mutex gsm;
  93. ui32 QID;
  94. Queries queries;
  95. SpellCastEnvironment * spellEnv;
  96. const Services * services() const override;
  97. const BattleCb * battle() const override;
  98. const GameCb * game() const override;
  99. vstd::CLoggerBase * logger() const override;
  100. events::EventBus * eventBus() const override;
  101. bool isValidObject(const CGObjectInstance *obj) const;
  102. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  103. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  104. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  105. int moveStack(int stack, BattleHex dest); //returned value - travelled distance
  106. void runBattle();
  107. ////used only in endBattle - don't touch elsewhere
  108. bool visitObjectAfterVictory;
  109. //
  110. void endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2); //ends battle
  111. void makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter);
  112. // damage, drain life & fire shield; returns amount of drained life
  113. int64_t applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary);
  114. void sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple);
  115. void addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple);
  116. void checkBattleStateChanges();
  117. void setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town);
  118. void setBattleResult(BattleResult::EResult resultType, int victoriusSide);
  119. CGameHandler(CVCMIServer * lobby);
  120. ~CGameHandler();
  121. //////////////////////////////////////////////////////////////////////////
  122. //from IGameCallback
  123. //do sth
  124. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override;
  125. bool removeObject(const CGObjectInstance * obj) override;
  126. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override;
  127. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override;
  128. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
  129. void showBlockingDialog(BlockingDialog *iw) override;
  130. void showTeleportDialog(TeleportDialog *iw) override;
  131. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
  132. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override;
  133. void giveResource(PlayerColor player, Res::ERes which, int val) override;
  134. void giveResources(PlayerColor player, TResources resources) override;
  135. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override;
  136. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override;
  137. bool changeStackType(const StackLocation &sl, const CCreature *c) override;
  138. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override;
  139. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  140. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override;
  141. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override;
  142. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  143. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override;
  144. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override;
  145. void removeAfterVisit(const CGObjectInstance *object) override;
  146. bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * art);
  147. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override;
  148. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override;
  149. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override;
  150. void removeArtifact(const ArtifactLocation &al) override;
  151. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override;
  152. void synchronizeArtifactHandlerLists();
  153. void showCompInfo(ShowInInfobox * comp) override;
  154. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  155. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  156. void startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank = false, const CGTownInstance *town = nullptr) override; //use hero=nullptr for no hero
  157. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override; //if any of armies is hero, hero will be used
  158. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank = false) override; //if any of armies is hero, hero will be used, visitable tile of second obj is place of battle
  159. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override;
  160. void giveHeroBonus(GiveBonus * bonus) override;
  161. void setMovePoints(SetMovePoints * smp) override;
  162. void setManaPoints(ObjectInstanceID hid, int val) override;
  163. void giveHero(ObjectInstanceID id, PlayerColor player) override;
  164. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) override;
  165. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override;
  166. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override;
  167. void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override;
  168. bool isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero) override;
  169. void setObjProperty(ObjectInstanceID objid, int prop, si64 val) override;
  170. void showInfoDialog(InfoWindow * iw) override;
  171. void showInfoDialog(const std::string & msg, PlayerColor player) override;
  172. //////////////////////////////////////////////////////////////////////////
  173. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  174. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  175. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  176. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  177. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  178. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  179. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  180. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  181. void levelUpCommander (const CCommanderInstance * c);
  182. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  183. //////////////////////////////////////////////////////////////////////////
  184. void init(StartInfo *si);
  185. void handleClientDisconnection(std::shared_ptr<CConnection> c);
  186. void handleReceivedPack(CPackForServer * pack);
  187. PlayerColor getPlayerAt(std::shared_ptr<CConnection> c) const;
  188. bool hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const;
  189. void playerMessage(PlayerColor player, const std::string &message, ObjectInstanceID currObj);
  190. void updateGateState();
  191. bool makeBattleAction(BattleAction &ba);
  192. bool makeAutomaticAction(const CStack *stack, BattleAction &ba); //used when action is taken by stack without volition of player (eg. unguided catapult attack)
  193. bool makeCustomAction(BattleAction &ba);
  194. void stackEnchantedTrigger(const CStack * stack);
  195. void stackTurnTrigger(const CStack *stack);
  196. bool handleDamageFromObstacle(const CStack * curStack, bool stackIsMoving = false); //checks if obstacle is land mine and handles possible consequences
  197. void removeObstacle(const CObstacleInstance &obstacle);
  198. bool queryReply( QueryID qid, const JsonNode & answer, PlayerColor player );
  199. bool hireHero( const CGObjectInstance *obj, ui8 hid, PlayerColor player );
  200. bool buildBoat( ObjectInstanceID objid );
  201. bool setFormation( ObjectInstanceID hid, ui8 formation );
  202. bool tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2);
  203. bool sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count);
  204. bool sendResources(ui32 val, PlayerColor player, Res::ERes r1, PlayerColor r2);
  205. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, Res::ERes resourceID);
  206. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  207. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  208. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  209. bool buyArtifact( const IMarket *m, const CGHeroInstance *h, Res::ERes rid, ArtifactID aid); //for artifact merchant and black market -> buying for any resource in special building / advobject
  210. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, Res::ERes rid); //for artifact merchant selling
  211. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  212. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  213. bool garrisonSwap(ObjectInstanceID tid);
  214. bool swapGarrisonOnSiege(ObjectInstanceID tid) override;
  215. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  216. bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level);
  217. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  218. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  219. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  220. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  221. bool bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot);
  222. bool bulkSplitStack(SlotID src, ObjectInstanceID srcOwner, si32 howMany);
  223. bool bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner);
  224. bool bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner);
  225. void save(const std::string &fname);
  226. bool load(const std::string &fname);
  227. void handleTimeEvents();
  228. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  229. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  230. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  231. void objectVisitEnded(const CObjectVisitQuery &query);
  232. void engageIntoBattle( PlayerColor player );
  233. bool dig(const CGHeroInstance *h);
  234. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  235. const ObjectInstanceID putNewObject(Obj ID, int subID, int3 pos);
  236. template <typename Handler> void serialize(Handler &h, const int version)
  237. {
  238. h & QID;
  239. h & states;
  240. h & finishingBattle;
  241. h & getRandomGenerator();
  242. #if SCRIPTING_ENABLED
  243. JsonNode scriptsState;
  244. if(h.saving)
  245. serverScripts->serializeState(h.saving, scriptsState);
  246. h & scriptsState;
  247. if(!h.saving)
  248. serverScripts->serializeState(h.saving, scriptsState);
  249. #endif
  250. }
  251. void sendMessageToAll(const std::string &message);
  252. void sendMessageTo(std::shared_ptr<CConnection> c, const std::string &message);
  253. void sendToAllClients(CPackForClient * pack);
  254. void sendAndApply(CPackForClient * pack) override;
  255. void applyAndSend(CPackForClient * pack);
  256. void sendAndApply(CGarrisonOperationPack * pack);
  257. void sendAndApply(SetResources * pack);
  258. void sendAndApply(NewStructures * pack);
  259. struct FinishingBattleHelper
  260. {
  261. FinishingBattleHelper();
  262. FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int RemainingBattleQueriesCount);
  263. const CGHeroInstance *winnerHero, *loserHero;
  264. PlayerColor victor, loser;
  265. int remainingBattleQueriesCount;
  266. template <typename Handler> void serialize(Handler &h, const int version)
  267. {
  268. h & winnerHero;
  269. h & loserHero;
  270. h & victor;
  271. h & loser;
  272. h & remainingBattleQueriesCount;
  273. }
  274. };
  275. std::unique_ptr<FinishingBattleHelper> finishingBattle;
  276. void battleAfterLevelUp(const BattleResult &result);
  277. void run(bool resume);
  278. void newTurn();
  279. void handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender);
  280. void handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender);
  281. void attackCasting(bool ranged, Bonus::BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender);
  282. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot);
  283. void spawnWanderingMonsters(CreatureID creatureID);
  284. void handleCheatCode(std::string & cheat, PlayerColor player, const CGHeroInstance * hero, const CGTownInstance * town, bool & cheated);
  285. CRandomGenerator & getRandomGenerator();
  286. #if SCRIPTING_ENABLED
  287. scripting::Pool * getGlobalContextPool() const override;
  288. scripting::Pool * getContextPool() const override;
  289. #endif
  290. friend class CVCMIServer;
  291. private:
  292. std::unique_ptr<events::EventBus> serverEventBus;
  293. #if SCRIPTING_ENABLED
  294. std::shared_ptr<scripting::PoolImpl> serverScripts;
  295. #endif
  296. void reinitScripting();
  297. std::list<PlayerColor> generatePlayerTurnOrder() const;
  298. void makeStackDoNothing(const CStack * next);
  299. void getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const;
  300. // Check for victory and loss conditions
  301. void checkVictoryLossConditionsForPlayer(PlayerColor player);
  302. void checkVictoryLossConditions(const std::set<PlayerColor> & playerColors);
  303. void checkVictoryLossConditionsForAll();
  304. const std::string complainNoCreatures;
  305. const std::string complainNotEnoughCreatures;
  306. const std::string complainInvalidSlot;
  307. };
  308. class ExceptionNotAllowedAction : public std::exception
  309. {
  310. };