HeroBonus.cpp 39 KB

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