HeroBonus.cpp 39 KB

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