CGameHandler.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. #pragma once
  2. #include "../lib/FunctionList.h"
  3. #include "../lib/IGameCallback.h"
  4. #include "../lib/BattleAction.h"
  5. #include "CQuery.h"
  6. /*
  7. * CGameHandler.h, part of VCMI engine
  8. *
  9. * Authors: listed in file AUTHORS in main folder
  10. *
  11. * License: GNU General Public License v2.0 or later
  12. * Full text of license available in license.txt file, in main folder
  13. *
  14. */
  15. class CGameHandler;
  16. class CVCMIServer;
  17. class CGameState;
  18. struct StartInfo;
  19. struct BattleResult;
  20. struct BattleAttack;
  21. struct BattleStackAttacked;
  22. struct CPack;
  23. struct Query;
  24. struct SetGarrisons;
  25. struct SetResource;
  26. struct SetResources;
  27. struct NewStructures;
  28. class CGHeroInstance;
  29. class IMarket;
  30. class ServerSpellCastEnvironment;
  31. struct PlayerStatus
  32. {
  33. bool makingTurn;
  34. PlayerStatus():makingTurn(false){};
  35. template <typename Handler> void serialize(Handler &h, const int version)
  36. {
  37. h & makingTurn;
  38. }
  39. };
  40. class PlayerStatuses
  41. {
  42. public:
  43. std::map<PlayerColor,PlayerStatus> players;
  44. boost::mutex mx;
  45. boost::condition_variable cv; //notifies when any changes are made
  46. void addPlayer(PlayerColor player);
  47. PlayerStatus operator[](PlayerColor player);
  48. bool checkFlag(PlayerColor player, bool PlayerStatus::*flag);
  49. void setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val);
  50. template <typename Handler> void serialize(Handler &h, const int version)
  51. {
  52. h & players;
  53. }
  54. };
  55. struct CasualtiesAfterBattle
  56. {
  57. typedef std::pair<StackLocation, int> TStackAndItsNewCount;
  58. typedef std::map<CreatureID, TQuantity> TSummoned;
  59. enum {ERASE = -1};
  60. const CArmedInstance * army;
  61. std::vector<TStackAndItsNewCount> newStackCounts;
  62. std::vector<ArtifactLocation> removedWarMachines;
  63. TSummoned summoned;
  64. ObjectInstanceID heroWithDeadCommander; //TODO: unify stack locations
  65. CasualtiesAfterBattle(const CArmedInstance * _army, BattleInfo *bat);
  66. void updateArmy(CGameHandler *gh);
  67. };
  68. class CGameHandler : public IGameCallback, CBattleInfoCallback
  69. {
  70. public:
  71. //use enums as parameters, because doMove(sth, true, false, true) is not readable
  72. enum EGuardLook {CHECK_FOR_GUARDS, IGNORE_GUARDS};
  73. enum EVisitDest {VISIT_DEST, DONT_VISIT_DEST};
  74. enum ELEaveTile {LEAVING_TILE, REMAINING_ON_TILE};
  75. CVCMIServer *s;
  76. std::map<PlayerColor, CConnection*> connections; //player color -> connection to client with interface of that player
  77. PlayerStatuses states; //player color -> player state
  78. std::set<CConnection*> conns;
  79. //queries stuff
  80. boost::recursive_mutex gsm;
  81. ui32 QID;
  82. Queries queries;
  83. bool isValidObject(const CGObjectInstance *obj) const;
  84. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  85. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  86. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  87. int moveStack(int stack, BattleHex dest); //returned value - travelled distance
  88. void runBattle();
  89. ////used only in endBattle - don't touch elsewhere
  90. bool visitObjectAfterVictory;
  91. //
  92. void endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2); //ends battle
  93. void prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance, int targetHex); //distance - number of hexes travelled before attacking
  94. void applyBattleEffects(BattleAttack &bat, const CStack *att, const CStack *def, int distance, bool secondary); //damage, drain life & fire shield
  95. void checkBattleStateChanges();
  96. void setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town);
  97. void setBattleResult(BattleResult::EResult resultType, int victoriusSide);
  98. void duelFinished();
  99. CGameHandler(void);
  100. ~CGameHandler(void);
  101. //////////////////////////////////////////////////////////////////////////
  102. //from IGameCallback
  103. //do sth
  104. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override;
  105. bool removeObject(const CGObjectInstance * obj) override;
  106. void setBlockVis(ObjectInstanceID objid, bool bv) override;
  107. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override;
  108. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override;
  109. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
  110. void showBlockingDialog(BlockingDialog *iw) override;
  111. void showTeleportDialog(TeleportDialog *iw) override;
  112. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
  113. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override;
  114. void giveResource(PlayerColor player, Res::ERes which, int val) override;
  115. void giveResources(PlayerColor player, TResources resources) override;
  116. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override;
  117. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override;
  118. bool changeStackType(const StackLocation &sl, const CCreature *c) override;
  119. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override;
  120. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  121. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override;
  122. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override;
  123. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  124. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override;
  125. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override;
  126. void removeAfterVisit(const CGObjectInstance *object) override;
  127. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition pos) override;
  128. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition pos) override;
  129. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override;
  130. void removeArtifact(const ArtifactLocation &al) override;
  131. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) override;
  132. void synchronizeArtifactHandlerLists() override;
  133. void showCompInfo(ShowInInfobox * comp) override;
  134. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  135. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  136. 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
  137. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank = false) override; //if any of armies is hero, hero will be used
  138. 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
  139. void setAmount(ObjectInstanceID objid, ui32 val) override;
  140. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override;
  141. void giveHeroBonus(GiveBonus * bonus) override;
  142. void setMovePoints(SetMovePoints * smp) override;
  143. void setManaPoints(ObjectInstanceID hid, int val) override;
  144. void giveHero(ObjectInstanceID id, PlayerColor player) override;
  145. void changeObjPos(ObjectInstanceID objid, int3 newPos, ui8 flags) override;
  146. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override;
  147. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override;
  148. void changeFogOfWar(std::unordered_set<int3, ShashInt3> &tiles, PlayerColor player, bool hide) override;
  149. bool isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero) override;
  150. //////////////////////////////////////////////////////////////////////////
  151. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  152. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  153. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  154. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  155. void vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h);
  156. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  157. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  158. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  159. void levelUpCommander (const CCommanderInstance * c);
  160. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  161. //////////////////////////////////////////////////////////////////////////
  162. void commitPackage(CPackForClient *pack) override;
  163. void init(StartInfo *si);
  164. void handleConnection(std::set<PlayerColor> players, CConnection &c);
  165. PlayerColor getPlayerAt(CConnection *c) const;
  166. void playerMessage(PlayerColor player, const std::string &message, ObjectInstanceID currObj);
  167. void updateGateState();
  168. bool makeBattleAction(BattleAction &ba);
  169. bool makeAutomaticAction(const CStack *stack, BattleAction &ba); //used when action is taken by stack without volition of player (eg. unguided catapult attack)
  170. bool makeCustomAction(BattleAction &ba);
  171. void stackAppearTrigger(const CStack *stack);
  172. void stackTurnTrigger(const CStack *stack);
  173. void handleDamageFromObstacle(const CObstacleInstance &obstacle, const CStack * curStack); //checks if obstacle is land mine and handles possible consequences
  174. void removeObstacle(const CObstacleInstance &obstacle);
  175. bool queryReply( QueryID qid, ui32 answer, PlayerColor player );
  176. bool hireHero( const CGObjectInstance *obj, ui8 hid, PlayerColor player );
  177. bool buildBoat( ObjectInstanceID objid );
  178. bool setFormation( ObjectInstanceID hid, ui8 formation );
  179. bool tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2);
  180. bool sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, SlotID slot, ui32 count);
  181. bool sendResources(ui32 val, PlayerColor player, Res::ERes r1, PlayerColor r2);
  182. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, Res::ERes resourceID);
  183. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  184. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  185. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  186. 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
  187. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, Res::ERes rid); //for artifact merchant selling
  188. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  189. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  190. bool garrisonSwap(ObjectInstanceID tid);
  191. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  192. bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level);
  193. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  194. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  195. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  196. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  197. void save(const std::string &fname);
  198. void close();
  199. void handleTimeEvents();
  200. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  201. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  202. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  203. void objectVisitEnded(const CObjectVisitQuery &query);
  204. void engageIntoBattle( PlayerColor player );
  205. bool dig(const CGHeroInstance *h);
  206. bool castSpell(const CGHeroInstance *h, SpellID spellID, const int3 &pos);
  207. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  208. template <typename Handler> void serialize(Handler &h, const int version)
  209. {
  210. h & QID & states & finishingBattle;
  211. if(version >= 761)
  212. {
  213. h & getRandomGenerator();
  214. }
  215. }
  216. void sendMessageToAll(const std::string &message);
  217. void sendMessageTo(CConnection &c, const std::string &message);
  218. void sendToAllClients(CPackForClient * info);
  219. void sendAndApply(CPackForClient * info) override;
  220. void applyAndSend(CPackForClient * info);
  221. void sendAndApply(CGarrisonOperationPack * info);
  222. void sendAndApply(SetResource * info);
  223. void sendAndApply(SetResources * info);
  224. void sendAndApply(NewStructures * info);
  225. struct FinishingBattleHelper
  226. {
  227. FinishingBattleHelper();
  228. FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, bool Duel, int RemainingBattleQueriesCount);
  229. //std::shared_ptr<const CBattleQuery> query;
  230. const CGHeroInstance *winnerHero, *loserHero;
  231. PlayerColor victor, loser;
  232. bool duel;
  233. int remainingBattleQueriesCount;
  234. template <typename Handler> void serialize(Handler &h, const int version)
  235. {
  236. h & /*query & */winnerHero & loserHero & victor & loser & duel & remainingBattleQueriesCount;
  237. }
  238. };
  239. std::unique_ptr<FinishingBattleHelper> finishingBattle;
  240. void battleAfterLevelUp(const BattleResult &result);
  241. void run(bool resume);
  242. void newTurn();
  243. void handleAttackBeforeCasting(BattleAttack *bat);
  244. void handleAfterAttackCasting (const BattleAttack & bat);
  245. void attackCasting(const BattleAttack & bat, Bonus::BonusType attackMode, const CStack * attacker);
  246. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, ArtifactPosition slot);
  247. void spawnWanderingMonsters(CreatureID creatureID);
  248. void handleCheatCode(std::string & cheat, PlayerColor player, const CGHeroInstance * hero, const CGTownInstance * town, bool & cheated);
  249. friend class CVCMIServer;
  250. CRandomGenerator & getRandomGenerator();
  251. private:
  252. ServerSpellCastEnvironment * spellEnv;
  253. std::list<PlayerColor> generatePlayerTurnOrder() const;
  254. void makeStackDoNothing(const CStack * next);
  255. void getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const;
  256. // Check for victory and loss conditions
  257. void checkVictoryLossConditionsForPlayer(PlayerColor player);
  258. void checkVictoryLossConditions(const std::set<PlayerColor> & playerColors);
  259. void checkVictoryLossConditionsForAll();
  260. };
  261. void makeStackDoNothing();