CGameHandler.h 16 KB

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