CGameHandler.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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/IGameCallback.h"
  13. #include "../lib/battle/CBattleInfoCallback.h"
  14. #include "../lib/ScriptHandler.h"
  15. VCMI_LIB_NAMESPACE_BEGIN
  16. struct SideInBattle;
  17. class IMarket;
  18. class SpellCastEnvironment;
  19. class CConnection;
  20. class CCommanderInstance;
  21. class EVictoryLossCheckResult;
  22. struct CPack;
  23. struct CPackForServer;
  24. struct NewTurn;
  25. struct CGarrisonOperationPack;
  26. struct SetResources;
  27. struct NewStructures;
  28. #if SCRIPTING_ENABLED
  29. namespace scripting
  30. {
  31. class PoolImpl;
  32. }
  33. #endif
  34. template<typename T> class CApplier;
  35. VCMI_LIB_NAMESPACE_END
  36. class HeroPoolProcessor;
  37. class CVCMIServer;
  38. class CBaseForGHApply;
  39. class PlayerMessageProcessor;
  40. class BattleProcessor;
  41. class QueriesProcessor;
  42. class CObjectVisitQuery;
  43. struct PlayerStatus
  44. {
  45. bool makingTurn;
  46. PlayerStatus():makingTurn(false){};
  47. template <typename Handler> void serialize(Handler &h, const int version)
  48. {
  49. h & makingTurn;
  50. }
  51. };
  52. class PlayerStatuses
  53. {
  54. public:
  55. std::map<PlayerColor,PlayerStatus> players;
  56. boost::mutex mx;
  57. boost::condition_variable cv; //notifies when any changes are made
  58. void addPlayer(PlayerColor player);
  59. PlayerStatus operator[](PlayerColor player);
  60. bool checkFlag(PlayerColor player, bool PlayerStatus::*flag);
  61. void setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val);
  62. template <typename Handler> void serialize(Handler &h, const int version)
  63. {
  64. h & players;
  65. }
  66. };
  67. class CGameHandler : public IGameCallback, public CBattleInfoCallback, public Environment
  68. {
  69. CVCMIServer * lobby;
  70. std::shared_ptr<CApplier<CBaseForGHApply>> applier;
  71. public:
  72. using CCallbackBase::setBattle;
  73. std::unique_ptr<HeroPoolProcessor> heroPool;
  74. std::unique_ptr<BattleProcessor> battles;
  75. std::unique_ptr<QueriesProcessor> queries;
  76. //use enums as parameters, because doMove(sth, true, false, true) is not readable
  77. enum EGuardLook {CHECK_FOR_GUARDS, IGNORE_GUARDS};
  78. enum EVisitDest {VISIT_DEST, DONT_VISIT_DEST};
  79. enum ELEaveTile {LEAVING_TILE, REMAINING_ON_TILE};
  80. std::unique_ptr<PlayerMessageProcessor> playerMessages;
  81. std::map<PlayerColor, std::set<std::shared_ptr<CConnection>>> connections; //player color -> connection to client with interface of that player
  82. PlayerStatuses states; //player color -> player state
  83. //queries stuff
  84. boost::recursive_mutex gsm;
  85. ui32 QID;
  86. SpellCastEnvironment * spellEnv;
  87. const Services * services() const override;
  88. const BattleCb * battle() const override;
  89. const GameCb * game() const override;
  90. vstd::CLoggerBase * logger() const override;
  91. events::EventBus * eventBus() const override;
  92. CVCMIServer * gameLobby() const;
  93. bool isValidObject(const CGObjectInstance *obj) const;
  94. bool isBlockedByQueries(const CPack *pack, PlayerColor player);
  95. bool isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2);
  96. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  97. CGameHandler() = default;
  98. CGameHandler(CVCMIServer * lobby);
  99. ~CGameHandler();
  100. //////////////////////////////////////////////////////////////////////////
  101. //from IGameCallback
  102. //do sth
  103. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells) override;
  104. bool removeObject(const CGObjectInstance * obj) override;
  105. void createObject(const int3 & visitablePosition, Obj type, int32_t subtype ) override;
  106. void setOwner(const CGObjectInstance * obj, PlayerColor owner) override;
  107. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) override;
  108. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs=false) override;
  109. void showBlockingDialog(BlockingDialog *iw) override;
  110. void showTeleportDialog(TeleportDialog *iw) override;
  111. void showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits) override;
  112. void showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId) override;
  113. void giveResource(PlayerColor player, GameResID which, int val) override;
  114. void giveResources(PlayerColor player, TResources resources) override;
  115. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) override;
  116. void takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures) override;
  117. bool changeStackType(const StackLocation &sl, const CCreature *c) override;
  118. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) override;
  119. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  120. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) override;
  121. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) override;
  122. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) override;
  123. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) override;
  124. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) override;
  125. void removeAfterVisit(const CGObjectInstance *object) override;
  126. bool giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos = ArtifactPosition::FIRST_AVAILABLE) override;
  127. bool giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos) override;
  128. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) override;
  129. void removeArtifact(const ArtifactLocation &al) override;
  130. bool moveArtifact(const ArtifactLocation & al1, const ArtifactLocation & al2) override;
  131. bool bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap);
  132. bool eraseArtifactByClient(const ArtifactLocation & al);
  133. void synchronizeArtifactHandlerLists();
  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. bool moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit = false, PlayerColor asker = PlayerColor::NEUTRAL) override;
  140. void giveHeroBonus(GiveBonus * bonus) override;
  141. void setMovePoints(SetMovePoints * smp) override;
  142. void setManaPoints(ObjectInstanceID hid, int val) override;
  143. void giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId = ObjectInstanceID()) override;
  144. void changeObjPos(ObjectInstanceID objid, int3 newPos) override;
  145. void heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2) override;
  146. void changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide) override;
  147. void changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide) override;
  148. void castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos) override;
  149. bool isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero) override;
  150. void setObjProperty(ObjectInstanceID objid, int prop, si64 val) override;
  151. void showInfoDialog(InfoWindow * iw) override;
  152. void showInfoDialog(const std::string & msg, PlayerColor player) override;
  153. //////////////////////////////////////////////////////////////////////////
  154. void useScholarSkill(ObjectInstanceID hero1, ObjectInstanceID hero2);
  155. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  156. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  157. bool teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker = PlayerColor::NEUTRAL);
  158. void visitCastleObjects(const CGTownInstance * obj, const CGHeroInstance * hero) override;
  159. void levelUpHero(const CGHeroInstance * hero, SecondarySkill skill);//handle client respond and send one more request if needed
  160. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  161. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  162. void levelUpCommander (const CCommanderInstance * c);
  163. void expGiven(const CGHeroInstance *hero); //triggers needed level-ups, handles also commander of this hero
  164. //////////////////////////////////////////////////////////////////////////
  165. void init(StartInfo *si);
  166. void handleClientDisconnection(std::shared_ptr<CConnection> c);
  167. void handleReceivedPack(CPackForServer * pack);
  168. PlayerColor getPlayerAt(std::shared_ptr<CConnection> c) const;
  169. bool hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const;
  170. bool queryReply( QueryID qid, const JsonNode & answer, PlayerColor player );
  171. bool buildBoat( ObjectInstanceID objid, PlayerColor player );
  172. bool setFormation( ObjectInstanceID hid, ui8 formation );
  173. bool tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2);
  174. bool sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count);
  175. bool sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2);
  176. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID);
  177. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot);
  178. bool assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo);
  179. bool buyArtifact( ObjectInstanceID hid, ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  180. bool buyArtifact( const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid); //for artifact merchant and black market -> buying for any resource in special building / advobject
  181. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid); //for artifact merchant selling
  182. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  183. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill skill);
  184. bool garrisonSwap(ObjectInstanceID tid);
  185. bool swapGarrisonOnSiege(ObjectInstanceID tid) override;
  186. bool upgradeCreature( ObjectInstanceID objid, SlotID pos, CreatureID upgID );
  187. bool recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dst, CreatureID crid, ui32 cram, si32 level);
  188. bool buildStructure(ObjectInstanceID tid, BuildingID bid, bool force=false);//force - for events: no cost, no checkings
  189. bool razeStructure(ObjectInstanceID tid, BuildingID bid);
  190. bool disbandCreature( ObjectInstanceID id, SlotID pos );
  191. bool arrangeStacks( ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player);
  192. bool bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot);
  193. bool bulkSplitStack(SlotID src, ObjectInstanceID srcOwner, si32 howMany);
  194. bool bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner);
  195. bool bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner);
  196. void save(const std::string &fname);
  197. bool load(const std::string &fname);
  198. void handleTimeEvents();
  199. void handleTownEvents(CGTownInstance *town, NewTurn &n);
  200. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  201. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  202. void objectVisitEnded(const CObjectVisitQuery &query);
  203. bool dig(const CGHeroInstance *h);
  204. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  205. template <typename Handler> void serialize(Handler &h, const int version)
  206. {
  207. h & QID;
  208. h & states;
  209. h & battles;
  210. h & heroPool;
  211. h & getRandomGenerator();
  212. h & playerMessages;
  213. if (!h.saving)
  214. deserializationFix();
  215. #if SCRIPTING_ENABLED
  216. JsonNode scriptsState;
  217. if(h.saving)
  218. serverScripts->serializeState(h.saving, scriptsState);
  219. h & scriptsState;
  220. if(!h.saving)
  221. serverScripts->serializeState(h.saving, scriptsState);
  222. #endif
  223. }
  224. void sendToAllClients(CPackForClient * pack);
  225. void sendAndApply(CPackForClient * pack) override;
  226. void applyAndSend(CPackForClient * pack);
  227. void sendAndApply(CGarrisonOperationPack * pack);
  228. void sendAndApply(SetResources * pack);
  229. void sendAndApply(NewStructures * pack);
  230. void wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer);
  231. void throwNotAllowedAction(CPackForServer * pack);
  232. void throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id);
  233. void throwOnWrongPlayer(CPackForServer * pack, PlayerColor player);
  234. void throwAndComplain(CPackForServer * pack, std::string txt);
  235. bool isPlayerOwns(CPackForServer * pack, ObjectInstanceID id);
  236. void run(bool resume);
  237. void newTurn();
  238. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot);
  239. void spawnWanderingMonsters(CreatureID creatureID);
  240. // Check for victory and loss conditions
  241. void checkVictoryLossConditionsForPlayer(PlayerColor player);
  242. void checkVictoryLossConditions(const std::set<PlayerColor> & playerColors);
  243. void checkVictoryLossConditionsForAll();
  244. CRandomGenerator & getRandomGenerator();
  245. #if SCRIPTING_ENABLED
  246. scripting::Pool * getGlobalContextPool() const override;
  247. scripting::Pool * getContextPool() const override;
  248. #endif
  249. std::list<PlayerColor> generatePlayerTurnOrder() const;
  250. friend class CVCMIServer;
  251. private:
  252. std::unique_ptr<events::EventBus> serverEventBus;
  253. #if SCRIPTING_ENABLED
  254. std::shared_ptr<scripting::PoolImpl> serverScripts;
  255. #endif
  256. void reinitScripting();
  257. void deserializationFix();
  258. void getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const;
  259. const std::string complainNoCreatures;
  260. const std::string complainNotEnoughCreatures;
  261. const std::string complainInvalidSlot;
  262. };
  263. class ExceptionNotAllowedAction : public std::exception
  264. {
  265. };