HeroBonus.cpp 68 KB

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