CGameHandler.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. #pragma once
  2. #include "../client/FunctionList.h"
  3. #include "../lib/CGameState.h"
  4. #include "../lib/Connection.h"
  5. #include "../lib/IGameCallback.h"
  6. #include "../lib/BattleAction.h"
  7. #include "../lib/NetPacks.h"
  8. /*
  9. * CGameHandler.h, part of VCMI engine
  10. *
  11. * Authors: listed in file AUTHORS in main folder
  12. *
  13. * License: GNU General Public License v2.0 or later
  14. * Full text of license available in license.txt file, in main folder
  15. *
  16. */
  17. class CGameHandler;
  18. class CVCMIServer;
  19. class CGameState;
  20. struct StartInfo;
  21. class CCPPObjectScript;
  22. class CScriptCallback;
  23. struct BattleResult;
  24. struct BattleAttack;
  25. struct BattleStackAttacked;
  26. struct CPack;
  27. struct Query;
  28. struct SetGarrisons;
  29. struct SetResource;
  30. struct SetResources;
  31. struct NewStructures;
  32. class CGHeroInstance;
  33. class IMarket;
  34. extern std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback functions - for selection dialogs
  35. extern boost::mutex gsm;
  36. struct PlayerStatus
  37. {
  38. bool makingTurn, engagedIntoBattle;
  39. std::set<ui32> queries;
  40. PlayerStatus():makingTurn(false),engagedIntoBattle(false){};
  41. template <typename Handler> void serialize(Handler &h, const int version)
  42. {
  43. h & makingTurn & engagedIntoBattle & queries;
  44. }
  45. };
  46. class PlayerStatuses
  47. {
  48. public:
  49. std::map<TPlayerColor,PlayerStatus> players;
  50. boost::mutex mx;
  51. boost::condition_variable cv; //notifies when any changes are made
  52. void addPlayer(TPlayerColor player);
  53. PlayerStatus operator[](TPlayerColor player);
  54. int getQueriesCount(TPlayerColor player); //returns 0 if there is no such player
  55. bool checkFlag(TPlayerColor player, bool PlayerStatus::*flag);
  56. void setFlag(TPlayerColor player, bool PlayerStatus::*flag, bool val);
  57. void addQuery(TPlayerColor player, ui32 id);
  58. void removeQuery(TPlayerColor player, ui32 id);
  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. enum {ERASE = -1};
  68. std::vector<TStackAndItsNewCount> newStackCounts;
  69. si32 heroWithDeadCommander; //TODO: unify stack loactions
  70. CasualtiesAfterBattle(const CArmedInstance *army, BattleInfo *bat);
  71. void takeFromArmy(CGameHandler *gh);
  72. };
  73. class CGameHandler : public IGameCallback, CBattleInfoCallback
  74. {
  75. private:
  76. void makeStackDoNothing(const CStack * next);
  77. bool isAllowedExchangeForQuery(int id1, int id2);
  78. public:
  79. CVCMIServer *s;
  80. std::map<int,CConnection*> connections; //player color -> connection to client with interface of that player
  81. PlayerStatuses states; //player color -> player state
  82. std::set<CConnection*> conns;
  83. //queries stuff
  84. boost::recursive_mutex gsm;
  85. ui32 QID;
  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. std::map<ui32, std::pair<si32,si32> > allowedExchanges;
  89. bool isBlockedByQueries(const CPack *pack, int packType, TPlayerColor player);
  90. bool isAllowedExchange(int id1, int id2);
  91. bool isAllowedArrangePack(const ArrangeStacks *pack);
  92. void giveSpells(const CGTownInstance *t, const CGHeroInstance *h);
  93. int moveStack(int stack, BattleHex dest); //returned value - travelled distance
  94. void startBattle(const CArmedInstance *armies[2], int3 tile, const CGHeroInstance *heroes[2], bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town = NULL); //use hero=NULL for no hero
  95. void runBattle();
  96. void checkLossVictory(TPlayerColor player);
  97. void winLoseHandle(ui8 players=255); //players: bit field - colours of players to be checked; default: all
  98. void getLossVicMessage(TPlayerColor player, si8 standard, bool victory, InfoWindow &out) const;
  99. ////used only in endBattle - don't touch elsewhere
  100. boost::function<void(BattleResult*)> * battleEndCallback;
  101. //const CArmedInstance * bEndArmy1, * bEndArmy2;
  102. bool visitObjectAfterVictory;
  103. //
  104. void endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2); //ends battle
  105. void prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance, int targetHex); //distance - number of hexes travelled before attacking
  106. void applyBattleEffects(BattleAttack &bat, const CStack *att, const CStack *def, int distance, bool secondary); //damage, drain life & fire shield
  107. void checkForBattleEnd();
  108. void setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town);
  109. void setBattleResult(BattleResult::EResult resultType, int victoriusSide);
  110. CGameHandler(void);
  111. ~CGameHandler(void);
  112. //////////////////////////////////////////////////////////////////////////
  113. //from IGameCallback
  114. //do sth
  115. void changeSpells(const CGHeroInstance * hero, bool give, const std::set<ui32> &spells) OVERRIDE;
  116. bool removeObject(const CGObjectInstance * obj) OVERRIDE;
  117. void setBlockVis(int objid, bool bv) OVERRIDE;
  118. void setOwner(const CGObjectInstance * obj, TPlayerColor owner) OVERRIDE;
  119. void setHoverName(const CGObjectInstance * objid, MetaString * name) OVERRIDE;
  120. void changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs=false) OVERRIDE;
  121. void changeSecSkill(const CGHeroInstance * hero, SecondarySkill::SecondarySkill which, int val, bool abs=false) OVERRIDE;
  122. //void showInfoDialog(InfoWindow *iw) OVERRIDE;
  123. void showBlockingDialog(BlockingDialog *iw, const CFunctionList<void(ui32)> &callback) OVERRIDE;
  124. ui32 showBlockingDialog(BlockingDialog *iw) OVERRIDE; //synchronous version of above
  125. void showGarrisonDialog(int upobj, int hid, bool removableUnits, const boost::function<void()> &cb) OVERRIDE;
  126. void showThievesGuildWindow(int player, int requestingObjId) OVERRIDE;
  127. void giveResource(TPlayerColor player, Res::ERes which, int val) OVERRIDE;
  128. void giveCreatures(const CArmedInstance *objid, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove) OVERRIDE;
  129. void takeCreatures(int objid, const std::vector<CStackBasicDescriptor> &creatures) OVERRIDE;
  130. bool changeStackType(const StackLocation &sl, CCreature *c) OVERRIDE;
  131. bool changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue = false) OVERRIDE;
  132. bool insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count) OVERRIDE;
  133. bool eraseStack(const StackLocation &sl, bool forceRemoval = false) OVERRIDE;
  134. bool swapStacks(const StackLocation &sl1, const StackLocation &sl2) OVERRIDE;
  135. bool addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count) OVERRIDE;
  136. void tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging) OVERRIDE;
  137. bool moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count = -1) OVERRIDE;
  138. void giveHeroNewArtifact(const CGHeroInstance *h, const CArtifact *artType, ArtifactPosition::ArtifactPosition pos) OVERRIDE;
  139. void giveHeroArtifact(const CGHeroInstance *h, const CArtifactInstance *a, ArtifactPosition::ArtifactPosition pos) OVERRIDE;
  140. void putArtifact(const ArtifactLocation &al, const CArtifactInstance *a) OVERRIDE;
  141. void removeArtifact(const ArtifactLocation &al) OVERRIDE;
  142. bool moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2) OVERRIDE;
  143. void showCompInfo(ShowInInfobox * comp) OVERRIDE;
  144. void heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) OVERRIDE;
  145. void stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero) OVERRIDE;
  146. //bool removeArtifact(const CArtifact* art, int hid) OVERRIDE;
  147. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank = false, boost::function<void(BattleResult*)> cb = 0, const CGTownInstance *town = NULL) OVERRIDE; //use hero=NULL for no hero
  148. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb = 0, bool creatureBank = false) OVERRIDE; //if any of armies is hero, hero will be used
  149. void startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb = 0, 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, boost::function<void(BattleResult*)> cb) OVERRIDE; //for hero<=>neutral army
  150. void setAmount(int objid, ui32 val) OVERRIDE;
  151. bool moveHero(si32 hid, int3 dst, ui8 instant, TPlayerColor asker = GameConstants::NEUTRAL_PLAYER) OVERRIDE;
  152. void giveHeroBonus(GiveBonus * bonus) OVERRIDE;
  153. void setMovePoints(SetMovePoints * smp) OVERRIDE;
  154. void setManaPoints(int hid, int val) OVERRIDE;
  155. void giveHero(int id, TPlayerColor player) OVERRIDE;
  156. void changeObjPos(int objid, int3 newPos, ui8 flags) OVERRIDE;
  157. void heroExchange(si32 hero1, si32 hero2) OVERRIDE;
  158. //////////////////////////////////////////////////////////////////////////
  159. void useScholarSkill(si32 hero1, si32 hero2);
  160. void setPortalDwelling(const CGTownInstance * town, bool forced, bool clear);
  161. bool tryAttackingGuard(const int3 &guardPos, const CGHeroInstance * h);
  162. void visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h);
  163. bool teleportHero(si32 hid, si32 dstid, ui8 source, TPlayerColor asker = GameConstants::NEUTRAL_PLAYER);
  164. void vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h);
  165. void levelUpHero(const CGHeroInstance * hero, SecondarySkill::SecondarySkill skill);//handle client respond and send one more request if needed
  166. void levelUpHero(const CGHeroInstance * hero);//initial call - check if hero have remaining levelups & handle them
  167. void levelUpCommander (const CCommanderInstance * c, int skill); //secondary skill 1 to 6, special skill : skill - 100
  168. void levelUpCommander (const CCommanderInstance * c);
  169. void afterBattleCallback(); // called after level-ups are finished
  170. //////////////////////////////////////////////////////////////////////////
  171. void commitPackage(CPackForClient *pack) OVERRIDE;
  172. void init(StartInfo *si);
  173. void handleConnection(std::set<int> players, CConnection &c);
  174. int getPlayerAt(CConnection *c) const;
  175. void playerMessage( TPlayerColor player, const std::string &message);
  176. bool makeBattleAction(BattleAction &ba);
  177. bool makeAutomaticAction(const CStack *stack, BattleAction &ba); //used when action is taken by stack without volition of player (eg. unguided catapult attack)
  178. void handleSpellCasting(int spellID, int spellLvl, BattleHex destination, ui8 casterSide, TPlayerColor casterColor, const CGHeroInstance * caster, const CGHeroInstance * secHero,
  179. int usedSpellPower, ECastingMode::ECastingMode mode, const CStack * stack, si32 selectedStack = -1);
  180. bool makeCustomAction(BattleAction &ba);
  181. void stackTurnTrigger(const CStack * stack);
  182. void handleDamageFromObstacle(const CObstacleInstance &obstacle, const CStack * curStack); //checks if obstacle is land mine and handles possible consequences
  183. void removeObstacle(const CObstacleInstance &obstacle);
  184. bool queryReply( ui32 qid, ui32 answer, TPlayerColor player );
  185. bool hireHero( const CGObjectInstance *obj, ui8 hid, TPlayerColor player );
  186. bool buildBoat( ui32 objid );
  187. bool setFormation( si32 hid, ui8 formation );
  188. bool tradeResources(const IMarket *market, ui32 val, TPlayerColor player, ui32 id1, ui32 id2);
  189. bool sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, TSlot slot, ui32 count);
  190. bool sendResources(ui32 val, TPlayerColor player, Res::ERes r1, TPlayerColor r2);
  191. bool sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, ui32 slot, Res::ERes resourceID);
  192. bool transformInUndead(const IMarket *market, const CGHeroInstance * hero, ui32 slot);
  193. bool assembleArtifacts (si32 heroID, ArtifactPosition::ArtifactPosition artifactSlot, bool assemble, ui32 assembleTo);
  194. bool buyArtifact( ui32 hid, ArtifactID::ArtifactID aid ); //for blacksmith and mage guild only -> buying for gold in common buildings
  195. bool buyArtifact( const IMarket *m, const CGHeroInstance *h, Res::ERes rid, ArtifactID::ArtifactID aid); //for artifact merchant and black market -> buying for any resource in special building / advobject
  196. bool sellArtifact( const IMarket *m, const CGHeroInstance *h, TArtifactInstanceID aid, Res::ERes rid); //for artifact merchant selling
  197. //void lootArtifacts (TArtHolder source, TArtHolder dest, std::vector<ui32> &arts); //after battle - move al arts to winer
  198. bool buySecSkill( const IMarket *m, const CGHeroInstance *h, SecondarySkill::SecondarySkill skill);
  199. bool garrisonSwap(si32 tid);
  200. bool upgradeCreature( ui32 objid, ui8 pos, ui32 upgID );
  201. bool recruitCreatures(si32 objid, CreatureID::CreatureID crid, ui32 cram, si32 level);
  202. bool buildStructure(si32 tid, si32 bid, bool force=false);//force - for events: no cost, no checkings
  203. bool razeStructure(si32 tid, si32 bid);
  204. bool disbandCreature( si32 id, ui8 pos );
  205. bool arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val, TPlayerColor player);
  206. void save(const std::string &fname);
  207. void close();
  208. void handleTimeEvents();
  209. void handleTownEvents(CGTownInstance *town, NewTurn &n, std::map<si32, std::map<si32, si32> > &newCreas);
  210. bool complain(const std::string &problem); //sends message to all clients, prints on the logs and return true
  211. void objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h );
  212. void engageIntoBattle( TPlayerColor player );
  213. bool dig(const CGHeroInstance *h);
  214. bool castSpell(const CGHeroInstance *h, int spellID, const int3 &pos);
  215. void moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging);
  216. template <typename Handler> void serialize(Handler &h, const int version)
  217. {
  218. h & QID & states;
  219. }
  220. ui32 getQueryResult(TPlayerColor player, int queryID);
  221. void sendMessageToAll(const std::string &message);
  222. void sendMessageTo(CConnection &c, const std::string &message);
  223. void applyAndAsk(Query * sel, TPlayerColor player, boost::function<void(ui32)> &callback);
  224. void prepareNewQuery(Query * queryPack, TPlayerColor player, const boost::function<void(ui32)> &callback = 0); //generates unique query id and writes it to the pack; blocks the player till query is answered (then callback is called)
  225. void ask(Query * sel, TPlayerColor player, const CFunctionList<void(ui32)> &callback);
  226. void sendToAllClients(CPackForClient * info);
  227. void sendAndApply(CPackForClient * info);
  228. void applyAndSend(CPackForClient * info);
  229. void sendAndApply(CGarrisonOperationPack * info);
  230. void sendAndApply(SetResource * info);
  231. void sendAndApply(SetResources * info);
  232. void sendAndApply(NewStructures * info);
  233. void run(bool resume);
  234. void newTurn();
  235. void handleAttackBeforeCasting (const BattleAttack & bat);
  236. void handleAfterAttackCasting (const BattleAttack & bat);
  237. void attackCasting(const BattleAttack & bat, Bonus::BonusType attackMode, const CStack * attacker);
  238. bool sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, ArtifactPosition::ArtifactPosition slot);
  239. void spawnWanderingMonsters(CreatureID::CreatureID creatureID);
  240. friend class CVCMIServer;
  241. friend class CScriptCallback;
  242. };
  243. void makeStackDoNothing();