HeroBonus.cpp 37 KB

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