HeroBonus.cpp 37 KB

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