HeroBonus.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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 "CSkillHandler.h"
  19. #include "CStack.h"
  20. #include "CArtHandler.h"
  21. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  22. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  23. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  24. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  25. #define BONUS_NAME(x) { #x, Bonus::x },
  26. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  27. #undef BONUS_NAME
  28. #define BONUS_VALUE(x) { #x, Bonus::x },
  29. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  30. #undef BONUS_VALUE
  31. #define BONUS_SOURCE(x) { #x, Bonus::x },
  32. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  33. #undef BONUS_SOURCE
  34. #define BONUS_ITEM(x) { #x, Bonus::x },
  35. const std::map<std::string, ui16> bonusDurationMap =
  36. {
  37. BONUS_ITEM(PERMANENT)
  38. BONUS_ITEM(ONE_BATTLE)
  39. BONUS_ITEM(ONE_DAY)
  40. BONUS_ITEM(ONE_WEEK)
  41. BONUS_ITEM(N_TURNS)
  42. BONUS_ITEM(N_DAYS)
  43. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  44. BONUS_ITEM(UNTIL_ATTACK)
  45. BONUS_ITEM(STACK_GETS_TURN)
  46. BONUS_ITEM(COMMANDER_KILLED)
  47. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  48. };
  49. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  50. {
  51. BONUS_ITEM(NO_LIMIT)
  52. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  53. BONUS_ITEM(ONLY_MELEE_FIGHT)
  54. BONUS_ITEM(ONLY_ENEMY_ARMY)
  55. };
  56. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  57. {
  58. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  59. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  60. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)}
  61. };
  62. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  63. {
  64. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  65. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  66. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  67. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  68. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  69. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  70. }; //untested
  71. ///CBonusProxy
  72. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector):
  73. cachedLast(0), target(Target), selector(Selector), data()
  74. {
  75. }
  76. TBonusListPtr CBonusProxy::get() const
  77. {
  78. if(CBonusSystemNode::treeChanged != cachedLast || !data)
  79. {
  80. //TODO: support limiters
  81. data = target->getAllBonuses(selector, nullptr);
  82. data->eliminateDuplicates();
  83. cachedLast = CBonusSystemNode::treeChanged;
  84. }
  85. return data;
  86. }
  87. const BonusList * CBonusProxy::operator->() const
  88. {
  89. return get().get();
  90. }
  91. int CBonusSystemNode::treeChanged = 1;
  92. const bool CBonusSystemNode::cachingEnabled = true;
  93. BonusList::BonusList(bool BelongsToTree) : 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) 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) 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) 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, bool useBind ) 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, 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) 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. logBonus->trace("#$# %s #propagated to# %s", b->Description(), 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->error("Bonus was duplicated (%s) at %s", b->Description(), nodeName());
  694. bonuses -= b;
  695. }
  696. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), 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. }
  706. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  707. {
  708. if (vstd::contains(children, child))
  709. children -= child;
  710. else
  711. {
  712. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  713. throw std::runtime_error("internal error");
  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)
  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)
  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->skillh->skillName(sid);
  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)
  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, ValueType ValType)
  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. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  987. {
  988. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  989. }
  990. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  991. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  992. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  993. {
  994. Bonus dummy;
  995. dummy.type = type;
  996. return sel(&dummy);
  997. }
  998. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  999. {
  1000. Bonus dummy;
  1001. dummy.type = type;
  1002. dummy.subtype = subtype;
  1003. return sel(&dummy);
  1004. }
  1005. }
  1006. const CStack * retreiveStackBattle(const CBonusSystemNode *node)
  1007. {
  1008. switch(node->getNodeType())
  1009. {
  1010. case CBonusSystemNode::STACK_BATTLE:
  1011. return static_cast<const CStack*>(node);
  1012. default:
  1013. return nullptr;
  1014. }
  1015. }
  1016. const CStackInstance * retreiveStackInstance(const CBonusSystemNode *node)
  1017. {
  1018. switch(node->getNodeType())
  1019. {
  1020. case CBonusSystemNode::STACK_INSTANCE:
  1021. return (static_cast<const CStackInstance *>(node));
  1022. case CBonusSystemNode::STACK_BATTLE:
  1023. return (static_cast<const CStack*>(node))->base;
  1024. default:
  1025. return nullptr;
  1026. }
  1027. }
  1028. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1029. {
  1030. switch(node->getNodeType())
  1031. {
  1032. case CBonusSystemNode::CREATURE:
  1033. return (static_cast<const CCreature *>(node));
  1034. case CBonusSystemNode::STACK_BATTLE:
  1035. return (static_cast<const CStack*>(node))->type;
  1036. default:
  1037. const CStackInstance *csi = retreiveStackInstance(node);
  1038. if(csi)
  1039. return csi->type;
  1040. return nullptr;
  1041. }
  1042. }
  1043. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1044. {
  1045. for (ui32 i = 0; i < bonusList.size(); i++)
  1046. {
  1047. auto b = bonusList[i];
  1048. out << "Bonus " << i << "\n" << *b << std::endl;
  1049. }
  1050. return out;
  1051. }
  1052. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1053. {
  1054. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1055. if(i->second == bonus.type)
  1056. out << "\tType: " << i->first << " \t";
  1057. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1058. printField(val);
  1059. printField(subtype);
  1060. printField(duration);
  1061. printField(source);
  1062. printField(sid);
  1063. printField(additionalInfo);
  1064. printField(turnsRemain);
  1065. printField(valType);
  1066. printField(effectRange);
  1067. #undef printField
  1068. return out;
  1069. }
  1070. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1071. {
  1072. if (limiter)
  1073. {
  1074. //If we already have limiter list, retrieve it
  1075. auto limiterList = std::dynamic_pointer_cast<LimiterList>(limiter);
  1076. if(!limiterList)
  1077. {
  1078. //Create a new limiter list with old limiter and the new one will be pushed later
  1079. limiterList = std::make_shared<LimiterList>();
  1080. limiterList->add(limiter);
  1081. limiter = limiterList;
  1082. }
  1083. limiterList->add(Limiter);
  1084. }
  1085. else
  1086. {
  1087. limiter = Limiter;
  1088. }
  1089. return this->shared_from_this();
  1090. }
  1091. ILimiter::~ILimiter()
  1092. {
  1093. }
  1094. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1095. {
  1096. return false;
  1097. }
  1098. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1099. {
  1100. const CCreature *c = retrieveCreature(&context.node);
  1101. if(!c)
  1102. return true;
  1103. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1104. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1105. }
  1106. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1107. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1108. {
  1109. }
  1110. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1111. {
  1112. creature = nullptr;
  1113. includeUpgrades = false;
  1114. }
  1115. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1116. {
  1117. creature = VLC->creh->creatures[id];
  1118. }
  1119. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1120. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1121. {
  1122. }
  1123. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1124. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1125. {
  1126. }
  1127. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1128. {
  1129. CSelector mySelector = isSubtypeRelevant
  1130. ? Selector::typeSubtype(type, subtype)
  1131. : Selector::type(type);
  1132. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1133. if(context.alreadyAccepted.getFirst(mySelector))
  1134. return ACCEPT;
  1135. //do not accept for now but it may change if more bonuses gets included
  1136. return NOT_SURE;
  1137. }
  1138. IPropagator::~IPropagator()
  1139. {
  1140. }
  1141. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1142. {
  1143. return false;
  1144. }
  1145. CPropagatorNodeType::CPropagatorNodeType()
  1146. :nodeType(0)
  1147. {
  1148. }
  1149. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1150. : nodeType(NodeType)
  1151. {
  1152. }
  1153. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1154. {
  1155. return nodeType == dest->getNodeType();
  1156. }
  1157. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter(int TerrainType)
  1158. : terrainType(TerrainType)
  1159. {
  1160. }
  1161. CreatureNativeTerrainLimiter::CreatureNativeTerrainLimiter()
  1162. : terrainType(-1)
  1163. {
  1164. }
  1165. int CreatureNativeTerrainLimiter::limit(const BonusLimitationContext &context) const
  1166. {
  1167. const CCreature *c = retrieveCreature(&context.node);
  1168. return !c || !c->isItNativeTerrain(terrainType); //drop bonus for non-creatures or non-native residents
  1169. //TODO neutral creatues
  1170. }
  1171. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1172. : faction(Faction)
  1173. {
  1174. }
  1175. CreatureFactionLimiter::CreatureFactionLimiter()
  1176. : faction(-1)
  1177. {
  1178. }
  1179. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1180. {
  1181. const CCreature *c = retrieveCreature(&context.node);
  1182. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1183. }
  1184. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1185. : alignment(-1)
  1186. {
  1187. }
  1188. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1189. : alignment(Alignment)
  1190. {
  1191. }
  1192. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1193. {
  1194. const CCreature *c = retrieveCreature(&context.node);
  1195. if(!c)
  1196. return true;
  1197. switch(alignment)
  1198. {
  1199. case EAlignment::GOOD:
  1200. return !c->isGood(); //if not good -> return true (drop bonus)
  1201. case EAlignment::NEUTRAL:
  1202. return c->isEvil() || c->isGood();
  1203. case EAlignment::EVIL:
  1204. return !c->isEvil();
  1205. default:
  1206. logBonus->warn("Warning: illegal alignment in limiter!");
  1207. return true;
  1208. }
  1209. }
  1210. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1211. :minRank(Min), maxRank(Max)
  1212. {
  1213. }
  1214. RankRangeLimiter::RankRangeLimiter()
  1215. {
  1216. minRank = maxRank = -1;
  1217. }
  1218. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1219. {
  1220. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1221. if(csi)
  1222. {
  1223. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1224. return true;
  1225. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1226. }
  1227. return true;
  1228. }
  1229. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1230. {
  1231. const CStack *s = retreiveStackBattle(&context.node);
  1232. if(s)
  1233. return s->owner != owner;
  1234. const CStackInstance *csi = retreiveStackInstance(&context.node);
  1235. if(csi && csi->armyObj)
  1236. return csi->armyObj->tempOwner != owner;
  1237. return true;
  1238. }
  1239. StackOwnerLimiter::StackOwnerLimiter()
  1240. : owner(-1)
  1241. {
  1242. }
  1243. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1244. : owner(Owner)
  1245. {
  1246. }
  1247. int LimiterList::limit( const BonusLimitationContext &context ) const
  1248. {
  1249. bool wasntSure = false;
  1250. for(auto limiter : limiters)
  1251. {
  1252. auto result = limiter->limit(context);
  1253. if(result == ILimiter::DISCARD)
  1254. return result;
  1255. if(result == ILimiter::NOT_SURE)
  1256. wasntSure = true;
  1257. }
  1258. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1259. }
  1260. void LimiterList::add( TLimiterPtr limiter )
  1261. {
  1262. limiters.push_back(limiter);
  1263. }