HeroBonus.h 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. /*
  2. * HeroBonus.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 "GameConstants.h"
  12. #include "JsonNode.h"
  13. class CCreature;
  14. struct Bonus;
  15. class IBonusBearer;
  16. class CBonusSystemNode;
  17. class ILimiter;
  18. class IPropagator;
  19. class IUpdater;
  20. class BonusList;
  21. typedef std::shared_ptr<BonusList> TBonusListPtr;
  22. typedef std::shared_ptr<const BonusList> TConstBonusListPtr;
  23. typedef std::shared_ptr<ILimiter> TLimiterPtr;
  24. typedef std::shared_ptr<IPropagator> TPropagatorPtr;
  25. typedef std::shared_ptr<IUpdater> TUpdaterPtr;
  26. typedef std::set<CBonusSystemNode*> TNodes;
  27. typedef std::set<const CBonusSystemNode*> TCNodes;
  28. typedef std::vector<CBonusSystemNode *> TNodesVector;
  29. class CSelector : std::function<bool(const Bonus*)>
  30. {
  31. typedef std::function<bool(const Bonus*)> TBase;
  32. public:
  33. CSelector() {}
  34. template<typename T>
  35. CSelector(const T &t, //SFINAE trick -> include this c-tor in overload resolution only if parameter is class
  36. //(includes functors, lambdas) or function. Without that VC is going mad about ambiguities.
  37. typename std::enable_if < boost::mpl::or_ < std::is_class<T>, std::is_function<T >> ::value>::type *dummy = nullptr)
  38. : TBase(t)
  39. {}
  40. CSelector(std::nullptr_t)
  41. {}
  42. CSelector And(CSelector rhs) const
  43. {
  44. //lambda may likely outlive "this" (it can be even a temporary) => we copy the OBJECT (not pointer)
  45. auto thisCopy = *this;
  46. return [thisCopy, rhs](const Bonus *b) mutable { return thisCopy(b) && rhs(b); };
  47. }
  48. CSelector Or(CSelector rhs) const
  49. {
  50. auto thisCopy = *this;
  51. return [thisCopy, rhs](const Bonus *b) mutable { return thisCopy(b) || rhs(b); };
  52. }
  53. bool operator()(const Bonus *b) const
  54. {
  55. return TBase::operator()(b);
  56. }
  57. operator bool() const
  58. {
  59. return !!static_cast<const TBase&>(*this);
  60. }
  61. };
  62. class DLL_LINKAGE CBonusProxy
  63. {
  64. public:
  65. CBonusProxy(const IBonusBearer * Target, CSelector Selector);
  66. CBonusProxy(const CBonusProxy & other);
  67. CBonusProxy(CBonusProxy && other);
  68. CBonusProxy & operator=(CBonusProxy && other);
  69. CBonusProxy & operator=(const CBonusProxy & other);
  70. const BonusList * operator->() const;
  71. TConstBonusListPtr getBonusList() const;
  72. protected:
  73. CSelector selector;
  74. const IBonusBearer * target;
  75. mutable int64_t bonusListCachedLast;
  76. mutable TConstBonusListPtr bonusList;
  77. };
  78. class DLL_LINKAGE CTotalsProxy : public CBonusProxy
  79. {
  80. public:
  81. CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue);
  82. CTotalsProxy(const CTotalsProxy & other);
  83. CTotalsProxy(CTotalsProxy && other) = delete;
  84. CTotalsProxy & operator=(const CTotalsProxy & other);
  85. CTotalsProxy & operator=(CTotalsProxy && other) = delete;
  86. int getMeleeValue() const;
  87. int getRangedValue() const;
  88. int getValue() const;
  89. /**
  90. Returns total value of all selected bonuses and sets bonusList as a pointer to the list of selected bonuses
  91. @param bonusList is the out list of all selected bonuses
  92. @return total value of all selected bonuses and 0 otherwise
  93. */
  94. int getValueAndList(TConstBonusListPtr & bonusList) const;
  95. private:
  96. int initialValue;
  97. mutable int64_t valueCachedLast;
  98. mutable int value;
  99. mutable int64_t meleeCachedLast;
  100. mutable int meleeValue;
  101. mutable int64_t rangedCachedLast;
  102. mutable int rangedValue;
  103. };
  104. class DLL_LINKAGE CCheckProxy
  105. {
  106. public:
  107. CCheckProxy(const IBonusBearer * Target, CSelector Selector);
  108. CCheckProxy(const CCheckProxy & other);
  109. bool getHasBonus() const;
  110. private:
  111. const IBonusBearer * target;
  112. CSelector selector;
  113. mutable int64_t cachedLast;
  114. mutable bool hasBonus;
  115. };
  116. class DLL_LINKAGE CAddInfo : public std::vector<si32>
  117. {
  118. public:
  119. enum { NONE = -1 };
  120. CAddInfo();
  121. CAddInfo(si32 value);
  122. bool operator==(si32 value) const;
  123. bool operator!=(si32 value) const;
  124. si32 & operator[](size_type pos);
  125. si32 operator[](size_type pos) const;
  126. std::string toString() const;
  127. JsonNode toJsonNode() const;
  128. };
  129. #define BONUS_TREE_DESERIALIZATION_FIX if(!h.saving && h.smartPointerSerialization) deserializationFix();
  130. #define BONUS_LIST \
  131. BONUS_NAME(NONE) \
  132. BONUS_NAME(LEVEL_COUNTER) /* for commander artifacts*/ \
  133. BONUS_NAME(MOVEMENT) /*both water/land*/ \
  134. BONUS_NAME(LAND_MOVEMENT) \
  135. BONUS_NAME(SEA_MOVEMENT) \
  136. BONUS_NAME(MORALE) \
  137. BONUS_NAME(LUCK) \
  138. BONUS_NAME(PRIMARY_SKILL) /*uses subtype to pick skill; additional info if set: 1 - only melee, 2 - only distance*/ \
  139. BONUS_NAME(SIGHT_RADIOUS) /*the correct word is RADIUS, but this one's already used in mods */\
  140. BONUS_NAME(MANA_REGENERATION) /*points per turn apart from normal (1 + mysticism)*/ \
  141. BONUS_NAME(FULL_MANA_REGENERATION) /*all mana points are replenished every day*/ \
  142. BONUS_NAME(NONEVIL_ALIGNMENT_MIX) /*good and neutral creatures can be mixed without morale penalty*/ \
  143. BONUS_NAME(SECONDARY_SKILL_PREMY) /*%*/ \
  144. BONUS_NAME(SURRENDER_DISCOUNT) /*%*/ \
  145. BONUS_NAME(STACKS_SPEED) /*additional info - percent of speed bonus applied after direct bonuses; >0 - added, <0 - subtracted to this part*/ \
  146. BONUS_NAME(FLYING_MOVEMENT) /*value - penalty percentage*/ \
  147. BONUS_NAME(SPELL_DURATION) \
  148. BONUS_NAME(AIR_SPELL_DMG_PREMY) \
  149. BONUS_NAME(EARTH_SPELL_DMG_PREMY) \
  150. BONUS_NAME(FIRE_SPELL_DMG_PREMY) \
  151. BONUS_NAME(WATER_SPELL_DMG_PREMY) \
  152. BONUS_NAME(WATER_WALKING) /*value - penalty percentage*/ \
  153. BONUS_NAME(NEGATE_ALL_NATURAL_IMMUNITIES) \
  154. BONUS_NAME(STACK_HEALTH) \
  155. BONUS_NAME(BLOCK_MORALE) \
  156. BONUS_NAME(BLOCK_LUCK) \
  157. BONUS_NAME(FIRE_SPELLS) \
  158. BONUS_NAME(AIR_SPELLS) \
  159. BONUS_NAME(WATER_SPELLS) \
  160. BONUS_NAME(EARTH_SPELLS) \
  161. BONUS_NAME(GENERATE_RESOURCE) /*daily value, uses subtype (resource type)*/ \
  162. BONUS_NAME(CREATURE_GROWTH) /*for legion artifacts: value - week growth bonus, subtype - monster level if aplicable*/ \
  163. BONUS_NAME(WHIRLPOOL_PROTECTION) /*hero won't lose army when teleporting through whirlpool*/ \
  164. BONUS_NAME(SPELL) /*hero knows spell, val - skill level (0 - 3), subtype - spell id*/ \
  165. BONUS_NAME(SPELLS_OF_LEVEL) /*hero knows all spells of given level, val - skill level; subtype - level*/ \
  166. BONUS_NAME(BATTLE_NO_FLEEING) /*for shackles of war*/ \
  167. BONUS_NAME(MAGIC_SCHOOL_SKILL) /* //eg. for magic plains terrain, subtype: school of magic (0 - all, 1 - fire, 2 - air, 4 - water, 8 - earth), value - level*/ \
  168. BONUS_NAME(FREE_SHOOTING) /*stacks can shoot even if otherwise blocked (sharpshooter's bow effect)*/ \
  169. BONUS_NAME(OPENING_BATTLE_SPELL) /*casts a spell at expert level at beginning of battle, val - spell power, subtype - spell id*/ \
  170. BONUS_NAME(IMPROVED_NECROMANCY) /* raise more powerful creatures: subtype - creature type raised, addInfo - [required necromancy level, required stack level] */ \
  171. BONUS_NAME(CREATURE_GROWTH_PERCENT) /*increases growth of all units in all towns, val - percentage*/ \
  172. BONUS_NAME(FREE_SHIP_BOARDING) /*movement points preserved with ship boarding and landing*/ \
  173. BONUS_NAME(NO_TYPE) \
  174. BONUS_NAME(FLYING) \
  175. BONUS_NAME(SHOOTER) \
  176. BONUS_NAME(CHARGE_IMMUNITY) \
  177. BONUS_NAME(ADDITIONAL_ATTACK) \
  178. BONUS_NAME(UNLIMITED_RETALIATIONS) \
  179. BONUS_NAME(NO_MELEE_PENALTY) \
  180. BONUS_NAME(JOUSTING) /*for champions*/ \
  181. BONUS_NAME(HATE) /*eg. angels hate devils, subtype - ID of hated creature, val - damage bonus percent */ \
  182. BONUS_NAME(KING1) \
  183. BONUS_NAME(KING2) \
  184. BONUS_NAME(KING3) \
  185. BONUS_NAME(MAGIC_RESISTANCE) /*in % (value)*/ \
  186. BONUS_NAME(CHANGES_SPELL_COST_FOR_ALLY) /*in mana points (value) , eg. mage*/ \
  187. BONUS_NAME(CHANGES_SPELL_COST_FOR_ENEMY) /*in mana points (value) , eg. pegasus */ \
  188. BONUS_NAME(SPELL_AFTER_ATTACK) /* subtype - spell id, value - chance %, addInfo[0] - level, addInfo[1] -> [0 - all attacks, 1 - shot only, 2 - melee only] */ \
  189. BONUS_NAME(SPELL_BEFORE_ATTACK) /* subtype - spell id, value - chance %, addInfo[0] - level, addInfo[1] -> [0 - all attacks, 1 - shot only, 2 - melee only] */ \
  190. BONUS_NAME(SPELL_RESISTANCE_AURA) /*eg. unicorns, value - resistance bonus in % for adjacent creatures*/ \
  191. BONUS_NAME(LEVEL_SPELL_IMMUNITY) /*creature is immune to all spell with level below or equal to value of this bonus */ \
  192. BONUS_NAME(BLOCK_MAGIC_ABOVE) /*blocks casting spells of the level > value */ \
  193. BONUS_NAME(BLOCK_ALL_MAGIC) /*blocks casting spells*/ \
  194. BONUS_NAME(TWO_HEX_ATTACK_BREATH) /*eg. dragons*/ \
  195. BONUS_NAME(SPELL_DAMAGE_REDUCTION) /*eg. golems; value - reduction in %, subtype - spell school; -1 - all, 0 - air, 1 - fire, 2 - water, 3 - earth*/ \
  196. BONUS_NAME(NO_WALL_PENALTY) \
  197. BONUS_NAME(NON_LIVING) /*eg. golems, cannot be rised or healed, only neutral morale */ \
  198. BONUS_NAME(RANDOM_SPELLCASTER) /*eg. master genie, val - level*/ \
  199. BONUS_NAME(BLOCKS_RETALIATION) /*eg. naga*/ \
  200. BONUS_NAME(SPELL_IMMUNITY) /*subid - spell id*/ \
  201. BONUS_NAME(MANA_CHANNELING) /*value in %, eg. familiar*/ \
  202. BONUS_NAME(SPELL_LIKE_ATTACK) /*subtype - spell, value - spell level; range is taken from spell, but damage from creature; eg. magog*/ \
  203. BONUS_NAME(THREE_HEADED_ATTACK) /*eg. cerberus*/ \
  204. BONUS_NAME(DAEMON_SUMMONING) /*pit lord, subtype - type of creatures, val - hp per unit*/ \
  205. BONUS_NAME(FIRE_IMMUNITY) /*subtype 0 - all, 1 - all except positive, 2 - only damage spells*/ \
  206. BONUS_NAME(WATER_IMMUNITY) \
  207. BONUS_NAME(EARTH_IMMUNITY) \
  208. BONUS_NAME(AIR_IMMUNITY) \
  209. BONUS_NAME(MIND_IMMUNITY) \
  210. BONUS_NAME(FIRE_SHIELD) \
  211. BONUS_NAME(UNDEAD) \
  212. BONUS_NAME(HP_REGENERATION) /*creature regenerates val HP every new round*/ \
  213. BONUS_NAME(FULL_HP_REGENERATION) /*first creature regenerates all HP every new round; subtype 0 - animation 4 (trolllike), 1 - animation 47 (wightlike)*/ \
  214. BONUS_NAME(MANA_DRAIN) /*value - spell points per turn*/ \
  215. BONUS_NAME(LIFE_DRAIN) \
  216. BONUS_NAME(DOUBLE_DAMAGE_CHANCE) /*value in %, eg. dread knight*/ \
  217. BONUS_NAME(RETURN_AFTER_STRIKE) \
  218. BONUS_NAME(SELF_MORALE) /*eg. minotaur*/ \
  219. BONUS_NAME(SPELLCASTER) /*subtype - spell id, value - level of school, additional info - weighted chance. use SPECIFIC_SPELL_POWER, CREATURE_SPELL_POWER or CREATURE_ENCHANT_POWER for calculating the power*/ \
  220. BONUS_NAME(CATAPULT) \
  221. BONUS_NAME(ENEMY_DEFENCE_REDUCTION) /*in % (value) eg. behemots*/ \
  222. BONUS_NAME(GENERAL_DAMAGE_REDUCTION) /* shield / air shield effect */ \
  223. BONUS_NAME(GENERAL_ATTACK_REDUCTION) /*eg. while stoned or blinded - in %,// subtype not used, use ONLY_MELEE_FIGHT / DISTANCE_FIGHT*/ \
  224. BONUS_NAME(DEFENSIVE_STANCE) /* val - bonus to defense while defending */ \
  225. BONUS_NAME(ATTACKS_ALL_ADJACENT) /*eg. hydra*/ \
  226. BONUS_NAME(MORE_DAMAGE_FROM_SPELL) /*value - damage increase in %, subtype - spell id*/ \
  227. BONUS_NAME(FEAR) \
  228. BONUS_NAME(FEARLESS) \
  229. BONUS_NAME(NO_DISTANCE_PENALTY) \
  230. BONUS_NAME(SELF_LUCK) /*halfling*/ \
  231. BONUS_NAME(ENCHANTER)/* for Enchanter spells, val - skill level, subtype - spell id, additionalInfo - cooldown */ \
  232. BONUS_NAME(HEALER) \
  233. BONUS_NAME(SIEGE_WEAPON) \
  234. BONUS_NAME(HYPNOTIZED) \
  235. BONUS_NAME(NO_RETALIATION) /*temporary bonus for basilisk, unicorn and scorpicore paralyze*/\
  236. BONUS_NAME(ADDITIONAL_RETALIATION) /*value - number of additional retaliations*/ \
  237. BONUS_NAME(MAGIC_MIRROR) /* value - chance of redirecting in %*/ \
  238. BONUS_NAME(ALWAYS_MINIMUM_DAMAGE) /*unit does its minimum damage from range; subtype: -1 - any attack, 0 - melee, 1 - ranged, value: additional damage penalty (it'll subtracted from dmg), additional info - multiplicative anti-bonus for dmg in % [eg 20 means that creature will inflict 80% of normal minimal dmg]*/ \
  239. BONUS_NAME(ALWAYS_MAXIMUM_DAMAGE) /*eg. bless effect, subtype: -1 - any attack, 0 - melee, 1 - ranged, value: additional damage, additional info - multiplicative bonus for dmg in %*/ \
  240. BONUS_NAME(ATTACKS_NEAREST_CREATURE) /*while in berserk*/ \
  241. BONUS_NAME(IN_FRENZY) /*value - level*/ \
  242. BONUS_NAME(SLAYER) /*value - level*/ \
  243. BONUS_NAME(FORGETFULL) /*forgetfulness spell effect, value - level*/ \
  244. BONUS_NAME(NOT_ACTIVE) /* subtype - spell ID (paralyze, blind, stone gaze) for graphical effect*/ \
  245. BONUS_NAME(NO_LUCK) /*eg. when fighting on cursed ground*/ \
  246. BONUS_NAME(NO_MORALE) /*eg. when fighting on cursed ground*/ \
  247. BONUS_NAME(DARKNESS) /*val = radius */ \
  248. BONUS_NAME(SPECIAL_SECONDARY_SKILL) /*subtype = id, val = value per level in percent*/ \
  249. BONUS_NAME(SPECIAL_SPELL_LEV) /*subtype = id, val = value per level in percent*/\
  250. BONUS_NAME(SPELL_DAMAGE) /*val = value*/\
  251. BONUS_NAME(SPECIFIC_SPELL_DAMAGE) /*subtype = id of spell, val = value*/\
  252. BONUS_NAME(SPECIAL_BLESS_DAMAGE) /*val = spell (bless), additionalInfo = value per level in percent*/\
  253. BONUS_NAME(MAXED_SPELL) /*val = id*/\
  254. BONUS_NAME(SPECIAL_PECULIAR_ENCHANT) /*blesses and curses with id = val dependent on unit's level, subtype = 0 or 1 for Coronius*/\
  255. BONUS_NAME(SPECIAL_UPGRADE) /*subtype = base, additionalInfo = target */\
  256. BONUS_NAME(DRAGON_NATURE) \
  257. BONUS_NAME(CREATURE_DAMAGE)/*subtype 0 = both, 1 = min, 2 = max*/\
  258. BONUS_NAME(EXP_MULTIPLIER)/* val - percent of additional exp gained by stack/commander (base value 100)*/\
  259. BONUS_NAME(SHOTS)\
  260. BONUS_NAME(DEATH_STARE) /*subtype 0 - gorgon, 1 - commander*/\
  261. BONUS_NAME(POISON) /*val - max health penalty from poison possible*/\
  262. BONUS_NAME(BIND_EFFECT) /*doesn't do anything particular, works as a marker)*/\
  263. BONUS_NAME(ACID_BREATH) /*additional val damage per creature after attack, additional info - chance in percent*/\
  264. BONUS_NAME(RECEPTIVE) /*accepts friendly spells even with immunity*/\
  265. BONUS_NAME(DIRECT_DAMAGE_IMMUNITY) /*direct damage spells, that is*/\
  266. BONUS_NAME(CASTS) /*how many times creature can cast activated spell*/ \
  267. BONUS_NAME(SPECIFIC_SPELL_POWER) /* value used for Thunderbolt and Resurrection cast by units, subtype - spell id */\
  268. BONUS_NAME(CREATURE_SPELL_POWER) /* value per unit, divided by 100 (so faerie Dragons have 800)*/ \
  269. BONUS_NAME(CREATURE_ENCHANT_POWER) /* total duration of spells cast by creature */ \
  270. BONUS_NAME(ENCHANTED) /* permanently enchanted with spell subID of level = val, if val > 3 then spell is mass and has level of val-3*/ \
  271. BONUS_NAME(REBIRTH) /* val - percent of life restored, subtype = 0 - regular, 1 - at least one unit (sacred Phoenix) */\
  272. BONUS_NAME(ADDITIONAL_UNITS) /*val of units with id = subtype will be added to hero's army at the beginning of battle */\
  273. BONUS_NAME(SPOILS_OF_WAR) /*val * 10^-6 * gained exp resources of subtype will be given to hero after battle*/\
  274. BONUS_NAME(BLOCK)\
  275. BONUS_NAME(DISGUISED) /* subtype - spell level */\
  276. BONUS_NAME(VISIONS) /* subtype - spell level */\
  277. BONUS_NAME(NO_TERRAIN_PENALTY) /* subtype - terrain type */\
  278. BONUS_NAME(SOUL_STEAL) /*val - number of units gained per enemy killed, subtype = 0 - gained units survive after battle, 1 - they do not*/ \
  279. BONUS_NAME(TRANSMUTATION) /*val - chance to trigger in %, subtype = 0 - resurrection based on HP, 1 - based on unit count, additional info - target creature ID (attacker default)*/\
  280. BONUS_NAME(SUMMON_GUARDIANS) /*val - amount in % of stack count, subtype = creature ID*/\
  281. BONUS_NAME(CATAPULT_EXTRA_SHOTS) /*val - number of additional shots, requires CATAPULT bonus to work*/\
  282. BONUS_NAME(RANGED_RETALIATION) /*allows shooters to perform ranged retaliation*/\
  283. BONUS_NAME(BLOCKS_RANGED_RETALIATION) /*disallows ranged retaliation for shooter unit, BLOCKS_RETALIATION bonus is for melee retaliation only*/\
  284. BONUS_NAME(SECONDARY_SKILL_VAL2) /*for secondary skills that have multiple effects, like eagle eye (max level and chance)*/ \
  285. BONUS_NAME(MANUAL_CONTROL) /* manually control warmachine with id = subtype, chance = val */ \
  286. BONUS_NAME(WIDE_BREATH) /* initial desigh: dragon breath affecting multiple nearby hexes */\
  287. BONUS_NAME(FIRST_STRIKE) /* first counterattack, then attack if possible */\
  288. BONUS_NAME(SYNERGY_TARGET) /* dummy skill for alternative upgrades mod */\
  289. BONUS_NAME(SHOOTS_ALL_ADJACENT) /* H4 Cyclops-like shoot (attacks all hexes neighboring with target) without spell-like mechanics */\
  290. BONUS_NAME(BLOCK_MAGIC_BELOW) /*blocks casting spells of the level < value */ \
  291. BONUS_NAME(DESTRUCTION) /*kills extra units after hit, subtype = 0 - kill percentage of units, 1 - kill amount, val = chance in percent to trigger, additional info - amount/percentage to kill*/ \
  292. BONUS_NAME(SPECIAL_CRYSTAL_GENERATION) /*crystal dragon crystal generation*/ \
  293. BONUS_NAME(NO_SPELLCAST_BY_DEFAULT) /*spellcast will not be default attack option for this creature*/ \
  294. BONUS_NAME(GARGOYLE) /* gargoyle is special than NON_LIVING, cannot be rised or healed */ \
  295. BONUS_NAME(SPECIAL_ADD_VALUE_ENCHANT) /*specialty spell like Aenin has, increased effect of spell, additionalInfo = value to add*/\
  296. BONUS_NAME(SPECIAL_FIXED_VALUE_ENCHANT) /*specialty spell like Melody has, constant spell effect (i.e. 3 luck), additionalInfo = value to fix.*/\
  297. BONUS_NAME(TOWN_MAGIC_WELL) /*one-time pseudo-bonus to implement Magic Well in the town*/ \
  298. /* end of list */
  299. #define BONUS_SOURCE_LIST \
  300. BONUS_SOURCE(ARTIFACT)\
  301. BONUS_SOURCE(ARTIFACT_INSTANCE)\
  302. BONUS_SOURCE(OBJECT)\
  303. BONUS_SOURCE(CREATURE_ABILITY)\
  304. BONUS_SOURCE(TERRAIN_NATIVE)\
  305. BONUS_SOURCE(TERRAIN_OVERLAY)\
  306. BONUS_SOURCE(SPELL_EFFECT)\
  307. BONUS_SOURCE(TOWN_STRUCTURE)\
  308. BONUS_SOURCE(HERO_BASE_SKILL)\
  309. BONUS_SOURCE(SECONDARY_SKILL)\
  310. BONUS_SOURCE(HERO_SPECIAL)\
  311. BONUS_SOURCE(ARMY)\
  312. BONUS_SOURCE(CAMPAIGN_BONUS)\
  313. BONUS_SOURCE(SPECIAL_WEEK)\
  314. BONUS_SOURCE(STACK_EXPERIENCE)\
  315. BONUS_SOURCE(COMMANDER) /*TODO: consider using simply STACK_INSTANCE */\
  316. BONUS_SOURCE(OTHER) /*used for defensive stance and default value of spell level limit*/
  317. #define BONUS_VALUE_LIST \
  318. BONUS_VALUE(ADDITIVE_VALUE)\
  319. BONUS_VALUE(BASE_NUMBER)\
  320. BONUS_VALUE(PERCENT_TO_ALL)\
  321. BONUS_VALUE(PERCENT_TO_BASE)\
  322. BONUS_VALUE(INDEPENDENT_MAX) /*used for SPELL bonus */\
  323. BONUS_VALUE(INDEPENDENT_MIN) //used for SECONDARY_SKILL_PREMY bonus
  324. /// Struct for handling bonuses of several types. Can be transferred to any hero
  325. struct DLL_LINKAGE Bonus : public std::enable_shared_from_this<Bonus>
  326. {
  327. enum { EVERY_TYPE = -1 };
  328. enum BonusType
  329. {
  330. #define BONUS_NAME(x) x,
  331. BONUS_LIST
  332. #undef BONUS_NAME
  333. };
  334. enum BonusDuration //when bonus is automatically removed
  335. {
  336. PERMANENT = 1,
  337. ONE_BATTLE = 2, //at the end of battle
  338. ONE_DAY = 4, //at the end of day
  339. ONE_WEEK = 8, //at the end of week (bonus lasts till the end of week, thats NOT 7 days
  340. N_TURNS = 16, //used during battles, after battle bonus is always removed
  341. N_DAYS = 32,
  342. UNTIL_BEING_ATTACKED = 64, /*removed after attack and counterattacks are performed*/
  343. UNTIL_ATTACK = 128, /*removed after attack and counterattacks are performed*/
  344. STACK_GETS_TURN = 256, /*removed when stack gets its turn - used for defensive stance*/
  345. COMMANDER_KILLED = 512
  346. };
  347. enum BonusSource
  348. {
  349. #define BONUS_SOURCE(x) x,
  350. BONUS_SOURCE_LIST
  351. #undef BONUS_SOURCE
  352. };
  353. enum LimitEffect
  354. {
  355. NO_LIMIT = 0,
  356. ONLY_DISTANCE_FIGHT=1, ONLY_MELEE_FIGHT, //used to mark bonuses for attack/defense primary skills from spells like Precision (distance only)
  357. ONLY_ENEMY_ARMY
  358. };
  359. enum ValueType
  360. {
  361. #define BONUS_VALUE(x) x,
  362. BONUS_VALUE_LIST
  363. #undef BONUS_VALUE
  364. };
  365. ui16 duration; //uses BonusDuration values
  366. si16 turnsRemain; //used if duration is N_TURNS, N_DAYS or ONE_WEEK
  367. BonusType type; //uses BonusType values - says to what is this bonus - 1 byte
  368. TBonusSubtype subtype; //-1 if not applicable - 4 bytes
  369. BonusSource source;//source type" uses BonusSource values - what gave that bonus
  370. si32 val;
  371. ui32 sid; //source id: id of object/artifact/spell
  372. ValueType valType;
  373. std::string stacking; // bonuses with the same stacking value don't stack (e.g. Angel/Archangel morale bonus)
  374. CAddInfo additionalInfo;
  375. LimitEffect effectRange; //if not NO_LIMIT, bonus will be omitted by default
  376. TLimiterPtr limiter;
  377. TPropagatorPtr propagator;
  378. TUpdaterPtr updater;
  379. TUpdaterPtr propagationUpdater;
  380. std::string description;
  381. Bonus(BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype=-1);
  382. Bonus(BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype=-1, ValueType ValType = ADDITIVE_VALUE);
  383. Bonus();
  384. template <typename Handler> void serialize(Handler &h, const int version)
  385. {
  386. h & duration;
  387. h & type;
  388. h & subtype;
  389. h & source;
  390. h & val;
  391. h & sid;
  392. h & description;
  393. if(version >= 783)
  394. {
  395. h & additionalInfo;
  396. }
  397. else
  398. {
  399. additionalInfo.resize(1, -1);
  400. h & additionalInfo[0];
  401. }
  402. h & turnsRemain;
  403. h & valType;
  404. if(version >= 784)
  405. {
  406. h & stacking;
  407. }
  408. h & effectRange;
  409. h & limiter;
  410. h & propagator;
  411. if(version >= 781)
  412. {
  413. h & updater;
  414. }
  415. if(version >= 801)
  416. {
  417. h & propagationUpdater;
  418. }
  419. if(version < 801 && !h.saving) //Opposite Side bonuses are introduced
  420. {
  421. updateOppositeBonuses();
  422. }
  423. }
  424. template <typename Ptr>
  425. static bool compareByAdditionalInfo(const Ptr& a, const Ptr& b)
  426. {
  427. return a->additionalInfo < b->additionalInfo;
  428. }
  429. static bool NDays(const Bonus *hb)
  430. {
  431. return hb->duration & Bonus::N_DAYS;
  432. }
  433. static bool NTurns(const Bonus *hb)
  434. {
  435. return hb->duration & Bonus::N_TURNS;
  436. }
  437. static bool OneDay(const Bonus *hb)
  438. {
  439. return hb->duration & Bonus::ONE_DAY;
  440. }
  441. static bool OneWeek(const Bonus *hb)
  442. {
  443. return hb->duration & Bonus::ONE_WEEK;
  444. }
  445. static bool OneBattle(const Bonus *hb)
  446. {
  447. return hb->duration & Bonus::ONE_BATTLE;
  448. }
  449. static bool Permanent(const Bonus *hb)
  450. {
  451. return hb->duration & Bonus::PERMANENT;
  452. }
  453. static bool UntilGetsTurn(const Bonus *hb)
  454. {
  455. return hb->duration & Bonus::STACK_GETS_TURN;
  456. }
  457. static bool UntilAttack(const Bonus *hb)
  458. {
  459. return hb->duration & Bonus::UNTIL_ATTACK;
  460. }
  461. static bool UntilBeingAttacked(const Bonus *hb)
  462. {
  463. return hb->duration & Bonus::UNTIL_BEING_ATTACKED;
  464. }
  465. static bool UntilCommanderKilled(const Bonus *hb)
  466. {
  467. return hb->duration & Bonus::COMMANDER_KILLED;
  468. }
  469. inline bool operator == (const BonusType & cf) const
  470. {
  471. return type == cf;
  472. }
  473. inline void operator += (const ui32 Val) //no return
  474. {
  475. val += Val;
  476. }
  477. STRONG_INLINE static ui32 getSid32(ui32 high, ui32 low)
  478. {
  479. return (high << 16) + low;
  480. }
  481. std::string Description() const;
  482. JsonNode toJsonNode() const;
  483. std::string nameForBonus() const; // generate suitable name for bonus - e.g. for storing in json struct
  484. std::shared_ptr<Bonus> addLimiter(TLimiterPtr Limiter); //returns this for convenient chain-calls
  485. std::shared_ptr<Bonus> addPropagator(TPropagatorPtr Propagator); //returns this for convenient chain-calls
  486. std::shared_ptr<Bonus> addUpdater(TUpdaterPtr Updater); //returns this for convenient chain-calls
  487. void updateOppositeBonuses();
  488. };
  489. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus);
  490. class DLL_LINKAGE BonusList
  491. {
  492. public:
  493. typedef std::vector<std::shared_ptr<Bonus>> TInternalContainer;
  494. private:
  495. TInternalContainer bonuses;
  496. bool belongsToTree;
  497. void changed();
  498. public:
  499. typedef TInternalContainer::const_reference const_reference;
  500. typedef TInternalContainer::value_type value_type;
  501. typedef TInternalContainer::const_iterator const_iterator;
  502. typedef TInternalContainer::iterator iterator;
  503. BonusList(bool BelongsToTree = false);
  504. BonusList(const BonusList &bonusList);
  505. BonusList(BonusList && other);
  506. BonusList& operator=(const BonusList &bonusList);
  507. // wrapper functions of the STL vector container
  508. TInternalContainer::size_type size() const { return bonuses.size(); }
  509. void push_back(std::shared_ptr<Bonus> x);
  510. TInternalContainer::iterator erase (const int position);
  511. void clear();
  512. bool empty() const { return bonuses.empty(); }
  513. void resize(TInternalContainer::size_type sz, std::shared_ptr<Bonus> c = nullptr );
  514. STRONG_INLINE std::shared_ptr<Bonus> &operator[] (TInternalContainer::size_type n) { return bonuses[n]; }
  515. STRONG_INLINE const std::shared_ptr<Bonus> &operator[] (TInternalContainer::size_type n) const { return bonuses[n]; }
  516. std::shared_ptr<Bonus> &back() { return bonuses.back(); }
  517. std::shared_ptr<Bonus> &front() { return bonuses.front(); }
  518. const std::shared_ptr<Bonus> &back() const { return bonuses.back(); }
  519. const std::shared_ptr<Bonus> &front() const { return bonuses.front(); }
  520. // There should be no non-const access to provide solid,robust bonus caching
  521. TInternalContainer::const_iterator begin() const { return bonuses.begin(); }
  522. TInternalContainer::const_iterator end() const { return bonuses.end(); }
  523. TInternalContainer::size_type operator-=(std::shared_ptr<Bonus> const &i);
  524. // BonusList functions
  525. void stackBonuses();
  526. int totalValue() const;
  527. void getBonuses(BonusList &out, const CSelector &selector, const CSelector &limit) const;
  528. void getAllBonuses(BonusList &out) const;
  529. void getBonuses(BonusList & out, const CSelector &selector) const;
  530. //special find functions
  531. std::shared_ptr<Bonus> getFirst(const CSelector &select);
  532. std::shared_ptr<const Bonus> getFirst(const CSelector &select) const;
  533. int valOfBonuses(const CSelector &select) const;
  534. // conversion / output
  535. JsonNode toJsonNode() const;
  536. // remove_if implementation for STL vector types
  537. template <class Predicate>
  538. void remove_if(Predicate pred)
  539. {
  540. BonusList newList;
  541. for (ui32 i = 0; i < bonuses.size(); i++)
  542. {
  543. auto b = bonuses[i];
  544. if (!pred(b.get()))
  545. newList.push_back(b);
  546. }
  547. bonuses.clear();
  548. bonuses.resize(newList.size());
  549. std::copy(newList.begin(), newList.end(), bonuses.begin());
  550. }
  551. template <class InputIterator>
  552. void insert(const int position, InputIterator first, InputIterator last);
  553. void insert(TInternalContainer::iterator position, TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x);
  554. template <typename Handler>
  555. void serialize(Handler &h, const int version)
  556. {
  557. h & static_cast<TInternalContainer&>(bonuses);
  558. }
  559. // C++ for range support
  560. auto begin () -> decltype (bonuses.begin())
  561. {
  562. return bonuses.begin();
  563. }
  564. auto end () -> decltype (bonuses.end())
  565. {
  566. return bonuses.end();
  567. }
  568. };
  569. // Extensions for BOOST_FOREACH to enable iterating of BonusList objects
  570. // Don't touch/call this functions
  571. inline BonusList::iterator range_begin(BonusList & x)
  572. {
  573. return x.begin();
  574. }
  575. inline BonusList::iterator range_end(BonusList & x)
  576. {
  577. return x.end();
  578. }
  579. inline BonusList::const_iterator range_begin(BonusList const &x)
  580. {
  581. return x.begin();
  582. }
  583. inline BonusList::const_iterator range_end(BonusList const &x)
  584. {
  585. return x.end();
  586. }
  587. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList);
  588. struct BonusLimitationContext
  589. {
  590. std::shared_ptr<const Bonus> b;
  591. const CBonusSystemNode & node;
  592. const BonusList & alreadyAccepted;
  593. const BonusList & stillUndecided;
  594. };
  595. class DLL_LINKAGE ILimiter
  596. {
  597. public:
  598. enum EDecision {ACCEPT, DISCARD, NOT_SURE};
  599. virtual ~ILimiter();
  600. virtual int limit(const BonusLimitationContext &context) const; //0 - accept bonus; 1 - drop bonus; 2 - delay (drops eventually)
  601. virtual std::string toString() const;
  602. virtual JsonNode toJsonNode() const;
  603. template <typename Handler> void serialize(Handler &h, const int version)
  604. {
  605. }
  606. };
  607. class DLL_LINKAGE IBonusBearer
  608. {
  609. private:
  610. static CSelector anaffectedByMoraleSelector;
  611. CCheckProxy anaffectedByMorale;
  612. static CSelector moraleSelector;
  613. CTotalsProxy moraleValue;
  614. static CSelector luckSelector;
  615. CTotalsProxy luckValue;
  616. static CSelector selfMoraleSelector;
  617. CCheckProxy selfMorale;
  618. static CSelector selfLuckSelector;
  619. CCheckProxy selfLuck;
  620. public:
  621. //new bonusing node interface
  622. // * selector is predicate that tests if HeroBonus matches our criteria
  623. // * root is node on which call was made (nullptr will be replaced with this)
  624. //interface
  625. IBonusBearer();
  626. virtual TConstBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const = 0;
  627. int valOfBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  628. bool hasBonus(const CSelector &selector, const std::string &cachingStr = "") const;
  629. bool hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  630. TConstBonusListPtr getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr = "") const;
  631. TConstBonusListPtr getBonuses(const CSelector &selector, const std::string &cachingStr = "") const;
  632. std::shared_ptr<const Bonus> getBonus(const CSelector &selector) const; //returns any bonus visible on node that matches (or nullptr if none matches)
  633. //legacy interface
  634. int valOfBonuses(Bonus::BonusType type, const CSelector &selector) const;
  635. int valOfBonuses(Bonus::BonusType type, int subtype = -1) const; //subtype -> subtype of bonus, if -1 then anyt;
  636. bool hasBonusOfType(Bonus::BonusType type, int subtype = -1) const;//determines if hero has a bonus of given type (and optionally subtype)
  637. bool hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const;
  638. //various hlp functions for non-trivial values
  639. //used for stacks and creatures only
  640. virtual int getMinDamage(bool ranged) const;
  641. virtual int getMaxDamage(bool ranged) const;
  642. virtual int getAttack(bool ranged) const;
  643. virtual int getDefense(bool ranged) const;
  644. int MoraleVal() const; //range [-3, +3]
  645. int LuckVal() const; //range [-3, +3]
  646. /**
  647. Returns total value of all morale bonuses and sets bonusList as a pointer to the list of selected bonuses.
  648. @param bonusList is the out param it's list of all selected bonuses
  649. @return total value of all morale in the range [-3, +3] and 0 otherwise
  650. */
  651. int MoraleValAndBonusList(TConstBonusListPtr & bonusList) const;
  652. int LuckValAndBonusList(TConstBonusListPtr & bonusList) const;
  653. ui32 MaxHealth() const; //get max HP of stack with all modifiers
  654. bool isLiving() const; //non-undead, non-non living or alive
  655. virtual si32 magicResistance() const;
  656. ui32 Speed(int turn = 0, bool useBind = false) const; //get speed of creature with all modificators
  657. si32 manaLimit() const; //maximum mana value for this hero (basically 10*knowledge)
  658. int getPrimSkillLevel(PrimarySkill::PrimarySkill id) const;
  659. virtual int64_t getTreeVersion() const = 0;
  660. };
  661. class DLL_LINKAGE CBonusSystemNode : public virtual IBonusBearer, public boost::noncopyable
  662. {
  663. public:
  664. enum ENodeTypes
  665. {
  666. NONE = -1,
  667. UNKNOWN, STACK_INSTANCE, STACK_BATTLE, SPECIALTY, ARTIFACT, CREATURE, ARTIFACT_INSTANCE, HERO, PLAYER, TEAM,
  668. TOWN_AND_VISITOR, BATTLE, COMMANDER, GLOBAL_EFFECTS, ALL_CREATURES, TOWN
  669. };
  670. private:
  671. BonusList bonuses; //wielded bonuses (local or up-propagated here)
  672. BonusList exportedBonuses; //bonuses coming from this node (wielded or propagated away)
  673. TNodesVector parents; //parents -> we inherit bonuses from them, we may attach our bonuses to them
  674. TNodesVector children;
  675. ENodeTypes nodeType;
  676. std::string description;
  677. bool isHypotheticNode;
  678. static const bool cachingEnabled;
  679. mutable BonusList cachedBonuses;
  680. mutable int64_t cachedLast;
  681. static std::atomic<int32_t> treeChanged;
  682. // Setting a value to cachingStr before getting any bonuses caches the result for later requests.
  683. // This string needs to be unique, that's why it has to be setted in the following manner:
  684. // [property key]_[value] => only for selector
  685. mutable std::map<std::string, TBonusListPtr > cachedRequests;
  686. mutable boost::mutex sync;
  687. void getAllBonusesRec(BonusList &out) const;
  688. TConstBonusListPtr getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr) const;
  689. std::shared_ptr<Bonus> getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr updater) const;
  690. public:
  691. explicit CBonusSystemNode();
  692. explicit CBonusSystemNode(bool isHypotetic);
  693. explicit CBonusSystemNode(ENodeTypes NodeType);
  694. CBonusSystemNode(CBonusSystemNode && other);
  695. virtual ~CBonusSystemNode();
  696. void limitBonuses(const BonusList &allBonuses, BonusList &out) const; //out will bo populed with bonuses that are not limited here
  697. TBonusListPtr limitBonuses(const BonusList &allBonuses) const; //same as above, returns out by val for convienence
  698. TConstBonusListPtr getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root = nullptr, const std::string &cachingStr = "") const override;
  699. void getParents(TCNodes &out) const; //retrieves list of parent nodes (nodes to inherit bonuses from),
  700. std::shared_ptr<const Bonus> getBonusLocalFirst(const CSelector & selector) const;
  701. //non-const interface
  702. void getParents(TNodes &out); //retrieves list of parent nodes (nodes to inherit bonuses from)
  703. void getRedParents(TNodes &out); //retrieves list of red parent nodes (nodes bonuses propagate from)
  704. void getRedAncestors(TNodes &out);
  705. void getRedChildren(TNodes &out);
  706. void getRedDescendants(TNodes &out);
  707. void getAllParents(TCNodes & out) const;
  708. static PlayerColor retrieveNodeOwner(const CBonusSystemNode * node);
  709. std::shared_ptr<Bonus> getBonusLocalFirst(const CSelector & selector);
  710. void attachTo(CBonusSystemNode *parent);
  711. void detachFrom(CBonusSystemNode *parent);
  712. void detachFromAll();
  713. virtual void addNewBonus(const std::shared_ptr<Bonus>& b);
  714. void accumulateBonus(const std::shared_ptr<Bonus>& b); //add value of bonus with same type/subtype or create new
  715. void newChildAttached(CBonusSystemNode *child);
  716. void childDetached(CBonusSystemNode *child);
  717. void propagateBonus(std::shared_ptr<Bonus> b, const CBonusSystemNode & source);
  718. void unpropagateBonus(std::shared_ptr<Bonus> b);
  719. void removeBonus(const std::shared_ptr<Bonus>& b);
  720. void removeBonuses(const CSelector & selector);
  721. void removeBonusesRecursive(const CSelector & s);
  722. void newRedDescendant(CBonusSystemNode *descendant); //propagation needed
  723. void removedRedDescendant(CBonusSystemNode *descendant); //de-propagation needed
  724. bool isIndependentNode() const; //node is independent when it has no parents nor children
  725. bool actsAsBonusSourceOnly() const;
  726. ///updates count of remaining turns and removes outdated bonuses by selector
  727. void reduceBonusDurations(const CSelector &s);
  728. virtual std::string bonusToString(const std::shared_ptr<Bonus>& bonus, bool description) const {return "";}; //description or bonus name
  729. virtual std::string nodeName() const;
  730. virtual std::string nodeShortInfo() const;
  731. bool isHypothetic() const { return isHypotheticNode; }
  732. void deserializationFix();
  733. void exportBonus(std::shared_ptr<Bonus> b);
  734. void exportBonuses();
  735. const BonusList &getBonusList() const;
  736. BonusList & getExportedBonusList();
  737. const BonusList & getExportedBonusList() const;
  738. CBonusSystemNode::ENodeTypes getNodeType() const;
  739. void setNodeType(CBonusSystemNode::ENodeTypes type);
  740. const TNodesVector &getParentNodes() const;
  741. const TNodesVector &getChildrenNodes() const;
  742. const std::string &getDescription() const;
  743. void setDescription(const std::string &description);
  744. static void treeHasChanged();
  745. int64_t getTreeVersion() const override;
  746. virtual PlayerColor getOwner() const
  747. {
  748. return PlayerColor::NEUTRAL;
  749. }
  750. template <typename Handler> void serialize(Handler &h, const int version)
  751. {
  752. // h & bonuses;
  753. h & nodeType;
  754. h & exportedBonuses;
  755. h & description;
  756. BONUS_TREE_DESERIALIZATION_FIX
  757. //h & parents & children;
  758. }
  759. friend class CBonusProxy;
  760. };
  761. class DLL_LINKAGE IPropagator
  762. {
  763. public:
  764. virtual ~IPropagator();
  765. virtual bool shouldBeAttached(CBonusSystemNode *dest);
  766. virtual CBonusSystemNode::ENodeTypes getPropagatorType() const;
  767. template <typename Handler> void serialize(Handler &h, const int version)
  768. {}
  769. };
  770. class DLL_LINKAGE CPropagatorNodeType : public IPropagator
  771. {
  772. CBonusSystemNode::ENodeTypes nodeType;
  773. public:
  774. CPropagatorNodeType();
  775. CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType);
  776. bool shouldBeAttached(CBonusSystemNode *dest) override;
  777. CBonusSystemNode::ENodeTypes getPropagatorType() const override;
  778. template <typename Handler> void serialize(Handler &h, const int version)
  779. {
  780. h & nodeType;
  781. }
  782. };
  783. namespace NBonus
  784. {
  785. //set of methods that may be safely called with nullptr objs
  786. DLL_LINKAGE int valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1); //subtype -> subtype of bonus, if -1 then any
  787. DLL_LINKAGE bool hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype = -1);//determines if hero has a bonus of given type (and optionally subtype)
  788. }
  789. template<typename T>
  790. class CSelectFieldEqual
  791. {
  792. T Bonus::*ptr;
  793. public:
  794. CSelectFieldEqual(T Bonus::*Ptr)
  795. : ptr(Ptr)
  796. {
  797. }
  798. CSelector operator()(const T &valueToCompareAgainst) const
  799. {
  800. auto ptr2 = ptr; //We need a COPY because we don't want to reference this (might be outlived by lambda)
  801. return [ptr2, valueToCompareAgainst](const Bonus *bonus)
  802. {
  803. return bonus->*ptr2 == valueToCompareAgainst;
  804. };
  805. }
  806. };
  807. template<typename T> //can be same, needed for subtype field
  808. class CSelectFieldEqualOrEvery
  809. {
  810. T Bonus::*ptr;
  811. T val;
  812. public:
  813. CSelectFieldEqualOrEvery(T Bonus::*Ptr, const T &Val)
  814. : ptr(Ptr), val(Val)
  815. {
  816. }
  817. bool operator()(const Bonus *bonus) const
  818. {
  819. return (bonus->*ptr == val) || (bonus->*ptr == static_cast<T>(Bonus::EVERY_TYPE));
  820. }
  821. CSelectFieldEqualOrEvery& operator()(const T &setVal)
  822. {
  823. val = setVal;
  824. return *this;
  825. }
  826. };
  827. class DLL_LINKAGE CWillLastTurns
  828. {
  829. public:
  830. int turnsRequested;
  831. bool operator()(const Bonus *bonus) const
  832. {
  833. return turnsRequested <= 0 //every present effect will last zero (or "less") turns
  834. || !Bonus::NTurns(bonus) //so do every not expriing after N-turns effect
  835. || bonus->turnsRemain > turnsRequested;
  836. }
  837. CWillLastTurns& operator()(const int &setVal)
  838. {
  839. turnsRequested = setVal;
  840. return *this;
  841. }
  842. };
  843. class DLL_LINKAGE CWillLastDays
  844. {
  845. public:
  846. int daysRequested;
  847. bool operator()(const Bonus *bonus) const
  848. {
  849. if(daysRequested <= 0 || Bonus::Permanent(bonus) || Bonus::OneBattle(bonus))
  850. return true;
  851. else if(Bonus::OneDay(bonus))
  852. return false;
  853. else if(Bonus::NDays(bonus) || Bonus::OneWeek(bonus))
  854. {
  855. return bonus->turnsRemain > daysRequested;
  856. }
  857. return false; // TODO: ONE_WEEK need support for turnsRemain, but for now we'll exclude all unhandled durations
  858. }
  859. CWillLastDays& operator()(const int &setVal)
  860. {
  861. daysRequested = setVal;
  862. return *this;
  863. }
  864. };
  865. class DLL_LINKAGE AggregateLimiter : public ILimiter
  866. {
  867. protected:
  868. std::vector<TLimiterPtr> limiters;
  869. virtual const std::string & getAggregator() const = 0;
  870. public:
  871. void add(TLimiterPtr limiter);
  872. JsonNode toJsonNode() const override;
  873. template <typename Handler> void serialize(Handler & h, const int version)
  874. {
  875. h & static_cast<ILimiter&>(*this);
  876. if(version >= 786)
  877. {
  878. h & limiters;
  879. }
  880. }
  881. };
  882. class DLL_LINKAGE AllOfLimiter : public AggregateLimiter
  883. {
  884. protected:
  885. const std::string & getAggregator() const override;
  886. public:
  887. static const std::string aggregator;
  888. int limit(const BonusLimitationContext & context) const override;
  889. };
  890. class DLL_LINKAGE AnyOfLimiter : public AggregateLimiter
  891. {
  892. protected:
  893. const std::string & getAggregator() const override;
  894. public:
  895. static const std::string aggregator;
  896. int limit(const BonusLimitationContext & context) const override;
  897. };
  898. class DLL_LINKAGE NoneOfLimiter : public AggregateLimiter
  899. {
  900. protected:
  901. const std::string & getAggregator() const override;
  902. public:
  903. static const std::string aggregator;
  904. int limit(const BonusLimitationContext & context) const override;
  905. };
  906. class DLL_LINKAGE CCreatureTypeLimiter : public ILimiter //affect only stacks of given creature (and optionally it's upgrades)
  907. {
  908. public:
  909. const CCreature *creature;
  910. bool includeUpgrades;
  911. CCreatureTypeLimiter();
  912. CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades = true);
  913. void setCreature (CreatureID id);
  914. int limit(const BonusLimitationContext &context) const override;
  915. virtual std::string toString() const override;
  916. virtual JsonNode toJsonNode() const override;
  917. template <typename Handler> void serialize(Handler &h, const int version)
  918. {
  919. h & static_cast<ILimiter&>(*this);
  920. h & creature;
  921. h & includeUpgrades;
  922. }
  923. };
  924. class DLL_LINKAGE HasAnotherBonusLimiter : public ILimiter //applies only to nodes that have another bonus working
  925. {
  926. public:
  927. Bonus::BonusType type;
  928. TBonusSubtype subtype;
  929. bool isSubtypeRelevant; //check for subtype only if this is true
  930. HasAnotherBonusLimiter(Bonus::BonusType bonus = Bonus::NONE);
  931. HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype);
  932. int limit(const BonusLimitationContext &context) const override;
  933. virtual std::string toString() const override;
  934. virtual JsonNode toJsonNode() const override;
  935. template <typename Handler> void serialize(Handler &h, const int version)
  936. {
  937. h & static_cast<ILimiter&>(*this);
  938. h & type;
  939. h & subtype;
  940. h & isSubtypeRelevant;
  941. }
  942. };
  943. class DLL_LINKAGE CreatureTerrainLimiter : public ILimiter //applies only to creatures that are on specified terrain, default native terrain
  944. {
  945. public:
  946. int terrainType;
  947. CreatureTerrainLimiter();
  948. CreatureTerrainLimiter(int TerrainType);
  949. int limit(const BonusLimitationContext &context) const override;
  950. virtual std::string toString() const override;
  951. virtual JsonNode toJsonNode() const override;
  952. template <typename Handler> void serialize(Handler &h, const int version)
  953. {
  954. h & static_cast<ILimiter&>(*this);
  955. h & terrainType;
  956. }
  957. };
  958. class DLL_LINKAGE CreatureFactionLimiter : public ILimiter //applies only to creatures of given faction
  959. {
  960. public:
  961. TFaction faction;
  962. CreatureFactionLimiter();
  963. CreatureFactionLimiter(TFaction faction);
  964. int limit(const BonusLimitationContext &context) const override;
  965. virtual std::string toString() const override;
  966. virtual JsonNode toJsonNode() const override;
  967. template <typename Handler> void serialize(Handler &h, const int version)
  968. {
  969. h & static_cast<ILimiter&>(*this);
  970. h & faction;
  971. }
  972. };
  973. class DLL_LINKAGE CreatureAlignmentLimiter : public ILimiter //applies only to creatures of given alignment
  974. {
  975. public:
  976. si8 alignment;
  977. CreatureAlignmentLimiter();
  978. CreatureAlignmentLimiter(si8 Alignment);
  979. int limit(const BonusLimitationContext &context) const override;
  980. virtual std::string toString() const override;
  981. virtual JsonNode toJsonNode() const override;
  982. template <typename Handler> void serialize(Handler &h, const int version)
  983. {
  984. h & static_cast<ILimiter&>(*this);
  985. h & alignment;
  986. }
  987. };
  988. class DLL_LINKAGE StackOwnerLimiter : public ILimiter //applies only to creatures of given alignment
  989. {
  990. public:
  991. PlayerColor owner;
  992. StackOwnerLimiter();
  993. StackOwnerLimiter(PlayerColor Owner);
  994. int limit(const BonusLimitationContext &context) const override;
  995. template <typename Handler> void serialize(Handler &h, const int version)
  996. {
  997. h & static_cast<ILimiter&>(*this);
  998. h & owner;
  999. }
  1000. };
  1001. class DLL_LINKAGE OppositeSideLimiter : public ILimiter //applies only to creatures of enemy army during combat
  1002. {
  1003. public:
  1004. PlayerColor owner;
  1005. OppositeSideLimiter();
  1006. OppositeSideLimiter(PlayerColor Owner);
  1007. int limit(const BonusLimitationContext &context) const override;
  1008. template <typename Handler> void serialize(Handler &h, const int version)
  1009. {
  1010. h & static_cast<ILimiter&>(*this);
  1011. h & owner;
  1012. }
  1013. };
  1014. class DLL_LINKAGE RankRangeLimiter : public ILimiter //applies to creatures with min <= Rank <= max
  1015. {
  1016. public:
  1017. ui8 minRank, maxRank;
  1018. RankRangeLimiter();
  1019. RankRangeLimiter(ui8 Min, ui8 Max = 255);
  1020. int limit(const BonusLimitationContext &context) const override;
  1021. template <typename Handler> void serialize(Handler &h, const int version)
  1022. {
  1023. h & static_cast<ILimiter&>(*this);
  1024. h & minRank;
  1025. h & maxRank;
  1026. }
  1027. };
  1028. namespace Selector
  1029. {
  1030. extern DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type();
  1031. extern DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype();
  1032. extern DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info();
  1033. extern DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType();
  1034. extern DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange();
  1035. extern DLL_LINKAGE CWillLastTurns turns;
  1036. extern DLL_LINKAGE CWillLastDays days;
  1037. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype);
  1038. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info);
  1039. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID);
  1040. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source);
  1041. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType);
  1042. /**
  1043. * Selects all bonuses
  1044. * Usage example: Selector::all.And(<functor>).And(<functor>)...)
  1045. */
  1046. extern DLL_LINKAGE CSelector all;
  1047. /**
  1048. * Selects nothing
  1049. * Usage example: Selector::none.Or(<functor>).Or(<functor>)...)
  1050. */
  1051. extern DLL_LINKAGE CSelector none;
  1052. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type);
  1053. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype);
  1054. }
  1055. extern DLL_LINKAGE const std::map<std::string, Bonus::BonusType> bonusNameMap;
  1056. extern DLL_LINKAGE const std::map<std::string, Bonus::ValueType> bonusValueMap;
  1057. extern DLL_LINKAGE const std::map<std::string, Bonus::BonusSource> bonusSourceMap;
  1058. extern DLL_LINKAGE const std::map<std::string, ui16> bonusDurationMap;
  1059. extern DLL_LINKAGE const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect;
  1060. extern DLL_LINKAGE const std::map<std::string, TLimiterPtr> bonusLimiterMap;
  1061. extern DLL_LINKAGE const std::map<std::string, TPropagatorPtr> bonusPropagatorMap;
  1062. extern DLL_LINKAGE const std::map<std::string, TUpdaterPtr> bonusUpdaterMap;
  1063. // BonusList template that requires full interface of CBonusSystemNode
  1064. template <class InputIterator>
  1065. void BonusList::insert(const int position, InputIterator first, InputIterator last)
  1066. {
  1067. bonuses.insert(bonuses.begin() + position, first, last);
  1068. changed();
  1069. }
  1070. // observers for updating bonuses based on certain events (e.g. hero gaining level)
  1071. class DLL_LINKAGE IUpdater
  1072. {
  1073. public:
  1074. virtual ~IUpdater();
  1075. virtual std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const;
  1076. virtual std::string toString() const;
  1077. virtual JsonNode toJsonNode() const;
  1078. template <typename Handler> void serialize(Handler & h, const int version)
  1079. {
  1080. }
  1081. };
  1082. class DLL_LINKAGE GrowsWithLevelUpdater : public IUpdater
  1083. {
  1084. public:
  1085. int valPer20;
  1086. int stepSize;
  1087. GrowsWithLevelUpdater();
  1088. GrowsWithLevelUpdater(int valPer20, int stepSize = 1);
  1089. template <typename Handler> void serialize(Handler & h, const int version)
  1090. {
  1091. h & static_cast<IUpdater &>(*this);
  1092. h & valPer20;
  1093. h & stepSize;
  1094. }
  1095. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1096. virtual std::string toString() const override;
  1097. virtual JsonNode toJsonNode() const override;
  1098. };
  1099. class DLL_LINKAGE TimesHeroLevelUpdater : public IUpdater
  1100. {
  1101. public:
  1102. TimesHeroLevelUpdater();
  1103. template <typename Handler> void serialize(Handler & h, const int version)
  1104. {
  1105. h & static_cast<IUpdater &>(*this);
  1106. }
  1107. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1108. virtual std::string toString() const override;
  1109. virtual JsonNode toJsonNode() const override;
  1110. };
  1111. class DLL_LINKAGE TimesStackLevelUpdater : public IUpdater
  1112. {
  1113. public:
  1114. TimesStackLevelUpdater();
  1115. template <typename Handler> void serialize(Handler & h, const int version)
  1116. {
  1117. h & static_cast<IUpdater &>(*this);
  1118. }
  1119. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const override;
  1120. virtual std::string toString() const override;
  1121. virtual JsonNode toJsonNode() const override;
  1122. };
  1123. class DLL_LINKAGE OwnerUpdater : public IUpdater
  1124. {
  1125. public:
  1126. OwnerUpdater();
  1127. template <typename Handler> void serialize(Handler& h, const int version)
  1128. {
  1129. h & static_cast<IUpdater &>(*this);
  1130. }
  1131. std::shared_ptr<Bonus> createUpdatedBonus(const std::shared_ptr<Bonus>& b, const CBonusSystemNode& context) const override;
  1132. virtual std::string toString() const override;
  1133. virtual JsonNode toJsonNode() const override;
  1134. };