CGameHandler.h 15 KB

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