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