HeroBonus.cpp 39 KB

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