HeroBonus.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470
  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 "CStack.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. return ret;
  534. }
  535. CBonusSystemNode::CBonusSystemNode() : bonuses(true), exportedBonuses(true), nodeType(UNKNOWN), cachedLast(0)
  536. {
  537. }
  538. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  539. bonuses(std::move(other.bonuses)),
  540. exportedBonuses(std::move(other.exportedBonuses)),
  541. nodeType(other.nodeType),
  542. description(other.description),
  543. cachedLast(0)
  544. {
  545. std::swap(parents, other.parents);
  546. std::swap(children, other.children);
  547. //fixing bonus tree without recalculation
  548. for(CBonusSystemNode * n : parents)
  549. {
  550. n->children -= &other;
  551. n->children.push_back(this);
  552. }
  553. for(CBonusSystemNode * n : children)
  554. {
  555. n->parents -= &other;
  556. n->parents.push_back(this);
  557. }
  558. //cache ignored
  559. //cachedBonuses
  560. //cachedRequests
  561. }
  562. CBonusSystemNode::~CBonusSystemNode()
  563. {
  564. detachFromAll();
  565. if(children.size())
  566. {
  567. while(children.size())
  568. children.front()->detachFrom(this);
  569. }
  570. }
  571. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  572. {
  573. assert(!vstd::contains(parents, parent));
  574. parents.push_back(parent);
  575. if(parent->actsAsBonusSourceOnly())
  576. parent->newRedDescendant(this);
  577. else
  578. newRedDescendant(parent);
  579. parent->newChildAttached(this);
  580. CBonusSystemNode::treeHasChanged();
  581. }
  582. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  583. {
  584. assert(vstd::contains(parents, parent));
  585. if(parent->actsAsBonusSourceOnly())
  586. parent->removedRedDescendant(this);
  587. else
  588. removedRedDescendant(parent);
  589. parents -= parent;
  590. parent->childDetached(this);
  591. CBonusSystemNode::treeHasChanged();
  592. }
  593. void CBonusSystemNode::popBonuses(const CSelector &s)
  594. {
  595. BonusList bl;
  596. exportedBonuses.getBonuses(bl, s, Selector::all);
  597. for(auto b : bl)
  598. removeBonus(b);
  599. for(CBonusSystemNode *child : children)
  600. child->popBonuses(s);
  601. }
  602. void CBonusSystemNode::updateBonuses(const CSelector &s)
  603. {
  604. BonusList bl;
  605. exportedBonuses.getBonuses(bl, s, Selector::all);
  606. for(auto b : bl)
  607. {
  608. b->turnsRemain--;
  609. if(b->turnsRemain <= 0)
  610. removeBonus(b);
  611. }
  612. for(CBonusSystemNode *child : children)
  613. child->updateBonuses(s);
  614. }
  615. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  616. {
  617. //turnsRemain shouldn't be zero for following durations
  618. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  619. {
  620. assert(b->turnsRemain);
  621. }
  622. assert(!vstd::contains(exportedBonuses, b));
  623. exportedBonuses.push_back(b);
  624. exportBonus(b);
  625. CBonusSystemNode::treeHasChanged();
  626. }
  627. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  628. {
  629. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  630. if(bonus)
  631. bonus->val += b->val;
  632. else
  633. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  634. }
  635. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  636. {
  637. exportedBonuses -= b;
  638. if(b->propagator)
  639. unpropagateBonus(b);
  640. else
  641. bonuses -= b;
  642. CBonusSystemNode::treeHasChanged();
  643. }
  644. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  645. {
  646. switch(nodeType)
  647. {
  648. case CREATURE:
  649. case ARTIFACT:
  650. case ARTIFACT_INSTANCE:
  651. return true;
  652. default:
  653. return false;
  654. }
  655. }
  656. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  657. {
  658. if(b->propagator->shouldBeAttached(this))
  659. {
  660. bonuses.push_back(b);
  661. BONUS_LOG_LINE("#$# " << b->Description() << " #propagated to# " << nodeName());
  662. }
  663. FOREACH_RED_CHILD(child)
  664. child->propagateBonus(b);
  665. }
  666. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  667. {
  668. if(b->propagator->shouldBeAttached(this))
  669. {
  670. bonuses -= b;
  671. while(vstd::contains(bonuses, b))
  672. {
  673. logBonus->errorStream() << "Bonus was duplicated (" << b->Description() << ") at " << nodeName();
  674. bonuses -= b;
  675. }
  676. BONUS_LOG_LINE("#$#" << b->Description() << " #is no longer propagated to# " << nodeName());
  677. }
  678. FOREACH_RED_CHILD(child)
  679. child->unpropagateBonus(b);
  680. }
  681. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  682. {
  683. assert(!vstd::contains(children, child));
  684. children.push_back(child);
  685. //BONUS_LOG_LINE(child->nodeName() << " #attached to# " << nodeName());
  686. }
  687. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  688. {
  689. if (vstd::contains(children, child))
  690. children -= child;
  691. else
  692. {
  693. logBonus->errorStream() << std::string("Error!" + child->nodeName() + " #cannot be detached from# " + nodeName());
  694. assert(0);
  695. }
  696. }
  697. void CBonusSystemNode::detachFromAll()
  698. {
  699. while(parents.size())
  700. detachFrom(parents.front());
  701. }
  702. bool CBonusSystemNode::isIndependentNode() const
  703. {
  704. return parents.empty() && children.empty();
  705. }
  706. std::string CBonusSystemNode::nodeName() const
  707. {
  708. return description.size()
  709. ? description
  710. : std::string("Bonus system node of type ") + typeid(*this).name();
  711. }
  712. void CBonusSystemNode::deserializationFix()
  713. {
  714. exportBonuses();
  715. }
  716. void CBonusSystemNode::getRedParents(TNodes &out)
  717. {
  718. FOREACH_PARENT(pname)
  719. {
  720. if(pname->actsAsBonusSourceOnly())
  721. {
  722. out.insert(pname);
  723. }
  724. }
  725. if(!actsAsBonusSourceOnly())
  726. {
  727. for(CBonusSystemNode *child : children)
  728. {
  729. out.insert(child);
  730. }
  731. }
  732. }
  733. void CBonusSystemNode::getRedChildren(TNodes &out)
  734. {
  735. FOREACH_PARENT(pname)
  736. {
  737. if(!pname->actsAsBonusSourceOnly())
  738. {
  739. out.insert(pname);
  740. }
  741. }
  742. if(actsAsBonusSourceOnly())
  743. {
  744. for(CBonusSystemNode *child : children)
  745. {
  746. out.insert(child);
  747. }
  748. }
  749. }
  750. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  751. {
  752. for(auto b : exportedBonuses)
  753. if(b->propagator)
  754. descendant->propagateBonus(b);
  755. FOREACH_RED_PARENT(parent)
  756. parent->newRedDescendant(descendant);
  757. }
  758. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  759. {
  760. for(auto b : exportedBonuses)
  761. if(b->propagator)
  762. descendant->unpropagateBonus(b);
  763. FOREACH_RED_PARENT(parent)
  764. parent->removedRedDescendant(descendant);
  765. }
  766. void CBonusSystemNode::getRedAncestors(TNodes &out)
  767. {
  768. getRedParents(out);
  769. FOREACH_RED_PARENT(p)
  770. p->getRedAncestors(out);
  771. }
  772. void CBonusSystemNode::getRedDescendants(TNodes &out)
  773. {
  774. getRedChildren(out);
  775. FOREACH_RED_CHILD(c)
  776. c->getRedChildren(out);
  777. }
  778. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  779. {
  780. if(b->propagator)
  781. propagateBonus(b);
  782. else
  783. bonuses.push_back(b);
  784. CBonusSystemNode::treeHasChanged();
  785. }
  786. void CBonusSystemNode::exportBonuses()
  787. {
  788. for(auto b : exportedBonuses)
  789. exportBonus(b);
  790. }
  791. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  792. {
  793. return nodeType;
  794. }
  795. const BonusList& CBonusSystemNode::getBonusList() const
  796. {
  797. return bonuses;
  798. }
  799. const TNodesVector& CBonusSystemNode::getParentNodes() const
  800. {
  801. return parents;
  802. }
  803. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  804. {
  805. return children;
  806. }
  807. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  808. {
  809. nodeType = type;
  810. }
  811. BonusList& CBonusSystemNode::getExportedBonusList()
  812. {
  813. return exportedBonuses;
  814. }
  815. const std::string& CBonusSystemNode::getDescription() const
  816. {
  817. return description;
  818. }
  819. void CBonusSystemNode::setDescription(const std::string &description)
  820. {
  821. this->description = description;
  822. }
  823. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  824. {
  825. assert(&allBonuses != &out); //todo should it work in-place?
  826. BonusList undecided = allBonuses,
  827. &accepted = out;
  828. while(true)
  829. {
  830. int undecidedCount = undecided.size();
  831. for(int i = 0; i < undecided.size(); i++)
  832. {
  833. auto b = undecided[i];
  834. BonusLimitationContext context = {b, *this, out};
  835. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  836. if(decision == ILimiter::DISCARD)
  837. {
  838. undecided.erase(i);
  839. i--; continue;
  840. }
  841. else if(decision == ILimiter::ACCEPT)
  842. {
  843. accepted.push_back(b);
  844. undecided.erase(i);
  845. i--; continue;
  846. }
  847. else
  848. assert(decision == ILimiter::NOT_SURE);
  849. }
  850. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  851. return;
  852. }
  853. }
  854. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  855. {
  856. auto ret = std::make_shared<BonusList>();
  857. limitBonuses(allBonuses, *ret);
  858. return ret;
  859. }
  860. void CBonusSystemNode::treeHasChanged()
  861. {
  862. treeChanged++;
  863. }
  864. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype /*= -1*/)
  865. {
  866. if(obj)
  867. return obj->valOfBonuses(type, subtype);
  868. return 0;
  869. }
  870. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype /*= -1*/)
  871. {
  872. if(obj)
  873. return obj->hasBonusOfType(type, subtype);
  874. return false;
  875. }
  876. std::string Bonus::Description() const
  877. {
  878. std::ostringstream str;
  879. if(description.empty())
  880. switch(source)
  881. {
  882. case ARTIFACT:
  883. str << VLC->arth->artifacts[sid]->Name();
  884. break;;
  885. case SPELL_EFFECT:
  886. str << SpellID(sid).toSpell()->name;
  887. break;
  888. case CREATURE_ABILITY:
  889. str << VLC->creh->creatures[sid]->namePl;
  890. break;
  891. case SECONDARY_SKILL:
  892. str << VLC->generaltexth->skillName[sid]/* << " secondary skill"*/;
  893. break;
  894. default:
  895. //todo: handle all possible sources
  896. str << "Unknown";
  897. break;
  898. }
  899. else
  900. str << description;
  901. if(val != 0)
  902. str << " " << std::showpos << val;
  903. return str.str();
  904. }
  905. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype/*=-1*/)
  906. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  907. {
  908. additionalInfo = -1;
  909. turnsRemain = 0;
  910. valType = ADDITIVE_VALUE;
  911. effectRange = NO_LIMIT;
  912. boost::algorithm::trim(description);
  913. }
  914. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype/*=-1*/, ValueType ValType /*= ADDITIVE_VALUE*/)
  915. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  916. {
  917. additionalInfo = -1;
  918. turnsRemain = 0;
  919. effectRange = NO_LIMIT;
  920. }
  921. Bonus::Bonus()
  922. {
  923. duration = PERMANENT;
  924. turnsRemain = 0;
  925. type = NONE;
  926. subtype = -1;
  927. additionalInfo = -1;
  928. valType = ADDITIVE_VALUE;
  929. effectRange = NO_LIMIT;
  930. val = 0;
  931. source = OTHER;
  932. sid = 0;
  933. }
  934. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  935. {
  936. propagator = Propagator;
  937. return this->shared_from_this();
  938. }
  939. namespace Selector
  940. {
  941. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  942. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  943. DLL_LINKAGE CSelectFieldEqual<si32> info(&Bonus::additionalInfo);
  944. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  945. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  946. DLL_LINKAGE CWillLastTurns turns;
  947. DLL_LINKAGE CWillLastDays days;
  948. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  949. {
  950. return type(Type).And(subtype(Subtype));
  951. }
  952. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, si32 info)
  953. {
  954. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  955. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  956. .And(CSelectFieldEqual<si32>(&Bonus::additionalInfo)(info));
  957. }
  958. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  959. {
  960. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  961. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  962. }
  963. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  964. {
  965. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  966. }
  967. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  968. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  969. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  970. {
  971. Bonus dummy;
  972. dummy.type = type;
  973. return sel(&dummy);
  974. }
  975. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  976. {
  977. Bonus dummy;
  978. dummy.type = type;
  979. dummy.subtype = subtype;
  980. return sel(&dummy);
  981. }
  982. }
  983. const CStack * retreiveStackBattle(const CBonusSystemNode *node)
  984. {
  985. switch(node->getNodeType())
  986. {
  987. case CBonusSystemNode::STACK_BATTLE:
  988. return static_cast<const CStack*>(node);
  989. default:
  990. return nullptr;
  991. }
  992. }
  993. const CStackInstance * retreiveStackInstance(const CBonusSystemNode *node)
  994. {
  995. switch(node->getNodeType())
  996. {
  997. case CBonusSystemNode::STACK_INSTANCE:
  998. return (static_cast<const CStackInstance *>(node));
  999. case CBonusSystemNode::STACK_BATTLE:
  1000. return (static_cast<const CStack*>(node))->base;
  1001. default:
  1002. return nullptr;
  1003. }
  1004. }
  1005. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1006. {
  1007. switch(node->getNodeType())
  1008. {
  1009. case CBonusSystemNode::CREATURE:
  1010. return (static_cast<const CCreature *>(node));
  1011. default:
  1012. const CStackInstance *csi = retreiveStackInstance(node);
  1013. if(csi)
  1014. return csi->type;
  1015. return nullptr;
  1016. }
  1017. }
  1018. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1019. {
  1020. for (ui32 i = 0; i < bonusList.size(); i++)
  1021. {
  1022. auto b = bonusList[i];
  1023. out << "Bonus " << i << "\n" << *b << std::endl;
  1024. }
  1025. return out;
  1026. }
  1027. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1028. {
  1029. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1030. if(i->second == bonus.type)
  1031. out << "\tType: " << i->first << " \t";
  1032. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1033. printField(val);
  1034. printField(subtype);
  1035. printField(duration);
  1036. printField(source);
  1037. printField(sid);
  1038. printField(additionalInfo);
  1039. printField(turnsRemain);
  1040. printField(valType);
  1041. printField(effectRange);
  1042. #undef printField
  1043. return out;
  1044. }
  1045. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1046. {
  1047. if (limiter)
  1048. {
  1049. //If we already have limiter list, retrieve it
  1050. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1051. if(!limiterList)
  1052. {
  1053. //Create a new limiter list with old limiter and the new one will be pushed later
  1054. limiterList = std::make_shared<LimiterList>();
  1055. limiterList->add(limiter);
  1056. limiter = limiterList;
  1057. }
  1058. limiterList->add(Limiter);
  1059. }
  1060. else
  1061. {
  1062. limiter = Limiter;
  1063. }
  1064. return this->shared_from_this();
  1065. }
  1066. ILimiter::~ILimiter()
  1067. {
  1068. }
  1069. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1070. {
  1071. return false;
  1072. }
  1073. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1074. {
  1075. const CCreature *c = retrieveCreature(&context.node);
  1076. if(!c)
  1077. return true;
  1078. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1079. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1080. }
  1081. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades /*= true*/)
  1082. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1083. {
  1084. }
  1085. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1086. {
  1087. creature = nullptr;
  1088. includeUpgrades = false;
  1089. }
  1090. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1091. {
  1092. creature = VLC->creh->creatures[id];
  1093. }
  1094. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1095. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1096. {
  1097. }
  1098. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1099. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1100. {
  1101. }
  1102. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1103. {
  1104. CSelector mySelector = isSubtypeRelevant
  1105. ? Selector::typeSubtype(type, subtype)
  1106. : Selector::type(type);
  1107. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1108. if(context.alreadyAccepted.getFirst(mySelector))
  1109. return ACCEPT;
  1110. //do not accept for now but it may change if more bonuses gets included
  1111. return NOT_SURE;
  1112. }
  1113. IPropagator::~IPropagator()
  1114. {
  1115. }
  1116. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1117. {
  1118. return false;
  1119. }
  1120. CPropagatorNodeType::CPropagatorNodeType()
  1121. :nodeType(0)
  1122. {
  1123. }
  1124. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1125. : nodeType(NodeType)
  1126. {
  1127. }
  1128. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1129. {
  1130. return nodeType == dest->getNodeType();
  1131. }
  1132. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1133. : terrainType(TerrainType)
  1134. {
  1135. }
  1136. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1137. : terrainType(-1)
  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. : faction(-1)
  1152. {
  1153. }
  1154. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1155. {
  1156. const CCreature *c = retrieveCreature(&context.node);
  1157. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1158. }
  1159. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1160. : alignment(-1)
  1161. {
  1162. }
  1163. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1164. : alignment(Alignment)
  1165. {
  1166. }
  1167. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1168. {
  1169. const CCreature *c = retrieveCreature(&context.node);
  1170. if(!c)
  1171. return true;
  1172. switch(alignment)
  1173. {
  1174. case EAlignment::GOOD:
  1175. return !c->isGood(); //if not good -> return true (drop bonus)
  1176. case EAlignment::NEUTRAL:
  1177. return c->isEvil() || c->isGood();
  1178. case EAlignment::EVIL:
  1179. return !c->isEvil();
  1180. default:
  1181. logBonus->warnStream() << "Warning: illegal alignment in limiter!";
  1182. return true;
  1183. }
  1184. }
  1185. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1186. :minRank(Min), maxRank(Max)
  1187. {
  1188. }
  1189. RankRangeLimiter::RankRangeLimiter()
  1190. {
  1191. minRank = maxRank = -1;
  1192. }
  1193. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1194. {
  1195. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1196. if(csi)
  1197. {
  1198. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1199. return true;
  1200. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1201. }
  1202. return true;
  1203. }
  1204. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1205. {
  1206. const CStack *s = retreiveStackBattle(&context.node);
  1207. if(s)
  1208. return s->owner != owner;
  1209. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1210. if(csi && csi->armyObj)
  1211. return csi->armyObj->tempOwner != owner;
  1212. return true;
  1213. }
  1214. StackOwnerLimiter::StackOwnerLimiter()
  1215. : owner(-1)
  1216. {
  1217. }
  1218. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1219. : owner(Owner)
  1220. {
  1221. }
  1222. int LimiterList::limit( const BonusLimitationContext &context ) const
  1223. {
  1224. bool wasntSure = false;
  1225. for(auto limiter : limiters)
  1226. {
  1227. auto result = limiter->limit(context);
  1228. if(result == ILimiter::DISCARD)
  1229. return result;
  1230. if(result == ILimiter::NOT_SURE)
  1231. wasntSure = true;
  1232. }
  1233. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1234. }
  1235. void LimiterList::add( TLimiterPtr limiter )
  1236. {
  1237. limiters.push_back(limiter);
  1238. }