HeroBonus.cpp 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248
  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 "CTownHandler.h"
  18. #include "CGeneralTextHandler.h"
  19. #include "CSkillHandler.h"
  20. #include "CStack.h"
  21. #include "CArtHandler.h"
  22. #include "StringConstants.h"
  23. #include "battle/BattleInfo.h"
  24. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  25. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  26. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  27. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  28. #define BONUS_NAME(x) { #x, Bonus::x },
  29. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  30. #undef BONUS_NAME
  31. #define BONUS_VALUE(x) { #x, Bonus::x },
  32. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  33. #undef BONUS_VALUE
  34. #define BONUS_SOURCE(x) { #x, Bonus::x },
  35. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  36. #undef BONUS_SOURCE
  37. #define BONUS_ITEM(x) { #x, Bonus::x },
  38. const std::map<std::string, ui16> bonusDurationMap =
  39. {
  40. BONUS_ITEM(PERMANENT)
  41. BONUS_ITEM(ONE_BATTLE)
  42. BONUS_ITEM(ONE_DAY)
  43. BONUS_ITEM(ONE_WEEK)
  44. BONUS_ITEM(N_TURNS)
  45. BONUS_ITEM(N_DAYS)
  46. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  47. BONUS_ITEM(UNTIL_ATTACK)
  48. BONUS_ITEM(STACK_GETS_TURN)
  49. BONUS_ITEM(COMMANDER_KILLED)
  50. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  51. };
  52. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  53. {
  54. BONUS_ITEM(NO_LIMIT)
  55. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  56. BONUS_ITEM(ONLY_MELEE_FIGHT)
  57. BONUS_ITEM(ONLY_ENEMY_ARMY)
  58. };
  59. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  60. {
  61. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  62. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  63. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)},
  64. {"CREATURE_NATIVE_TERRAIN", std::make_shared<CreatureTerrainLimiter>()}
  65. };
  66. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  67. {
  68. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  69. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  70. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  71. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  72. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  73. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  74. }; //untested
  75. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  76. {
  77. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  78. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()}
  79. };
  80. ///CBonusProxy
  81. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector)
  82. : cachedLast(0),
  83. target(Target),
  84. selector(Selector),
  85. data()
  86. {
  87. }
  88. CBonusProxy::CBonusProxy(const CBonusProxy & other)
  89. : cachedLast(other.cachedLast),
  90. target(other.target),
  91. selector(other.selector),
  92. data(other.data)
  93. {
  94. }
  95. CBonusProxy::CBonusProxy(CBonusProxy && other)
  96. : cachedLast(0),
  97. target(other.target),
  98. selector(),
  99. data()
  100. {
  101. std::swap(cachedLast, other.cachedLast);
  102. std::swap(selector, other.selector);
  103. std::swap(data, other.data);
  104. }
  105. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  106. {
  107. cachedLast = other.cachedLast;
  108. selector = other.selector;
  109. data = other.data;
  110. return *this;
  111. }
  112. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other)
  113. {
  114. std::swap(cachedLast, other.cachedLast);
  115. std::swap(selector, other.selector);
  116. std::swap(data, other.data);
  117. return *this;
  118. }
  119. TBonusListPtr CBonusProxy::get() const
  120. {
  121. if(target->getTreeVersion() != cachedLast || !data)
  122. {
  123. //TODO: support limiters
  124. data = target->getAllBonuses(selector, Selector::all);
  125. cachedLast = target->getTreeVersion();
  126. }
  127. return data;
  128. }
  129. const BonusList * CBonusProxy::operator->() const
  130. {
  131. return get().get();
  132. }
  133. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue)
  134. : target(Target),
  135. selector(Selector),
  136. initialValue(InitialValue),
  137. meleeCachedLast(0),
  138. meleeValue(0),
  139. rangedCachedLast(0),
  140. rangedValue(0),
  141. value(0),
  142. cachedLast(0)
  143. {
  144. }
  145. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  146. : target(other.target),
  147. selector(other.selector),
  148. initialValue(other.initialValue),
  149. meleeCachedLast(other.meleeCachedLast),
  150. meleeValue(other.meleeValue),
  151. rangedCachedLast(other.rangedCachedLast),
  152. rangedValue(other.rangedValue)
  153. {
  154. }
  155. CTotalsProxy & CTotalsProxy::operator=(const CTotalsProxy & other)
  156. {
  157. initialValue = other.initialValue;
  158. meleeCachedLast = other.meleeCachedLast;
  159. meleeValue = other.meleeValue;
  160. rangedCachedLast = other.rangedCachedLast;
  161. rangedValue = other.rangedValue;
  162. value = other.value;
  163. cachedLast = other.cachedLast;
  164. return *this;
  165. }
  166. int CTotalsProxy::getValue() const
  167. {
  168. const auto treeVersion = target->getTreeVersion();
  169. if(treeVersion != cachedLast)
  170. {
  171. auto bonuses = target->getBonuses(selector);
  172. value = initialValue + bonuses->totalValue();
  173. cachedLast = treeVersion;
  174. }
  175. return value;
  176. }
  177. int CTotalsProxy::getMeleeValue() const
  178. {
  179. static const auto limit = Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_MELEE_FIGHT));
  180. const auto treeVersion = target->getTreeVersion();
  181. if(treeVersion != meleeCachedLast)
  182. {
  183. auto bonuses = target->getBonuses(selector, limit);
  184. meleeValue = initialValue + bonuses->totalValue();
  185. meleeCachedLast = treeVersion;
  186. }
  187. return meleeValue;
  188. }
  189. int CTotalsProxy::getRangedValue() const
  190. {
  191. static const auto limit = Selector::effectRange(Bonus::NO_LIMIT).Or(Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT));
  192. const auto treeVersion = target->getTreeVersion();
  193. if(treeVersion != rangedCachedLast)
  194. {
  195. auto bonuses = target->getBonuses(selector, limit);
  196. rangedValue = initialValue + bonuses->totalValue();
  197. rangedCachedLast = treeVersion;
  198. }
  199. return rangedValue;
  200. }
  201. ///CCheckProxy
  202. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector)
  203. : target(Target),
  204. selector(Selector),
  205. cachedLast(0),
  206. hasBonus(false)
  207. {
  208. }
  209. CCheckProxy::CCheckProxy(const CCheckProxy & other)
  210. : target(other.target),
  211. selector(other.selector),
  212. cachedLast(other.cachedLast),
  213. hasBonus(other.hasBonus)
  214. {
  215. }
  216. bool CCheckProxy::getHasBonus() const
  217. {
  218. const auto treeVersion = target->getTreeVersion();
  219. if(treeVersion != cachedLast)
  220. {
  221. hasBonus = target->hasBonus(selector);
  222. cachedLast = treeVersion;
  223. }
  224. return hasBonus;
  225. }
  226. CAddInfo::CAddInfo()
  227. {
  228. }
  229. CAddInfo::CAddInfo(si32 value)
  230. {
  231. if(value != CAddInfo::NONE)
  232. push_back(value);
  233. }
  234. bool CAddInfo::operator==(si32 value) const
  235. {
  236. switch(size())
  237. {
  238. case 0:
  239. return value == CAddInfo::NONE;
  240. case 1:
  241. return operator[](0) == value;
  242. default:
  243. return false;
  244. }
  245. }
  246. bool CAddInfo::operator!=(si32 value) const
  247. {
  248. return !operator==(value);
  249. }
  250. si32 & CAddInfo::operator[](size_type pos)
  251. {
  252. if(pos >= size())
  253. resize(pos + 1, CAddInfo::NONE);
  254. return vector::operator[](pos);
  255. }
  256. si32 CAddInfo::operator[](size_type pos) const
  257. {
  258. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  259. }
  260. std::string CAddInfo::toString() const
  261. {
  262. return toJsonNode().toJson(true);
  263. }
  264. JsonNode CAddInfo::toJsonNode() const
  265. {
  266. if(size() < 2)
  267. {
  268. return JsonUtils::intNode(operator[](0));
  269. }
  270. else
  271. {
  272. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  273. for(si32 value : *this)
  274. node.Vector().push_back(JsonUtils::intNode(value));
  275. return node;
  276. }
  277. }
  278. std::atomic<int32_t> CBonusSystemNode::treeChanged(1);
  279. const bool CBonusSystemNode::cachingEnabled = true;
  280. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  281. {
  282. }
  283. BonusList::BonusList(const BonusList &bonusList)
  284. {
  285. bonuses.resize(bonusList.size());
  286. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  287. belongsToTree = false;
  288. }
  289. BonusList::BonusList(BonusList&& other):
  290. belongsToTree(false)
  291. {
  292. std::swap(belongsToTree, other.belongsToTree);
  293. std::swap(bonuses, other.bonuses);
  294. }
  295. BonusList& BonusList::operator=(const BonusList &bonusList)
  296. {
  297. bonuses.resize(bonusList.size());
  298. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  299. belongsToTree = false;
  300. return *this;
  301. }
  302. void BonusList::changed()
  303. {
  304. if(belongsToTree)
  305. CBonusSystemNode::treeHasChanged();
  306. }
  307. void BonusList::stackBonuses()
  308. {
  309. boost::sort(bonuses, [](std::shared_ptr<Bonus> b1, std::shared_ptr<Bonus> b2) -> bool
  310. {
  311. if(b1 == b2)
  312. return false;
  313. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  314. COMPARE_ATT(stacking);
  315. COMPARE_ATT(type);
  316. COMPARE_ATT(subtype);
  317. COMPARE_ATT(valType);
  318. #undef COMPARE_ATT
  319. return b1->val > b2->val;
  320. });
  321. // remove non-stacking
  322. size_t next = 1;
  323. while(next < bonuses.size())
  324. {
  325. bool remove;
  326. const std::shared_ptr<Bonus> last = bonuses[next-1];
  327. const std::shared_ptr<Bonus> current = bonuses[next];
  328. if(current->stacking.empty())
  329. remove = current == last;
  330. else if(current->stacking == "ALWAYS")
  331. remove = false;
  332. else
  333. remove = current->stacking == last->stacking
  334. && current->type == last->type
  335. && current->subtype == last->subtype
  336. && current->valType == last->valType;
  337. if(remove)
  338. bonuses.erase(bonuses.begin() + next);
  339. else
  340. next++;
  341. }
  342. }
  343. int BonusList::totalValue() const
  344. {
  345. int base = 0;
  346. int percentToBase = 0;
  347. int percentToAll = 0;
  348. int additive = 0;
  349. int indepMax = 0;
  350. bool hasIndepMax = false;
  351. int indepMin = 0;
  352. bool hasIndepMin = false;
  353. for(std::shared_ptr<Bonus> b : bonuses)
  354. {
  355. switch(b->valType)
  356. {
  357. case Bonus::BASE_NUMBER:
  358. base += b->val;
  359. break;
  360. case Bonus::PERCENT_TO_ALL:
  361. percentToAll += b->val;
  362. break;
  363. case Bonus::PERCENT_TO_BASE:
  364. percentToBase += b->val;
  365. break;
  366. case Bonus::ADDITIVE_VALUE:
  367. additive += b->val;
  368. break;
  369. case Bonus::INDEPENDENT_MAX:
  370. if (!hasIndepMax)
  371. {
  372. indepMax = b->val;
  373. hasIndepMax = true;
  374. }
  375. else
  376. {
  377. vstd::amax(indepMax, b->val);
  378. }
  379. break;
  380. case Bonus::INDEPENDENT_MIN:
  381. if (!hasIndepMin)
  382. {
  383. indepMin = b->val;
  384. hasIndepMin = true;
  385. }
  386. else
  387. {
  388. vstd::amin(indepMin, b->val);
  389. }
  390. break;
  391. }
  392. }
  393. int modifiedBase = base + (base * percentToBase) / 100;
  394. modifiedBase += additive;
  395. int valFirst = (modifiedBase * (100 + percentToAll)) / 100;
  396. if(hasIndepMin && hasIndepMax)
  397. assert(indepMin < indepMax);
  398. const int notIndepBonuses = boost::count_if(bonuses, [](const std::shared_ptr<Bonus>& b)
  399. {
  400. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  401. });
  402. if (hasIndepMax)
  403. {
  404. if(notIndepBonuses)
  405. vstd::amax(valFirst, indepMax);
  406. else
  407. valFirst = indepMax;
  408. }
  409. if (hasIndepMin)
  410. {
  411. if(notIndepBonuses)
  412. vstd::amin(valFirst, indepMin);
  413. else
  414. valFirst = indepMin;
  415. }
  416. return valFirst;
  417. }
  418. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  419. {
  420. for (auto & b : bonuses)
  421. {
  422. if(select(b.get()))
  423. return b;
  424. }
  425. return nullptr;
  426. }
  427. const std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &selector) const
  428. {
  429. for (auto & b : bonuses)
  430. {
  431. if(selector(b.get()))
  432. return b;
  433. }
  434. return nullptr;
  435. }
  436. void BonusList::getBonuses(BonusList & out, const CSelector &selector) const
  437. {
  438. getBonuses(out, selector, nullptr);
  439. }
  440. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  441. {
  442. for (auto & b : bonuses)
  443. {
  444. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  445. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  446. out.push_back(b);
  447. }
  448. }
  449. void BonusList::getAllBonuses(BonusList &out) const
  450. {
  451. for(auto & b : bonuses)
  452. out.push_back(b);
  453. }
  454. int BonusList::valOfBonuses(const CSelector &select) const
  455. {
  456. BonusList ret;
  457. CSelector limit = nullptr;
  458. getBonuses(ret, select, limit);
  459. return ret.totalValue();
  460. }
  461. JsonNode BonusList::toJsonNode() const
  462. {
  463. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  464. for(std::shared_ptr<Bonus> b : bonuses)
  465. node.Vector().push_back(b->toJsonNode());
  466. return node;
  467. }
  468. void BonusList::push_back(std::shared_ptr<Bonus> x)
  469. {
  470. bonuses.push_back(x);
  471. changed();
  472. }
  473. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  474. {
  475. changed();
  476. return bonuses.erase(bonuses.begin() + position);
  477. }
  478. void BonusList::clear()
  479. {
  480. bonuses.clear();
  481. changed();
  482. }
  483. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  484. {
  485. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  486. if(itr == bonuses.end())
  487. return false;
  488. bonuses.erase(itr);
  489. changed();
  490. return true;
  491. }
  492. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  493. {
  494. bonuses.resize(sz, c);
  495. changed();
  496. }
  497. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  498. {
  499. bonuses.insert(position, n, x);
  500. changed();
  501. }
  502. CSelector IBonusBearer::anaffectedByMoraleSelector
  503. = Selector::type(Bonus::NON_LIVING)
  504. .Or(Selector::type(Bonus::UNDEAD))
  505. .Or(Selector::type(Bonus::NO_MORALE))
  506. .Or(Selector::type(Bonus::SIEGE_WEAPON));
  507. CSelector IBonusBearer::moraleSelector = Selector::type(Bonus::MORALE);
  508. CSelector IBonusBearer::selfMoraleSelector = Selector::type(Bonus::SELF_MORALE);
  509. IBonusBearer::IBonusBearer()
  510. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  511. moraleValue(this, moraleSelector, 0),
  512. selfMorale(this, selfMoraleSelector)
  513. {
  514. }
  515. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  516. {
  517. return valOfBonuses(Selector::type(type).And(selector));
  518. }
  519. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  520. {
  521. boost::format fmt("type_%ds_%d");
  522. fmt % (int)type % subtype;
  523. CSelector s = Selector::type(type);
  524. if(subtype != -1)
  525. s = s.And(Selector::subtype(subtype));
  526. return valOfBonuses(s, fmt.str());
  527. }
  528. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  529. {
  530. CSelector limit = nullptr;
  531. TBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  532. return hlp->totalValue();
  533. }
  534. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  535. {
  536. return getBonuses(selector, cachingStr)->size() > 0;
  537. }
  538. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  539. {
  540. return getBonuses(selector, limit, cachingStr)->size() > 0;
  541. }
  542. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  543. {
  544. boost::format fmt("type_%ds_%d");
  545. fmt % (int)type % subtype;
  546. CSelector s = Selector::type(type);
  547. if(subtype != -1)
  548. s = s.And(Selector::subtype(subtype));
  549. return hasBonus(s, fmt.str());
  550. }
  551. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  552. {
  553. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  554. }
  555. const TBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  556. {
  557. return getAllBonuses(selector, limit, nullptr, cachingStr);
  558. }
  559. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  560. {
  561. boost::format fmt("source_%did_%d");
  562. fmt % (int)source % sourceID;
  563. return hasBonus(Selector::source(source,sourceID), fmt.str());
  564. }
  565. int IBonusBearer::MoraleVal() const
  566. {
  567. if(anaffectedByMorale.getHasBonus())
  568. return 0;
  569. int ret = moraleValue.getValue();
  570. if(selfMorale.getHasBonus()) //eg. minotaur
  571. vstd::amax(ret, +1);
  572. return vstd::abetween(ret, -3, +3);
  573. }
  574. int IBonusBearer::LuckVal() const
  575. {
  576. if(hasBonusOfType(Bonus::NO_LUCK))
  577. return 0;
  578. int ret = valOfBonuses(Bonus::LUCK);
  579. if(hasBonusOfType(Bonus::SELF_LUCK)) //eg. halfling
  580. vstd::amax(ret, +1);
  581. return vstd::abetween(ret, -3, +3);
  582. }
  583. ui32 IBonusBearer::MaxHealth() const
  584. {
  585. const std::string cachingStr = "type_STACK_HEALTH";
  586. static const auto selector = Selector::type(Bonus::STACK_HEALTH);
  587. auto value = valOfBonuses(selector, cachingStr);
  588. return std::max(1, value); //never 0
  589. }
  590. int IBonusBearer::getAttack(bool ranged) const
  591. {
  592. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  593. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  594. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  595. }
  596. int IBonusBearer::getDefence(bool ranged) const
  597. {
  598. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  599. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  600. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  601. }
  602. int IBonusBearer::getMinDamage(bool ranged) const
  603. {
  604. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  605. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  606. return valOfBonuses(selector, cachingStr);
  607. }
  608. int IBonusBearer::getMaxDamage(bool ranged) const
  609. {
  610. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  611. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  612. return valOfBonuses(selector, cachingStr);
  613. }
  614. si32 IBonusBearer::manaLimit() const
  615. {
  616. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  617. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  618. / 10.0);
  619. }
  620. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  621. {
  622. static const CSelector selectorAllSkills = Selector::type(Bonus::PRIMARY_SKILL);
  623. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  624. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  625. int ret = allSkills->valOfBonuses(Selector::subtype(id));
  626. vstd::amax(ret, id/2); //minimal value is 0 for attack and defense and 1 for spell power and knowledge
  627. return ret;
  628. }
  629. si32 IBonusBearer::magicResistance() const
  630. {
  631. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  632. }
  633. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  634. {
  635. //war machines cannot move
  636. if(hasBonus(Selector::type(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  637. {
  638. return 0;
  639. }
  640. //bind effect check - doesn't influence stack initiative
  641. if(useBind && hasBonus(Selector::type(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  642. {
  643. return 0;
  644. }
  645. return valOfBonuses(Selector::type(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  646. }
  647. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  648. {
  649. static const std::string cachingStr = "IBonusBearer::isLiving";
  650. static const CSelector selector = Selector::type(Bonus::UNDEAD)
  651. .Or(Selector::type(Bonus::NON_LIVING))
  652. .Or(Selector::type(Bonus::GARGOYLE))
  653. .Or(Selector::type(Bonus::SIEGE_WEAPON));
  654. return !hasBonus(selector, cachingStr);
  655. }
  656. const std::shared_ptr<Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  657. {
  658. auto bonuses = getAllBonuses(selector, Selector::all);
  659. return bonuses->getFirst(Selector::all);
  660. }
  661. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  662. {
  663. auto ret = bonuses.getFirst(selector);
  664. if(ret)
  665. return ret;
  666. FOREACH_PARENT(pname)
  667. {
  668. ret = pname->getBonusLocalFirst(selector);
  669. if (ret)
  670. return ret;
  671. }
  672. return nullptr;
  673. }
  674. const std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  675. {
  676. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  677. }
  678. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  679. {
  680. for (auto & elem : parents)
  681. {
  682. const CBonusSystemNode *parent = elem;
  683. out.insert(parent);
  684. }
  685. }
  686. void CBonusSystemNode::getParents(TNodes &out)
  687. {
  688. for (auto & elem : parents)
  689. {
  690. const CBonusSystemNode *parent = elem;
  691. out.insert(const_cast<CBonusSystemNode*>(parent));
  692. }
  693. }
  694. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  695. {
  696. BonusList beforeUpdate;
  697. FOREACH_CPARENT(p)
  698. {
  699. p->getBonusesRec(beforeUpdate, selector, limit);
  700. }
  701. bonuses.getBonuses(beforeUpdate, selector, limit);
  702. for(auto b : beforeUpdate)
  703. out.push_back(update(b));
  704. }
  705. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  706. {
  707. BonusList beforeUpdate;
  708. FOREACH_CPARENT(p)
  709. {
  710. p->getAllBonusesRec(beforeUpdate);
  711. }
  712. bonuses.getAllBonuses(beforeUpdate);
  713. for(auto b : beforeUpdate)
  714. out.push_back(update(b));
  715. }
  716. const TBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  717. {
  718. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  719. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  720. {
  721. // Exclusive access for one thread
  722. static boost::mutex m;
  723. boost::mutex::scoped_lock lock(m);
  724. // If the bonus system tree changes(state of a single node or the relations to each other) then
  725. // cache all bonus objects. Selector objects doesn't matter.
  726. if (cachedLast != treeChanged)
  727. {
  728. cachedBonuses.clear();
  729. cachedRequests.clear();
  730. BonusList allBonuses;
  731. getAllBonusesRec(allBonuses);
  732. limitBonuses(allBonuses, cachedBonuses);
  733. cachedBonuses.stackBonuses();
  734. cachedLast = treeChanged;
  735. }
  736. // If a bonus system request comes with a caching string then look up in the map if there are any
  737. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  738. if (cachingStr != "")
  739. {
  740. auto it = cachedRequests.find(cachingStr);
  741. if(it != cachedRequests.end())
  742. {
  743. //Cached list contains bonuses for our query with applied limiters
  744. return it->second;
  745. }
  746. }
  747. //We still don't have the bonuses (didn't returned them from cache)
  748. //Perform bonus selection
  749. auto ret = std::make_shared<BonusList>();
  750. cachedBonuses.getBonuses(*ret, selector, limit);
  751. // Save the results in the cache
  752. if(cachingStr != "")
  753. cachedRequests[cachingStr] = ret;
  754. return ret;
  755. }
  756. else
  757. {
  758. return getAllBonusesWithoutCaching(selector, limit, root);
  759. }
  760. }
  761. const TBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  762. {
  763. auto ret = std::make_shared<BonusList>();
  764. // Get bonus results without caching enabled.
  765. BonusList beforeLimiting, afterLimiting;
  766. getAllBonusesRec(beforeLimiting);
  767. if(!root || root == this)
  768. {
  769. limitBonuses(beforeLimiting, afterLimiting);
  770. }
  771. else if(root)
  772. {
  773. //We want to limit our query against an external node. We get all its bonuses,
  774. // add the ones we're considering and see if they're cut out by limiters
  775. BonusList rootBonuses, limitedRootBonuses;
  776. getAllBonusesRec(rootBonuses);
  777. for(auto b : beforeLimiting)
  778. rootBonuses.push_back(b);
  779. root->limitBonuses(rootBonuses, limitedRootBonuses);
  780. for(auto b : beforeLimiting)
  781. if(vstd::contains(limitedRootBonuses, b))
  782. afterLimiting.push_back(b);
  783. }
  784. afterLimiting.getBonuses(*ret, selector, limit);
  785. ret->stackBonuses();
  786. return ret;
  787. }
  788. const std::shared_ptr<Bonus> CBonusSystemNode::update(const std::shared_ptr<Bonus> b) const
  789. {
  790. if(b->updater)
  791. return b->updater->update(b, *this);
  792. return b;
  793. }
  794. CBonusSystemNode::CBonusSystemNode()
  795. : bonuses(true),
  796. exportedBonuses(true),
  797. nodeType(UNKNOWN),
  798. cachedLast(0)
  799. {
  800. }
  801. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  802. : bonuses(true),
  803. exportedBonuses(true),
  804. nodeType(NodeType),
  805. cachedLast(0)
  806. {
  807. }
  808. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  809. bonuses(std::move(other.bonuses)),
  810. exportedBonuses(std::move(other.exportedBonuses)),
  811. nodeType(other.nodeType),
  812. description(other.description),
  813. cachedLast(0)
  814. {
  815. std::swap(parents, other.parents);
  816. std::swap(children, other.children);
  817. //fixing bonus tree without recalculation
  818. for(CBonusSystemNode * n : parents)
  819. {
  820. n->children -= &other;
  821. n->children.push_back(this);
  822. }
  823. for(CBonusSystemNode * n : children)
  824. {
  825. n->parents -= &other;
  826. n->parents.push_back(this);
  827. }
  828. //cache ignored
  829. //cachedBonuses
  830. //cachedRequests
  831. }
  832. CBonusSystemNode::~CBonusSystemNode()
  833. {
  834. detachFromAll();
  835. if(children.size())
  836. {
  837. while(children.size())
  838. children.front()->detachFrom(this);
  839. }
  840. }
  841. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  842. {
  843. assert(!vstd::contains(parents, parent));
  844. parents.push_back(parent);
  845. if(parent->actsAsBonusSourceOnly())
  846. parent->newRedDescendant(this);
  847. else
  848. newRedDescendant(parent);
  849. parent->newChildAttached(this);
  850. CBonusSystemNode::treeHasChanged();
  851. }
  852. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  853. {
  854. assert(vstd::contains(parents, parent));
  855. if(parent->actsAsBonusSourceOnly())
  856. parent->removedRedDescendant(this);
  857. else
  858. removedRedDescendant(parent);
  859. parents -= parent;
  860. parent->childDetached(this);
  861. CBonusSystemNode::treeHasChanged();
  862. }
  863. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  864. {
  865. removeBonuses(s);
  866. for(CBonusSystemNode * child : children)
  867. child->removeBonusesRecursive(s);
  868. }
  869. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  870. {
  871. BonusList bl;
  872. exportedBonuses.getBonuses(bl, s, Selector::all);
  873. for(auto b : bl)
  874. {
  875. b->turnsRemain--;
  876. if(b->turnsRemain <= 0)
  877. removeBonus(b);
  878. }
  879. for(CBonusSystemNode *child : children)
  880. child->reduceBonusDurations(s);
  881. }
  882. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  883. {
  884. //turnsRemain shouldn't be zero for following durations
  885. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  886. {
  887. assert(b->turnsRemain);
  888. }
  889. assert(!vstd::contains(exportedBonuses, b));
  890. exportedBonuses.push_back(b);
  891. exportBonus(b);
  892. CBonusSystemNode::treeHasChanged();
  893. }
  894. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  895. {
  896. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  897. if(bonus)
  898. bonus->val += b->val;
  899. else
  900. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  901. }
  902. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  903. {
  904. exportedBonuses -= b;
  905. if(b->propagator)
  906. unpropagateBonus(b);
  907. else
  908. bonuses -= b;
  909. CBonusSystemNode::treeHasChanged();
  910. }
  911. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  912. {
  913. BonusList toRemove;
  914. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  915. for(auto bonus : toRemove)
  916. removeBonus(bonus);
  917. }
  918. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  919. {
  920. switch(nodeType)
  921. {
  922. case CREATURE:
  923. case ARTIFACT:
  924. case ARTIFACT_INSTANCE:
  925. return true;
  926. default:
  927. return false;
  928. }
  929. }
  930. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  931. {
  932. if(b->propagator->shouldBeAttached(this))
  933. {
  934. bonuses.push_back(b);
  935. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  936. }
  937. FOREACH_RED_CHILD(child)
  938. child->propagateBonus(b);
  939. }
  940. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  941. {
  942. if(b->propagator->shouldBeAttached(this))
  943. {
  944. bonuses -= b;
  945. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  946. }
  947. FOREACH_RED_CHILD(child)
  948. child->unpropagateBonus(b);
  949. }
  950. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  951. {
  952. assert(!vstd::contains(children, child));
  953. children.push_back(child);
  954. }
  955. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  956. {
  957. if (vstd::contains(children, child))
  958. children -= child;
  959. else
  960. {
  961. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  962. throw std::runtime_error("internal error");
  963. }
  964. }
  965. void CBonusSystemNode::detachFromAll()
  966. {
  967. while(parents.size())
  968. detachFrom(parents.front());
  969. }
  970. bool CBonusSystemNode::isIndependentNode() const
  971. {
  972. return parents.empty() && children.empty();
  973. }
  974. std::string CBonusSystemNode::nodeName() const
  975. {
  976. return description.size()
  977. ? description
  978. : std::string("Bonus system node of type ") + typeid(*this).name();
  979. }
  980. void CBonusSystemNode::deserializationFix()
  981. {
  982. exportBonuses();
  983. }
  984. void CBonusSystemNode::getRedParents(TNodes &out)
  985. {
  986. FOREACH_PARENT(pname)
  987. {
  988. if(pname->actsAsBonusSourceOnly())
  989. {
  990. out.insert(pname);
  991. }
  992. }
  993. if(!actsAsBonusSourceOnly())
  994. {
  995. for(CBonusSystemNode *child : children)
  996. {
  997. out.insert(child);
  998. }
  999. }
  1000. }
  1001. void CBonusSystemNode::getRedChildren(TNodes &out)
  1002. {
  1003. FOREACH_PARENT(pname)
  1004. {
  1005. if(!pname->actsAsBonusSourceOnly())
  1006. {
  1007. out.insert(pname);
  1008. }
  1009. }
  1010. if(actsAsBonusSourceOnly())
  1011. {
  1012. for(CBonusSystemNode *child : children)
  1013. {
  1014. out.insert(child);
  1015. }
  1016. }
  1017. }
  1018. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  1019. {
  1020. for(auto b : exportedBonuses)
  1021. if(b->propagator)
  1022. descendant->propagateBonus(b);
  1023. FOREACH_RED_PARENT(parent)
  1024. parent->newRedDescendant(descendant);
  1025. }
  1026. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  1027. {
  1028. for(auto b : exportedBonuses)
  1029. if(b->propagator)
  1030. descendant->unpropagateBonus(b);
  1031. FOREACH_RED_PARENT(parent)
  1032. parent->removedRedDescendant(descendant);
  1033. }
  1034. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1035. {
  1036. getRedParents(out);
  1037. FOREACH_RED_PARENT(p)
  1038. p->getRedAncestors(out);
  1039. }
  1040. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1041. {
  1042. getRedChildren(out);
  1043. FOREACH_RED_CHILD(c)
  1044. c->getRedChildren(out);
  1045. }
  1046. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  1047. {
  1048. if(b->propagator)
  1049. propagateBonus(b);
  1050. else
  1051. bonuses.push_back(b);
  1052. CBonusSystemNode::treeHasChanged();
  1053. }
  1054. void CBonusSystemNode::exportBonuses()
  1055. {
  1056. for(auto b : exportedBonuses)
  1057. exportBonus(b);
  1058. }
  1059. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1060. {
  1061. return nodeType;
  1062. }
  1063. const BonusList& CBonusSystemNode::getBonusList() const
  1064. {
  1065. return bonuses;
  1066. }
  1067. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1068. {
  1069. return parents;
  1070. }
  1071. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1072. {
  1073. return children;
  1074. }
  1075. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1076. {
  1077. nodeType = type;
  1078. }
  1079. BonusList& CBonusSystemNode::getExportedBonusList()
  1080. {
  1081. return exportedBonuses;
  1082. }
  1083. const std::string& CBonusSystemNode::getDescription() const
  1084. {
  1085. return description;
  1086. }
  1087. void CBonusSystemNode::setDescription(const std::string &description)
  1088. {
  1089. this->description = description;
  1090. }
  1091. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1092. {
  1093. assert(&allBonuses != &out); //todo should it work in-place?
  1094. BonusList undecided = allBonuses,
  1095. &accepted = out;
  1096. while(true)
  1097. {
  1098. int undecidedCount = undecided.size();
  1099. for(int i = 0; i < undecided.size(); i++)
  1100. {
  1101. auto b = undecided[i];
  1102. BonusLimitationContext context = {b, *this, out, undecided};
  1103. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1104. if(decision == ILimiter::DISCARD)
  1105. {
  1106. undecided.erase(i);
  1107. i--; continue;
  1108. }
  1109. else if(decision == ILimiter::ACCEPT)
  1110. {
  1111. accepted.push_back(b);
  1112. undecided.erase(i);
  1113. i--; continue;
  1114. }
  1115. else
  1116. assert(decision == ILimiter::NOT_SURE);
  1117. }
  1118. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1119. return;
  1120. }
  1121. }
  1122. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1123. {
  1124. auto ret = std::make_shared<BonusList>();
  1125. limitBonuses(allBonuses, *ret);
  1126. return ret;
  1127. }
  1128. void CBonusSystemNode::treeHasChanged()
  1129. {
  1130. treeChanged++;
  1131. }
  1132. int64_t CBonusSystemNode::getTreeVersion() const
  1133. {
  1134. int64_t ret = treeChanged;
  1135. return ret << 32;
  1136. }
  1137. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1138. {
  1139. if(obj)
  1140. return obj->valOfBonuses(type, subtype);
  1141. return 0;
  1142. }
  1143. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1144. {
  1145. if(obj)
  1146. return obj->hasBonusOfType(type, subtype);
  1147. return false;
  1148. }
  1149. std::string Bonus::Description() const
  1150. {
  1151. std::ostringstream str;
  1152. if(description.empty())
  1153. {
  1154. if(stacking.empty() || stacking == "ALWAYS")
  1155. {
  1156. switch(source)
  1157. {
  1158. case ARTIFACT:
  1159. str << VLC->arth->artifacts[sid]->Name();
  1160. break;
  1161. case SPELL_EFFECT:
  1162. str << SpellID(sid).toSpell()->name;
  1163. break;
  1164. case CREATURE_ABILITY:
  1165. str << VLC->creh->creatures[sid]->namePl;
  1166. break;
  1167. case SECONDARY_SKILL:
  1168. str << VLC->skillh->skillName(sid);
  1169. break;
  1170. case HERO_SPECIAL:
  1171. str << VLC->heroh->heroes[sid]->name;
  1172. break;
  1173. default:
  1174. //todo: handle all possible sources
  1175. str << "Unknown";
  1176. break;
  1177. }
  1178. }
  1179. else
  1180. str << stacking;
  1181. }
  1182. else
  1183. {
  1184. str << description;
  1185. }
  1186. if(val != 0)
  1187. str << " " << std::showpos << val;
  1188. return str.str();
  1189. }
  1190. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1191. {
  1192. switch(type)
  1193. {
  1194. case Bonus::PRIMARY_SKILL:
  1195. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1196. case Bonus::SECONDARY_SKILL_PREMY:
  1197. return JsonUtils::stringNode(CSkillHandler::encodeSkillWithType(subtype));
  1198. case Bonus::SPECIAL_SPELL_LEV:
  1199. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1200. case Bonus::SPECIAL_BLESS_DAMAGE:
  1201. case Bonus::MAXED_SPELL:
  1202. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1203. return JsonUtils::stringNode("spell." + (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  1204. case Bonus::IMPROVED_NECROMANCY:
  1205. case Bonus::SPECIAL_UPGRADE:
  1206. return JsonUtils::stringNode("creature." + CreatureID::encode(subtype));
  1207. case Bonus::GENERATE_RESOURCE:
  1208. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1209. default:
  1210. return JsonUtils::intNode(subtype);
  1211. }
  1212. }
  1213. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1214. {
  1215. switch(type)
  1216. {
  1217. case Bonus::SPECIAL_UPGRADE:
  1218. return JsonUtils::stringNode("creature." + CreatureID::encode(addInfo[0]));
  1219. default:
  1220. return addInfo.toJsonNode();
  1221. }
  1222. }
  1223. JsonNode durationToJson(ui16 duration)
  1224. {
  1225. std::vector<std::string> durationNames;
  1226. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1227. {
  1228. if(duration & durBit)
  1229. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1230. }
  1231. if(durationNames.size() == 1)
  1232. {
  1233. return JsonUtils::stringNode(durationNames[0]);
  1234. }
  1235. else
  1236. {
  1237. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1238. for(std::string dur : durationNames)
  1239. node.Vector().push_back(JsonUtils::stringNode(dur));
  1240. return node;
  1241. }
  1242. }
  1243. JsonNode Bonus::toJsonNode() const
  1244. {
  1245. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1246. // only add values that might reasonably be found in config files
  1247. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1248. if(subtype != -1)
  1249. root["subtype"] = subtypeToJson(type, subtype);
  1250. if(additionalInfo != CAddInfo::NONE)
  1251. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1252. if(val != 0)
  1253. root["val"].Integer() = val;
  1254. if(valType != ADDITIVE_VALUE)
  1255. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1256. if(stacking != "")
  1257. root["stacking"].String() = stacking;
  1258. if(description != "")
  1259. root["description"].String() = description;
  1260. if(effectRange != NO_LIMIT)
  1261. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1262. if(duration != PERMANENT)
  1263. root["duration"] = durationToJson(duration);
  1264. if(turnsRemain)
  1265. root["turns"].Integer() = turnsRemain;
  1266. if(limiter)
  1267. root["limiters"] = limiter->toJsonNode();
  1268. if(updater)
  1269. root["updater"] = updater->toJsonNode();
  1270. if(propagator)
  1271. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1272. return root;
  1273. }
  1274. std::string Bonus::nameForBonus() const
  1275. {
  1276. switch(type)
  1277. {
  1278. case Bonus::PRIMARY_SKILL:
  1279. return PrimarySkill::names[subtype];
  1280. case Bonus::SECONDARY_SKILL_PREMY:
  1281. return CSkillHandler::encodeSkill(subtype);
  1282. case Bonus::SPECIAL_SPELL_LEV:
  1283. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1284. case Bonus::SPECIAL_BLESS_DAMAGE:
  1285. case Bonus::MAXED_SPELL:
  1286. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1287. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1288. case Bonus::SPECIAL_UPGRADE:
  1289. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1290. case Bonus::GENERATE_RESOURCE:
  1291. return GameConstants::RESOURCE_NAMES[subtype];
  1292. case Bonus::STACKS_SPEED:
  1293. return "speed";
  1294. default:
  1295. return vstd::findKey(bonusNameMap, type);
  1296. }
  1297. }
  1298. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1299. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1300. {
  1301. turnsRemain = 0;
  1302. valType = ADDITIVE_VALUE;
  1303. effectRange = NO_LIMIT;
  1304. boost::algorithm::trim(description);
  1305. }
  1306. Bonus::Bonus(ui16 Dur, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1307. : duration(Dur), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1308. {
  1309. turnsRemain = 0;
  1310. effectRange = NO_LIMIT;
  1311. }
  1312. Bonus::Bonus()
  1313. {
  1314. duration = PERMANENT;
  1315. turnsRemain = 0;
  1316. type = NONE;
  1317. subtype = -1;
  1318. valType = ADDITIVE_VALUE;
  1319. effectRange = NO_LIMIT;
  1320. val = 0;
  1321. source = OTHER;
  1322. sid = 0;
  1323. }
  1324. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1325. {
  1326. propagator = Propagator;
  1327. return this->shared_from_this();
  1328. }
  1329. namespace Selector
  1330. {
  1331. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> type(&Bonus::type);
  1332. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> subtype(&Bonus::subtype);
  1333. DLL_LINKAGE CSelectFieldEqual<CAddInfo> info(&Bonus::additionalInfo);
  1334. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> sourceType(&Bonus::source);
  1335. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> effectRange(&Bonus::effectRange);
  1336. DLL_LINKAGE CWillLastTurns turns;
  1337. DLL_LINKAGE CWillLastDays days;
  1338. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1339. {
  1340. return type(Type).And(subtype(Subtype));
  1341. }
  1342. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1343. {
  1344. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1345. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1346. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1347. }
  1348. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1349. {
  1350. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1351. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1352. }
  1353. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1354. {
  1355. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1356. }
  1357. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1358. {
  1359. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1360. }
  1361. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1362. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1363. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1364. {
  1365. Bonus dummy;
  1366. dummy.type = type;
  1367. return sel(&dummy);
  1368. }
  1369. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1370. {
  1371. Bonus dummy;
  1372. dummy.type = type;
  1373. dummy.subtype = subtype;
  1374. return sel(&dummy);
  1375. }
  1376. }
  1377. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1378. {
  1379. switch(node->getNodeType())
  1380. {
  1381. case CBonusSystemNode::STACK_BATTLE:
  1382. return static_cast<const CStack*>(node);
  1383. default:
  1384. return nullptr;
  1385. }
  1386. }
  1387. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1388. {
  1389. switch(node->getNodeType())
  1390. {
  1391. case CBonusSystemNode::STACK_INSTANCE:
  1392. return (static_cast<const CStackInstance *>(node));
  1393. case CBonusSystemNode::STACK_BATTLE:
  1394. return (static_cast<const CStack*>(node))->base;
  1395. default:
  1396. return nullptr;
  1397. }
  1398. }
  1399. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1400. {
  1401. switch(node->getNodeType())
  1402. {
  1403. case CBonusSystemNode::CREATURE:
  1404. return (static_cast<const CCreature *>(node));
  1405. case CBonusSystemNode::STACK_BATTLE:
  1406. return (static_cast<const CStack*>(node))->type;
  1407. default:
  1408. const CStackInstance * csi = retrieveStackInstance(node);
  1409. if(csi)
  1410. return csi->type;
  1411. return nullptr;
  1412. }
  1413. }
  1414. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1415. {
  1416. for (ui32 i = 0; i < bonusList.size(); i++)
  1417. {
  1418. auto b = bonusList[i];
  1419. out << "Bonus " << i << "\n" << *b << std::endl;
  1420. }
  1421. return out;
  1422. }
  1423. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1424. {
  1425. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1426. if(i->second == bonus.type)
  1427. out << "\tType: " << i->first << " \t";
  1428. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1429. printField(val);
  1430. printField(subtype);
  1431. printField(duration);
  1432. printField(source);
  1433. printField(sid);
  1434. if(bonus.additionalInfo != CAddInfo::NONE)
  1435. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1436. printField(turnsRemain);
  1437. printField(valType);
  1438. if(!bonus.stacking.empty())
  1439. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1440. printField(effectRange);
  1441. #undef printField
  1442. if(bonus.limiter)
  1443. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1444. if(bonus.updater)
  1445. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1446. return out;
  1447. }
  1448. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1449. {
  1450. if (limiter)
  1451. {
  1452. //If we already have limiter list, retrieve it
  1453. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1454. if(!limiterList)
  1455. {
  1456. //Create a new limiter list with old limiter and the new one will be pushed later
  1457. limiterList = std::make_shared<AllOfLimiter>();
  1458. limiterList->add(limiter);
  1459. limiter = limiterList;
  1460. }
  1461. limiterList->add(Limiter);
  1462. }
  1463. else
  1464. {
  1465. limiter = Limiter;
  1466. }
  1467. return this->shared_from_this();
  1468. }
  1469. ILimiter::~ILimiter()
  1470. {
  1471. }
  1472. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1473. {
  1474. return false;
  1475. }
  1476. std::string ILimiter::toString() const
  1477. {
  1478. return typeid(*this).name();
  1479. }
  1480. JsonNode ILimiter::toJsonNode() const
  1481. {
  1482. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1483. root["type"].String() = toString();
  1484. return root;
  1485. }
  1486. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1487. {
  1488. const CCreature *c = retrieveCreature(&context.node);
  1489. if(!c)
  1490. return true;
  1491. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1492. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1493. }
  1494. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1495. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1496. {
  1497. }
  1498. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1499. {
  1500. creature = nullptr;
  1501. includeUpgrades = false;
  1502. }
  1503. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1504. {
  1505. creature = VLC->creh->creatures[id];
  1506. }
  1507. std::string CCreatureTypeLimiter::toString() const
  1508. {
  1509. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1510. fmt % creature->identifier % (includeUpgrades ? "true" : "false");
  1511. return fmt.str();
  1512. }
  1513. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1514. {
  1515. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1516. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1517. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1518. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1519. return root;
  1520. }
  1521. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1522. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1523. {
  1524. }
  1525. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1526. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1527. {
  1528. }
  1529. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1530. {
  1531. CSelector mySelector = isSubtypeRelevant
  1532. ? Selector::typeSubtype(type, subtype)
  1533. : Selector::type(type);
  1534. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1535. if(context.alreadyAccepted.getFirst(mySelector))
  1536. return ACCEPT;
  1537. //if there are no matching bonuses pending, we can (and must) reject right away
  1538. if(!context.stillUndecided.getFirst(mySelector))
  1539. return DISCARD;
  1540. //do not accept for now but it may change if more bonuses gets included
  1541. return NOT_SURE;
  1542. }
  1543. std::string HasAnotherBonusLimiter::toString() const
  1544. {
  1545. std::string typeName = vstd::findKey(bonusNameMap, type);
  1546. if(isSubtypeRelevant)
  1547. {
  1548. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1549. fmt % typeName % subtype;
  1550. return fmt.str();
  1551. }
  1552. else
  1553. {
  1554. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1555. fmt % typeName;
  1556. return fmt.str();
  1557. }
  1558. }
  1559. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1560. {
  1561. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1562. std::string typeName = vstd::findKey(bonusNameMap, type);
  1563. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1564. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1565. if(isSubtypeRelevant)
  1566. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1567. return root;
  1568. }
  1569. IPropagator::~IPropagator()
  1570. {
  1571. }
  1572. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1573. {
  1574. return false;
  1575. }
  1576. CPropagatorNodeType::CPropagatorNodeType()
  1577. :nodeType(0)
  1578. {
  1579. }
  1580. CPropagatorNodeType::CPropagatorNodeType(int NodeType)
  1581. : nodeType(NodeType)
  1582. {
  1583. }
  1584. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1585. {
  1586. return nodeType == dest->getNodeType();
  1587. }
  1588. CreatureTerrainLimiter::CreatureTerrainLimiter(int TerrainType)
  1589. : terrainType(TerrainType)
  1590. {
  1591. }
  1592. CreatureTerrainLimiter::CreatureTerrainLimiter()
  1593. : terrainType(-1)
  1594. {
  1595. }
  1596. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  1597. {
  1598. const CStack *stack = retrieveStackBattle(&context.node);
  1599. if(stack)
  1600. {
  1601. if(terrainType == -1)//terrainType not specified = native
  1602. return !stack->isOnNativeTerrain();
  1603. return !stack->isOnTerrain(terrainType);
  1604. }
  1605. return true;
  1606. //TODO neutral creatues
  1607. }
  1608. std::string CreatureTerrainLimiter::toString() const
  1609. {
  1610. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  1611. fmt % (terrainType >= 0 ? GameConstants::TERRAIN_NAMES[terrainType] : "native");
  1612. return fmt.str();
  1613. }
  1614. JsonNode CreatureTerrainLimiter::toJsonNode() const
  1615. {
  1616. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1617. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  1618. if(terrainType >= 0)
  1619. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::TERRAIN_NAMES[terrainType]));
  1620. return root;
  1621. }
  1622. CreatureFactionLimiter::CreatureFactionLimiter(int Faction)
  1623. : faction(Faction)
  1624. {
  1625. }
  1626. CreatureFactionLimiter::CreatureFactionLimiter()
  1627. : faction(-1)
  1628. {
  1629. }
  1630. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1631. {
  1632. const CCreature *c = retrieveCreature(&context.node);
  1633. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1634. }
  1635. std::string CreatureFactionLimiter::toString() const
  1636. {
  1637. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  1638. fmt % VLC->townh->factions[faction]->identifier;
  1639. return fmt.str();
  1640. }
  1641. JsonNode CreatureFactionLimiter::toJsonNode() const
  1642. {
  1643. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1644. root["type"].String() = "CREATURE_FACTION_LIMITER";
  1645. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->townh->factions[faction]->identifier));
  1646. return root;
  1647. }
  1648. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1649. : alignment(-1)
  1650. {
  1651. }
  1652. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1653. : alignment(Alignment)
  1654. {
  1655. }
  1656. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1657. {
  1658. const CCreature *c = retrieveCreature(&context.node);
  1659. if(!c)
  1660. return true;
  1661. switch(alignment)
  1662. {
  1663. case EAlignment::GOOD:
  1664. return !c->isGood(); //if not good -> return true (drop bonus)
  1665. case EAlignment::NEUTRAL:
  1666. return c->isEvil() || c->isGood();
  1667. case EAlignment::EVIL:
  1668. return !c->isEvil();
  1669. default:
  1670. logBonus->warn("Warning: illegal alignment in limiter!");
  1671. return true;
  1672. }
  1673. }
  1674. std::string CreatureAlignmentLimiter::toString() const
  1675. {
  1676. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  1677. fmt % EAlignment::names[alignment];
  1678. return fmt.str();
  1679. }
  1680. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  1681. {
  1682. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1683. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  1684. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  1685. return root;
  1686. }
  1687. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1688. :minRank(Min), maxRank(Max)
  1689. {
  1690. }
  1691. RankRangeLimiter::RankRangeLimiter()
  1692. {
  1693. minRank = maxRank = -1;
  1694. }
  1695. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1696. {
  1697. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1698. if(csi)
  1699. {
  1700. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1701. return true;
  1702. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1703. }
  1704. return true;
  1705. }
  1706. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1707. {
  1708. const CStack * s = retrieveStackBattle(&context.node);
  1709. if(s)
  1710. return s->owner != owner;
  1711. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1712. if(csi && csi->armyObj)
  1713. return csi->armyObj->tempOwner != owner;
  1714. return true;
  1715. }
  1716. StackOwnerLimiter::StackOwnerLimiter()
  1717. : owner(-1)
  1718. {
  1719. }
  1720. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1721. : owner(Owner)
  1722. {
  1723. }
  1724. // Aggregate/Boolean Limiters
  1725. void AggregateLimiter::add(TLimiterPtr limiter)
  1726. {
  1727. if(limiter)
  1728. limiters.push_back(limiter);
  1729. }
  1730. JsonNode AggregateLimiter::toJsonNode() const
  1731. {
  1732. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  1733. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  1734. for(auto l : limiters)
  1735. result.Vector().push_back(l->toJsonNode());
  1736. return result;
  1737. }
  1738. const std::string AllOfLimiter::aggregator = "allOf";
  1739. const std::string & AllOfLimiter::getAggregator() const
  1740. {
  1741. return aggregator;
  1742. }
  1743. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  1744. {
  1745. bool wasntSure = false;
  1746. for(auto limiter : limiters)
  1747. {
  1748. auto result = limiter->limit(context);
  1749. if(result == ILimiter::DISCARD)
  1750. return result;
  1751. if(result == ILimiter::NOT_SURE)
  1752. wasntSure = true;
  1753. }
  1754. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1755. }
  1756. const std::string AnyOfLimiter::aggregator = "anyOf";
  1757. const std::string & AnyOfLimiter::getAggregator() const
  1758. {
  1759. return aggregator;
  1760. }
  1761. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  1762. {
  1763. bool wasntSure = false;
  1764. for(auto limiter : limiters)
  1765. {
  1766. auto result = limiter->limit(context);
  1767. if(result == ILimiter::ACCEPT)
  1768. return result;
  1769. if(result == ILimiter::NOT_SURE)
  1770. wasntSure = true;
  1771. }
  1772. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  1773. }
  1774. const std::string NoneOfLimiter::aggregator = "noneOf";
  1775. const std::string & NoneOfLimiter::getAggregator() const
  1776. {
  1777. return aggregator;
  1778. }
  1779. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  1780. {
  1781. bool wasntSure = false;
  1782. for(auto limiter : limiters)
  1783. {
  1784. auto result = limiter->limit(context);
  1785. if(result == ILimiter::ACCEPT)
  1786. return ILimiter::DISCARD;
  1787. if(result == ILimiter::NOT_SURE)
  1788. wasntSure = true;
  1789. }
  1790. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1791. }
  1792. // Updaters
  1793. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1794. {
  1795. updater = Updater;
  1796. return this->shared_from_this();
  1797. }
  1798. IUpdater::~IUpdater()
  1799. {
  1800. }
  1801. const std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1802. {
  1803. return b;
  1804. }
  1805. std::string IUpdater::toString() const
  1806. {
  1807. return typeid(*this).name();
  1808. }
  1809. JsonNode IUpdater::toJsonNode() const
  1810. {
  1811. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1812. }
  1813. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1814. {
  1815. }
  1816. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1817. {
  1818. }
  1819. const std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1820. {
  1821. if(context.getNodeType() == CBonusSystemNode::HERO)
  1822. {
  1823. int level = static_cast<const CGHeroInstance &>(context).level;
  1824. int steps = stepSize ? level / stepSize : level;
  1825. //rounding follows format for HMM3 creature specialty bonus
  1826. int newVal = (valPer20 * steps + 19) / 20;
  1827. //return copy of bonus with updated val
  1828. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1829. newBonus->val = newVal;
  1830. return newBonus;
  1831. }
  1832. return b;
  1833. }
  1834. std::string GrowsWithLevelUpdater::toString() const
  1835. {
  1836. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1837. }
  1838. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1839. {
  1840. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1841. root["type"].String() = "GROWS_WITH_LEVEL";
  1842. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1843. if(stepSize > 1)
  1844. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1845. return root;
  1846. }
  1847. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1848. {
  1849. }
  1850. const std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1851. {
  1852. if(context.getNodeType() == CBonusSystemNode::HERO)
  1853. {
  1854. int level = static_cast<const CGHeroInstance &>(context).level;
  1855. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1856. newBonus->val *= level;
  1857. return newBonus;
  1858. }
  1859. return b;
  1860. }
  1861. std::string TimesHeroLevelUpdater::toString() const
  1862. {
  1863. return "TimesHeroLevelUpdater";
  1864. }
  1865. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1866. {
  1867. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1868. }
  1869. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1870. {
  1871. }
  1872. const std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> b, const CBonusSystemNode & context) const
  1873. {
  1874. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1875. {
  1876. int level = static_cast<const CStackInstance &>(context).getLevel();
  1877. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1878. newBonus->val *= level;
  1879. return newBonus;
  1880. }
  1881. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1882. {
  1883. const CStack & stack = static_cast<const CStack &>(context);
  1884. //only update if stack doesn't have an instance (summons, war machines)
  1885. //otherwise we'd end up multiplying twice
  1886. if(stack.base == nullptr)
  1887. {
  1888. int level = stack.type->level;
  1889. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1890. newBonus->val *= level;
  1891. return newBonus;
  1892. }
  1893. }
  1894. return b;
  1895. }
  1896. std::string TimesStackLevelUpdater::toString() const
  1897. {
  1898. return "TimesStackLevelUpdater";
  1899. }
  1900. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1901. {
  1902. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1903. }