HeroBonus.cpp 58 KB

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