HeroBonus.cpp 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848
  1. /*
  2. * HeroBonus.cpp, 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. #include "StdInc.h"
  11. #include "HeroBonus.h"
  12. #include "VCMI_Lib.h"
  13. #include "spells/CSpellHandler.h"
  14. #include "CCreatureHandler.h"
  15. #include "CCreatureSet.h"
  16. #include "CHeroHandler.h"
  17. #include "CGeneralTextHandler.h"
  18. #include "CSkillHandler.h"
  19. #include "CStack.h"
  20. #include "CArtHandler.h"
  21. #include "StringConstants.h"
  22. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  23. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  24. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  25. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  26. #define BONUS_NAME(x) { #x, Bonus::x },
  27. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  28. #undef BONUS_NAME
  29. #define BONUS_VALUE(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  31. #undef BONUS_VALUE
  32. #define BONUS_SOURCE(x) { #x, Bonus::x },
  33. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  34. #undef BONUS_SOURCE
  35. #define BONUS_ITEM(x) { #x, Bonus::x },
  36. const std::map<std::string, ui16> bonusDurationMap =
  37. {
  38. BONUS_ITEM(PERMANENT)
  39. BONUS_ITEM(ONE_BATTLE)
  40. BONUS_ITEM(ONE_DAY)
  41. BONUS_ITEM(ONE_WEEK)
  42. BONUS_ITEM(N_TURNS)
  43. BONUS_ITEM(N_DAYS)
  44. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  45. BONUS_ITEM(UNTIL_ATTACK)
  46. BONUS_ITEM(STACK_GETS_TURN)
  47. BONUS_ITEM(COMMANDER_KILLED)
  48. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  49. };
  50. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  51. {
  52. BONUS_ITEM(NO_LIMIT)
  53. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  54. BONUS_ITEM(ONLY_MELEE_FIGHT)
  55. BONUS_ITEM(ONLY_ENEMY_ARMY)
  56. };
  57. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  58. {
  59. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  60. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  61. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)}
  62. };
  63. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  64. {
  65. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  66. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  67. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  68. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  69. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  70. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  71. }; //untested
  72. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  73. {
  74. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  75. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()}
  76. };
  77. ///CBonusProxy
  78. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  79. : cachedLast(0),
  80. target(Target),
  81. selector(Selector),
  82. data()
  83. {
  84. }
  85. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  86. : cachedLast(other.cachedLast),
  87. target(other.target),
  88. selector(other.selector),
  89. data(other.data)
  90. {
  91. }
  92. CBonusProxy::CBonusProxy(CBonusProxy && other)
  93. : cachedLast(0),
  94. target(other.target),
  95. selector(),
  96. data()
  97. {
  98. std::swap(cachedLast, other.cachedLast);
  99. std::swap(selector, other.selector);
  100. std::swap(data, other.data);
  101. }
  102. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  103. {
  104. cachedLast = other.cachedLast;
  105. selector = other.selector;
  106. data = other.data;
  107. return *this;
  108. }
  109. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  110. {
  111. std::swap(cachedLast, other.cachedLast);
  112. std::swap(selector, other.selector);
  113. std::swap(data, other.data);
  114. return *this;
  115. }
  116. TBonusListPtr CBonusProxy::get() const
  117. {
  118. if(target->getTreeVersion() != cachedLast || !data)
  119. {
  120. //TODO: support limiters
  121. data = target->getAllBonuses(selector, Selector::all);
  122. data->eliminateDuplicates();
  123. cachedLast = target->getTreeVersion();
  124. }
  125. return data;
  126. }
  127. const BonusList * CBonusProxy::operator->() const
  128. {
  129. return get().get();
  130. }
  131. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  132. const bool CBonusSystemNode::cachingEnabled = true;
  133. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  134. {
  135. }
  136. BonusList::BonusList(const BonusList &bonusList)
  137. {
  138. bonuses.resize(bonusList.size());
  139. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  140. belongsToTree = false;
  141. }
  142. BonusList::BonusList(BonusList&& other):
  143. belongsToTree(false)
  144. {
  145. std::swap(belongsToTree, other.belongsToTree);
  146. std::swap(bonuses, other.bonuses);
  147. }
  148. BonusList& BonusList::operator=(const BonusList &bonusList)
  149. {
  150. bonuses.resize(bonusList.size());
  151. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  152. belongsToTree = false;
  153. return *this;
  154. }
  155. void BonusList::changed()
  156. {
  157. if(belongsToTree)
  158. CBonusSystemNode::treeHasChanged();
  159. }
  160. int BonusList::totalValue() const
  161. {
  162. int base = 0;
  163. int percentToBase = 0;
  164. int percentToAll = 0;
  165. int additive = 0;
  166. int indepMax = 0;
  167. bool hasIndepMax = false;
  168. int indepMin = 0;
  169. bool hasIndepMin = false;
  170. for (auto& b : bonuses)
  171. {
  172. switch(b->valType)
  173. {
  174. case Bonus::BASE_NUMBER:
  175. base += b->val;
  176. break;
  177. case Bonus::PERCENT_TO_ALL:
  178. percentToAll += b->val;
  179. break;
  180. case Bonus::PERCENT_TO_BASE:
  181. percentToBase += b->val;
  182. break;
  183. case Bonus::ADDITIVE_VALUE:
  184. additive += b->val;
  185. break;
  186. case Bonus::INDEPENDENT_MAX:
  187. if (!hasIndepMax)
  188. {
  189. indepMax = b->val;
  190. hasIndepMax = true;
  191. }
  192. else
  193. {
  194. vstd::amax(indepMax, b->val);
  195. }
  196. break;
  197. case Bonus::INDEPENDENT_MIN:
  198. if (!hasIndepMin)
  199. {
  200. indepMin = b->val;
  201. hasIndepMin = true;
  202. }
  203. else
  204. {
  205. vstd::amin(indepMin, b->val);
  206. }
  207. break;
  208. }
  209. }
  210. int modifiedBase = base + (base * percentToBase) / 100;
  211. modifiedBase += additive;
  212. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  213. if(hasIndepMin && hasIndepMax)
  214. assert(indepMin < indepMax);
  215. const int notIndepBonuses = boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  216. {
  217. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  218. });
  219. if (hasIndepMax)
  220. {
  221. if(notIndepBonuses)
  222. vstd::amax(valFirst, indepMax);
  223. else
  224. valFirst = indepMax;
  225. }
  226. if (hasIndepMin)
  227. {
  228. if(notIndepBonuses)
  229. vstd::amin(valFirst, indepMin);
  230. else
  231. valFirst = indepMin;
  232. }
  233. return valFirst;
  234. }
  235. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  236. {
  237. for (auto & b : bonuses)
  238. {
  239. if(select(b.get()))
  240. return b;
  241. }
  242. return nullptr;
  243. }
  244. const std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &selector) const
  245. {
  246. for (auto & b : bonuses)
  247. {
  248. if(selector(b.get()))
  249. return b;
  250. }
  251. return nullptr;
  252. }
  253. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  254. {
  255. getBonuses(out, selector, nullptr);
  256. }
  257. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  258. {
  259. for (auto & b : bonuses)
  260. {
  261. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  262. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  263. out.push_back(b);
  264. }
  265. }
  266. void BonusList::getAllBonuses(BonusList &out) const
  267. {
  268. for(auto & b : bonuses)
  269. out.push_back(b);
  270. }
  271. int BonusList::valOfBonuses(const CSelector &select) const
  272. {
  273. BonusList ret;
  274. CSelector limit = nullptr;
  275. getBonuses(ret, select, limit);
  276. ret.eliminateDuplicates();
  277. return ret.totalValue();
  278. }
  279. void BonusList::eliminateDuplicates()
  280. {
  281. sort( bonuses.begin(), bonuses.end() );
  282. bonuses.erase( unique( bonuses.begin(), bonuses.end() ), bonuses.end() );
  283. }
  284. void BonusList::push_back(std::shared_ptr<Bonus> x)
  285. {
  286. bonuses.push_back(x);
  287. changed();
  288. }
  289. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  290. {
  291. changed();
  292. return bonuses.erase(bonuses.begin() + position);
  293. }
  294. void BonusList::clear()
  295. {
  296. bonuses.clear();
  297. changed();
  298. }
  299. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  300. {
  301. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  302. if(itr == bonuses.end())
  303. return false;
  304. bonuses.erase(itr);
  305. changed();
  306. return true;
  307. }
  308. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  309. {
  310. bonuses.resize(sz, c);
  311. changed();
  312. }
  313. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  314. {
  315. bonuses.insert(position, n, x);
  316. changed();
  317. }
  318. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  319. {
  320. return valOfBonuses(Selector::type(type).And(selector));
  321. }
  322. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  323. {
  324. std::stringstream cachingStr;
  325. cachingStr << "type_" << type << "s_" << subtype;
  326. CSelector s = Selector::type(type);
  327. if(subtype != -1)
  328. s = s.And(Selector::subtype(subtype));
  329. return valOfBonuses(s, cachingStr.str());
  330. }
  331. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  332. {
  333. CSelector limit = nullptr;
  334. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  335. return hlp->totalValue();
  336. }
  337. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  338. {
  339. return getBonuses(selector, cachingStr)->size() > 0;
  340. }
  341. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  342. {
  343. return getBonuses(selector, limit, cachingStr)->size() > 0;
  344. }
  345. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  346. {
  347. std::stringstream cachingStr;
  348. cachingStr << "type_" << type << "s_" << subtype;
  349. CSelector s = Selector::type(type);
  350. if(subtype != -1)
  351. s = s.And(Selector::subtype(subtype));
  352. return hasBonus(s, cachingStr.str());
  353. }
  354. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  355. {
  356. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  357. }
  358. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  359. {
  360. return getAllBonuses(selector, limit, nullptr, cachingStr);
  361. }
  362. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  363. {
  364. std::stringstream cachingStr;
  365. cachingStr << "source_" << source << "id_" << sourceID;
  366. return hasBonus(Selector::source(source,sourceID), cachingStr.str());
  367. }
  368. int IBonusBearer::MoraleVal() const
  369. {
  370. if(hasBonusOfType(Bonus::NON_LIVING) || hasBonusOfType(Bonus::UNDEAD) ||
  371. hasBonusOfType(Bonus::NO_MORALE) || hasBonusOfType(Bonus::SIEGE_WEAPON))
  372. return 0;
  373. int ret = valOfBonuses(Bonus::MORALE);
  374. if(hasBonusOfType(Bonus::SELF_MORALE)) //eg. minotaur
  375. vstd::amax(ret, +1);
  376. return vstd::abetween(ret, -3, +3);
  377. }
  378. int IBonusBearer::LuckVal() const
  379. {
  380. if(hasBonusOfType(Bonus::NO_LUCK))
  381. return 0;
  382. int ret = valOfBonuses(Bonus::LUCK);
  383. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  384. vstd::amax(ret, +1);
  385. return vstd::abetween(ret, -3, +3);
  386. }
  387. ui32 IBonusBearer::MaxHealth() const
  388. {
  389. const std::string cachingStr = "type_STACK_HEALTH";
  390. static const auto selector = Selector::type(Bonus::STACK_HEALTH);
  391. auto value = valOfBonuses(selector, cachingStr);
  392. return std::max(1, value); //never 0
  393. }
  394. int IBonusBearer::getAttack(bool ranged) const
  395. {
  396. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  397. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  398. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  399. }
  400. int IBonusBearer::getDefence(bool ranged) const
  401. {
  402. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  403. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  404. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  405. }
  406. int IBonusBearer::getMinDamage(bool ranged) const
  407. {
  408. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  409. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  410. return valOfBonuses(selector, cachingStr);
  411. }
  412. int IBonusBearer::getMaxDamage(bool ranged) const
  413. {
  414. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  415. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  416. return valOfBonuses(selector, cachingStr);
  417. }
  418. si32 IBonusBearer::manaLimit() const
  419. {
  420. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  421. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  422. / 10.0);
  423. }
  424. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  425. {
  426. int ret = valOfBonuses(Bonus::PRIMARY_SKILL, id);
  427. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  428. return ret;
  429. }
  430. si32 IBonusBearer::magicResistance() const
  431. {
  432. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  433. }
  434. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  435. {
  436. //war machines cannot move
  437. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  438. {
  439. return 0;
  440. }
  441. //bind effect check - doesn't influence stack initiative
  442. if(useBind && hasBonus(Selector::type(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  443. {
  444. return 0;
  445. }
  446. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  447. }
  448. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  449. {
  450. std::stringstream cachingStr;
  451. cachingStr << "type_" << Bonus::UNDEAD << "s_-1Otype_" << Bonus::NON_LIVING << "s_-11type_" << Bonus::SIEGE_WEAPON; //I don't really get what string labels mean?
  452. return !hasBonus(Selector::type(Bonus::UNDEAD)
  453. .Or(Selector::type(Bonus::NON_LIVING))
  454. .Or(Selector::type(Bonus::SIEGE_WEAPON)), cachingStr.str());
  455. }
  456. const std::shared_ptr<Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  457. {
  458. auto bonuses = getAllBonuses(selector, Selector::all);
  459. return bonuses->getFirst(Selector::all);
  460. }
  461. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  462. {
  463. auto ret = bonuses.getFirst(selector);
  464. if(ret)
  465. return ret;
  466. FOREACH_PARENT(pname)
  467. {
  468. ret = pname->getBonusLocalFirst(selector);
  469. if (ret)
  470. return ret;
  471. }
  472. return nullptr;
  473. }
  474. const std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  475. {
  476. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  477. }
  478. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  479. {
  480. for (auto & elem : parents)
  481. {
  482. const CBonusSystemNode *parent = elem;
  483. out.insert(parent);
  484. }
  485. }
  486. void CBonusSystemNode::getParents(TNodes &out)
  487. {
  488. for (auto & elem : parents)
  489. {
  490. const CBonusSystemNode *parent = elem;
  491. out.insert(const_cast<CBonusSystemNode*>(parent));
  492. }
  493. }
  494. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  495. {
  496. BonusList beforeUpdate;
  497. FOREACH_CPARENT(p)
  498. {
  499. p->getBonusesRec(beforeUpdate, selector, limit);
  500. }
  501. bonuses.getBonuses(beforeUpdate, selector, limit);
  502. for(auto b : beforeUpdate)
  503. out.push_back(update(b));
  504. }
  505. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  506. {
  507. BonusList beforeUpdate;
  508. FOREACH_CPARENT(p)
  509. {
  510. p->getAllBonusesRec(beforeUpdate);
  511. }
  512. bonuses.getAllBonuses(beforeUpdate);
  513. for(auto b : beforeUpdate)
  514. out.push_back(update(b));
  515. }
  516. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  517. {
  518. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  519. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  520. {
  521. // Exclusive access for one thread
  522. static boost::mutex m;
  523. boost::mutex::scoped_lock lock(m);
  524. // If the bonus system tree changes(state of a single node or the relations to each other) then
  525. // cache all bonus objects. Selector objects doesn't matter.
  526. if (cachedLast != treeChanged)
  527. {
  528. cachedBonuses.clear();
  529. cachedRequests.clear();
  530. BonusList allBonuses;
  531. getAllBonusesRec(allBonuses);
  532. allBonuses.eliminateDuplicates();
  533. limitBonuses(allBonuses, cachedBonuses);
  534. cachedLast = treeChanged;
  535. }
  536. // If a bonus system request comes with a caching string then look up in the map if there are any
  537. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  538. if (cachingStr != "")
  539. {
  540. auto it = cachedRequests.find(cachingStr);
  541. if(it != cachedRequests.end())
  542. {
  543. //Cached list contains bonuses for our query with applied limiters
  544. return it->second;
  545. }
  546. }
  547. //We still don't have the bonuses (didn't returned them from cache)
  548. //Perform bonus selection
  549. auto ret = std::make_shared<BonusList>();
  550. cachedBonuses.getBonuses(*ret, selector, limit);
  551. // Save the results in the cache
  552. if(cachingStr != "")
  553. cachedRequests[cachingStr] = ret;
  554. return ret;
  555. }
  556. else
  557. {
  558. return getAllBonusesWithoutCaching(selector, limit, root);
  559. }
  560. }
  561. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  562. {
  563. auto ret = std::make_shared<BonusList>();
  564. // Get bonus results without caching enabled.
  565. BonusList beforeLimiting, afterLimiting;
  566. getAllBonusesRec(beforeLimiting);
  567. beforeLimiting.eliminateDuplicates();
  568. if(!root || root == this)
  569. {
  570. limitBonuses(beforeLimiting, afterLimiting);
  571. afterLimiting.getBonuses(*ret, selector, limit);
  572. }
  573. else if(root)
  574. {
  575. //We want to limit our query against an external node. We get all its bonuses,
  576. // add the ones we're considering and see if they're cut out by limiters
  577. BonusList rootBonuses, limitedRootBonuses;
  578. getAllBonusesRec(rootBonuses);
  579. for(auto b : beforeLimiting)
  580. rootBonuses.push_back(b);
  581. rootBonuses.eliminateDuplicates();
  582. root->limitBonuses(rootBonuses, limitedRootBonuses);
  583. for(auto b : beforeLimiting)
  584. if(vstd::contains(limitedRootBonuses, b))
  585. afterLimiting.push_back(b);
  586. afterLimiting.getBonuses(*ret, selector, limit);
  587. }
  588. return ret;
  589. }
  590. const std::shared_ptr<Bonus> CBonusSystemNode::update(const std::shared_ptr<Bonus> b) const
  591. {
  592. if(b->updater)
  593. return b->updater->update(b, *this);
  594. return b;
  595. }
  596. CBonusSystemNode::CBonusSystemNode()
  597. : bonuses(true),
  598. exportedBonuses(true),
  599. nodeType(UNKNOWN),
  600. cachedLast(0)
  601. {
  602. }
  603. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  604. : bonuses(true),
  605. exportedBonuses(true),
  606. nodeType(NodeType),
  607. cachedLast(0)
  608. {
  609. }
  610. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  611. bonuses(std::move(other.bonuses)),
  612. exportedBonuses(std::move(other.exportedBonuses)),
  613. nodeType(other.nodeType),
  614. description(other.description),
  615. cachedLast(0)
  616. {
  617. std::swap(parents, other.parents);
  618. std::swap(children, other.children);
  619. //fixing bonus tree without recalculation
  620. for(CBonusSystemNode * n : parents)
  621. {
  622. n->children -= &other;
  623. n->children.push_back(this);
  624. }
  625. for(CBonusSystemNode * n : children)
  626. {
  627. n->parents -= &other;
  628. n->parents.push_back(this);
  629. }
  630. //cache ignored
  631. //cachedBonuses
  632. //cachedRequests
  633. }
  634. CBonusSystemNode::~CBonusSystemNode()
  635. {
  636. detachFromAll();
  637. if(children.size())
  638. {
  639. while(children.size())
  640. children.front()->detachFrom(this);
  641. }
  642. }
  643. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  644. {
  645. assert(!vstd::contains(parents, parent));
  646. parents.push_back(parent);
  647. if(parent->actsAsBonusSourceOnly())
  648. parent->newRedDescendant(this);
  649. else
  650. newRedDescendant(parent);
  651. parent->newChildAttached(this);
  652. CBonusSystemNode::treeHasChanged();
  653. }
  654. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  655. {
  656. assert(vstd::contains(parents, parent));
  657. if(parent->actsAsBonusSourceOnly())
  658. parent->removedRedDescendant(this);
  659. else
  660. removedRedDescendant(parent);
  661. parents -= parent;
  662. parent->childDetached(this);
  663. CBonusSystemNode::treeHasChanged();
  664. }
  665. void CBonusSystemNode::removeBonusesRecursive(const CSelector &s)
  666. {
  667. BonusList bl;
  668. exportedBonuses.getBonuses(bl, s, Selector::all);
  669. for(auto b : bl)
  670. removeBonus(b);
  671. for(CBonusSystemNode *child : children)
  672. child->removeBonusesRecursive(s);
  673. }
  674. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  675. {
  676. BonusList bl;
  677. exportedBonuses.getBonuses(bl, s, Selector::all);
  678. for(auto b : bl)
  679. {
  680. b->turnsRemain--;
  681. if(b->turnsRemain <= 0)
  682. removeBonus(b);
  683. }
  684. for(CBonusSystemNode *child : children)
  685. child->reduceBonusDurations(s);
  686. }
  687. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  688. {
  689. //turnsRemain shouldn't be zero for following durations
  690. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  691. {
  692. assert(b->turnsRemain);
  693. }
  694. assert(!vstd::contains(exportedBonuses, b));
  695. exportedBonuses.push_back(b);
  696. exportBonus(b);
  697. CBonusSystemNode::treeHasChanged();
  698. }
  699. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  700. {
  701. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  702. if(bonus)
  703. bonus->val += b->val;
  704. else
  705. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  706. }
  707. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  708. {
  709. exportedBonuses -= b;
  710. if(b->propagator)
  711. unpropagateBonus(b);
  712. else
  713. bonuses -= b;
  714. CBonusSystemNode::treeHasChanged();
  715. }
  716. void CBonusSystemNode::removeBonuses(const CSelector &selector)
  717. {
  718. BonusList toRemove;
  719. exportedBonuses.getBonuses(toRemove, selector);
  720. for(auto bonus : toRemove)
  721. removeBonus(bonus);
  722. }
  723. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  724. {
  725. switch(nodeType)
  726. {
  727. case CREATURE:
  728. case ARTIFACT:
  729. case ARTIFACT_INSTANCE:
  730. return true;
  731. default:
  732. return false;
  733. }
  734. }
  735. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  736. {
  737. if(b->propagator->shouldBeAttached(this))
  738. {
  739. bonuses.push_back(b);
  740. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  741. }
  742. FOREACH_RED_CHILD(child)
  743. child->propagateBonus(b);
  744. }
  745. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  746. {
  747. if(b->propagator->shouldBeAttached(this))
  748. {
  749. bonuses -= b;
  750. while(vstd::contains(bonuses, b))
  751. {
  752. logBonus->error("Bonus was duplicated (%s) at %s", b->Description(), nodeName());
  753. bonuses -= b;
  754. }
  755. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  756. }
  757. FOREACH_RED_CHILD(child)
  758. child->unpropagateBonus(b);
  759. }
  760. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  761. {
  762. assert(!vstd::contains(children, child));
  763. children.push_back(child);
  764. }
  765. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  766. {
  767. if (vstd::contains(children, child))
  768. children -= child;
  769. else
  770. {
  771. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  772. throw std::runtime_error("internal error");
  773. }
  774. }
  775. void CBonusSystemNode::detachFromAll()
  776. {
  777. while(parents.size())
  778. detachFrom(parents.front());
  779. }
  780. bool CBonusSystemNode::isIndependentNode() const
  781. {
  782. return parents.empty() && children.empty();
  783. }
  784. std::string CBonusSystemNode::nodeName() const
  785. {
  786. return description.size()
  787. ? description
  788. : std::string("Bonus system node of type ") + typeid(*this).name();
  789. }
  790. void CBonusSystemNode::deserializationFix()
  791. {
  792. exportBonuses();
  793. }
  794. void CBonusSystemNode::getRedParents(TNodes &out)
  795. {
  796. FOREACH_PARENT(pname)
  797. {
  798. if(pname->actsAsBonusSourceOnly())
  799. {
  800. out.insert(pname);
  801. }
  802. }
  803. if(!actsAsBonusSourceOnly())
  804. {
  805. for(CBonusSystemNode *child : children)
  806. {
  807. out.insert(child);
  808. }
  809. }
  810. }
  811. void CBonusSystemNode::getRedChildren(TNodes &out)
  812. {
  813. FOREACH_PARENT(pname)
  814. {
  815. if(!pname->actsAsBonusSourceOnly())
  816. {
  817. out.insert(pname);
  818. }
  819. }
  820. if(actsAsBonusSourceOnly())
  821. {
  822. for(CBonusSystemNode *child : children)
  823. {
  824. out.insert(child);
  825. }
  826. }
  827. }
  828. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  829. {
  830. for(auto b : exportedBonuses)
  831. if(b->propagator)
  832. descendant->propagateBonus(b);
  833. FOREACH_RED_PARENT(parent)
  834. parent->newRedDescendant(descendant);
  835. }
  836. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  837. {
  838. for(auto b : exportedBonuses)
  839. if(b->propagator)
  840. descendant->unpropagateBonus(b);
  841. FOREACH_RED_PARENT(parent)
  842. parent->removedRedDescendant(descendant);
  843. }
  844. void CBonusSystemNode::getRedAncestors(TNodes &out)
  845. {
  846. getRedParents(out);
  847. FOREACH_RED_PARENT(p)
  848. p->getRedAncestors(out);
  849. }
  850. void CBonusSystemNode::getRedDescendants(TNodes &out)
  851. {
  852. getRedChildren(out);
  853. FOREACH_RED_CHILD(c)
  854. c->getRedChildren(out);
  855. }
  856. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  857. {
  858. if(b->propagator)
  859. propagateBonus(b);
  860. else
  861. bonuses.push_back(b);
  862. CBonusSystemNode::treeHasChanged();
  863. }
  864. void CBonusSystemNode::exportBonuses()
  865. {
  866. for(auto b : exportedBonuses)
  867. exportBonus(b);
  868. }
  869. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  870. {
  871. return nodeType;
  872. }
  873. const BonusList& CBonusSystemNode::getBonusList() const
  874. {
  875. return bonuses;
  876. }
  877. const TNodesVector& CBonusSystemNode::getParentNodes() const
  878. {
  879. return parents;
  880. }
  881. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  882. {
  883. return children;
  884. }
  885. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  886. {
  887. nodeType = type;
  888. }
  889. BonusList& CBonusSystemNode::getExportedBonusList()
  890. {
  891. return exportedBonuses;
  892. }
  893. const std::string& CBonusSystemNode::getDescription() const
  894. {
  895. return description;
  896. }
  897. void CBonusSystemNode::setDescription(const std::string &description)
  898. {
  899. this->description = description;
  900. }
  901. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  902. {
  903. assert(&allBonuses != &out); //todo should it work in-place?
  904. BonusList undecided = allBonuses,
  905. &accepted = out;
  906. while(true)
  907. {
  908. int undecidedCount = undecided.size();
  909. for(int i = 0; i < undecided.size(); i++)
  910. {
  911. auto b = undecided[i];
  912. BonusLimitationContext context = {b, *this, out};
  913. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  914. if(decision == ILimiter::DISCARD)
  915. {
  916. undecided.erase(i);
  917. i--; continue;
  918. }
  919. else if(decision == ILimiter::ACCEPT)
  920. {
  921. accepted.push_back(b);
  922. undecided.erase(i);
  923. i--; continue;
  924. }
  925. else
  926. assert(decision == ILimiter::NOT_SURE);
  927. }
  928. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  929. return;
  930. }
  931. }
  932. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  933. {
  934. auto ret = std::make_shared<BonusList>();
  935. limitBonuses(allBonuses, *ret);
  936. return ret;
  937. }
  938. void CBonusSystemNode::treeHasChanged()
  939. {
  940. treeChanged++;
  941. }
  942. int64_t CBonusSystemNode::getTreeVersion() const
  943. {
  944. int64_t ret = treeChanged;
  945. return ret << 32;
  946. }
  947. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  948. {
  949. if(obj)
  950. return obj->valOfBonuses(type, subtype);
  951. return 0;
  952. }
  953. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  954. {
  955. if(obj)
  956. return obj->hasBonusOfType(type, subtype);
  957. return false;
  958. }
  959. std::string Bonus::Description() const
  960. {
  961. std::ostringstream str;
  962. if(description.empty())
  963. switch(source)
  964. {
  965. case ARTIFACT:
  966. str << VLC->arth->artifacts[sid]->Name();
  967. break;
  968. case SPELL_EFFECT:
  969. str << SpellID(sid).toSpell()->name;
  970. break;
  971. case CREATURE_ABILITY:
  972. str << VLC->creh->creatures[sid]->namePl;
  973. break;
  974. case SECONDARY_SKILL:
  975. str << VLC->skillh->skillName(sid);
  976. break;
  977. default:
  978. //todo: handle all possible sources
  979. str << "Unknown";
  980. break;
  981. }
  982. else
  983. str << description;
  984. if(val != 0)
  985. str << " " << std::showpos << val;
  986. return str.str();
  987. }
  988. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  989. {
  990. switch(type)
  991. {
  992. case Bonus::PRIMARY_SKILL:
  993. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  994. case Bonus::SECONDARY_SKILL_PREMY:
  995. return JsonUtils::stringNode("skill." + NSecondarySkill::names[subtype]);
  996. case Bonus::SPECIAL_SPELL_LEV:
  997. case Bonus::SPECIFIC_SPELL_DAMAGE:
  998. case Bonus::SPECIAL_BLESS_DAMAGE:
  999. case Bonus::MAXED_SPELL:
  1000. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1001. return JsonUtils::stringNode("spell." + (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  1002. case Bonus::SPECIAL_UPGRADE:
  1003. return JsonUtils::stringNode("creature." + CreatureID::encode(subtype));
  1004. case Bonus::GENERATE_RESOURCE:
  1005. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1006. default:
  1007. return JsonUtils::intNode(subtype);
  1008. }
  1009. }
  1010. JsonNode additionalInfoToJson(Bonus::BonusType type, int addInfo)
  1011. {
  1012. switch(type)
  1013. {
  1014. case Bonus::SPECIAL_UPGRADE:
  1015. return JsonUtils::stringNode("creature." + CreatureID::encode(addInfo));
  1016. default:
  1017. return JsonUtils::intNode(addInfo);
  1018. }
  1019. }
  1020. JsonNode Bonus::toJsonNode() const
  1021. {
  1022. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1023. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1024. if(subtype != -1)
  1025. root["subtype"] = subtypeToJson(type, subtype);
  1026. if(additionalInfo != -1)
  1027. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1028. if(val != 0)
  1029. root["val"].Integer() = val;
  1030. if(valType != ADDITIVE_VALUE)
  1031. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1032. if(limiter)
  1033. root["limiters"].Vector().push_back(limiter->toJsonNode());
  1034. if(updater)
  1035. root["updater"] = updater->toJsonNode();
  1036. return root;
  1037. }
  1038. std::string Bonus::nameForBonus() const
  1039. {
  1040. switch(type)
  1041. {
  1042. case Bonus::PRIMARY_SKILL:
  1043. return PrimarySkill::names[subtype];
  1044. case Bonus::SECONDARY_SKILL_PREMY:
  1045. return NSecondarySkill::names[subtype];
  1046. case Bonus::SPECIAL_SPELL_LEV:
  1047. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1048. case Bonus::SPECIAL_BLESS_DAMAGE:
  1049. case Bonus::MAXED_SPELL:
  1050. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1051. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1052. case Bonus::SPECIAL_UPGRADE:
  1053. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo);
  1054. case Bonus::GENERATE_RESOURCE:
  1055. return GameConstants::RESOURCE_NAMES[subtype];
  1056. case Bonus::STACKS_SPEED:
  1057. return "speed";
  1058. default:
  1059. return vstd::findKey(bonusNameMap, type);
  1060. }
  1061. }
  1062. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1063. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1064. {
  1065. additionalInfo = -1;
  1066. turnsRemain = 0;
  1067. valType = ADDITIVE_VALUE;
  1068. effectRange = NO_LIMIT;
  1069. boost::algorithm::trim(description);
  1070. }
  1071. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1072. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1073. {
  1074. additionalInfo = -1;
  1075. turnsRemain = 0;
  1076. effectRange = NO_LIMIT;
  1077. }
  1078. Bonus::Bonus()
  1079. {
  1080. duration = PERMANENT;
  1081. turnsRemain = 0;
  1082. type = NONE;
  1083. subtype = -1;
  1084. additionalInfo = -1;
  1085. valType = ADDITIVE_VALUE;
  1086. effectRange = NO_LIMIT;
  1087. val = 0;
  1088. source = OTHER;
  1089. sid = 0;
  1090. }
  1091. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1092. {
  1093. propagator = Propagator;
  1094. return this->shared_from_this();
  1095. }
  1096. namespace Selector
  1097. {
  1098. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1099. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1100. DLL_LINKAGE CSelectFieldEqual<si32> info(&Bonus::additionalInfo);
  1101. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1102. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1103. DLL_LINKAGE CWillLastTurns turns;
  1104. DLL_LINKAGE CWillLastDays days;
  1105. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1106. {
  1107. return type(Type).And(subtype(Subtype));
  1108. }
  1109. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, si32 info)
  1110. {
  1111. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1112. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1113. .And(CSelectFieldEqual<si32>(&Bonus::additionalInfo)(info));
  1114. }
  1115. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1116. {
  1117. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1118. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1119. }
  1120. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1121. {
  1122. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1123. }
  1124. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1125. {
  1126. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1127. }
  1128. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1129. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1130. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1131. {
  1132. Bonus dummy;
  1133. dummy.type = type;
  1134. return sel(&dummy);
  1135. }
  1136. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1137. {
  1138. Bonus dummy;
  1139. dummy.type = type;
  1140. dummy.subtype = subtype;
  1141. return sel(&dummy);
  1142. }
  1143. }
  1144. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1145. {
  1146. switch(node->getNodeType())
  1147. {
  1148. case CBonusSystemNode::STACK_BATTLE:
  1149. return static_cast<const CStack*>(node);
  1150. default:
  1151. return nullptr;
  1152. }
  1153. }
  1154. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1155. {
  1156. switch(node->getNodeType())
  1157. {
  1158. case CBonusSystemNode::STACK_INSTANCE:
  1159. return (static_cast<const CStackInstance *>(node));
  1160. case CBonusSystemNode::STACK_BATTLE:
  1161. return (static_cast<const CStack*>(node))->base;
  1162. default:
  1163. return nullptr;
  1164. }
  1165. }
  1166. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1167. {
  1168. switch(node->getNodeType())
  1169. {
  1170. case CBonusSystemNode::CREATURE:
  1171. return (static_cast<const CCreature *>(node));
  1172. case CBonusSystemNode::STACK_BATTLE:
  1173. return (static_cast<const CStack*>(node))->type;
  1174. default:
  1175. const CStackInstance * csi = retrieveStackInstance(node);
  1176. if(csi)
  1177. return csi->type;
  1178. return nullptr;
  1179. }
  1180. }
  1181. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1182. {
  1183. for (ui32 i = 0; i < bonusList.size(); i++)
  1184. {
  1185. auto b = bonusList[i];
  1186. out << "Bonus " << i << "\n" << *b << std::endl;
  1187. }
  1188. return out;
  1189. }
  1190. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1191. {
  1192. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1193. if(i->second == bonus.type)
  1194. out << "\tType: " << i->first << " \t";
  1195. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1196. printField(val);
  1197. printField(subtype);
  1198. printField(duration);
  1199. printField(source);
  1200. printField(sid);
  1201. printField(additionalInfo);
  1202. printField(turnsRemain);
  1203. printField(valType);
  1204. printField(effectRange);
  1205. #undef printField
  1206. if(bonus.limiter)
  1207. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1208. if(bonus.updater)
  1209. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1210. return out;
  1211. }
  1212. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1213. {
  1214. if (limiter)
  1215. {
  1216. //If we already have limiter list, retrieve it
  1217. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1218. if(!limiterList)
  1219. {
  1220. //Create a new limiter list with old limiter and the new one will be pushed later
  1221. limiterList = std::make_shared<LimiterList>();
  1222. limiterList->add(limiter);
  1223. limiter = limiterList;
  1224. }
  1225. limiterList->add(Limiter);
  1226. }
  1227. else
  1228. {
  1229. limiter = Limiter;
  1230. }
  1231. return this->shared_from_this();
  1232. }
  1233. ILimiter::~ILimiter()
  1234. {
  1235. }
  1236. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1237. {
  1238. return false;
  1239. }
  1240. std::string ILimiter::toString() const
  1241. {
  1242. return typeid(*this).name();
  1243. }
  1244. JsonNode ILimiter::toJsonNode() const
  1245. {
  1246. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1247. root["type"].String() = toString();
  1248. return root;
  1249. }
  1250. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1251. {
  1252. const CCreature *c = retrieveCreature(&context.node);
  1253. if(!c)
  1254. return true;
  1255. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1256. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1257. }
  1258. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1259. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1260. {
  1261. }
  1262. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1263. {
  1264. creature = nullptr;
  1265. includeUpgrades = false;
  1266. }
  1267. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1268. {
  1269. creature = VLC->creh->creatures[id];
  1270. }
  1271. std::string CCreatureTypeLimiter::toString() const
  1272. {
  1273. char buf[100];
  1274. sprintf(buf, "CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)",
  1275. creature->identifier.c_str(),
  1276. (includeUpgrades ? "true" : "false"));
  1277. return std::string(buf);
  1278. }
  1279. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1280. {
  1281. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1282. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1283. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1284. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1285. return root;
  1286. }
  1287. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1288. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1289. {
  1290. }
  1291. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1292. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1293. {
  1294. }
  1295. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1296. {
  1297. CSelector mySelector = isSubtypeRelevant
  1298. ? Selector::typeSubtype(type, subtype)
  1299. : Selector::type(type);
  1300. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1301. if(context.alreadyAccepted.getFirst(mySelector))
  1302. return ACCEPT;
  1303. //do not accept for now but it may change if more bonuses gets included
  1304. return NOT_SURE;
  1305. }
  1306. std::string HasAnotherBonusLimiter::toString() const
  1307. {
  1308. char buf[100];
  1309. std::string typeName = vstd::findKey(bonusNameMap, type);
  1310. if(isSubtypeRelevant)
  1311. sprintf(buf, "HasAnotherBonusLimiter(type=%s, subtype=%d)", typeName.c_str(), subtype);
  1312. else
  1313. sprintf(buf, "HasAnotherBonusLimiter(type=%s)", typeName.c_str());
  1314. return std::string(buf);
  1315. }
  1316. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1317. {
  1318. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1319. std::string typeName = vstd::findKey(bonusNameMap, type);
  1320. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1321. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1322. if(isSubtypeRelevant)
  1323. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1324. return root;
  1325. }
  1326. IPropagator::~IPropagator()
  1327. {
  1328. }
  1329. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1330. {
  1331. return false;
  1332. }
  1333. CPropagatorNodeType::CPropagatorNodeType()
  1334. :nodeType(0)
  1335. {
  1336. }
  1337. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1338. : nodeType(NodeType)
  1339. {
  1340. }
  1341. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1342. {
  1343. return nodeType == dest->getNodeType();
  1344. }
  1345. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1346. : terrainType(TerrainType)
  1347. {
  1348. }
  1349. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1350. : terrainType(-1)
  1351. {
  1352. }
  1353. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1354. {
  1355. const CCreature *c = retrieveCreature(&context.node);
  1356. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1357. //TODO neutral creatues
  1358. }
  1359. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1360. : faction(Faction)
  1361. {
  1362. }
  1363. CreatureFactionLimiter::CreatureFactionLimiter()
  1364. : faction(-1)
  1365. {
  1366. }
  1367. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1368. {
  1369. const CCreature *c = retrieveCreature(&context.node);
  1370. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1371. }
  1372. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1373. : alignment(-1)
  1374. {
  1375. }
  1376. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1377. : alignment(Alignment)
  1378. {
  1379. }
  1380. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1381. {
  1382. const CCreature *c = retrieveCreature(&context.node);
  1383. if(!c)
  1384. return true;
  1385. switch(alignment)
  1386. {
  1387. case EAlignment::GOOD:
  1388. return !c->isGood(); //if not good -> return true (drop bonus)
  1389. case EAlignment::NEUTRAL:
  1390. return c->isEvil() || c->isGood();
  1391. case EAlignment::EVIL:
  1392. return !c->isEvil();
  1393. default:
  1394. logBonus->warn("Warning: illegal alignment in limiter!");
  1395. return true;
  1396. }
  1397. }
  1398. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1399. :minRank(Min), maxRank(Max)
  1400. {
  1401. }
  1402. RankRangeLimiter::RankRangeLimiter()
  1403. {
  1404. minRank = maxRank = -1;
  1405. }
  1406. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1407. {
  1408. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1409. if(csi)
  1410. {
  1411. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1412. return true;
  1413. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1414. }
  1415. return true;
  1416. }
  1417. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1418. {
  1419. const CStack * s = retrieveStackBattle(&context.node);
  1420. if(s)
  1421. return s->owner != owner;
  1422. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1423. if(csi && csi->armyObj)
  1424. return csi->armyObj->tempOwner != owner;
  1425. return true;
  1426. }
  1427. StackOwnerLimiter::StackOwnerLimiter()
  1428. : owner(-1)
  1429. {
  1430. }
  1431. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1432. : owner(Owner)
  1433. {
  1434. }
  1435. int LimiterList::limit( const BonusLimitationContext &context ) const
  1436. {
  1437. bool wasntSure = false;
  1438. for(auto limiter : limiters)
  1439. {
  1440. auto result = limiter->limit(context);
  1441. if(result == ILimiter::DISCARD)
  1442. return result;
  1443. if(result == ILimiter::NOT_SURE)
  1444. wasntSure = true;
  1445. }
  1446. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1447. }
  1448. void LimiterList::add( TLimiterPtr limiter )
  1449. {
  1450. limiters.push_back(limiter);
  1451. }
  1452. // Updaters
  1453. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1454. {
  1455. updater = Updater;
  1456. return this->shared_from_this();
  1457. }
  1458. IUpdater::~IUpdater()
  1459. {
  1460. }
  1461. const std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1462. {
  1463. return b;
  1464. }
  1465. std::string IUpdater::toString() const
  1466. {
  1467. return typeid(*this).name();
  1468. }
  1469. JsonNode IUpdater::toJsonNode() const
  1470. {
  1471. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1472. }
  1473. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1474. {
  1475. }
  1476. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1477. {
  1478. }
  1479. const std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1480. {
  1481. if(context.getNodeType() == CBonusSystemNode::HERO)
  1482. {
  1483. int level = static_cast<const CGHeroInstance &>(context).level;
  1484. int steps = stepSize ? level / stepSize : level;
  1485. //rounding follows format for HMM3 creature specialty bonus
  1486. int newVal = (valPer20 * steps + 19) / 20;
  1487. //return copy of bonus with updated val
  1488. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1489. newBonus->val = newVal;
  1490. return newBonus;
  1491. }
  1492. return b;
  1493. }
  1494. std::string GrowsWithLevelUpdater::toString() const
  1495. {
  1496. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1497. }
  1498. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1499. {
  1500. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1501. root["type"].String() = "GROWS_WITH_LEVEL";
  1502. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1503. if(stepSize > 1)
  1504. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1505. return root;
  1506. }
  1507. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1508. {
  1509. }
  1510. const std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1511. {
  1512. if(context.getNodeType() == CBonusSystemNode::HERO)
  1513. {
  1514. int level = static_cast<const CGHeroInstance &>(context).level;
  1515. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1516. newBonus->val *= level;
  1517. return newBonus;
  1518. }
  1519. return b;
  1520. }
  1521. std::string TimesHeroLevelUpdater::toString() const
  1522. {
  1523. return "TimesHeroLevelUpdater";
  1524. }
  1525. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1526. {
  1527. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1528. }
  1529. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1530. {
  1531. }
  1532. const std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1533. {
  1534. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1535. {
  1536. int level = static_cast<const CStackInstance &>(context).getLevel();
  1537. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1538. newBonus->val *= level;
  1539. return newBonus;
  1540. }
  1541. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1542. {
  1543. const CStack & stack = static_cast<const CStack &>(context);
  1544. //only update if stack doesn't have an instance (summons, war machines)
  1545. //otherwise we'd end up multiplying twice
  1546. if(stack.base == nullptr)
  1547. {
  1548. int level = stack.type->level;
  1549. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1550. newBonus->val *= level;
  1551. return newBonus;
  1552. }
  1553. }
  1554. return b;
  1555. }
  1556. std::string TimesStackLevelUpdater::toString() const
  1557. {
  1558. return "TimesStackLevelUpdater";
  1559. }
  1560. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1561. {
  1562. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1563. }