HeroBonus.cpp 59 KB

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