HeroBonus.cpp 65 KB

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