HeroBonus.cpp 39 KB

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