HeroBonus.cpp 66 KB

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