CGameHandler.h 17 KB

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