HeroBonus.cpp 53 KB

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