HeroBonus.cpp 39 KB

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