HeroBonus.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  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. :nodeType(0)
  1124. {
  1125. }
  1126. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1127. : nodeType(NodeType)
  1128. {
  1129. }
  1130. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1131. {
  1132. return nodeType == dest->getNodeType();
  1133. }
  1134. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1135. : terrainType(TerrainType)
  1136. {
  1137. }
  1138. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1139. : terrainType(-1)
  1140. {
  1141. }
  1142. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1143. {
  1144. const CCreature *c = retrieveCreature(&context.node);
  1145. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1146. //TODO neutral creatues
  1147. }
  1148. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1149. : faction(Faction)
  1150. {
  1151. }
  1152. CreatureFactionLimiter::CreatureFactionLimiter()
  1153. : faction(-1)
  1154. {
  1155. }
  1156. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1157. {
  1158. const CCreature *c = retrieveCreature(&context.node);
  1159. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1160. }
  1161. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1162. : alignment(-1)
  1163. {
  1164. }
  1165. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1166. : alignment(Alignment)
  1167. {
  1168. }
  1169. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1170. {
  1171. const CCreature *c = retrieveCreature(&context.node);
  1172. if(!c)
  1173. return true;
  1174. switch(alignment)
  1175. {
  1176. case EAlignment::GOOD:
  1177. return !c->isGood(); //if not good -> return true (drop bonus)
  1178. case EAlignment::NEUTRAL:
  1179. return c->isEvil() || c->isGood();
  1180. case EAlignment::EVIL:
  1181. return !c->isEvil();
  1182. default:
  1183. logBonus->warnStream() << "Warning: illegal alignment in limiter!";
  1184. return true;
  1185. }
  1186. }
  1187. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1188. :minRank(Min), maxRank(Max)
  1189. {
  1190. }
  1191. RankRangeLimiter::RankRangeLimiter()
  1192. {
  1193. minRank = maxRank = -1;
  1194. }
  1195. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1196. {
  1197. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1198. if(csi)
  1199. {
  1200. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1201. return true;
  1202. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1203. }
  1204. return true;
  1205. }
  1206. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1207. {
  1208. const CStack *s = retreiveStackBattle(&context.node);
  1209. if(s)
  1210. return s->owner != owner;
  1211. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1212. if(csi && csi->armyObj)
  1213. return csi->armyObj->tempOwner != owner;
  1214. return true;
  1215. }
  1216. StackOwnerLimiter::StackOwnerLimiter()
  1217. : owner(-1)
  1218. {
  1219. }
  1220. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1221. : owner(Owner)
  1222. {
  1223. }
  1224. int LimiterList::limit( const BonusLimitationContext &context ) const
  1225. {
  1226. bool wasntSure = false;
  1227. for(auto limiter : limiters)
  1228. {
  1229. auto result = limiter->limit(context);
  1230. if(result == ILimiter::DISCARD)
  1231. return result;
  1232. if(result == ILimiter::NOT_SURE)
  1233. wasntSure = true;
  1234. }
  1235. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1236. }
  1237. void LimiterList::add( TLimiterPtr limiter )
  1238. {
  1239. limiters.push_back(limiter);
  1240. }