HeroBonus.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979
  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 "CGeneralTextHandler.h"
  18. #include "CSkillHandler.h"
  19. #include "CStack.h"
  20. #include "CArtHandler.h"
  21. #include "StringConstants.h"
  22. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  23. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  24. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  25. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  26. #define BONUS_NAME(x) { #x, Bonus::x },
  27. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  28. #undef BONUS_NAME
  29. #define BONUS_VALUE(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  31. #undef BONUS_VALUE
  32. #define BONUS_SOURCE(x) { #x, Bonus::x },
  33. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  34. #undef BONUS_SOURCE
  35. #define BONUS_ITEM(x) { #x, Bonus::x },
  36. const std::map<std::string, ui16> bonusDurationMap =
  37. {
  38. BONUS_ITEM(PERMANENT)
  39. BONUS_ITEM(ONE_BATTLE)
  40. BONUS_ITEM(ONE_DAY)
  41. BONUS_ITEM(ONE_WEEK)
  42. BONUS_ITEM(N_TURNS)
  43. BONUS_ITEM(N_DAYS)
  44. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  45. BONUS_ITEM(UNTIL_ATTACK)
  46. BONUS_ITEM(STACK_GETS_TURN)
  47. BONUS_ITEM(COMMANDER_KILLED)
  48. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  49. };
  50. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  51. {
  52. BONUS_ITEM(NO_LIMIT)
  53. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  54. BONUS_ITEM(ONLY_MELEE_FIGHT)
  55. BONUS_ITEM(ONLY_ENEMY_ARMY)
  56. };
  57. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  58. {
  59. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  60. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  61. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)}
  62. };
  63. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  64. {
  65. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  66. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  67. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  68. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  69. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  70. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  71. }; //untested
  72. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  73. {
  74. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  75. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()}
  76. };
  77. ///CBonusProxy
  78. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  79. : cachedLast(0),
  80. target(Target),
  81. selector(Selector),
  82. data()
  83. {
  84. }
  85. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  86. : cachedLast(other.cachedLast),
  87. target(other.target),
  88. selector(other.selector),
  89. data(other.data)
  90. {
  91. }
  92. CBonusProxy::CBonusProxy(CBonusProxy && other)
  93. : cachedLast(0),
  94. target(other.target),
  95. selector(),
  96. data()
  97. {
  98. std::swap(cachedLast, other.cachedLast);
  99. std::swap(selector, other.selector);
  100. std::swap(data, other.data);
  101. }
  102. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  103. {
  104. cachedLast = other.cachedLast;
  105. selector = other.selector;
  106. data = other.data;
  107. return *this;
  108. }
  109. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  110. {
  111. std::swap(cachedLast, other.cachedLast);
  112. std::swap(selector, other.selector);
  113. std::swap(data, other.data);
  114. return *this;
  115. }
  116. TBonusListPtr CBonusProxy::get() const
  117. {
  118. if(target->getTreeVersion() != cachedLast || !data)
  119. {
  120. //TODO: support limiters
  121. data = target->getAllBonuses(selector, Selector::all);
  122. cachedLast = target->getTreeVersion();
  123. }
  124. return data;
  125. }
  126. const BonusList * CBonusProxy::operator->() const
  127. {
  128. return get().get();
  129. }
  130. CAddInfo::CAddInfo()
  131. {
  132. }
  133. CAddInfo::CAddInfo(si32 value)
  134. {
  135. if(value != CAddInfo::NONE)
  136. push_back(value);
  137. }
  138. bool CAddInfo::operator==(si32 value) const
  139. {
  140. switch(size())
  141. {
  142. case 0:
  143. return value == CAddInfo::NONE;
  144. case 1:
  145. return operator[](0) == value;
  146. default:
  147. return false;
  148. }
  149. }
  150. bool CAddInfo::operator!=(si32 value) const
  151. {
  152. return !operator==(value);
  153. }
  154. si32 & CAddInfo::operator[](size_type pos)
  155. {
  156. if(pos >= size())
  157. resize(pos + 1, CAddInfo::NONE);
  158. return vector::operator[](pos);
  159. }
  160. si32 CAddInfo::operator[](size_type pos) const
  161. {
  162. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  163. }
  164. std::string CAddInfo::toString() const
  165. {
  166. return toJsonNode().toJson(true);
  167. }
  168. JsonNode CAddInfo::toJsonNode() const
  169. {
  170. if(size() < 2)
  171. {
  172. return JsonUtils::intNode(operator[](0));
  173. }
  174. else
  175. {
  176. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  177. for(si32 value : *this)
  178. node.Vector().push_back(JsonUtils::intNode(value));
  179. return node;
  180. }
  181. }
  182. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  183. const bool CBonusSystemNode::cachingEnabled = true;
  184. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  185. {
  186. }
  187. BonusList::BonusList(const BonusList &bonusList)
  188. {
  189. bonuses.resize(bonusList.size());
  190. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  191. belongsToTree = false;
  192. }
  193. BonusList::BonusList(BonusList&& other):
  194. belongsToTree(false)
  195. {
  196. std::swap(belongsToTree, other.belongsToTree);
  197. std::swap(bonuses, other.bonuses);
  198. }
  199. BonusList& BonusList::operator=(const BonusList &bonusList)
  200. {
  201. bonuses.resize(bonusList.size());
  202. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  203. belongsToTree = false;
  204. return *this;
  205. }
  206. void BonusList::changed()
  207. {
  208. if(belongsToTree)
  209. CBonusSystemNode::treeHasChanged();
  210. }
  211. void BonusList::stackBonuses()
  212. {
  213. boost::sort(bonuses, [](std::shared_ptr<Bonus> b1, std::shared_ptr<Bonus> b2) -> bool
  214. {
  215. if(b1 == b2)
  216. return false;
  217. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  218. COMPARE_ATT(stacking);
  219. COMPARE_ATT(type);
  220. COMPARE_ATT(subtype);
  221. COMPARE_ATT(valType);
  222. #undef COMPARE_ATT
  223. return b1->val > b2->val;
  224. });
  225. // remove non-stacking
  226. size_t next = 1;
  227. while(next < bonuses.size())
  228. {
  229. bool remove;
  230. const std::shared_ptr<Bonus> last = bonuses[next-1];
  231. const std::shared_ptr<Bonus> current = bonuses[next];
  232. if(current->stacking.empty())
  233. remove = current == last;
  234. else if(current->stacking == "ALWAYS")
  235. remove = false;
  236. else
  237. remove = current->stacking == last->stacking
  238. && current->type == last->type
  239. && current->subtype == last->subtype
  240. && current->valType == last->valType;
  241. if(remove)
  242. bonuses.erase(bonuses.begin() + next);
  243. else
  244. next++;
  245. }
  246. }
  247. int BonusList::totalValue() const
  248. {
  249. int base = 0;
  250. int percentToBase = 0;
  251. int percentToAll = 0;
  252. int additive = 0;
  253. int indepMax = 0;
  254. bool hasIndepMax = false;
  255. int indepMin = 0;
  256. bool hasIndepMin = false;
  257. for(std::shared_ptr<Bonus> b : bonuses)
  258. {
  259. switch(b->valType)
  260. {
  261. case Bonus::BASE_NUMBER:
  262. base += b->val;
  263. break;
  264. case Bonus::PERCENT_TO_ALL:
  265. percentToAll += b->val;
  266. break;
  267. case Bonus::PERCENT_TO_BASE:
  268. percentToBase += b->val;
  269. break;
  270. case Bonus::ADDITIVE_VALUE:
  271. additive += b->val;
  272. break;
  273. case Bonus::INDEPENDENT_MAX:
  274. if (!hasIndepMax)
  275. {
  276. indepMax = b->val;
  277. hasIndepMax = true;
  278. }
  279. else
  280. {
  281. vstd::amax(indepMax, b->val);
  282. }
  283. break;
  284. case Bonus::INDEPENDENT_MIN:
  285. if (!hasIndepMin)
  286. {
  287. indepMin = b->val;
  288. hasIndepMin = true;
  289. }
  290. else
  291. {
  292. vstd::amin(indepMin, b->val);
  293. }
  294. break;
  295. }
  296. }
  297. int modifiedBase = base + (base * percentToBase) / 100;
  298. modifiedBase += additive;
  299. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  300. if(hasIndepMin && hasIndepMax)
  301. assert(indepMin < indepMax);
  302. const int notIndepBonuses = boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  303. {
  304. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  305. });
  306. if (hasIndepMax)
  307. {
  308. if(notIndepBonuses)
  309. vstd::amax(valFirst, indepMax);
  310. else
  311. valFirst = indepMax;
  312. }
  313. if (hasIndepMin)
  314. {
  315. if(notIndepBonuses)
  316. vstd::amin(valFirst, indepMin);
  317. else
  318. valFirst = indepMin;
  319. }
  320. return valFirst;
  321. }
  322. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  323. {
  324. for (auto & b : bonuses)
  325. {
  326. if(select(b.get()))
  327. return b;
  328. }
  329. return nullptr;
  330. }
  331. const std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &selector) const
  332. {
  333. for (auto & b : bonuses)
  334. {
  335. if(selector(b.get()))
  336. return b;
  337. }
  338. return nullptr;
  339. }
  340. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  341. {
  342. getBonuses(out, selector, nullptr);
  343. }
  344. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  345. {
  346. for (auto & b : bonuses)
  347. {
  348. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  349. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  350. out.push_back(b);
  351. }
  352. }
  353. void BonusList::getAllBonuses(BonusList &out) const
  354. {
  355. for(auto & b : bonuses)
  356. out.push_back(b);
  357. }
  358. int BonusList::valOfBonuses(const CSelector &select) const
  359. {
  360. BonusList ret;
  361. CSelector limit = nullptr;
  362. getBonuses(ret, select, limit);
  363. return ret.totalValue();
  364. }
  365. JsonNode BonusList::toJsonNode() const
  366. {
  367. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  368. for(std::shared_ptr<Bonus> b : bonuses)
  369. node.Vector().push_back(b->toJsonNode());
  370. return node;
  371. }
  372. void BonusList::push_back(std::shared_ptr<Bonus> x)
  373. {
  374. bonuses.push_back(x);
  375. changed();
  376. }
  377. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  378. {
  379. changed();
  380. return bonuses.erase(bonuses.begin() + position);
  381. }
  382. void BonusList::clear()
  383. {
  384. bonuses.clear();
  385. changed();
  386. }
  387. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  388. {
  389. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  390. if(itr == bonuses.end())
  391. return false;
  392. bonuses.erase(itr);
  393. changed();
  394. return true;
  395. }
  396. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  397. {
  398. bonuses.resize(sz, c);
  399. changed();
  400. }
  401. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  402. {
  403. bonuses.insert(position, n, x);
  404. changed();
  405. }
  406. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  407. {
  408. return valOfBonuses(Selector::type(type).And(selector));
  409. }
  410. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  411. {
  412. std::stringstream cachingStr;
  413. cachingStr << "type_" << type << "s_" << subtype;
  414. CSelector s = Selector::type(type);
  415. if(subtype != -1)
  416. s = s.And(Selector::subtype(subtype));
  417. return valOfBonuses(s, cachingStr.str());
  418. }
  419. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  420. {
  421. CSelector limit = nullptr;
  422. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  423. return hlp->totalValue();
  424. }
  425. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  426. {
  427. return getBonuses(selector, cachingStr)->size() > 0;
  428. }
  429. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  430. {
  431. return getBonuses(selector, limit, cachingStr)->size() > 0;
  432. }
  433. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  434. {
  435. std::stringstream cachingStr;
  436. cachingStr << "type_" << type << "s_" << subtype;
  437. CSelector s = Selector::type(type);
  438. if(subtype != -1)
  439. s = s.And(Selector::subtype(subtype));
  440. return hasBonus(s, cachingStr.str());
  441. }
  442. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  443. {
  444. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  445. }
  446. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  447. {
  448. return getAllBonuses(selector, limit, nullptr, cachingStr);
  449. }
  450. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  451. {
  452. std::stringstream cachingStr;
  453. cachingStr << "source_" << source << "id_" << sourceID;
  454. return hasBonus(Selector::source(source,sourceID), cachingStr.str());
  455. }
  456. int IBonusBearer::MoraleVal() const
  457. {
  458. if(hasBonusOfType(Bonus::NON_LIVING) || hasBonusOfType(Bonus::UNDEAD) ||
  459. hasBonusOfType(Bonus::NO_MORALE) || hasBonusOfType(Bonus::SIEGE_WEAPON))
  460. return 0;
  461. int ret = valOfBonuses(Bonus::MORALE);
  462. if(hasBonusOfType(Bonus::SELF_MORALE)) //eg. minotaur
  463. vstd::amax(ret, +1);
  464. return vstd::abetween(ret, -3, +3);
  465. }
  466. int IBonusBearer::LuckVal() const
  467. {
  468. if(hasBonusOfType(Bonus::NO_LUCK))
  469. return 0;
  470. int ret = valOfBonuses(Bonus::LUCK);
  471. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  472. vstd::amax(ret, +1);
  473. return vstd::abetween(ret, -3, +3);
  474. }
  475. ui32 IBonusBearer::MaxHealth() const
  476. {
  477. const std::string cachingStr = "type_STACK_HEALTH";
  478. static const auto selector = Selector::type(Bonus::STACK_HEALTH);
  479. auto value = valOfBonuses(selector, cachingStr);
  480. return std::max(1, value); //never 0
  481. }
  482. int IBonusBearer::getAttack(bool ranged) const
  483. {
  484. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  485. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  486. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  487. }
  488. int IBonusBearer::getDefence(bool ranged) const
  489. {
  490. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  491. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  492. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  493. }
  494. int IBonusBearer::getMinDamage(bool ranged) const
  495. {
  496. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  497. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  498. return valOfBonuses(selector, cachingStr);
  499. }
  500. int IBonusBearer::getMaxDamage(bool ranged) const
  501. {
  502. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  503. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  504. return valOfBonuses(selector, cachingStr);
  505. }
  506. si32 IBonusBearer::manaLimit() const
  507. {
  508. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  509. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  510. / 10.0);
  511. }
  512. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  513. {
  514. int ret = valOfBonuses(Bonus::PRIMARY_SKILL, id);
  515. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  516. return ret;
  517. }
  518. si32 IBonusBearer::magicResistance() const
  519. {
  520. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  521. }
  522. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  523. {
  524. //war machines cannot move
  525. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  526. {
  527. return 0;
  528. }
  529. //bind effect check - doesn't influence stack initiative
  530. if(useBind && hasBonus(Selector::type(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  531. {
  532. return 0;
  533. }
  534. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  535. }
  536. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  537. {
  538. std::stringstream cachingStr;
  539. cachingStr << "type_" << Bonus::UNDEAD << "s_-1Otype_" << Bonus::NON_LIVING << "s_-11type_" << Bonus::SIEGE_WEAPON; //I don't really get what string labels mean?
  540. return !hasBonus(Selector::type(Bonus::UNDEAD)
  541. .Or(Selector::type(Bonus::NON_LIVING))
  542. .Or(Selector::type(Bonus::SIEGE_WEAPON)), cachingStr.str());
  543. }
  544. const std::shared_ptr<Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  545. {
  546. auto bonuses = getAllBonuses(selector, Selector::all);
  547. return bonuses->getFirst(Selector::all);
  548. }
  549. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  550. {
  551. auto ret = bonuses.getFirst(selector);
  552. if(ret)
  553. return ret;
  554. FOREACH_PARENT(pname)
  555. {
  556. ret = pname->getBonusLocalFirst(selector);
  557. if (ret)
  558. return ret;
  559. }
  560. return nullptr;
  561. }
  562. const std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  563. {
  564. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  565. }
  566. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  567. {
  568. for (auto & elem : parents)
  569. {
  570. const CBonusSystemNode *parent = elem;
  571. out.insert(parent);
  572. }
  573. }
  574. void CBonusSystemNode::getParents(TNodes &out)
  575. {
  576. for (auto & elem : parents)
  577. {
  578. const CBonusSystemNode *parent = elem;
  579. out.insert(const_cast<CBonusSystemNode*>(parent));
  580. }
  581. }
  582. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  583. {
  584. BonusList beforeUpdate;
  585. FOREACH_CPARENT(p)
  586. {
  587. p->getBonusesRec(beforeUpdate, selector, limit);
  588. }
  589. bonuses.getBonuses(beforeUpdate, selector, limit);
  590. for(auto b : beforeUpdate)
  591. out.push_back(update(b));
  592. }
  593. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  594. {
  595. BonusList beforeUpdate;
  596. FOREACH_CPARENT(p)
  597. {
  598. p->getAllBonusesRec(beforeUpdate);
  599. }
  600. bonuses.getAllBonuses(beforeUpdate);
  601. for(auto b : beforeUpdate)
  602. out.push_back(update(b));
  603. }
  604. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  605. {
  606. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  607. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  608. {
  609. // Exclusive access for one thread
  610. static boost::mutex m;
  611. boost::mutex::scoped_lock lock(m);
  612. // If the bonus system tree changes(state of a single node or the relations to each other) then
  613. // cache all bonus objects. Selector objects doesn't matter.
  614. if (cachedLast != treeChanged)
  615. {
  616. cachedBonuses.clear();
  617. cachedRequests.clear();
  618. BonusList allBonuses;
  619. getAllBonusesRec(allBonuses);
  620. limitBonuses(allBonuses, cachedBonuses);
  621. cachedBonuses.stackBonuses();
  622. cachedLast = treeChanged;
  623. }
  624. // If a bonus system request comes with a caching string then look up in the map if there are any
  625. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  626. if (cachingStr != "")
  627. {
  628. auto it = cachedRequests.find(cachingStr);
  629. if(it != cachedRequests.end())
  630. {
  631. //Cached list contains bonuses for our query with applied limiters
  632. return it->second;
  633. }
  634. }
  635. //We still don't have the bonuses (didn't returned them from cache)
  636. //Perform bonus selection
  637. auto ret = std::make_shared<BonusList>();
  638. cachedBonuses.getBonuses(*ret, selector, limit);
  639. // Save the results in the cache
  640. if(cachingStr != "")
  641. cachedRequests[cachingStr] = ret;
  642. return ret;
  643. }
  644. else
  645. {
  646. return getAllBonusesWithoutCaching(selector, limit, root);
  647. }
  648. }
  649. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  650. {
  651. auto ret = std::make_shared<BonusList>();
  652. // Get bonus results without caching enabled.
  653. BonusList beforeLimiting, afterLimiting;
  654. getAllBonusesRec(beforeLimiting);
  655. if(!root || root == this)
  656. {
  657. limitBonuses(beforeLimiting, afterLimiting);
  658. }
  659. else if(root)
  660. {
  661. //We want to limit our query against an external node. We get all its bonuses,
  662. // add the ones we're considering and see if they're cut out by limiters
  663. BonusList rootBonuses, limitedRootBonuses;
  664. getAllBonusesRec(rootBonuses);
  665. for(auto b : beforeLimiting)
  666. rootBonuses.push_back(b);
  667. root->limitBonuses(rootBonuses, limitedRootBonuses);
  668. for(auto b : beforeLimiting)
  669. if(vstd::contains(limitedRootBonuses, b))
  670. afterLimiting.push_back(b);
  671. }
  672. afterLimiting.getBonuses(*ret, selector, limit);
  673. ret->stackBonuses();
  674. return ret;
  675. }
  676. const std::shared_ptr<Bonus> CBonusSystemNode::update(const std::shared_ptr<Bonus> b) const
  677. {
  678. if(b->updater)
  679. return b->updater->update(b, *this);
  680. return b;
  681. }
  682. CBonusSystemNode::CBonusSystemNode()
  683. : bonuses(true),
  684. exportedBonuses(true),
  685. nodeType(UNKNOWN),
  686. cachedLast(0)
  687. {
  688. }
  689. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  690. : bonuses(true),
  691. exportedBonuses(true),
  692. nodeType(NodeType),
  693. cachedLast(0)
  694. {
  695. }
  696. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  697. bonuses(std::move(other.bonuses)),
  698. exportedBonuses(std::move(other.exportedBonuses)),
  699. nodeType(other.nodeType),
  700. description(other.description),
  701. cachedLast(0)
  702. {
  703. std::swap(parents, other.parents);
  704. std::swap(children, other.children);
  705. //fixing bonus tree without recalculation
  706. for(CBonusSystemNode * n : parents)
  707. {
  708. n->children -= &other;
  709. n->children.push_back(this);
  710. }
  711. for(CBonusSystemNode * n : children)
  712. {
  713. n->parents -= &other;
  714. n->parents.push_back(this);
  715. }
  716. //cache ignored
  717. //cachedBonuses
  718. //cachedRequests
  719. }
  720. CBonusSystemNode::~CBonusSystemNode()
  721. {
  722. detachFromAll();
  723. if(children.size())
  724. {
  725. while(children.size())
  726. children.front()->detachFrom(this);
  727. }
  728. }
  729. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  730. {
  731. assert(!vstd::contains(parents, parent));
  732. parents.push_back(parent);
  733. if(parent->actsAsBonusSourceOnly())
  734. parent->newRedDescendant(this);
  735. else
  736. newRedDescendant(parent);
  737. parent->newChildAttached(this);
  738. CBonusSystemNode::treeHasChanged();
  739. }
  740. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  741. {
  742. assert(vstd::contains(parents, parent));
  743. if(parent->actsAsBonusSourceOnly())
  744. parent->removedRedDescendant(this);
  745. else
  746. removedRedDescendant(parent);
  747. parents -= parent;
  748. parent->childDetached(this);
  749. CBonusSystemNode::treeHasChanged();
  750. }
  751. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  752. {
  753. removeBonuses(s);
  754. for(CBonusSystemNode * child : children)
  755. child->removeBonusesRecursive(s);
  756. }
  757. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  758. {
  759. BonusList bl;
  760. exportedBonuses.getBonuses(bl, s, Selector::all);
  761. for(auto b : bl)
  762. {
  763. b->turnsRemain--;
  764. if(b->turnsRemain <= 0)
  765. removeBonus(b);
  766. }
  767. for(CBonusSystemNode *child : children)
  768. child->reduceBonusDurations(s);
  769. }
  770. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  771. {
  772. //turnsRemain shouldn't be zero for following durations
  773. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  774. {
  775. assert(b->turnsRemain);
  776. }
  777. assert(!vstd::contains(exportedBonuses, b));
  778. exportedBonuses.push_back(b);
  779. exportBonus(b);
  780. CBonusSystemNode::treeHasChanged();
  781. }
  782. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  783. {
  784. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  785. if(bonus)
  786. bonus->val += b->val;
  787. else
  788. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  789. }
  790. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  791. {
  792. exportedBonuses -= b;
  793. if(b->propagator)
  794. unpropagateBonus(b);
  795. else
  796. bonuses -= b;
  797. CBonusSystemNode::treeHasChanged();
  798. }
  799. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  800. {
  801. BonusList toRemove;
  802. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  803. for(auto bonus : toRemove)
  804. removeBonus(bonus);
  805. }
  806. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  807. {
  808. switch(nodeType)
  809. {
  810. case CREATURE:
  811. case ARTIFACT:
  812. case ARTIFACT_INSTANCE:
  813. return true;
  814. default:
  815. return false;
  816. }
  817. }
  818. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  819. {
  820. if(b->propagator->shouldBeAttached(this))
  821. {
  822. bonuses.push_back(b);
  823. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  824. }
  825. FOREACH_RED_CHILD(child)
  826. child->propagateBonus(b);
  827. }
  828. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  829. {
  830. if(b->propagator->shouldBeAttached(this))
  831. {
  832. bonuses -= b;
  833. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  834. }
  835. FOREACH_RED_CHILD(child)
  836. child->unpropagateBonus(b);
  837. }
  838. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  839. {
  840. assert(!vstd::contains(children, child));
  841. children.push_back(child);
  842. }
  843. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  844. {
  845. if (vstd::contains(children, child))
  846. children -= child;
  847. else
  848. {
  849. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  850. throw std::runtime_error("internal error");
  851. }
  852. }
  853. void CBonusSystemNode::detachFromAll()
  854. {
  855. while(parents.size())
  856. detachFrom(parents.front());
  857. }
  858. bool CBonusSystemNode::isIndependentNode() const
  859. {
  860. return parents.empty() && children.empty();
  861. }
  862. std::string CBonusSystemNode::nodeName() const
  863. {
  864. return description.size()
  865. ? description
  866. : std::string("Bonus system node of type ") + typeid(*this).name();
  867. }
  868. void CBonusSystemNode::deserializationFix()
  869. {
  870. exportBonuses();
  871. }
  872. void CBonusSystemNode::getRedParents(TNodes &out)
  873. {
  874. FOREACH_PARENT(pname)
  875. {
  876. if(pname->actsAsBonusSourceOnly())
  877. {
  878. out.insert(pname);
  879. }
  880. }
  881. if(!actsAsBonusSourceOnly())
  882. {
  883. for(CBonusSystemNode *child : children)
  884. {
  885. out.insert(child);
  886. }
  887. }
  888. }
  889. void CBonusSystemNode::getRedChildren(TNodes &out)
  890. {
  891. FOREACH_PARENT(pname)
  892. {
  893. if(!pname->actsAsBonusSourceOnly())
  894. {
  895. out.insert(pname);
  896. }
  897. }
  898. if(actsAsBonusSourceOnly())
  899. {
  900. for(CBonusSystemNode *child : children)
  901. {
  902. out.insert(child);
  903. }
  904. }
  905. }
  906. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  907. {
  908. for(auto b : exportedBonuses)
  909. if(b->propagator)
  910. descendant->propagateBonus(b);
  911. FOREACH_RED_PARENT(parent)
  912. parent->newRedDescendant(descendant);
  913. }
  914. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  915. {
  916. for(auto b : exportedBonuses)
  917. if(b->propagator)
  918. descendant->unpropagateBonus(b);
  919. FOREACH_RED_PARENT(parent)
  920. parent->removedRedDescendant(descendant);
  921. }
  922. void CBonusSystemNode::getRedAncestors(TNodes &out)
  923. {
  924. getRedParents(out);
  925. FOREACH_RED_PARENT(p)
  926. p->getRedAncestors(out);
  927. }
  928. void CBonusSystemNode::getRedDescendants(TNodes &out)
  929. {
  930. getRedChildren(out);
  931. FOREACH_RED_CHILD(c)
  932. c->getRedChildren(out);
  933. }
  934. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  935. {
  936. if(b->propagator)
  937. propagateBonus(b);
  938. else
  939. bonuses.push_back(b);
  940. CBonusSystemNode::treeHasChanged();
  941. }
  942. void CBonusSystemNode::exportBonuses()
  943. {
  944. for(auto b : exportedBonuses)
  945. exportBonus(b);
  946. }
  947. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  948. {
  949. return nodeType;
  950. }
  951. const BonusList& CBonusSystemNode::getBonusList() const
  952. {
  953. return bonuses;
  954. }
  955. const TNodesVector& CBonusSystemNode::getParentNodes() const
  956. {
  957. return parents;
  958. }
  959. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  960. {
  961. return children;
  962. }
  963. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  964. {
  965. nodeType = type;
  966. }
  967. BonusList& CBonusSystemNode::getExportedBonusList()
  968. {
  969. return exportedBonuses;
  970. }
  971. const std::string& CBonusSystemNode::getDescription() const
  972. {
  973. return description;
  974. }
  975. void CBonusSystemNode::setDescription(const std::string &description)
  976. {
  977. this->description = description;
  978. }
  979. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  980. {
  981. assert(&allBonuses != &out); //todo should it work in-place?
  982. BonusList undecided = allBonuses,
  983. &accepted = out;
  984. while(true)
  985. {
  986. int undecidedCount = undecided.size();
  987. for(int i = 0; i < undecided.size(); i++)
  988. {
  989. auto b = undecided[i];
  990. BonusLimitationContext context = {b, *this, out};
  991. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  992. if(decision == ILimiter::DISCARD)
  993. {
  994. undecided.erase(i);
  995. i--; continue;
  996. }
  997. else if(decision == ILimiter::ACCEPT)
  998. {
  999. accepted.push_back(b);
  1000. undecided.erase(i);
  1001. i--; continue;
  1002. }
  1003. else
  1004. assert(decision == ILimiter::NOT_SURE);
  1005. }
  1006. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1007. return;
  1008. }
  1009. }
  1010. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1011. {
  1012. auto ret = std::make_shared<BonusList>();
  1013. limitBonuses(allBonuses, *ret);
  1014. return ret;
  1015. }
  1016. void CBonusSystemNode::treeHasChanged()
  1017. {
  1018. treeChanged++;
  1019. }
  1020. int64_t CBonusSystemNode::getTreeVersion() const
  1021. {
  1022. int64_t ret = treeChanged;
  1023. return ret << 32;
  1024. }
  1025. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1026. {
  1027. if(obj)
  1028. return obj->valOfBonuses(type, subtype);
  1029. return 0;
  1030. }
  1031. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1032. {
  1033. if(obj)
  1034. return obj->hasBonusOfType(type, subtype);
  1035. return false;
  1036. }
  1037. std::string Bonus::Description() const
  1038. {
  1039. std::ostringstream str;
  1040. if(description.empty())
  1041. {
  1042. if(stacking.empty() || stacking == "ALWAYS")
  1043. {
  1044. switch(source)
  1045. {
  1046. case ARTIFACT:
  1047. str << VLC->arth->artifacts[sid]->Name();
  1048. break;
  1049. case SPELL_EFFECT:
  1050. str << SpellID(sid).toSpell()->name;
  1051. break;
  1052. case CREATURE_ABILITY:
  1053. str << VLC->creh->creatures[sid]->namePl;
  1054. break;
  1055. case SECONDARY_SKILL:
  1056. str << VLC->skillh->skillName(sid);
  1057. break;
  1058. default:
  1059. //todo: handle all possible sources
  1060. str << "Unknown";
  1061. break;
  1062. }
  1063. }
  1064. else
  1065. str << stacking;
  1066. }
  1067. else
  1068. {
  1069. str << description;
  1070. }
  1071. if(val != 0)
  1072. str << " " << std::showpos << val;
  1073. return str.str();
  1074. }
  1075. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1076. {
  1077. switch(type)
  1078. {
  1079. case Bonus::PRIMARY_SKILL:
  1080. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1081. case Bonus::SECONDARY_SKILL_PREMY:
  1082. return JsonUtils::stringNode("skill." + NSecondarySkill::names[subtype]);
  1083. case Bonus::SPECIAL_SPELL_LEV:
  1084. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1085. case Bonus::SPECIAL_BLESS_DAMAGE:
  1086. case Bonus::MAXED_SPELL:
  1087. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1088. return JsonUtils::stringNode("spell." + (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  1089. case Bonus::IMPROVED_NECROMANCY:
  1090. case Bonus::SPECIAL_UPGRADE:
  1091. return JsonUtils::stringNode("creature." + CreatureID::encode(subtype));
  1092. case Bonus::GENERATE_RESOURCE:
  1093. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1094. default:
  1095. return JsonUtils::intNode(subtype);
  1096. }
  1097. }
  1098. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1099. {
  1100. switch(type)
  1101. {
  1102. case Bonus::SPECIAL_UPGRADE:
  1103. return JsonUtils::stringNode("creature." + CreatureID::encode(addInfo[0]));
  1104. default:
  1105. return addInfo.toJsonNode();
  1106. }
  1107. }
  1108. JsonNode durationToJson(ui16 duration)
  1109. {
  1110. std::vector<std::string> durationNames;
  1111. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1112. {
  1113. if(duration & durBit)
  1114. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1115. }
  1116. if(durationNames.size() == 1)
  1117. {
  1118. return JsonUtils::stringNode(durationNames[0]);
  1119. }
  1120. else
  1121. {
  1122. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1123. for(std::string dur : durationNames)
  1124. node.Vector().push_back(JsonUtils::stringNode(dur));
  1125. return node;
  1126. }
  1127. }
  1128. JsonNode Bonus::toJsonNode() const
  1129. {
  1130. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1131. // only add values that might reasonably be found in config files
  1132. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1133. if(subtype != -1)
  1134. root["subtype"] = subtypeToJson(type, subtype);
  1135. if(additionalInfo != CAddInfo::NONE)
  1136. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1137. if(val != 0)
  1138. root["val"].Integer() = val;
  1139. if(valType != ADDITIVE_VALUE)
  1140. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1141. if(stacking != "")
  1142. root["stacking"].String() = stacking;
  1143. if(description != "")
  1144. root["description"].String() = description;
  1145. if(effectRange != NO_LIMIT)
  1146. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1147. if(duration != PERMANENT)
  1148. root["duration"] = durationToJson(duration);
  1149. if(turnsRemain)
  1150. root["turns"].Integer() = turnsRemain;
  1151. if(limiter)
  1152. root["limiters"].Vector().push_back(limiter->toJsonNode());
  1153. if(updater)
  1154. root["updater"] = updater->toJsonNode();
  1155. if(propagator)
  1156. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1157. return root;
  1158. }
  1159. std::string Bonus::nameForBonus() const
  1160. {
  1161. switch(type)
  1162. {
  1163. case Bonus::PRIMARY_SKILL:
  1164. return PrimarySkill::names[subtype];
  1165. case Bonus::SECONDARY_SKILL_PREMY:
  1166. return NSecondarySkill::names[subtype];
  1167. case Bonus::SPECIAL_SPELL_LEV:
  1168. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1169. case Bonus::SPECIAL_BLESS_DAMAGE:
  1170. case Bonus::MAXED_SPELL:
  1171. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1172. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1173. case Bonus::SPECIAL_UPGRADE:
  1174. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1175. case Bonus::GENERATE_RESOURCE:
  1176. return GameConstants::RESOURCE_NAMES[subtype];
  1177. case Bonus::STACKS_SPEED:
  1178. return "speed";
  1179. default:
  1180. return vstd::findKey(bonusNameMap, type);
  1181. }
  1182. }
  1183. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1184. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1185. {
  1186. turnsRemain = 0;
  1187. valType = ADDITIVE_VALUE;
  1188. effectRange = NO_LIMIT;
  1189. boost::algorithm::trim(description);
  1190. }
  1191. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1192. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1193. {
  1194. turnsRemain = 0;
  1195. effectRange = NO_LIMIT;
  1196. }
  1197. Bonus::Bonus()
  1198. {
  1199. duration = PERMANENT;
  1200. turnsRemain = 0;
  1201. type = NONE;
  1202. subtype = -1;
  1203. valType = ADDITIVE_VALUE;
  1204. effectRange = NO_LIMIT;
  1205. val = 0;
  1206. source = OTHER;
  1207. sid = 0;
  1208. }
  1209. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1210. {
  1211. propagator = Propagator;
  1212. return this->shared_from_this();
  1213. }
  1214. namespace Selector
  1215. {
  1216. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1217. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1218. DLL_LINKAGE CSelectFieldEqual<CAddInfo> info(&Bonus::additionalInfo);
  1219. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1220. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1221. DLL_LINKAGE CWillLastTurns turns;
  1222. DLL_LINKAGE CWillLastDays days;
  1223. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1224. {
  1225. return type(Type).And(subtype(Subtype));
  1226. }
  1227. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1228. {
  1229. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1230. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1231. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1232. }
  1233. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1234. {
  1235. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1236. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1237. }
  1238. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1239. {
  1240. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1241. }
  1242. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1243. {
  1244. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1245. }
  1246. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1247. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1248. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1249. {
  1250. Bonus dummy;
  1251. dummy.type = type;
  1252. return sel(&dummy);
  1253. }
  1254. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1255. {
  1256. Bonus dummy;
  1257. dummy.type = type;
  1258. dummy.subtype = subtype;
  1259. return sel(&dummy);
  1260. }
  1261. }
  1262. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1263. {
  1264. switch(node->getNodeType())
  1265. {
  1266. case CBonusSystemNode::STACK_BATTLE:
  1267. return static_cast<const CStack*>(node);
  1268. default:
  1269. return nullptr;
  1270. }
  1271. }
  1272. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1273. {
  1274. switch(node->getNodeType())
  1275. {
  1276. case CBonusSystemNode::STACK_INSTANCE:
  1277. return (static_cast<const CStackInstance *>(node));
  1278. case CBonusSystemNode::STACK_BATTLE:
  1279. return (static_cast<const CStack*>(node))->base;
  1280. default:
  1281. return nullptr;
  1282. }
  1283. }
  1284. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1285. {
  1286. switch(node->getNodeType())
  1287. {
  1288. case CBonusSystemNode::CREATURE:
  1289. return (static_cast<const CCreature *>(node));
  1290. case CBonusSystemNode::STACK_BATTLE:
  1291. return (static_cast<const CStack*>(node))->type;
  1292. default:
  1293. const CStackInstance * csi = retrieveStackInstance(node);
  1294. if(csi)
  1295. return csi->type;
  1296. return nullptr;
  1297. }
  1298. }
  1299. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1300. {
  1301. for (ui32 i = 0; i < bonusList.size(); i++)
  1302. {
  1303. auto b = bonusList[i];
  1304. out << "Bonus " << i << "\n" << *b << std::endl;
  1305. }
  1306. return out;
  1307. }
  1308. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1309. {
  1310. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1311. if(i->second == bonus.type)
  1312. out << "\tType: " << i->first << " \t";
  1313. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1314. printField(val);
  1315. printField(subtype);
  1316. printField(duration);
  1317. printField(source);
  1318. printField(sid);
  1319. if(bonus.additionalInfo != CAddInfo::NONE)
  1320. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1321. printField(turnsRemain);
  1322. printField(valType);
  1323. if(!bonus.stacking.empty())
  1324. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1325. printField(effectRange);
  1326. #undef printField
  1327. if(bonus.limiter)
  1328. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1329. if(bonus.updater)
  1330. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1331. return out;
  1332. }
  1333. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1334. {
  1335. if (limiter)
  1336. {
  1337. //If we already have limiter list, retrieve it
  1338. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1339. if(!limiterList)
  1340. {
  1341. //Create a new limiter list with old limiter and the new one will be pushed later
  1342. limiterList = std::make_shared<LimiterList>();
  1343. limiterList->add(limiter);
  1344. limiter = limiterList;
  1345. }
  1346. limiterList->add(Limiter);
  1347. }
  1348. else
  1349. {
  1350. limiter = Limiter;
  1351. }
  1352. return this->shared_from_this();
  1353. }
  1354. ILimiter::~ILimiter()
  1355. {
  1356. }
  1357. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1358. {
  1359. return false;
  1360. }
  1361. std::string ILimiter::toString() const
  1362. {
  1363. return typeid(*this).name();
  1364. }
  1365. JsonNode ILimiter::toJsonNode() const
  1366. {
  1367. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1368. root["type"].String() = toString();
  1369. return root;
  1370. }
  1371. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1372. {
  1373. const CCreature *c = retrieveCreature(&context.node);
  1374. if(!c)
  1375. return true;
  1376. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1377. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1378. }
  1379. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1380. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1381. {
  1382. }
  1383. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1384. {
  1385. creature = nullptr;
  1386. includeUpgrades = false;
  1387. }
  1388. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1389. {
  1390. creature = VLC->creh->creatures[id];
  1391. }
  1392. std::string CCreatureTypeLimiter::toString() const
  1393. {
  1394. char buf[100];
  1395. sprintf(buf, "CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)",
  1396. creature->identifier.c_str(),
  1397. (includeUpgrades ? "true" : "false"));
  1398. return std::string(buf);
  1399. }
  1400. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1401. {
  1402. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1403. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1404. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1405. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1406. return root;
  1407. }
  1408. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1409. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1410. {
  1411. }
  1412. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1413. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1414. {
  1415. }
  1416. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1417. {
  1418. CSelector mySelector = isSubtypeRelevant
  1419. ? Selector::typeSubtype(type, subtype)
  1420. : Selector::type(type);
  1421. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1422. if(context.alreadyAccepted.getFirst(mySelector))
  1423. return ACCEPT;
  1424. //do not accept for now but it may change if more bonuses gets included
  1425. return NOT_SURE;
  1426. }
  1427. std::string HasAnotherBonusLimiter::toString() const
  1428. {
  1429. char buf[100];
  1430. std::string typeName = vstd::findKey(bonusNameMap, type);
  1431. if(isSubtypeRelevant)
  1432. sprintf(buf, "HasAnotherBonusLimiter(type=%s, subtype=%d)", typeName.c_str(), subtype);
  1433. else
  1434. sprintf(buf, "HasAnotherBonusLimiter(type=%s)", typeName.c_str());
  1435. return std::string(buf);
  1436. }
  1437. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1438. {
  1439. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1440. std::string typeName = vstd::findKey(bonusNameMap, type);
  1441. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1442. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1443. if(isSubtypeRelevant)
  1444. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1445. return root;
  1446. }
  1447. IPropagator::~IPropagator()
  1448. {
  1449. }
  1450. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1451. {
  1452. return false;
  1453. }
  1454. CPropagatorNodeType::CPropagatorNodeType()
  1455. :nodeType(0)
  1456. {
  1457. }
  1458. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1459. : nodeType(NodeType)
  1460. {
  1461. }
  1462. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1463. {
  1464. return nodeType == dest->getNodeType();
  1465. }
  1466. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1467. : terrainType(TerrainType)
  1468. {
  1469. }
  1470. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1471. : terrainType(-1)
  1472. {
  1473. }
  1474. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1475. {
  1476. const CCreature *c = retrieveCreature(&context.node);
  1477. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1478. //TODO neutral creatues
  1479. }
  1480. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1481. : faction(Faction)
  1482. {
  1483. }
  1484. CreatureFactionLimiter::CreatureFactionLimiter()
  1485. : faction(-1)
  1486. {
  1487. }
  1488. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1489. {
  1490. const CCreature *c = retrieveCreature(&context.node);
  1491. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1492. }
  1493. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1494. : alignment(-1)
  1495. {
  1496. }
  1497. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1498. : alignment(Alignment)
  1499. {
  1500. }
  1501. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1502. {
  1503. const CCreature *c = retrieveCreature(&context.node);
  1504. if(!c)
  1505. return true;
  1506. switch(alignment)
  1507. {
  1508. case EAlignment::GOOD:
  1509. return !c->isGood(); //if not good -> return true (drop bonus)
  1510. case EAlignment::NEUTRAL:
  1511. return c->isEvil() || c->isGood();
  1512. case EAlignment::EVIL:
  1513. return !c->isEvil();
  1514. default:
  1515. logBonus->warn("Warning: illegal alignment in limiter!");
  1516. return true;
  1517. }
  1518. }
  1519. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1520. :minRank(Min), maxRank(Max)
  1521. {
  1522. }
  1523. RankRangeLimiter::RankRangeLimiter()
  1524. {
  1525. minRank = maxRank = -1;
  1526. }
  1527. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1528. {
  1529. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1530. if(csi)
  1531. {
  1532. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1533. return true;
  1534. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1535. }
  1536. return true;
  1537. }
  1538. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1539. {
  1540. const CStack * s = retrieveStackBattle(&context.node);
  1541. if(s)
  1542. return s->owner != owner;
  1543. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1544. if(csi && csi->armyObj)
  1545. return csi->armyObj->tempOwner != owner;
  1546. return true;
  1547. }
  1548. StackOwnerLimiter::StackOwnerLimiter()
  1549. : owner(-1)
  1550. {
  1551. }
  1552. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1553. : owner(Owner)
  1554. {
  1555. }
  1556. int LimiterList::limit( const BonusLimitationContext &context ) const
  1557. {
  1558. bool wasntSure = false;
  1559. for(auto limiter : limiters)
  1560. {
  1561. auto result = limiter->limit(context);
  1562. if(result == ILimiter::DISCARD)
  1563. return result;
  1564. if(result == ILimiter::NOT_SURE)
  1565. wasntSure = true;
  1566. }
  1567. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1568. }
  1569. void LimiterList::add( TLimiterPtr limiter )
  1570. {
  1571. limiters.push_back(limiter);
  1572. }
  1573. // Updaters
  1574. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1575. {
  1576. updater = Updater;
  1577. return this->shared_from_this();
  1578. }
  1579. IUpdater::~IUpdater()
  1580. {
  1581. }
  1582. const std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1583. {
  1584. return b;
  1585. }
  1586. std::string IUpdater::toString() const
  1587. {
  1588. return typeid(*this).name();
  1589. }
  1590. JsonNode IUpdater::toJsonNode() const
  1591. {
  1592. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1593. }
  1594. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1595. {
  1596. }
  1597. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1598. {
  1599. }
  1600. const std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1601. {
  1602. if(context.getNodeType() == CBonusSystemNode::HERO)
  1603. {
  1604. int level = static_cast<const CGHeroInstance &>(context).level;
  1605. int steps = stepSize ? level / stepSize : level;
  1606. //rounding follows format for HMM3 creature specialty bonus
  1607. int newVal = (valPer20 * steps + 19) / 20;
  1608. //return copy of bonus with updated val
  1609. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1610. newBonus->val = newVal;
  1611. return newBonus;
  1612. }
  1613. return b;
  1614. }
  1615. std::string GrowsWithLevelUpdater::toString() const
  1616. {
  1617. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1618. }
  1619. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1620. {
  1621. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1622. root["type"].String() = "GROWS_WITH_LEVEL";
  1623. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1624. if(stepSize > 1)
  1625. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1626. return root;
  1627. }
  1628. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1629. {
  1630. }
  1631. const std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1632. {
  1633. if(context.getNodeType() == CBonusSystemNode::HERO)
  1634. {
  1635. int level = static_cast<const CGHeroInstance &>(context).level;
  1636. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1637. newBonus->val *= level;
  1638. return newBonus;
  1639. }
  1640. return b;
  1641. }
  1642. std::string TimesHeroLevelUpdater::toString() const
  1643. {
  1644. return "TimesHeroLevelUpdater";
  1645. }
  1646. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1647. {
  1648. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1649. }
  1650. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1651. {
  1652. }
  1653. const std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1654. {
  1655. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1656. {
  1657. int level = static_cast<const CStackInstance &>(context).getLevel();
  1658. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1659. newBonus->val *= level;
  1660. return newBonus;
  1661. }
  1662. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1663. {
  1664. const CStack & stack = static_cast<const CStack &>(context);
  1665. //only update if stack doesn't have an instance (summons, war machines)
  1666. //otherwise we'd end up multiplying twice
  1667. if(stack.base == nullptr)
  1668. {
  1669. int level = stack.type->level;
  1670. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1671. newBonus->val *= level;
  1672. return newBonus;
  1673. }
  1674. }
  1675. return b;
  1676. }
  1677. std::string TimesStackLevelUpdater::toString() const
  1678. {
  1679. return "TimesStackLevelUpdater";
  1680. }
  1681. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1682. {
  1683. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1684. }