HeroBonus.cpp 38 KB

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