HeroBonus.cpp 38 KB

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