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. #include "GameConstants.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(UNITL_BEING_ATTACKED)
  44. BONUS_ITEM(UNTIL_ATTACK)
  45. BONUS_ITEM(STACK_GETS_TURN)
  46. BONUS_ITEM(COMMANDER_KILLED)
  47. };
  48. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  49. {
  50. BONUS_ITEM(NO_LIMIT)
  51. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  52. BONUS_ITEM(ONLY_MELEE_FIGHT)
  53. BONUS_ITEM(ONLY_ENEMY_ARMY)
  54. };
  55. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  56. {
  57. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  58. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  59. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)}
  60. };
  61. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  62. {
  63. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  64. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  65. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  66. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  67. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  68. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  69. }; //untested
  70. #define BONUS_LOG_LINE(x) logBonus->traceStream() << x
  71. int CBonusSystemNode::treeChanged = 1;
  72. const bool CBonusSystemNode::cachingEnabled = true;
  73. BonusList::BonusList(bool BelongsToTree /* =false */) : belongsToTree(BelongsToTree)
  74. {
  75. }
  76. BonusList::BonusList(const BonusList &bonusList)
  77. {
  78. bonuses.resize(bonusList.size());
  79. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  80. belongsToTree = false;
  81. }
  82. BonusList& BonusList::operator=(const BonusList &bonusList)
  83. {
  84. bonuses.resize(bonusList.size());
  85. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  86. belongsToTree = false;
  87. return *this;
  88. }
  89. int BonusList::totalValue() const
  90. {
  91. int base = 0;
  92. int percentToBase = 0;
  93. int percentToAll = 0;
  94. int additive = 0;
  95. int indepMax = 0;
  96. bool hasIndepMax = false;
  97. int indepMin = 0;
  98. bool hasIndepMin = false;
  99. for (auto & elem : bonuses)
  100. {
  101. Bonus *b = elem;
  102. switch(b->valType)
  103. {
  104. case Bonus::BASE_NUMBER:
  105. base += b->val;
  106. break;
  107. case Bonus::PERCENT_TO_ALL:
  108. percentToAll += b->val;
  109. break;
  110. case Bonus::PERCENT_TO_BASE:
  111. percentToBase += b->val;
  112. break;
  113. case Bonus::ADDITIVE_VALUE:
  114. additive += b->val;
  115. break;
  116. case Bonus::INDEPENDENT_MAX:
  117. if (!hasIndepMax)
  118. {
  119. indepMax = b->val;
  120. hasIndepMax = true;
  121. }
  122. else
  123. {
  124. vstd::amax(indepMax, b->val);
  125. }
  126. break;
  127. case Bonus::INDEPENDENT_MIN:
  128. if (!hasIndepMin)
  129. {
  130. indepMin = b->val;
  131. hasIndepMin = true;
  132. }
  133. else
  134. {
  135. vstd::amin(indepMin, b->val);
  136. }
  137. break;
  138. }
  139. }
  140. int modifiedBase = base + (base * percentToBase) / 100;
  141. modifiedBase += additive;
  142. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  143. if(hasIndepMin && hasIndepMax)
  144. assert(indepMin < indepMax);
  145. const int notIndepBonuses = boost::count_if(bonuses, [](const Bonus *b)
  146. {
  147. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  148. });
  149. if (hasIndepMax)
  150. {
  151. if(notIndepBonuses)
  152. vstd::amax(valFirst, indepMax);
  153. else
  154. valFirst = indepMax;
  155. }
  156. if (hasIndepMin)
  157. {
  158. if(notIndepBonuses)
  159. vstd::amin(valFirst, indepMin);
  160. else
  161. valFirst = indepMin;
  162. }
  163. return valFirst;
  164. }
  165. const Bonus * BonusList::getFirst(const CSelector &selector) const
  166. {
  167. for (auto & elem : bonuses)
  168. {
  169. const Bonus *b = elem;
  170. if(selector(b))
  171. return &*b;
  172. }
  173. return nullptr;
  174. }
  175. Bonus * BonusList::getFirst(const CSelector &select)
  176. {
  177. for (auto & elem : bonuses)
  178. {
  179. Bonus *b = elem;
  180. if(select(b))
  181. return &*b;
  182. }
  183. return nullptr;
  184. }
  185. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  186. {
  187. getBonuses(out, selector, nullptr);
  188. }
  189. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  190. {
  191. for (auto & elem : bonuses)
  192. {
  193. Bonus *b = elem;
  194. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  195. if(selector(b) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b))))
  196. out.push_back(b);
  197. }
  198. }
  199. void BonusList::getAllBonuses(BonusList &out) const
  200. {
  201. for(Bonus *b : bonuses)
  202. out.push_back(b);
  203. }
  204. int BonusList::valOfBonuses(const CSelector &select) const
  205. {
  206. BonusList ret;
  207. CSelector limit = nullptr;
  208. getBonuses(ret, select, limit);
  209. ret.eliminateDuplicates();
  210. return ret.totalValue();
  211. }
  212. // void BonusList::limit(const CBonusSystemNode &node)
  213. // {
  214. // remove_if(std::bind(&CBonusSystemNode::isLimitedOnUs, std::ref(node), _1));
  215. // }
  216. void BonusList::eliminateDuplicates()
  217. {
  218. sort( bonuses.begin(), bonuses.end() );
  219. bonuses.erase( unique( bonuses.begin(), bonuses.end() ), bonuses.end() );
  220. }
  221. void BonusList::push_back(Bonus* const &x)
  222. {
  223. bonuses.push_back(x);
  224. if (belongsToTree)
  225. CBonusSystemNode::treeHasChanged();
  226. }
  227. std::vector<Bonus*>::iterator BonusList::erase(const int position)
  228. {
  229. if (belongsToTree)
  230. CBonusSystemNode::treeHasChanged();
  231. return bonuses.erase(bonuses.begin() + position);
  232. }
  233. void BonusList::clear()
  234. {
  235. bonuses.clear();
  236. if (belongsToTree)
  237. CBonusSystemNode::treeHasChanged();
  238. }
  239. std::vector<BonusList*>::size_type BonusList::operator-=(Bonus* const &i)
  240. {
  241. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  242. if(itr == bonuses.end())
  243. return false;
  244. bonuses.erase(itr);
  245. if (belongsToTree)
  246. CBonusSystemNode::treeHasChanged();
  247. return true;
  248. }
  249. void BonusList::resize(std::vector<Bonus*>::size_type sz, Bonus* c )
  250. {
  251. bonuses.resize(sz, c);
  252. if (belongsToTree)
  253. CBonusSystemNode::treeHasChanged();
  254. }
  255. void BonusList::insert(std::vector<Bonus*>::iterator position, std::vector<Bonus*>::size_type n, Bonus* const &x)
  256. {
  257. bonuses.insert(position, n, x);
  258. if (belongsToTree)
  259. CBonusSystemNode::treeHasChanged();
  260. }
  261. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  262. {
  263. return valOfBonuses(Selector::type(type).And(selector));
  264. }
  265. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype /*= -1*/) const
  266. {
  267. std::stringstream cachingStr;
  268. cachingStr << "type_" << type << "s_" << subtype;
  269. CSelector s = Selector::type(type);
  270. if(subtype != -1)
  271. s = s.And(Selector::subtype(subtype));
  272. return valOfBonuses(s, cachingStr.str());
  273. }
  274. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  275. {
  276. CSelector limit = nullptr;
  277. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  278. return hlp->totalValue();
  279. }
  280. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr /*= ""*/) const
  281. {
  282. return getBonuses(selector, cachingStr)->size() > 0;
  283. }
  284. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype /*= -1*/) const
  285. {
  286. std::stringstream cachingStr;
  287. cachingStr << "type_" << type << "s_" << subtype;
  288. CSelector s = Selector::type(type);
  289. if(subtype != -1)
  290. s = s.And(Selector::subtype(subtype));
  291. return hasBonus(s, cachingStr.str());
  292. }
  293. int IBonusBearer::getBonusesCount(Bonus::BonusSource from, int id) const
  294. {
  295. std::stringstream cachingStr;
  296. cachingStr << "source_" << from << "id_" << id;
  297. return getBonusesCount(Selector::source(from, id), cachingStr.str());
  298. }
  299. int IBonusBearer::getBonusesCount(const CSelector &selector, const std::string &cachingStr /* =""*/) const
  300. {
  301. return getBonuses(selector, cachingStr)->size();
  302. }
  303. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr /*= ""*/) const
  304. {
  305. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  306. }
  307. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr /*= ""*/) const
  308. {
  309. return getAllBonuses(selector, limit, nullptr, cachingStr);
  310. }
  311. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  312. {
  313. std::stringstream cachingStr;
  314. cachingStr << "source_" << source << "id_" << sourceID;
  315. return hasBonus(Selector::source(source,sourceID), cachingStr.str());
  316. }
  317. int IBonusBearer::MoraleVal() const
  318. {
  319. if(hasBonusOfType(Bonus::NON_LIVING) || hasBonusOfType(Bonus::UNDEAD) ||
  320. hasBonusOfType(Bonus::NO_MORALE) || hasBonusOfType(Bonus::SIEGE_WEAPON))
  321. return 0;
  322. int ret = valOfBonuses(Bonus::MORALE);
  323. if(hasBonusOfType(Bonus::SELF_MORALE)) //eg. minotaur
  324. vstd::amax(ret, +1);
  325. return vstd::abetween(ret, -3, +3);
  326. }
  327. int IBonusBearer::LuckVal() const
  328. {
  329. if(hasBonusOfType(Bonus::NO_LUCK))
  330. return 0;
  331. int ret = valOfBonuses(Bonus::LUCK);
  332. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  333. vstd::amax(ret, +1);
  334. return vstd::abetween(ret, -3, +3);
  335. }
  336. si32 IBonusBearer::Attack() const
  337. {
  338. si32 ret = valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  339. if (double frenzyPower = valOfBonuses(Bonus::IN_FRENZY)) //frenzy for attacker
  340. {
  341. ret += (frenzyPower/100) * (double)Defense(false);
  342. }
  343. vstd::amax(ret, 0);
  344. return ret;
  345. }
  346. si32 IBonusBearer::Defense(bool withFrenzy /*= true*/) const
  347. {
  348. si32 ret = valOfBonuses(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  349. if(withFrenzy && hasBonusOfType(Bonus::IN_FRENZY)) //frenzy for defender
  350. {
  351. return 0;
  352. }
  353. vstd::amax(ret, 0);
  354. return ret;
  355. }
  356. ui32 IBonusBearer::MaxHealth() const
  357. {
  358. return std::max(1, valOfBonuses(Bonus::STACK_HEALTH)); //never 0
  359. }
  360. ui32 IBonusBearer::getMinDamage() const
  361. {
  362. std::stringstream cachingStr;
  363. cachingStr << "type_" << Bonus::CREATURE_DAMAGE << "s_0Otype_" << Bonus::CREATURE_DAMAGE << "s_1";
  364. return valOfBonuses(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1)), cachingStr.str());
  365. }
  366. ui32 IBonusBearer::getMaxDamage() const
  367. {
  368. std::stringstream cachingStr;
  369. cachingStr << "type_" << Bonus::CREATURE_DAMAGE << "s_0Otype_" << Bonus::CREATURE_DAMAGE << "s_2";
  370. return valOfBonuses(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2)), cachingStr.str());
  371. }
  372. si32 IBonusBearer::manaLimit() const
  373. {
  374. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  375. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  376. / 10.0);
  377. }
  378. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  379. {
  380. int ret = 0;
  381. if(id == PrimarySkill::ATTACK)
  382. ret = Attack();
  383. else if(id == PrimarySkill::DEFENSE)
  384. ret = Defense();
  385. else
  386. ret = valOfBonuses(Bonus::PRIMARY_SKILL, id);
  387. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  388. return ret;
  389. }
  390. si32 IBonusBearer::magicResistance() const
  391. {
  392. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  393. }
  394. ui32 IBonusBearer::Speed( int turn /*= 0*/ , bool useBind /* = false*/) const
  395. {
  396. //war machines cannot move
  397. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  398. {
  399. return 0;
  400. }
  401. //bind effect check - doesn't influence stack initiative
  402. if (useBind && getEffect (SpellID::BIND))
  403. {
  404. return 0;
  405. }
  406. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  407. }
  408. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  409. {
  410. std::stringstream cachingStr;
  411. cachingStr << "type_" << Bonus::UNDEAD << "s_-1Otype_" << Bonus::NON_LIVING << "s_-11type_" << Bonus::SIEGE_WEAPON; //I don't really get what string labels mean?
  412. return !hasBonus(Selector::type(Bonus::UNDEAD)
  413. .Or(Selector::type(Bonus::NON_LIVING))
  414. .Or(Selector::type(Bonus::SIEGE_WEAPON)), cachingStr.str());
  415. }
  416. const TBonusListPtr IBonusBearer::getSpellBonuses() const
  417. {
  418. std::stringstream cachingStr;
  419. cachingStr << "!type_" << Bonus::NONE << "source_" << Bonus::SPELL_EFFECT;
  420. CSelector selector = Selector::sourceType(Bonus::SPELL_EFFECT)
  421. .And(CSelector([](const Bonus * b)->bool
  422. {
  423. return b->type != Bonus::NONE;
  424. }));
  425. return getBonuses(selector, Selector::anyRange(), cachingStr.str());
  426. }
  427. const Bonus * IBonusBearer::getEffect(ui16 id, int turn /*= 0*/) const
  428. {
  429. //TODO should check only local bonuses?
  430. auto bonuses = getAllBonuses();
  431. for(const Bonus *it : *bonuses)
  432. {
  433. if(it->source == Bonus::SPELL_EFFECT && it->sid == id)
  434. {
  435. if(!turn || it->turnsRemain > turn)
  436. return &(*it);
  437. }
  438. }
  439. return nullptr;
  440. }
  441. ui8 IBonusBearer::howManyEffectsSet(ui16 id) const
  442. {
  443. //TODO should check only local bonuses?
  444. ui8 ret = 0;
  445. auto bonuses = getAllBonuses();
  446. for(const Bonus *it : *bonuses)
  447. {
  448. if(it->source == Bonus::SPELL_EFFECT && it->sid == id) //effect found
  449. {
  450. ++ret;
  451. }
  452. }
  453. return ret;
  454. }
  455. const TBonusListPtr IBonusBearer::getAllBonuses() const
  456. {
  457. auto matchAll= [] (const Bonus *) { return true; };
  458. auto matchNone= [] (const Bonus *) { return true; };
  459. return getAllBonuses(matchAll, matchNone);
  460. }
  461. const Bonus * IBonusBearer::getBonus(const CSelector &selector) const
  462. {
  463. auto bonuses = getAllBonuses();
  464. return bonuses->getFirst(selector);
  465. }
  466. Bonus * CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  467. {
  468. Bonus *ret = bonuses.getFirst(selector);
  469. if(ret)
  470. return ret;
  471. FOREACH_PARENT(pname)
  472. {
  473. ret = pname->getBonusLocalFirst(selector);
  474. if (ret)
  475. return ret;
  476. }
  477. return nullptr;
  478. }
  479. const Bonus * CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  480. {
  481. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  482. }
  483. void CBonusSystemNode::getParents(TCNodes &out) const /*retreives list of parent nodes (nodes to inherit bonuses from) */
  484. {
  485. for (auto & elem : parents)
  486. {
  487. const CBonusSystemNode *parent = elem;
  488. out.insert(parent);
  489. }
  490. }
  491. void CBonusSystemNode::getParents(TNodes &out)
  492. {
  493. for (auto & elem : parents)
  494. {
  495. const CBonusSystemNode *parent = elem;
  496. out.insert(const_cast<CBonusSystemNode*>(parent));
  497. }
  498. }
  499. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  500. {
  501. FOREACH_CPARENT(p)
  502. {
  503. p->getBonusesRec(out, selector, limit);
  504. }
  505. bonuses.getBonuses(out, selector, limit);
  506. }
  507. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  508. {
  509. FOREACH_CPARENT(p)
  510. {
  511. p->getAllBonusesRec(out);
  512. }
  513. bonuses.getAllBonuses(out);
  514. }
  515. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/, const std::string &cachingStr /*= ""*/) const
  516. {
  517. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  518. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  519. {
  520. // Exclusive access for one thread
  521. static boost::mutex m;
  522. boost::mutex::scoped_lock lock(m);
  523. // If the bonus system tree changes(state of a single node or the relations to each other) then
  524. // cache all bonus objects. Selector objects doesn't matter.
  525. if (cachedLast != treeChanged)
  526. {
  527. cachedBonuses.clear();
  528. cachedRequests.clear();
  529. BonusList allBonuses;
  530. getAllBonusesRec(allBonuses);
  531. allBonuses.eliminateDuplicates();
  532. limitBonuses(allBonuses, cachedBonuses);
  533. cachedLast = treeChanged;
  534. }
  535. // If a bonus system request comes with a caching string then look up in the map if there are any
  536. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  537. if (cachingStr != "")
  538. {
  539. auto it = cachedRequests.find(cachingStr);
  540. if(it != cachedRequests.end())
  541. {
  542. //Cached list contains bonuses for our query with applied limiters
  543. return it->second;
  544. }
  545. }
  546. //We still don't have the bonuses (didn't returned them from cache)
  547. //Perform bonus selection
  548. auto ret = std::make_shared<BonusList>();
  549. cachedBonuses.getBonuses(*ret, selector, limit);
  550. // Save the results in the cache
  551. if(cachingStr != "")
  552. cachedRequests[cachingStr] = ret;
  553. return ret;
  554. }
  555. else
  556. {
  557. return getAllBonusesWithoutCaching(selector, limit, root);
  558. }
  559. }
  560. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root /*= nullptr*/) const
  561. {
  562. auto ret = std::make_shared<BonusList>();
  563. // Get bonus results without caching enabled.
  564. BonusList beforeLimiting, afterLimiting;
  565. getAllBonusesRec(beforeLimiting);
  566. beforeLimiting.eliminateDuplicates();
  567. if(!root || root == this)
  568. {
  569. limitBonuses(beforeLimiting, afterLimiting);
  570. afterLimiting.getBonuses(*ret, selector, limit);
  571. }
  572. else if(root)
  573. {
  574. //We want to limit our query against an external node. We get all its bonuses,
  575. // add the ones we're considering and see if they're cut out by limiters
  576. BonusList rootBonuses, limitedRootBonuses;
  577. getAllBonusesRec(rootBonuses);
  578. for(Bonus *b : beforeLimiting)
  579. rootBonuses.push_back(b);
  580. rootBonuses.eliminateDuplicates();
  581. root->limitBonuses(rootBonuses, limitedRootBonuses);
  582. for(Bonus *b : beforeLimiting)
  583. if(vstd::contains(limitedRootBonuses, b))
  584. afterLimiting.push_back(b);
  585. afterLimiting.getBonuses(*ret, selector, limit);
  586. }
  587. else
  588. beforeLimiting.getBonuses(*ret, selector, limit);
  589. return ret;
  590. }
  591. CBonusSystemNode::CBonusSystemNode() : bonuses(true), exportedBonuses(true), nodeType(UNKNOWN), cachedLast(0)
  592. {
  593. }
  594. CBonusSystemNode::~CBonusSystemNode()
  595. {
  596. detachFromAll();
  597. if(children.size())
  598. {
  599. logBonus->warnStream() << "Warning: an orphaned child!";
  600. while(children.size())
  601. children.front()->detachFrom(this);
  602. }
  603. for(Bonus *b : exportedBonuses)
  604. delete b;
  605. }
  606. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  607. {
  608. assert(!vstd::contains(parents, parent));
  609. parents.push_back(parent);
  610. if(parent->actsAsBonusSourceOnly())
  611. parent->newRedDescendant(this);
  612. else
  613. newRedDescendant(parent);
  614. parent->newChildAttached(this);
  615. CBonusSystemNode::treeHasChanged();
  616. }
  617. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  618. {
  619. assert(vstd::contains(parents, parent));
  620. if(parent->actsAsBonusSourceOnly())
  621. parent->removedRedDescendant(this);
  622. else
  623. removedRedDescendant(parent);
  624. parents -= parent;
  625. parent->childDetached(this);
  626. CBonusSystemNode::treeHasChanged();
  627. }
  628. void CBonusSystemNode::popBonuses(const CSelector &s)
  629. {
  630. BonusList bl;
  631. exportedBonuses.getBonuses(bl, s);
  632. for(Bonus *b : bl)
  633. removeBonus(b);
  634. for(CBonusSystemNode *child : children)
  635. child->popBonuses(s);
  636. }
  637. void CBonusSystemNode::updateBonuses(const CSelector &s)
  638. {
  639. BonusList bl;
  640. exportedBonuses.getBonuses(bl, s);
  641. for(Bonus *b : bl)
  642. {
  643. b->turnsRemain--;
  644. if(b->turnsRemain <= 0)
  645. removeBonus(b);
  646. }
  647. for(CBonusSystemNode *child : children)
  648. child->updateBonuses(s);
  649. }
  650. void CBonusSystemNode::addNewBonus(Bonus *b)
  651. {
  652. //turnsRemain shouldn't be zero for following durations
  653. if(Bonus::NTurns(b) || Bonus::NDays(b) || Bonus::OneWeek(b))
  654. {
  655. assert(b->turnsRemain);
  656. }
  657. assert(!vstd::contains(exportedBonuses,b));
  658. exportedBonuses.push_back(b);
  659. exportBonus(b);
  660. CBonusSystemNode::treeHasChanged();
  661. }
  662. void CBonusSystemNode::accumulateBonus(Bonus &b)
  663. {
  664. Bonus *bonus = exportedBonuses.getFirst(Selector::typeSubtype(b.type, b.subtype)); //only local bonuses are interesting //TODO: what about value type?
  665. if(bonus)
  666. bonus->val += b.val;
  667. else
  668. addNewBonus(new Bonus(b)); //duplicate needed, original may get destroyed
  669. }
  670. void CBonusSystemNode::removeBonus(Bonus *b)
  671. {
  672. exportedBonuses -= b;
  673. if(b->propagator)
  674. unpropagateBonus(b);
  675. else
  676. bonuses -= b;
  677. vstd::clear_pointer(b);
  678. CBonusSystemNode::treeHasChanged();
  679. }
  680. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  681. {
  682. switch(nodeType)
  683. {
  684. case CREATURE:
  685. case ARTIFACT:
  686. case ARTIFACT_INSTANCE:
  687. return true;
  688. default:
  689. return false;
  690. }
  691. }
  692. void CBonusSystemNode::propagateBonus(Bonus * b)
  693. {
  694. if(b->propagator->shouldBeAttached(this))
  695. {
  696. bonuses.push_back(b);
  697. BONUS_LOG_LINE("#$# " << b->Description() << " #propagated to# " << nodeName());
  698. }
  699. FOREACH_RED_CHILD(child)
  700. child->propagateBonus(b);
  701. }
  702. void CBonusSystemNode::unpropagateBonus(Bonus * b)
  703. {
  704. if(b->propagator->shouldBeAttached(this))
  705. {
  706. bonuses -= b;
  707. while(vstd::contains(bonuses, b))
  708. {
  709. logBonus->errorStream() << "Bonus was duplicated (" << b->Description() << ") at " << nodeName();
  710. bonuses -= b;
  711. }
  712. BONUS_LOG_LINE("#$#" << b->Description() << " #is no longer propagated to# " << nodeName());
  713. }
  714. FOREACH_RED_CHILD(child)
  715. child->unpropagateBonus(b);
  716. }
  717. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  718. {
  719. assert(!vstd::contains(children, child));
  720. children.push_back(child);
  721. //BONUS_LOG_LINE(child->nodeName() << " #attached to# " << nodeName());
  722. }
  723. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  724. {
  725. if (vstd::contains(children, child))
  726. children -= child;
  727. else
  728. {
  729. logBonus->errorStream() << std::string("Error!" + child->nodeName() + " #cannot be detached from# " + nodeName());
  730. assert(0);
  731. }
  732. }
  733. void CBonusSystemNode::detachFromAll()
  734. {
  735. while(parents.size())
  736. detachFrom(parents.front());
  737. }
  738. bool CBonusSystemNode::isIndependentNode() const
  739. {
  740. return parents.empty() && children.empty();
  741. }
  742. std::string CBonusSystemNode::nodeName() const
  743. {
  744. return description.size()
  745. ? description
  746. : std::string("Bonus system node of type ") + typeid(*this).name();
  747. }
  748. void CBonusSystemNode::deserializationFix()
  749. {
  750. exportBonuses();
  751. }
  752. void CBonusSystemNode::getRedParents(TNodes &out)
  753. {
  754. FOREACH_PARENT(pname)
  755. {
  756. if(pname->actsAsBonusSourceOnly())
  757. {
  758. out.insert(pname);
  759. }
  760. }
  761. if(!actsAsBonusSourceOnly())
  762. {
  763. for(CBonusSystemNode *child : children)
  764. {
  765. out.insert(child);
  766. }
  767. }
  768. }
  769. void CBonusSystemNode::getRedChildren(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::newRedDescendant(CBonusSystemNode *descendant)
  787. {
  788. for(Bonus *b : exportedBonuses)
  789. if(b->propagator)
  790. descendant->propagateBonus(b);
  791. FOREACH_RED_PARENT(parent)
  792. parent->newRedDescendant(descendant);
  793. }
  794. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  795. {
  796. for(Bonus *b : exportedBonuses)
  797. if(b->propagator)
  798. descendant->unpropagateBonus(b);
  799. FOREACH_RED_PARENT(parent)
  800. parent->removedRedDescendant(descendant);
  801. }
  802. void CBonusSystemNode::getRedAncestors(TNodes &out)
  803. {
  804. getRedParents(out);
  805. FOREACH_RED_PARENT(p)
  806. p->getRedAncestors(out);
  807. }
  808. void CBonusSystemNode::getRedDescendants(TNodes &out)
  809. {
  810. getRedChildren(out);
  811. FOREACH_RED_CHILD(c)
  812. c->getRedChildren(out);
  813. }
  814. void CBonusSystemNode::battleTurnPassed()
  815. {
  816. updateBonuses(Bonus::NTurns);
  817. }
  818. void CBonusSystemNode::exportBonus(Bonus * b)
  819. {
  820. if(b->propagator)
  821. propagateBonus(b);
  822. else
  823. bonuses.push_back(b);
  824. CBonusSystemNode::treeHasChanged();
  825. }
  826. void CBonusSystemNode::exportBonuses()
  827. {
  828. for(Bonus *b : exportedBonuses)
  829. exportBonus(b);
  830. }
  831. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  832. {
  833. return nodeType;
  834. }
  835. const BonusList& CBonusSystemNode::getBonusList() const
  836. {
  837. return bonuses;
  838. }
  839. const TNodesVector& CBonusSystemNode::getParentNodes() const
  840. {
  841. return parents;
  842. }
  843. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  844. {
  845. return children;
  846. }
  847. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  848. {
  849. nodeType = type;
  850. }
  851. BonusList& CBonusSystemNode::getExportedBonusList()
  852. {
  853. return exportedBonuses;
  854. }
  855. const std::string& CBonusSystemNode::getDescription() const
  856. {
  857. return description;
  858. }
  859. void CBonusSystemNode::setDescription(const std::string &description)
  860. {
  861. this->description = description;
  862. }
  863. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  864. {
  865. assert(&allBonuses != &out); //todo should it work in-place?
  866. BonusList undecided = allBonuses,
  867. &accepted = out;
  868. while(true)
  869. {
  870. int undecidedCount = undecided.size();
  871. for(int i = 0; i < undecided.size(); i++)
  872. {
  873. Bonus *b = undecided[i];
  874. BonusLimitationContext context = {b, *this, out};
  875. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  876. if(decision == ILimiter::DISCARD)
  877. {
  878. undecided.erase(i);
  879. i--; continue;
  880. }
  881. else if(decision == ILimiter::ACCEPT)
  882. {
  883. accepted.push_back(b);
  884. undecided.erase(i);
  885. i--; continue;
  886. }
  887. else
  888. assert(decision == ILimiter::NOT_SURE);
  889. }
  890. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  891. return;
  892. }
  893. }
  894. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  895. {
  896. auto ret = std::make_shared<BonusList>();
  897. limitBonuses(allBonuses, *ret);
  898. return ret;
  899. }
  900. void CBonusSystemNode::treeHasChanged()
  901. {
  902. treeChanged++;
  903. }
  904. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype /*= -1*/)
  905. {
  906. if(obj)
  907. return obj->valOfBonuses(type, subtype);
  908. return 0;
  909. }
  910. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype /*= -1*/)
  911. {
  912. if(obj)
  913. return obj->hasBonusOfType(type, subtype);
  914. return false;
  915. }
  916. int NBonus::getCount(const CBonusSystemNode *obj, Bonus::BonusSource from, int id)
  917. {
  918. if(obj)
  919. return obj->getBonusesCount(from, id);
  920. return 0;
  921. }
  922. const CSpell * Bonus::sourceSpell() const
  923. {
  924. if(source == SPELL_EFFECT)
  925. return SpellID(sid).toSpell();
  926. return nullptr;
  927. }
  928. std::string Bonus::Description() const
  929. {
  930. std::ostringstream str;
  931. if(description.empty())
  932. switch(source)
  933. {
  934. case ARTIFACT:
  935. str << VLC->arth->artifacts[sid]->Name();
  936. break;;
  937. case SPELL_EFFECT:
  938. str << SpellID(sid).toSpell()->name;
  939. break;
  940. case CREATURE_ABILITY:
  941. str << VLC->creh->creatures[sid]->namePl;
  942. break;
  943. case SECONDARY_SKILL:
  944. str << VLC->generaltexth->skillName[sid]/* << " secondary skill"*/;
  945. break;
  946. default:
  947. //todo: handle all possible sources
  948. str << "Unknown";
  949. break;
  950. }
  951. else
  952. str << description;
  953. if(val != 0)
  954. str << " " << std::showpos << val;
  955. return str.str();
  956. }
  957. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype/*=-1*/)
  958. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  959. {
  960. additionalInfo = -1;
  961. turnsRemain = 0;
  962. valType = ADDITIVE_VALUE;
  963. effectRange = NO_LIMIT;
  964. boost::algorithm::trim(description);
  965. }
  966. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype/*=-1*/, ValueType ValType /*= ADDITIVE_VALUE*/)
  967. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  968. {
  969. additionalInfo = -1;
  970. turnsRemain = 0;
  971. effectRange = NO_LIMIT;
  972. }
  973. Bonus::Bonus()
  974. {
  975. duration = PERMANENT;
  976. turnsRemain = 0;
  977. type = NONE;
  978. subtype = -1;
  979. additionalInfo = -1;
  980. valType = ADDITIVE_VALUE;
  981. effectRange = NO_LIMIT;
  982. val = 0;
  983. source = OTHER;
  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. }