HeroBonus.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202
  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 "ILimiter.h"
  13. #include "../VCMI_Lib.h"
  14. #include "../spells/CSpellHandler.h"
  15. #include "../CCreatureHandler.h"
  16. #include "../CCreatureSet.h"
  17. #include "../CHeroHandler.h"
  18. #include "../CTownHandler.h"
  19. #include "../CGeneralTextHandler.h"
  20. #include "../CSkillHandler.h"
  21. #include "../CStack.h"
  22. #include "../CArtHandler.h"
  23. #include "../CModHandler.h"
  24. #include "../TerrainHandler.h"
  25. #include "../StringConstants.h"
  26. #include "../battle/BattleInfo.h"
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  29. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  30. #define BONUS_NAME(x) { #x, Bonus::x },
  31. const std::map<std::string, Bonus::BonusType> bonusNameMap = {
  32. BONUS_LIST
  33. };
  34. #undef BONUS_NAME
  35. #define BONUS_VALUE(x) { #x, Bonus::x },
  36. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  37. #undef BONUS_VALUE
  38. #define BONUS_SOURCE(x) { #x, Bonus::x },
  39. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  40. #undef BONUS_SOURCE
  41. #define BONUS_ITEM(x) { #x, Bonus::x },
  42. const std::map<std::string, ui16> bonusDurationMap =
  43. {
  44. BONUS_ITEM(PERMANENT)
  45. BONUS_ITEM(ONE_BATTLE)
  46. BONUS_ITEM(ONE_DAY)
  47. BONUS_ITEM(ONE_WEEK)
  48. BONUS_ITEM(N_TURNS)
  49. BONUS_ITEM(N_DAYS)
  50. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  51. BONUS_ITEM(UNTIL_ATTACK)
  52. BONUS_ITEM(STACK_GETS_TURN)
  53. BONUS_ITEM(COMMANDER_KILLED)
  54. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  55. };
  56. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  57. {
  58. BONUS_ITEM(NO_LIMIT)
  59. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  60. BONUS_ITEM(ONLY_MELEE_FIGHT)
  61. };
  62. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  63. {
  64. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  65. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  66. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  67. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  68. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  69. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  70. }; //untested
  71. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  72. {
  73. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  74. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()},
  75. {"ARMY_MOVEMENT", std::make_shared<ArmyMovementUpdater>()},
  76. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>()}
  77. };
  78. const std::set<std::string> deprecatedBonusSet = {
  79. "SECONDARY_SKILL_PREMY",
  80. "SECONDARY_SKILL_VAL2",
  81. "MAXED_SPELL",
  82. "LAND_MOVEMENT",
  83. "SEA_MOVEMENT",
  84. "SIGHT_RADIOUS",
  85. "NO_TYPE",
  86. "SPECIAL_SECONDARY_SKILL",
  87. "FULL_HP_REGENERATION",
  88. "KING1",
  89. "KING2",
  90. "KING3",
  91. "BLOCK_MORALE",
  92. "BLOCK_LUCK",
  93. "SELF_MORALE",
  94. "SELF_LUCK"
  95. };
  96. ///CBonusProxy
  97. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector):
  98. bonusListCachedLast(0),
  99. target(Target),
  100. selector(std::move(Selector)),
  101. currentBonusListIndex(0)
  102. {
  103. }
  104. CBonusProxy::CBonusProxy(const CBonusProxy & other):
  105. bonusListCachedLast(other.bonusListCachedLast),
  106. target(other.target),
  107. selector(other.selector),
  108. currentBonusListIndex(other.currentBonusListIndex)
  109. {
  110. bonusList[currentBonusListIndex] = other.bonusList[currentBonusListIndex];
  111. }
  112. CBonusProxy::CBonusProxy(CBonusProxy && other) noexcept:
  113. bonusListCachedLast(0),
  114. target(other.target),
  115. currentBonusListIndex(0)
  116. {
  117. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  118. std::swap(selector, other.selector);
  119. std::swap(bonusList, other.bonusList);
  120. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  121. }
  122. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  123. {
  124. boost::lock_guard<boost::mutex> lock(swapGuard);
  125. selector = other.selector;
  126. swapBonusList(other.bonusList[other.currentBonusListIndex]);
  127. bonusListCachedLast = other.bonusListCachedLast;
  128. return *this;
  129. }
  130. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other) noexcept
  131. {
  132. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  133. std::swap(selector, other.selector);
  134. std::swap(bonusList, other.bonusList);
  135. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  136. return *this;
  137. }
  138. void CBonusProxy::swapBonusList(TConstBonusListPtr other) const
  139. {
  140. // The idea here is to avoid changing active bonusList while it can be read by a different thread.
  141. // Because such use of shared ptr is not thread safe
  142. // So to avoid this we change the second offline instance and swap active index
  143. auto newCurrent = 1 - currentBonusListIndex;
  144. bonusList[newCurrent] = std::move(other);
  145. currentBonusListIndex = newCurrent;
  146. }
  147. TConstBonusListPtr CBonusProxy::getBonusList() const
  148. {
  149. auto needUpdateBonusList = [&]() -> bool
  150. {
  151. return target->getTreeVersion() != bonusListCachedLast || !bonusList[currentBonusListIndex];
  152. };
  153. // avoid locking if everything is up-to-date
  154. if(needUpdateBonusList())
  155. {
  156. boost::lock_guard<boost::mutex>lock(swapGuard);
  157. if(needUpdateBonusList())
  158. {
  159. //TODO: support limiters
  160. swapBonusList(target->getAllBonuses(selector, Selector::all));
  161. bonusListCachedLast = target->getTreeVersion();
  162. }
  163. }
  164. return bonusList[currentBonusListIndex];
  165. }
  166. const BonusList * CBonusProxy::operator->() const
  167. {
  168. return getBonusList().get();
  169. }
  170. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue):
  171. CBonusProxy(Target, std::move(Selector)),
  172. initialValue(InitialValue),
  173. meleeCachedLast(0),
  174. meleeValue(0),
  175. rangedCachedLast(0),
  176. rangedValue(0)
  177. {
  178. }
  179. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  180. : CBonusProxy(other),
  181. initialValue(other.initialValue),
  182. meleeCachedLast(other.meleeCachedLast),
  183. meleeValue(other.meleeValue),
  184. rangedCachedLast(other.rangedCachedLast),
  185. rangedValue(other.rangedValue)
  186. {
  187. }
  188. int CTotalsProxy::getValue() const
  189. {
  190. const auto treeVersion = target->getTreeVersion();
  191. if(treeVersion != valueCachedLast)
  192. {
  193. auto bonuses = getBonusList();
  194. value = initialValue + bonuses->totalValue();
  195. valueCachedLast = treeVersion;
  196. }
  197. return value;
  198. }
  199. int CTotalsProxy::getValueAndList(TConstBonusListPtr & outBonusList) const
  200. {
  201. const auto treeVersion = target->getTreeVersion();
  202. outBonusList = getBonusList();
  203. if(treeVersion != valueCachedLast)
  204. {
  205. value = initialValue + outBonusList->totalValue();
  206. valueCachedLast = treeVersion;
  207. }
  208. return value;
  209. }
  210. int CTotalsProxy::getMeleeValue() const
  211. {
  212. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT));
  213. const auto treeVersion = target->getTreeVersion();
  214. if(treeVersion != meleeCachedLast)
  215. {
  216. auto bonuses = target->getBonuses(selector, limit);
  217. meleeValue = initialValue + bonuses->totalValue();
  218. meleeCachedLast = treeVersion;
  219. }
  220. return meleeValue;
  221. }
  222. int CTotalsProxy::getRangedValue() const
  223. {
  224. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT));
  225. const auto treeVersion = target->getTreeVersion();
  226. if(treeVersion != rangedCachedLast)
  227. {
  228. auto bonuses = target->getBonuses(selector, limit);
  229. rangedValue = initialValue + bonuses->totalValue();
  230. rangedCachedLast = treeVersion;
  231. }
  232. return rangedValue;
  233. }
  234. ///CCheckProxy
  235. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector):
  236. target(Target),
  237. selector(std::move(Selector)),
  238. cachedLast(0),
  239. hasBonus(false)
  240. {
  241. }
  242. //This constructor should be placed here to avoid side effects
  243. CCheckProxy::CCheckProxy(const CCheckProxy & other) = default;
  244. bool CCheckProxy::getHasBonus() const
  245. {
  246. const auto treeVersion = target->getTreeVersion();
  247. if(treeVersion != cachedLast)
  248. {
  249. hasBonus = target->hasBonus(selector);
  250. cachedLast = treeVersion;
  251. }
  252. return hasBonus;
  253. }
  254. //This constructor should be placed here to avoid side effects
  255. CAddInfo::CAddInfo() = default;
  256. CAddInfo::CAddInfo(si32 value)
  257. {
  258. if(value != CAddInfo::NONE)
  259. push_back(value);
  260. }
  261. bool CAddInfo::operator==(si32 value) const
  262. {
  263. switch(size())
  264. {
  265. case 0:
  266. return value == CAddInfo::NONE;
  267. case 1:
  268. return operator[](0) == value;
  269. default:
  270. return false;
  271. }
  272. }
  273. bool CAddInfo::operator!=(si32 value) const
  274. {
  275. return !operator==(value);
  276. }
  277. si32 & CAddInfo::operator[](size_type pos)
  278. {
  279. if(pos >= size())
  280. resize(pos + 1, CAddInfo::NONE);
  281. return vector::operator[](pos);
  282. }
  283. si32 CAddInfo::operator[](size_type pos) const
  284. {
  285. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  286. }
  287. std::string CAddInfo::toString() const
  288. {
  289. return toJsonNode().toJson(true);
  290. }
  291. JsonNode CAddInfo::toJsonNode() const
  292. {
  293. if(size() < 2)
  294. {
  295. return JsonUtils::intNode(operator[](0));
  296. }
  297. else
  298. {
  299. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  300. for(si32 value : *this)
  301. node.Vector().push_back(JsonUtils::intNode(value));
  302. return node;
  303. }
  304. }
  305. std::atomic<int64_t> CBonusSystemNode::treeChanged(1);
  306. constexpr bool CBonusSystemNode::cachingEnabled = true;
  307. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  308. {
  309. }
  310. BonusList::BonusList(const BonusList & bonusList): belongsToTree(false)
  311. {
  312. bonuses.resize(bonusList.size());
  313. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  314. }
  315. BonusList::BonusList(BonusList && other) noexcept: belongsToTree(false)
  316. {
  317. std::swap(belongsToTree, other.belongsToTree);
  318. std::swap(bonuses, other.bonuses);
  319. }
  320. BonusList& BonusList::operator=(const BonusList &bonusList)
  321. {
  322. bonuses.resize(bonusList.size());
  323. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  324. belongsToTree = false;
  325. return *this;
  326. }
  327. void BonusList::changed() const
  328. {
  329. if(belongsToTree)
  330. CBonusSystemNode::treeHasChanged();
  331. }
  332. void BonusList::stackBonuses()
  333. {
  334. boost::sort(bonuses, [](const std::shared_ptr<Bonus> & b1, const std::shared_ptr<Bonus> & b2) -> bool
  335. {
  336. if(b1 == b2)
  337. return false;
  338. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  339. COMPARE_ATT(stacking);
  340. COMPARE_ATT(type);
  341. COMPARE_ATT(subtype);
  342. COMPARE_ATT(valType);
  343. #undef COMPARE_ATT
  344. return b1->val > b2->val;
  345. });
  346. // remove non-stacking
  347. size_t next = 1;
  348. while(next < bonuses.size())
  349. {
  350. bool remove = false;
  351. std::shared_ptr<Bonus> last = bonuses[next-1];
  352. std::shared_ptr<Bonus> current = bonuses[next];
  353. if(current->stacking.empty())
  354. remove = current == last;
  355. else if(current->stacking == "ALWAYS")
  356. remove = false;
  357. else
  358. remove = current->stacking == last->stacking
  359. && current->type == last->type
  360. && current->subtype == last->subtype
  361. && current->valType == last->valType;
  362. if(remove)
  363. bonuses.erase(bonuses.begin() + next);
  364. else
  365. next++;
  366. }
  367. }
  368. int BonusList::totalValue() const
  369. {
  370. struct BonusCollection
  371. {
  372. int base = 0;
  373. int percentToBase = 0;
  374. int percentToAll = 0;
  375. int additive = 0;
  376. int percentToSource = 0;
  377. int indepMin = std::numeric_limits<int>::max();
  378. int indepMax = std::numeric_limits<int>::min();
  379. };
  380. auto percent = [](int64_t base, int64_t percent) -> int {
  381. return static_cast<int>(std::clamp<int64_t>((base * (100 + percent)) / 100, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()));
  382. };
  383. std::array <BonusCollection, Bonus::BonusSource::NUM_BONUS_SOURCE> sources = {};
  384. BonusCollection any;
  385. bool hasIndepMax = false;
  386. bool hasIndepMin = false;
  387. for(const auto & b : bonuses)
  388. {
  389. switch(b->valType)
  390. {
  391. case Bonus::BASE_NUMBER:
  392. sources[b->source].base += b->val;
  393. break;
  394. case Bonus::PERCENT_TO_ALL:
  395. sources[b->source].percentToAll += b->val;
  396. break;
  397. case Bonus::PERCENT_TO_BASE:
  398. sources[b->source].percentToBase += b->val;
  399. break;
  400. case Bonus::PERCENT_TO_SOURCE:
  401. sources[b->source].percentToSource += b->val;
  402. break;
  403. case Bonus::PERCENT_TO_TARGET_TYPE:
  404. sources[b->targetSourceType].percentToSource += b->val;
  405. break;
  406. case Bonus::ADDITIVE_VALUE:
  407. sources[b->source].additive += b->val;
  408. break;
  409. case Bonus::INDEPENDENT_MAX:
  410. hasIndepMax = true;
  411. vstd::amax(sources[b->source].indepMax, b->val);
  412. break;
  413. case Bonus::INDEPENDENT_MIN:
  414. hasIndepMin = true;
  415. vstd::amin(sources[b->source].indepMin, b->val);
  416. break;
  417. }
  418. }
  419. for(const auto & src : sources)
  420. {
  421. any.base += percent(src.base, src.percentToSource);
  422. any.percentToBase += percent(src.percentToBase, src.percentToSource);
  423. any.percentToAll += percent(src.percentToAll, src.percentToSource);
  424. any.additive += percent(src.additive, src.percentToSource);
  425. if(hasIndepMin)
  426. vstd::amin(any.indepMin, percent(src.indepMin, src.percentToSource));
  427. if(hasIndepMax)
  428. vstd::amax(any.indepMax, percent(src.indepMax, src.percentToSource));
  429. }
  430. any.base = percent(any.base, any.percentToBase);
  431. any.base += any.additive;
  432. auto valFirst = percent(any.base ,any.percentToAll);
  433. if(hasIndepMin && hasIndepMax && any.indepMin < any.indepMax)
  434. any.indepMax = any.indepMin;
  435. const int notIndepBonuses = static_cast<int>(std::count_if(bonuses.cbegin(), bonuses.cend(), [](const std::shared_ptr<Bonus>& b)
  436. {
  437. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  438. }));
  439. if(notIndepBonuses)
  440. return std::clamp(valFirst, any.indepMax, any.indepMin);
  441. return hasIndepMin ? any.indepMin : hasIndepMax ? any.indepMax : 0;
  442. }
  443. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  444. {
  445. for (auto & b : bonuses)
  446. {
  447. if(select(b.get()))
  448. return b;
  449. }
  450. return nullptr;
  451. }
  452. std::shared_ptr<const Bonus> BonusList::getFirst(const CSelector &selector) const
  453. {
  454. for(const auto & b : bonuses)
  455. {
  456. if(selector(b.get()))
  457. return b;
  458. }
  459. return nullptr;
  460. }
  461. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  462. {
  463. out.reserve(bonuses.size());
  464. for(const auto & b : bonuses)
  465. {
  466. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  467. auto noFightLimit = b->effectRange == Bonus::NO_LIMIT;
  468. if(selector(b.get()) && ((!limit && noFightLimit) || ((bool)limit && limit(b.get()))))
  469. out.push_back(b);
  470. }
  471. }
  472. void BonusList::getAllBonuses(BonusList &out) const
  473. {
  474. for(const auto & b : bonuses)
  475. out.push_back(b);
  476. }
  477. int BonusList::valOfBonuses(const CSelector &select) const
  478. {
  479. BonusList ret;
  480. CSelector limit = nullptr;
  481. getBonuses(ret, select, limit);
  482. return ret.totalValue();
  483. }
  484. JsonNode BonusList::toJsonNode() const
  485. {
  486. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  487. for(const std::shared_ptr<Bonus> & b : bonuses)
  488. node.Vector().push_back(b->toJsonNode());
  489. return node;
  490. }
  491. void BonusList::push_back(const std::shared_ptr<Bonus> & x)
  492. {
  493. bonuses.push_back(x);
  494. changed();
  495. }
  496. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  497. {
  498. changed();
  499. return bonuses.erase(bonuses.begin() + position);
  500. }
  501. void BonusList::clear()
  502. {
  503. bonuses.clear();
  504. changed();
  505. }
  506. std::vector<BonusList *>::size_type BonusList::operator-=(const std::shared_ptr<Bonus> & i)
  507. {
  508. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  509. if(itr == bonuses.end())
  510. return false;
  511. bonuses.erase(itr);
  512. changed();
  513. return true;
  514. }
  515. void BonusList::resize(BonusList::TInternalContainer::size_type sz, const std::shared_ptr<Bonus> & c)
  516. {
  517. bonuses.resize(sz, c);
  518. changed();
  519. }
  520. void BonusList::reserve(TInternalContainer::size_type sz)
  521. {
  522. bonuses.reserve(sz);
  523. }
  524. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, const std::shared_ptr<Bonus> & x)
  525. {
  526. bonuses.insert(position, n, x);
  527. changed();
  528. }
  529. CSelector IBonusBearer::anaffectedByMoraleSelector =
  530. Selector::type()(Bonus::NON_LIVING)
  531. .Or(Selector::type()(Bonus::UNDEAD))
  532. .Or(Selector::type()(Bonus::SIEGE_WEAPON))
  533. .Or(Selector::type()(Bonus::NO_MORALE));
  534. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  535. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  536. IBonusBearer::IBonusBearer()
  537. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  538. moraleValue(this, moraleSelector, 0),
  539. luckValue(this, luckSelector, 0)
  540. {
  541. }
  542. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  543. {
  544. return valOfBonuses(Selector::type()(type).And(selector));
  545. }
  546. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  547. {
  548. //This part is performance-critical
  549. std::string cachingStr = "type_" + std::to_string(static_cast<int>(type)) + "_" + std::to_string(subtype);
  550. CSelector s = Selector::type()(type);
  551. if(subtype != -1)
  552. s = s.And(Selector::subtype()(subtype));
  553. return valOfBonuses(s, cachingStr);
  554. }
  555. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  556. {
  557. CSelector limit = nullptr;
  558. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  559. return hlp->totalValue();
  560. }
  561. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  562. {
  563. //TODO: We don't need to count all bonuses and could break on first matching
  564. return getBonuses(selector, cachingStr)->size() > 0;
  565. }
  566. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  567. {
  568. return getBonuses(selector, limit, cachingStr)->size() > 0;
  569. }
  570. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  571. {
  572. //This part is performance-ciritcal
  573. std::string cachingStr = "type_" + std::to_string(static_cast<int>(type)) + "_" + std::to_string(subtype);
  574. CSelector s = Selector::type()(type);
  575. if(subtype != -1)
  576. s = s.And(Selector::subtype()(subtype));
  577. return hasBonus(s, cachingStr);
  578. }
  579. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  580. {
  581. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  582. }
  583. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  584. {
  585. return getAllBonuses(selector, limit, nullptr, cachingStr);
  586. }
  587. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  588. {
  589. boost::format fmt("source_%did_%d");
  590. fmt % static_cast<int>(source) % sourceID;
  591. return hasBonus(Selector::source(source,sourceID), fmt.str());
  592. }
  593. int IBonusBearer::MoraleVal() const
  594. {
  595. if(anaffectedByMorale.getHasBonus())
  596. return 0;
  597. return std::clamp(moraleValue.getValue(), -3, +3);
  598. }
  599. int IBonusBearer::LuckVal() const
  600. {
  601. if(hasBonusOfType(Bonus::NO_LUCK))
  602. return 0;
  603. return std::clamp(luckValue.getValue(), -3, +3);
  604. }
  605. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  606. {
  607. if(anaffectedByMorale.getHasBonus())
  608. {
  609. if(!bonusList->empty())
  610. bonusList = std::make_shared<const BonusList>();
  611. return 0;
  612. }
  613. return std::clamp(moraleValue.getValueAndList(bonusList), -3, +3);
  614. }
  615. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  616. {
  617. if(hasBonusOfType(Bonus::NO_LUCK))
  618. {
  619. if(!bonusList->empty())
  620. bonusList = std::make_shared<const BonusList>();
  621. return 0;
  622. }
  623. return std::clamp(luckValue.getValueAndList(bonusList), -3, +3);
  624. }
  625. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  626. {
  627. auto bonuses = getAllBonuses(selector, Selector::all);
  628. return bonuses->getFirst(Selector::all);
  629. }
  630. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  631. {
  632. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  633. }
  634. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  635. {
  636. auto ret = bonuses.getFirst(selector);
  637. if(ret)
  638. return ret;
  639. FOREACH_PARENT(pname)
  640. {
  641. ret = pname->getBonusLocalFirst(selector);
  642. if (ret)
  643. return ret;
  644. }
  645. return nullptr;
  646. }
  647. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  648. {
  649. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  650. }
  651. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  652. {
  653. for(const auto & elem : parents)
  654. {
  655. const CBonusSystemNode *parent = elem;
  656. out.insert(parent);
  657. }
  658. }
  659. void CBonusSystemNode::getParents(TNodes &out)
  660. {
  661. for (auto & elem : parents)
  662. {
  663. const CBonusSystemNode *parent = elem;
  664. out.insert(const_cast<CBonusSystemNode*>(parent));
  665. }
  666. }
  667. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  668. {
  669. for(auto * parent : parents)
  670. {
  671. out.insert(parent);
  672. parent->getAllParents(out);
  673. }
  674. }
  675. void CBonusSystemNode::getAllBonusesRec(BonusList &out, const CSelector & selector) const
  676. {
  677. //out has been reserved sufficient capacity at getAllBonuses() call
  678. BonusList beforeUpdate;
  679. TCNodes lparents;
  680. getAllParents(lparents);
  681. if(!lparents.empty())
  682. {
  683. //estimate on how many bonuses are missing yet - must be positive
  684. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  685. }
  686. else
  687. {
  688. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  689. }
  690. for(const auto * parent : lparents)
  691. {
  692. parent->getAllBonusesRec(beforeUpdate, selector);
  693. }
  694. bonuses.getAllBonuses(beforeUpdate);
  695. for(const auto & b : beforeUpdate)
  696. {
  697. //We should not run updaters on non-selected bonuses
  698. auto updated = selector(b.get()) && b->updater
  699. ? getUpdatedBonus(b, b->updater)
  700. : b;
  701. //do not add bonus with updater
  702. bool bonusExists = false;
  703. for(const auto & bonus : out)
  704. {
  705. if (bonus == updated)
  706. bonusExists = true;
  707. if (bonus->updater && bonus->updater == updated->updater)
  708. bonusExists = true;
  709. }
  710. if (!bonusExists)
  711. out.push_back(updated);
  712. }
  713. }
  714. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  715. {
  716. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  717. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  718. {
  719. // Exclusive access for one thread
  720. boost::lock_guard<boost::mutex> lock(sync);
  721. // If the bonus system tree changes(state of a single node or the relations to each other) then
  722. // cache all bonus objects. Selector objects doesn't matter.
  723. if (cachedLast != treeChanged)
  724. {
  725. BonusList allBonuses;
  726. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  727. cachedBonuses.clear();
  728. cachedRequests.clear();
  729. getAllBonusesRec(allBonuses, Selector::all);
  730. limitBonuses(allBonuses, cachedBonuses);
  731. cachedBonuses.stackBonuses();
  732. cachedLast = treeChanged;
  733. }
  734. // If a bonus system request comes with a caching string then look up in the map if there are any
  735. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  736. if(!cachingStr.empty())
  737. {
  738. auto it = cachedRequests.find(cachingStr);
  739. if(it != cachedRequests.end())
  740. {
  741. //Cached list contains bonuses for our query with applied limiters
  742. return it->second;
  743. }
  744. }
  745. //We still don't have the bonuses (didn't returned them from cache)
  746. //Perform bonus selection
  747. auto ret = std::make_shared<BonusList>();
  748. cachedBonuses.getBonuses(*ret, selector, limit);
  749. // Save the results in the cache
  750. if(!cachingStr.empty())
  751. cachedRequests[cachingStr] = ret;
  752. return ret;
  753. }
  754. else
  755. {
  756. return getAllBonusesWithoutCaching(selector, limit, root);
  757. }
  758. }
  759. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  760. {
  761. auto ret = std::make_shared<BonusList>();
  762. // Get bonus results without caching enabled.
  763. BonusList beforeLimiting;
  764. BonusList afterLimiting;
  765. getAllBonusesRec(beforeLimiting, selector);
  766. if(!root || root == this)
  767. {
  768. limitBonuses(beforeLimiting, afterLimiting);
  769. }
  770. else if(root)
  771. {
  772. //We want to limit our query against an external node. We get all its bonuses,
  773. // add the ones we're considering and see if they're cut out by limiters
  774. BonusList rootBonuses;
  775. BonusList limitedRootBonuses;
  776. getAllBonusesRec(rootBonuses, selector);
  777. for(const auto & b : beforeLimiting)
  778. rootBonuses.push_back(b);
  779. root->limitBonuses(rootBonuses, limitedRootBonuses);
  780. for(const auto & b : beforeLimiting)
  781. if(vstd::contains(limitedRootBonuses, b))
  782. afterLimiting.push_back(b);
  783. }
  784. afterLimiting.getBonuses(*ret, selector, limit);
  785. ret->stackBonuses();
  786. return ret;
  787. }
  788. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr & updater) const
  789. {
  790. assert(updater);
  791. return updater->createUpdatedBonus(b, * this);
  792. }
  793. CBonusSystemNode::CBonusSystemNode()
  794. :CBonusSystemNode(false)
  795. {
  796. }
  797. CBonusSystemNode::CBonusSystemNode(bool isHypotetic):
  798. bonuses(true),
  799. exportedBonuses(true),
  800. nodeType(UNKNOWN),
  801. cachedLast(0),
  802. isHypotheticNode(isHypotetic)
  803. {
  804. }
  805. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType):
  806. bonuses(true),
  807. exportedBonuses(true),
  808. nodeType(NodeType),
  809. cachedLast(0),
  810. isHypotheticNode(false)
  811. {
  812. }
  813. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other) noexcept:
  814. bonuses(std::move(other.bonuses)),
  815. exportedBonuses(std::move(other.exportedBonuses)),
  816. nodeType(other.nodeType),
  817. description(other.description),
  818. cachedLast(0),
  819. isHypotheticNode(other.isHypotheticNode)
  820. {
  821. std::swap(parents, other.parents);
  822. std::swap(children, other.children);
  823. //fixing bonus tree without recalculation
  824. if(!isHypothetic())
  825. {
  826. for(CBonusSystemNode * n : parents)
  827. {
  828. n->children -= &other;
  829. n->children.push_back(this);
  830. }
  831. }
  832. for(CBonusSystemNode * n : children)
  833. {
  834. n->parents -= &other;
  835. n->parents.push_back(this);
  836. }
  837. //cache ignored
  838. //cachedBonuses
  839. //cachedRequests
  840. }
  841. CBonusSystemNode::~CBonusSystemNode()
  842. {
  843. detachFromAll();
  844. if(!children.empty())
  845. {
  846. while(!children.empty())
  847. children.front()->detachFrom(*this);
  848. }
  849. }
  850. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  851. {
  852. assert(!vstd::contains(parents, &parent));
  853. parents.push_back(&parent);
  854. if(!isHypothetic())
  855. {
  856. if(parent.actsAsBonusSourceOnly())
  857. parent.newRedDescendant(*this);
  858. else
  859. newRedDescendant(parent);
  860. parent.newChildAttached(*this);
  861. }
  862. CBonusSystemNode::treeHasChanged();
  863. }
  864. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  865. {
  866. assert(vstd::contains(parents, &parent));
  867. if(!isHypothetic())
  868. {
  869. if(parent.actsAsBonusSourceOnly())
  870. parent.removedRedDescendant(*this);
  871. else
  872. removedRedDescendant(parent);
  873. }
  874. if (vstd::contains(parents, &parent))
  875. {
  876. parents -= &parent;
  877. }
  878. else
  879. {
  880. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  881. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  882. }
  883. if(!isHypothetic())
  884. {
  885. parent.childDetached(*this);
  886. }
  887. CBonusSystemNode::treeHasChanged();
  888. }
  889. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  890. {
  891. removeBonuses(s);
  892. for(CBonusSystemNode * child : children)
  893. child->removeBonusesRecursive(s);
  894. }
  895. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  896. {
  897. BonusList bl;
  898. exportedBonuses.getBonuses(bl, s, Selector::all);
  899. for(const auto & b : bl)
  900. {
  901. b->turnsRemain--;
  902. if(b->turnsRemain <= 0)
  903. removeBonus(b);
  904. }
  905. for(CBonusSystemNode *child : children)
  906. child->reduceBonusDurations(s);
  907. }
  908. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  909. {
  910. //turnsRemain shouldn't be zero for following durations
  911. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  912. {
  913. assert(b->turnsRemain);
  914. }
  915. assert(!vstd::contains(exportedBonuses, b));
  916. exportedBonuses.push_back(b);
  917. exportBonus(b);
  918. CBonusSystemNode::treeHasChanged();
  919. }
  920. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  921. {
  922. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  923. if(bonus)
  924. bonus->val += b->val;
  925. else
  926. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  927. }
  928. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  929. {
  930. exportedBonuses -= b;
  931. if(b->propagator)
  932. unpropagateBonus(b);
  933. else
  934. bonuses -= b;
  935. CBonusSystemNode::treeHasChanged();
  936. }
  937. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  938. {
  939. BonusList toRemove;
  940. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  941. for(const auto & bonus : toRemove)
  942. removeBonus(bonus);
  943. }
  944. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  945. {
  946. switch(nodeType)
  947. {
  948. case CREATURE:
  949. case ARTIFACT:
  950. case ARTIFACT_INSTANCE:
  951. return true;
  952. default:
  953. return false;
  954. }
  955. }
  956. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  957. {
  958. if(b->propagator->shouldBeAttached(this))
  959. {
  960. auto propagated = b->propagationUpdater
  961. ? source.getUpdatedBonus(b, b->propagationUpdater)
  962. : b;
  963. bonuses.push_back(propagated);
  964. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  965. }
  966. FOREACH_RED_CHILD(child)
  967. child->propagateBonus(b, source);
  968. }
  969. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  970. {
  971. if(b->propagator->shouldBeAttached(this))
  972. {
  973. bonuses -= b;
  974. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  975. }
  976. FOREACH_RED_CHILD(child)
  977. child->unpropagateBonus(b);
  978. }
  979. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  980. {
  981. assert(!vstd::contains(children, &child));
  982. children.push_back(&child);
  983. }
  984. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  985. {
  986. if(vstd::contains(children, &child))
  987. children -= &child;
  988. else
  989. {
  990. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  991. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  992. }
  993. }
  994. void CBonusSystemNode::detachFromAll()
  995. {
  996. while(!parents.empty())
  997. detachFrom(*parents.front());
  998. }
  999. bool CBonusSystemNode::isIndependentNode() const
  1000. {
  1001. return parents.empty() && children.empty();
  1002. }
  1003. std::string CBonusSystemNode::nodeName() const
  1004. {
  1005. return !description.empty()
  1006. ? description
  1007. : std::string("Bonus system node of type ") + typeid(*this).name();
  1008. }
  1009. std::string CBonusSystemNode::nodeShortInfo() const
  1010. {
  1011. std::ostringstream str;
  1012. str << "'" << typeid(* this).name() << "'";
  1013. description.length() > 0
  1014. ? str << " (" << description << ")"
  1015. : str << " (no description)";
  1016. return str.str();
  1017. }
  1018. void CBonusSystemNode::deserializationFix()
  1019. {
  1020. exportBonuses();
  1021. }
  1022. void CBonusSystemNode::getRedParents(TNodes & out)
  1023. {
  1024. FOREACH_PARENT(pname)
  1025. {
  1026. if(pname->actsAsBonusSourceOnly())
  1027. {
  1028. out.insert(pname);
  1029. }
  1030. }
  1031. if(!actsAsBonusSourceOnly())
  1032. {
  1033. for(CBonusSystemNode *child : children)
  1034. {
  1035. out.insert(child);
  1036. }
  1037. }
  1038. }
  1039. void CBonusSystemNode::getRedChildren(TNodes &out)
  1040. {
  1041. FOREACH_PARENT(pname)
  1042. {
  1043. if(!pname->actsAsBonusSourceOnly())
  1044. {
  1045. out.insert(pname);
  1046. }
  1047. }
  1048. if(actsAsBonusSourceOnly())
  1049. {
  1050. for(CBonusSystemNode *child : children)
  1051. {
  1052. out.insert(child);
  1053. }
  1054. }
  1055. }
  1056. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  1057. {
  1058. for(const auto & b : exportedBonuses)
  1059. {
  1060. if(b->propagator)
  1061. descendant.propagateBonus(b, *this);
  1062. }
  1063. TNodes redParents;
  1064. getRedAncestors(redParents); //get all red parents recursively
  1065. for(auto * parent : redParents)
  1066. {
  1067. for(const auto & b : parent->exportedBonuses)
  1068. {
  1069. if(b->propagator)
  1070. descendant.propagateBonus(b, *this);
  1071. }
  1072. }
  1073. }
  1074. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  1075. {
  1076. for(const auto & b : exportedBonuses)
  1077. if(b->propagator)
  1078. descendant.unpropagateBonus(b);
  1079. TNodes redParents;
  1080. getRedAncestors(redParents); //get all red parents recursively
  1081. for(auto * parent : redParents)
  1082. {
  1083. for(const auto & b : parent->exportedBonuses)
  1084. if(b->propagator)
  1085. descendant.unpropagateBonus(b);
  1086. }
  1087. }
  1088. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1089. {
  1090. getRedParents(out);
  1091. TNodes redParents;
  1092. getRedParents(redParents);
  1093. for(CBonusSystemNode * parent : redParents)
  1094. parent->getRedAncestors(out);
  1095. }
  1096. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  1097. {
  1098. if(b->propagator)
  1099. propagateBonus(b, *this);
  1100. else
  1101. bonuses.push_back(b);
  1102. CBonusSystemNode::treeHasChanged();
  1103. }
  1104. void CBonusSystemNode::exportBonuses()
  1105. {
  1106. for(const auto & b : exportedBonuses)
  1107. exportBonus(b);
  1108. }
  1109. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1110. {
  1111. return nodeType;
  1112. }
  1113. const BonusList& CBonusSystemNode::getBonusList() const
  1114. {
  1115. return bonuses;
  1116. }
  1117. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1118. {
  1119. return parents;
  1120. }
  1121. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1122. {
  1123. return children;
  1124. }
  1125. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1126. {
  1127. nodeType = type;
  1128. }
  1129. BonusList & CBonusSystemNode::getExportedBonusList()
  1130. {
  1131. return exportedBonuses;
  1132. }
  1133. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1134. {
  1135. return exportedBonuses;
  1136. }
  1137. const std::string& CBonusSystemNode::getDescription() const
  1138. {
  1139. return description;
  1140. }
  1141. void CBonusSystemNode::setDescription(const std::string &description)
  1142. {
  1143. this->description = description;
  1144. }
  1145. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1146. {
  1147. assert(&allBonuses != &out); //todo should it work in-place?
  1148. BonusList undecided = allBonuses;
  1149. BonusList & accepted = out;
  1150. while(true)
  1151. {
  1152. int undecidedCount = static_cast<int>(undecided.size());
  1153. for(int i = 0; i < undecided.size(); i++)
  1154. {
  1155. auto b = undecided[i];
  1156. BonusLimitationContext context = {*b, *this, out, undecided};
  1157. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  1158. if(decision == ILimiter::EDecision::DISCARD)
  1159. {
  1160. undecided.erase(i);
  1161. i--; continue;
  1162. }
  1163. else if(decision == ILimiter::EDecision::ACCEPT)
  1164. {
  1165. accepted.push_back(b);
  1166. undecided.erase(i);
  1167. i--; continue;
  1168. }
  1169. else
  1170. assert(decision == ILimiter::EDecision::NOT_SURE);
  1171. }
  1172. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1173. return;
  1174. }
  1175. }
  1176. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1177. {
  1178. auto ret = std::make_shared<BonusList>();
  1179. limitBonuses(allBonuses, *ret);
  1180. return ret;
  1181. }
  1182. void CBonusSystemNode::treeHasChanged()
  1183. {
  1184. treeChanged++;
  1185. }
  1186. int64_t CBonusSystemNode::getTreeVersion() const
  1187. {
  1188. return treeChanged;
  1189. }
  1190. std::string Bonus::Description(std::optional<si32> customValue) const
  1191. {
  1192. std::ostringstream str;
  1193. if(description.empty())
  1194. {
  1195. if(stacking.empty() || stacking == "ALWAYS")
  1196. {
  1197. switch(source)
  1198. {
  1199. case ARTIFACT:
  1200. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getNameTranslated();
  1201. break;
  1202. case SPELL_EFFECT:
  1203. str << SpellID(sid).toSpell(VLC->spells())->getNameTranslated();
  1204. break;
  1205. case CREATURE_ABILITY:
  1206. str << VLC->creh->objects[sid]->getNamePluralTranslated();
  1207. break;
  1208. case SECONDARY_SKILL:
  1209. str << VLC->skillh->getByIndex(sid)->getNameTranslated();
  1210. break;
  1211. case HERO_SPECIAL:
  1212. str << VLC->heroh->objects[sid]->getNameTranslated();
  1213. break;
  1214. default:
  1215. //todo: handle all possible sources
  1216. str << "Unknown";
  1217. break;
  1218. }
  1219. }
  1220. else
  1221. str << stacking;
  1222. }
  1223. else
  1224. {
  1225. str << description;
  1226. }
  1227. if(auto value = customValue.value_or(val))
  1228. str << " " << std::showpos << value;
  1229. return str.str();
  1230. }
  1231. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1232. {
  1233. switch(type)
  1234. {
  1235. case Bonus::PRIMARY_SKILL:
  1236. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1237. case Bonus::SPECIAL_SPELL_LEV:
  1238. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1239. case Bonus::SPELL:
  1240. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1241. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1242. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1243. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1244. case Bonus::IMPROVED_NECROMANCY:
  1245. case Bonus::SPECIAL_UPGRADE:
  1246. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1247. case Bonus::GENERATE_RESOURCE:
  1248. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1249. default:
  1250. return JsonUtils::intNode(subtype);
  1251. }
  1252. }
  1253. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1254. {
  1255. switch(type)
  1256. {
  1257. case Bonus::SPECIAL_UPGRADE:
  1258. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1259. default:
  1260. return addInfo.toJsonNode();
  1261. }
  1262. }
  1263. JsonNode durationToJson(ui16 duration)
  1264. {
  1265. std::vector<std::string> durationNames;
  1266. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1267. {
  1268. if(duration & durBit)
  1269. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1270. }
  1271. if(durationNames.size() == 1)
  1272. {
  1273. return JsonUtils::stringNode(durationNames[0]);
  1274. }
  1275. else
  1276. {
  1277. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1278. for(const std::string & dur : durationNames)
  1279. node.Vector().push_back(JsonUtils::stringNode(dur));
  1280. return node;
  1281. }
  1282. }
  1283. JsonNode Bonus::toJsonNode() const
  1284. {
  1285. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1286. // only add values that might reasonably be found in config files
  1287. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1288. if(subtype != -1)
  1289. root["subtype"] = subtypeToJson(type, subtype);
  1290. if(additionalInfo != CAddInfo::NONE)
  1291. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1292. if(duration != 0)
  1293. {
  1294. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1295. for(const auto & kv : bonusDurationMap)
  1296. {
  1297. if(duration & kv.second)
  1298. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1299. }
  1300. root["duration"] = durationVec;
  1301. }
  1302. if(turnsRemain != 0)
  1303. root["turns"].Integer() = turnsRemain;
  1304. if(source != OTHER)
  1305. root["sourceType"].String() = vstd::findKey(bonusSourceMap, source);
  1306. if(targetSourceType != OTHER)
  1307. root["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetSourceType);
  1308. if(sid != 0)
  1309. root["sourceID"].Integer() = sid;
  1310. if(val != 0)
  1311. root["val"].Integer() = val;
  1312. if(valType != ADDITIVE_VALUE)
  1313. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1314. if(!stacking.empty())
  1315. root["stacking"].String() = stacking;
  1316. if(!description.empty())
  1317. root["description"].String() = description;
  1318. if(effectRange != NO_LIMIT)
  1319. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1320. if(duration != PERMANENT)
  1321. root["duration"] = durationToJson(duration);
  1322. if(turnsRemain)
  1323. root["turns"].Integer() = turnsRemain;
  1324. if(limiter)
  1325. root["limiters"] = limiter->toJsonNode();
  1326. if(updater)
  1327. root["updater"] = updater->toJsonNode();
  1328. if(propagator)
  1329. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1330. return root;
  1331. }
  1332. std::string Bonus::nameForBonus() const
  1333. {
  1334. switch(type)
  1335. {
  1336. case Bonus::PRIMARY_SKILL:
  1337. return PrimarySkill::names[subtype];
  1338. case Bonus::SPECIAL_SPELL_LEV:
  1339. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1340. case Bonus::SPELL:
  1341. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1342. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1343. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1344. return VLC->spells()->getByIndex(subtype)->getJsonKey();
  1345. case Bonus::SPECIAL_UPGRADE:
  1346. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1347. case Bonus::GENERATE_RESOURCE:
  1348. return GameConstants::RESOURCE_NAMES[subtype];
  1349. case Bonus::STACKS_SPEED:
  1350. return "speed";
  1351. default:
  1352. return vstd::findKey(bonusNameMap, type);
  1353. }
  1354. }
  1355. BonusParams::BonusParams(std::string deprecatedTypeStr, std::string deprecatedSubtypeStr, int deprecatedSubtype):
  1356. isConverted(true)
  1357. {
  1358. if(deprecatedTypeStr == "SECONDARY_SKILL_PREMY" || deprecatedTypeStr == "SPECIAL_SECONDARY_SKILL")
  1359. {
  1360. if(deprecatedSubtype == SecondarySkill::PATHFINDING || deprecatedSubtypeStr == "skill.pathfinding")
  1361. type = Bonus::ROUGH_TERRAIN_DISCOUNT;
  1362. else if(deprecatedSubtype == SecondarySkill::DIPLOMACY || deprecatedSubtypeStr == "skill.diplomacy")
  1363. type = Bonus::WANDERING_CREATURES_JOIN_BONUS;
  1364. else if(deprecatedSubtype == SecondarySkill::WISDOM || deprecatedSubtypeStr == "skill.wisdom")
  1365. type = Bonus::MAX_LEARNABLE_SPELL_LEVEL;
  1366. else if(deprecatedSubtype == SecondarySkill::MYSTICISM || deprecatedSubtypeStr == "skill.mysticism")
  1367. type = Bonus::MANA_REGENERATION;
  1368. else if(deprecatedSubtype == SecondarySkill::NECROMANCY || deprecatedSubtypeStr == "skill.necromancy")
  1369. type = Bonus::UNDEAD_RAISE_PERCENTAGE;
  1370. else if(deprecatedSubtype == SecondarySkill::LEARNING || deprecatedSubtypeStr == "skill.learning")
  1371. type = Bonus::HERO_EXPERIENCE_GAIN_PERCENT;
  1372. else if(deprecatedSubtype == SecondarySkill::RESISTANCE || deprecatedSubtypeStr == "skill.resistance")
  1373. type = Bonus::MAGIC_RESISTANCE;
  1374. else if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1375. type = Bonus::LEARN_BATTLE_SPELL_CHANCE;
  1376. else if(deprecatedSubtype == SecondarySkill::SCOUTING || deprecatedSubtypeStr == "skill.scouting")
  1377. type = Bonus::SIGHT_RADIUS;
  1378. else if(deprecatedSubtype == SecondarySkill::INTELLIGENCE || deprecatedSubtypeStr == "skill.intelligence")
  1379. {
  1380. type = Bonus::MANA_PER_KNOWLEDGE;
  1381. valueType = Bonus::PERCENT_TO_BASE;
  1382. valueTypeRelevant = true;
  1383. }
  1384. else if(deprecatedSubtype == SecondarySkill::SORCERY || deprecatedSubtypeStr == "skill.sorcery")
  1385. type = Bonus::SPELL_DAMAGE;
  1386. else if(deprecatedSubtype == SecondarySkill::SCHOLAR || deprecatedSubtypeStr == "skill.scholar")
  1387. type = Bonus::LEARN_MEETING_SPELL_LIMIT;
  1388. else if(deprecatedSubtype == SecondarySkill::ARCHERY|| deprecatedSubtypeStr == "skill.archery")
  1389. {
  1390. subtype = 1;
  1391. subtypeRelevant = true;
  1392. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1393. }
  1394. else if(deprecatedSubtype == SecondarySkill::OFFENCE || deprecatedSubtypeStr == "skill.offence")
  1395. {
  1396. subtype = 0;
  1397. subtypeRelevant = true;
  1398. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1399. }
  1400. else if(deprecatedSubtype == SecondarySkill::ARMORER || deprecatedSubtypeStr == "skill.armorer")
  1401. {
  1402. subtype = -1;
  1403. subtypeRelevant = true;
  1404. type = Bonus::GENERAL_DAMAGE_REDUCTION;
  1405. }
  1406. else if(deprecatedSubtype == SecondarySkill::NAVIGATION || deprecatedSubtypeStr == "skill.navigation")
  1407. {
  1408. subtype = 0;
  1409. subtypeRelevant = true;
  1410. valueType = Bonus::PERCENT_TO_BASE;
  1411. valueTypeRelevant = true;
  1412. type = Bonus::MOVEMENT;
  1413. }
  1414. else if(deprecatedSubtype == SecondarySkill::LOGISTICS || deprecatedSubtypeStr == "skill.logistics")
  1415. {
  1416. subtype = 1;
  1417. subtypeRelevant = true;
  1418. valueType = Bonus::PERCENT_TO_BASE;
  1419. valueTypeRelevant = true;
  1420. type = Bonus::MOVEMENT;
  1421. }
  1422. else if(deprecatedSubtype == SecondarySkill::ESTATES || deprecatedSubtypeStr == "skill.estates")
  1423. {
  1424. type = Bonus::GENERATE_RESOURCE;
  1425. subtype = GameResID(EGameResID::GOLD);
  1426. subtypeRelevant = true;
  1427. }
  1428. else if(deprecatedSubtype == SecondarySkill::AIR_MAGIC || deprecatedSubtypeStr == "skill.airMagic")
  1429. {
  1430. type = Bonus::MAGIC_SCHOOL_SKILL;
  1431. subtypeRelevant = true;
  1432. subtype = 4;
  1433. }
  1434. else if(deprecatedSubtype == SecondarySkill::WATER_MAGIC || deprecatedSubtypeStr == "skill.waterMagic")
  1435. {
  1436. type = Bonus::MAGIC_SCHOOL_SKILL;
  1437. subtypeRelevant = true;
  1438. subtype = 1;
  1439. }
  1440. else if(deprecatedSubtype == SecondarySkill::FIRE_MAGIC || deprecatedSubtypeStr == "skill.fireMagic")
  1441. {
  1442. type = Bonus::MAGIC_SCHOOL_SKILL;
  1443. subtypeRelevant = true;
  1444. subtype = 2;
  1445. }
  1446. else if(deprecatedSubtype == SecondarySkill::EARTH_MAGIC || deprecatedSubtypeStr == "skill.earthMagic")
  1447. {
  1448. type = Bonus::MAGIC_SCHOOL_SKILL;
  1449. subtypeRelevant = true;
  1450. subtype = 8;
  1451. }
  1452. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1453. {
  1454. type = Bonus::BONUS_DAMAGE_CHANCE;
  1455. subtypeRelevant = true;
  1456. subtypeStr = "core:creature.ballista";
  1457. }
  1458. else if (deprecatedSubtype == SecondarySkill::FIRST_AID || deprecatedSubtypeStr == "skill.firstAid")
  1459. {
  1460. type = Bonus::SPECIFIC_SPELL_POWER;
  1461. subtypeRelevant = true;
  1462. subtypeStr = "core:spell.firstAid";
  1463. }
  1464. else if (deprecatedSubtype == SecondarySkill::BALLISTICS || deprecatedSubtypeStr == "skill.ballistics")
  1465. {
  1466. type = Bonus::CATAPULT_EXTRA_SHOTS;
  1467. subtypeRelevant = true;
  1468. subtypeStr = "core:spell.catapultShot";
  1469. }
  1470. else
  1471. isConverted = false;
  1472. }
  1473. else if (deprecatedTypeStr == "SECONDARY_SKILL_VAL2")
  1474. {
  1475. if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1476. type = Bonus::LEARN_BATTLE_SPELL_LEVEL_LIMIT;
  1477. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1478. {
  1479. type = Bonus::HERO_GRANTS_ATTACKS;
  1480. subtypeRelevant = true;
  1481. subtypeStr = "core:creature.ballista";
  1482. }
  1483. else
  1484. isConverted = false;
  1485. }
  1486. else if (deprecatedTypeStr == "SEA_MOVEMENT")
  1487. {
  1488. subtype = 0;
  1489. subtypeRelevant = true;
  1490. valueType = Bonus::ADDITIVE_VALUE;
  1491. valueTypeRelevant = true;
  1492. type = Bonus::MOVEMENT;
  1493. }
  1494. else if (deprecatedTypeStr == "LAND_MOVEMENT")
  1495. {
  1496. subtype = 1;
  1497. subtypeRelevant = true;
  1498. valueType = Bonus::ADDITIVE_VALUE;
  1499. valueTypeRelevant = true;
  1500. type = Bonus::MOVEMENT;
  1501. }
  1502. else if (deprecatedTypeStr == "MAXED_SPELL")
  1503. {
  1504. type = Bonus::SPELL;
  1505. subtypeStr = deprecatedSubtypeStr;
  1506. subtypeRelevant = true;
  1507. valueType = Bonus::INDEPENDENT_MAX;
  1508. valueTypeRelevant = true;
  1509. val = 3;
  1510. valRelevant = true;
  1511. }
  1512. else if (deprecatedTypeStr == "FULL_HP_REGENERATION")
  1513. {
  1514. type = Bonus::HP_REGENERATION;
  1515. val = 100000; //very high value to always chose stack health
  1516. valRelevant = true;
  1517. }
  1518. else if (deprecatedTypeStr == "KING1")
  1519. {
  1520. type = Bonus::KING;
  1521. val = 0;
  1522. valRelevant = true;
  1523. }
  1524. else if (deprecatedTypeStr == "KING2")
  1525. {
  1526. type = Bonus::KING;
  1527. val = 2;
  1528. valRelevant = true;
  1529. }
  1530. else if (deprecatedTypeStr == "KING3")
  1531. {
  1532. type = Bonus::KING;
  1533. val = 3;
  1534. valRelevant = true;
  1535. }
  1536. else if (deprecatedTypeStr == "SIGHT_RADIOUS")
  1537. type = Bonus::SIGHT_RADIUS;
  1538. else if (deprecatedTypeStr == "SELF_MORALE")
  1539. {
  1540. type = Bonus::MORALE;
  1541. val = 1;
  1542. valRelevant = true;
  1543. valueType = Bonus::INDEPENDENT_MAX;
  1544. valueTypeRelevant = true;
  1545. }
  1546. else if (deprecatedTypeStr == "SELF_LUCK")
  1547. {
  1548. type = Bonus::LUCK;
  1549. val = 1;
  1550. valRelevant = true;
  1551. valueType = Bonus::INDEPENDENT_MAX;
  1552. valueTypeRelevant = true;
  1553. }
  1554. else
  1555. isConverted = false;
  1556. }
  1557. const JsonNode & BonusParams::toJson()
  1558. {
  1559. assert(isConverted);
  1560. if(ret.isNull())
  1561. {
  1562. ret["type"].String() = vstd::findKey(bonusNameMap, type);
  1563. if(subtypeRelevant && !subtypeStr.empty())
  1564. ret["subtype"].String() = subtypeStr;
  1565. else if(subtypeRelevant)
  1566. ret["subtype"].Integer() = subtype;
  1567. if(valueTypeRelevant)
  1568. ret["valueType"].String() = vstd::findKey(bonusValueMap, valueType);
  1569. if(valRelevant)
  1570. ret["val"].Float() = val;
  1571. if(targetTypeRelevant)
  1572. ret["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetType);
  1573. jsonCreated = true;
  1574. }
  1575. return ret;
  1576. };
  1577. CSelector BonusParams::toSelector()
  1578. {
  1579. assert(isConverted);
  1580. if(subtypeRelevant && !subtypeStr.empty())
  1581. JsonUtils::resolveIdentifier(subtype, toJson(), "subtype");
  1582. auto ret = Selector::type()(type);
  1583. if(subtypeRelevant)
  1584. ret = ret.And(Selector::subtype()(subtype));
  1585. if(valueTypeRelevant)
  1586. ret = ret.And(Selector::valueType(valueType));
  1587. if(targetTypeRelevant)
  1588. ret = ret.And(Selector::targetSourceType()(targetType));
  1589. return ret;
  1590. }
  1591. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype):
  1592. duration(static_cast<ui16>(Duration)),
  1593. type(Type),
  1594. subtype(Subtype),
  1595. source(Src),
  1596. val(Val),
  1597. sid(ID),
  1598. description(std::move(Desc))
  1599. {
  1600. boost::algorithm::trim(description);
  1601. targetSourceType = OTHER;
  1602. }
  1603. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType):
  1604. duration(static_cast<ui16>(Duration)),
  1605. type(Type),
  1606. subtype(Subtype),
  1607. source(Src),
  1608. val(Val),
  1609. sid(ID),
  1610. valType(ValType)
  1611. {
  1612. turnsRemain = 0;
  1613. effectRange = NO_LIMIT;
  1614. targetSourceType = OTHER;
  1615. }
  1616. std::shared_ptr<Bonus> Bonus::addPropagator(const TPropagatorPtr & Propagator)
  1617. {
  1618. propagator = Propagator;
  1619. return this->shared_from_this();
  1620. }
  1621. namespace Selector
  1622. {
  1623. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1624. {
  1625. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1626. return stype;
  1627. }
  1628. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1629. {
  1630. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1631. return ssubtype;
  1632. }
  1633. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1634. {
  1635. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1636. return sinfo;
  1637. }
  1638. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1639. {
  1640. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1641. return ssourceType;
  1642. }
  1643. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1644. {
  1645. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1646. return ssourceType;
  1647. }
  1648. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1649. {
  1650. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1651. return seffectRange;
  1652. }
  1653. DLL_LINKAGE CWillLastTurns turns;
  1654. DLL_LINKAGE CWillLastDays days;
  1655. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1656. {
  1657. return type()(Type).And(subtype()(Subtype));
  1658. }
  1659. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, const CAddInfo & info)
  1660. {
  1661. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1662. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1663. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1664. }
  1665. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1666. {
  1667. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1668. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1669. }
  1670. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1671. {
  1672. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1673. }
  1674. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1675. {
  1676. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1677. }
  1678. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1679. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1680. }
  1681. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1682. {
  1683. for (ui32 i = 0; i < bonusList.size(); i++)
  1684. {
  1685. const auto & b = bonusList[i];
  1686. out << "Bonus " << i << "\n" << *b << std::endl;
  1687. }
  1688. return out;
  1689. }
  1690. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1691. {
  1692. for(const auto & i : bonusNameMap)
  1693. if(i.second == bonus.type)
  1694. out << "\tType: " << i.first << " \t";
  1695. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1696. printField(val);
  1697. printField(subtype);
  1698. printField(duration);
  1699. printField(source);
  1700. printField(sid);
  1701. if(bonus.additionalInfo != CAddInfo::NONE)
  1702. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1703. printField(turnsRemain);
  1704. printField(valType);
  1705. if(!bonus.stacking.empty())
  1706. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1707. printField(effectRange);
  1708. #undef printField
  1709. if(bonus.limiter)
  1710. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1711. if(bonus.updater)
  1712. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1713. return out;
  1714. }
  1715. std::shared_ptr<Bonus> Bonus::addLimiter(const TLimiterPtr & Limiter)
  1716. {
  1717. if (limiter)
  1718. {
  1719. //If we already have limiter list, retrieve it
  1720. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1721. if(!limiterList)
  1722. {
  1723. //Create a new limiter list with old limiter and the new one will be pushed later
  1724. limiterList = std::make_shared<AllOfLimiter>();
  1725. limiterList->add(limiter);
  1726. limiter = limiterList;
  1727. }
  1728. limiterList->add(Limiter);
  1729. }
  1730. else
  1731. {
  1732. limiter = Limiter;
  1733. }
  1734. return this->shared_from_this();
  1735. }
  1736. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1737. {
  1738. return false;
  1739. }
  1740. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1741. {
  1742. return CBonusSystemNode::ENodeTypes::NONE;
  1743. }
  1744. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1745. : nodeType(NodeType)
  1746. {
  1747. }
  1748. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1749. {
  1750. return nodeType;
  1751. }
  1752. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1753. {
  1754. return nodeType == dest->getNodeType();
  1755. }
  1756. // Updaters
  1757. std::shared_ptr<Bonus> Bonus::addUpdater(const TUpdaterPtr & Updater)
  1758. {
  1759. updater = Updater;
  1760. return this->shared_from_this();
  1761. }
  1762. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1763. {
  1764. return b;
  1765. }
  1766. std::string IUpdater::toString() const
  1767. {
  1768. return typeid(*this).name();
  1769. }
  1770. JsonNode IUpdater::toJsonNode() const
  1771. {
  1772. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1773. }
  1774. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1775. {
  1776. }
  1777. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1778. {
  1779. if(context.getNodeType() == CBonusSystemNode::HERO)
  1780. {
  1781. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  1782. int steps = stepSize ? level / stepSize : level;
  1783. //rounding follows format for HMM3 creature specialty bonus
  1784. int newVal = (valPer20 * steps + 19) / 20;
  1785. //return copy of bonus with updated val
  1786. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1787. newBonus->val = newVal;
  1788. return newBonus;
  1789. }
  1790. return b;
  1791. }
  1792. std::string GrowsWithLevelUpdater::toString() const
  1793. {
  1794. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1795. }
  1796. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1797. {
  1798. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1799. root["type"].String() = "GROWS_WITH_LEVEL";
  1800. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1801. if(stepSize > 1)
  1802. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1803. return root;
  1804. }
  1805. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1806. {
  1807. if(context.getNodeType() == CBonusSystemNode::HERO)
  1808. {
  1809. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  1810. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1811. newBonus->val *= level;
  1812. return newBonus;
  1813. }
  1814. return b;
  1815. }
  1816. std::string TimesHeroLevelUpdater::toString() const
  1817. {
  1818. return "TimesHeroLevelUpdater";
  1819. }
  1820. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1821. {
  1822. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1823. }
  1824. ArmyMovementUpdater::ArmyMovementUpdater():
  1825. base(20),
  1826. divider(3),
  1827. multiplier(10),
  1828. max(700)
  1829. {
  1830. }
  1831. ArmyMovementUpdater::ArmyMovementUpdater(int base, int divider, int multiplier, int max):
  1832. base(base),
  1833. divider(divider),
  1834. multiplier(multiplier),
  1835. max(max)
  1836. {
  1837. }
  1838. std::shared_ptr<Bonus> ArmyMovementUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1839. {
  1840. if(b->type == Bonus::MOVEMENT && context.getNodeType() == CBonusSystemNode::HERO)
  1841. {
  1842. auto speed = static_cast<const CGHeroInstance &>(context).getLowestCreatureSpeed();
  1843. si32 armySpeed = speed * base / divider;
  1844. auto counted = armySpeed * multiplier;
  1845. auto newBonus = std::make_shared<Bonus>(*b);
  1846. newBonus->source = Bonus::ARMY;
  1847. newBonus->val += vstd::amin(counted, max);
  1848. return newBonus;
  1849. }
  1850. if(b->type != Bonus::MOVEMENT)
  1851. logGlobal->error("ArmyMovementUpdater should only be used for MOVEMENT bonus!");
  1852. return b;
  1853. }
  1854. std::string ArmyMovementUpdater::toString() const
  1855. {
  1856. return "ArmyMovementUpdater";
  1857. }
  1858. JsonNode ArmyMovementUpdater::toJsonNode() const
  1859. {
  1860. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1861. root["type"].String() = "ARMY_MOVEMENT";
  1862. root["parameters"].Vector().push_back(JsonUtils::intNode(base));
  1863. root["parameters"].Vector().push_back(JsonUtils::intNode(divider));
  1864. root["parameters"].Vector().push_back(JsonUtils::intNode(multiplier));
  1865. root["parameters"].Vector().push_back(JsonUtils::intNode(max));
  1866. return root;
  1867. }
  1868. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1869. {
  1870. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1871. {
  1872. int level = dynamic_cast<const CStackInstance &>(context).getLevel();
  1873. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1874. newBonus->val *= level;
  1875. return newBonus;
  1876. }
  1877. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1878. {
  1879. const auto & stack = dynamic_cast<const CStack &>(context);
  1880. //only update if stack doesn't have an instance (summons, war machines)
  1881. //otherwise we'd end up multiplying twice
  1882. if(stack.base == nullptr)
  1883. {
  1884. int level = stack.unitType()->getLevel();
  1885. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1886. newBonus->val *= level;
  1887. return newBonus;
  1888. }
  1889. }
  1890. return b;
  1891. }
  1892. std::string TimesStackLevelUpdater::toString() const
  1893. {
  1894. return "TimesStackLevelUpdater";
  1895. }
  1896. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1897. {
  1898. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1899. }
  1900. std::string OwnerUpdater::toString() const
  1901. {
  1902. return "OwnerUpdater";
  1903. }
  1904. JsonNode OwnerUpdater::toJsonNode() const
  1905. {
  1906. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  1907. }
  1908. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1909. {
  1910. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  1911. if(owner == PlayerColor::UNFLAGGABLE)
  1912. owner = PlayerColor::NEUTRAL;
  1913. std::shared_ptr<Bonus> updated =
  1914. std::make_shared<Bonus>(static_cast<Bonus::BonusDuration>(b->duration), b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  1915. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  1916. return updated;
  1917. }
  1918. VCMI_LIB_NAMESPACE_END