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