2
0

HeroBonus.cpp 67 KB

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