HeroBonus.cpp 58 KB

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