HeroBonus.cpp 39 KB

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