HeroBonus.cpp 38 KB

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