2
0

HeroBonus.cpp 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800
  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 "TerrainHandler.h"
  24. #include "StringConstants.h"
  25. #include "battle/BattleInfo.h"
  26. VCMI_LIB_NAMESPACE_BEGIN
  27. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  28. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  29. #define BONUS_NAME(x) { #x, Bonus::x },
  30. const std::map<std::string, Bonus::BonusType> bonusNameMap = {
  31. BONUS_LIST
  32. };
  33. #undef BONUS_NAME
  34. #define BONUS_VALUE(x) { #x, Bonus::x },
  35. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  36. #undef BONUS_VALUE
  37. #define BONUS_SOURCE(x) { #x, Bonus::x },
  38. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  39. #undef BONUS_SOURCE
  40. #define BONUS_ITEM(x) { #x, Bonus::x },
  41. const std::map<std::string, ui16> bonusDurationMap =
  42. {
  43. BONUS_ITEM(PERMANENT)
  44. BONUS_ITEM(ONE_BATTLE)
  45. BONUS_ITEM(ONE_DAY)
  46. BONUS_ITEM(ONE_WEEK)
  47. BONUS_ITEM(N_TURNS)
  48. BONUS_ITEM(N_DAYS)
  49. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  50. BONUS_ITEM(UNTIL_ATTACK)
  51. BONUS_ITEM(STACK_GETS_TURN)
  52. BONUS_ITEM(COMMANDER_KILLED)
  53. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  54. };
  55. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  56. {
  57. BONUS_ITEM(NO_LIMIT)
  58. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  59. BONUS_ITEM(ONLY_MELEE_FIGHT)
  60. };
  61. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  62. {
  63. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  64. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  65. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)},
  66. {"CREATURE_NATIVE_TERRAIN", std::make_shared<CreatureTerrainLimiter>()},
  67. {"CREATURE_FACTION", std::make_shared<AllOfLimiter>(std::initializer_list<TLimiterPtr>{std::make_shared<CreatureLevelLimiter>(), std::make_shared<FactionLimiter>()})},
  68. {"SAME_FACTION", std::make_shared<FactionLimiter>()},
  69. {"CREATURES_ONLY", std::make_shared<CreatureLevelLimiter>()},
  70. {"OPPOSITE_SIDE", std::make_shared<OppositeSideLimiter>()},
  71. };
  72. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  73. {
  74. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  75. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  76. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  77. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  78. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  79. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)}
  80. }; //untested
  81. const std::map<std::string, TUpdaterPtr> bonusUpdaterMap =
  82. {
  83. {"TIMES_HERO_LEVEL", std::make_shared<TimesHeroLevelUpdater>()},
  84. {"TIMES_STACK_LEVEL", std::make_shared<TimesStackLevelUpdater>()},
  85. {"ARMY_MOVEMENT", std::make_shared<ArmyMovementUpdater>()},
  86. {"BONUS_OWNER_UPDATER", std::make_shared<OwnerUpdater>()}
  87. };
  88. const std::set<std::string> deprecatedBonusSet = {
  89. "SECONDARY_SKILL_PREMY",
  90. "SECONDARY_SKILL_VAL2",
  91. "MAXED_SPELL",
  92. "LAND_MOVEMENT",
  93. "SEA_MOVEMENT",
  94. "SIGHT_RADIOUS",
  95. "NO_TYPE",
  96. "SPECIAL_SECONDARY_SKILL",
  97. "FULL_HP_REGENERATION",
  98. "KING1",
  99. "KING2",
  100. "KING3",
  101. "BLOCK_MORALE",
  102. "BLOCK_LUCK",
  103. "SELF_MORALE",
  104. "SELF_LUCK"
  105. };
  106. ///CBonusProxy
  107. CBonusProxy::CBonusProxy(const IBonusBearer * Target, CSelector Selector):
  108. bonusListCachedLast(0),
  109. target(Target),
  110. selector(std::move(Selector)),
  111. currentBonusListIndex(0)
  112. {
  113. }
  114. CBonusProxy::CBonusProxy(const CBonusProxy & other):
  115. bonusListCachedLast(other.bonusListCachedLast),
  116. target(other.target),
  117. selector(other.selector),
  118. currentBonusListIndex(other.currentBonusListIndex)
  119. {
  120. bonusList[currentBonusListIndex] = other.bonusList[currentBonusListIndex];
  121. }
  122. CBonusProxy::CBonusProxy(CBonusProxy && other) noexcept:
  123. bonusListCachedLast(0),
  124. target(other.target),
  125. currentBonusListIndex(0)
  126. {
  127. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  128. std::swap(selector, other.selector);
  129. std::swap(bonusList, other.bonusList);
  130. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  131. }
  132. CBonusProxy & CBonusProxy::operator=(const CBonusProxy & other)
  133. {
  134. boost::lock_guard<boost::mutex> lock(swapGuard);
  135. selector = other.selector;
  136. swapBonusList(other.bonusList[other.currentBonusListIndex]);
  137. bonusListCachedLast = other.bonusListCachedLast;
  138. return *this;
  139. }
  140. CBonusProxy & CBonusProxy::operator=(CBonusProxy && other) noexcept
  141. {
  142. std::swap(bonusListCachedLast, other.bonusListCachedLast);
  143. std::swap(selector, other.selector);
  144. std::swap(bonusList, other.bonusList);
  145. std::swap(currentBonusListIndex, other.currentBonusListIndex);
  146. return *this;
  147. }
  148. void CBonusProxy::swapBonusList(TConstBonusListPtr other) const
  149. {
  150. // The idea here is to avoid changing active bonusList while it can be read by a different thread.
  151. // Because such use of shared ptr is not thread safe
  152. // So to avoid this we change the second offline instance and swap active index
  153. auto newCurrent = 1 - currentBonusListIndex;
  154. bonusList[newCurrent] = std::move(other);
  155. currentBonusListIndex = newCurrent;
  156. }
  157. TConstBonusListPtr CBonusProxy::getBonusList() const
  158. {
  159. auto needUpdateBonusList = [&]() -> bool
  160. {
  161. return target->getTreeVersion() != bonusListCachedLast || !bonusList[currentBonusListIndex];
  162. };
  163. // avoid locking if everything is up-to-date
  164. if(needUpdateBonusList())
  165. {
  166. boost::lock_guard<boost::mutex>lock(swapGuard);
  167. if(needUpdateBonusList())
  168. {
  169. //TODO: support limiters
  170. swapBonusList(target->getAllBonuses(selector, Selector::all));
  171. bonusListCachedLast = target->getTreeVersion();
  172. }
  173. }
  174. return bonusList[currentBonusListIndex];
  175. }
  176. const BonusList * CBonusProxy::operator->() const
  177. {
  178. return getBonusList().get();
  179. }
  180. CTotalsProxy::CTotalsProxy(const IBonusBearer * Target, CSelector Selector, int InitialValue):
  181. CBonusProxy(Target, std::move(Selector)),
  182. initialValue(InitialValue),
  183. meleeCachedLast(0),
  184. meleeValue(0),
  185. rangedCachedLast(0),
  186. rangedValue(0)
  187. {
  188. }
  189. CTotalsProxy::CTotalsProxy(const CTotalsProxy & other)
  190. : CBonusProxy(other),
  191. initialValue(other.initialValue),
  192. meleeCachedLast(other.meleeCachedLast),
  193. meleeValue(other.meleeValue),
  194. rangedCachedLast(other.rangedCachedLast),
  195. rangedValue(other.rangedValue)
  196. {
  197. }
  198. int CTotalsProxy::getValue() const
  199. {
  200. const auto treeVersion = target->getTreeVersion();
  201. if(treeVersion != valueCachedLast)
  202. {
  203. auto bonuses = getBonusList();
  204. value = initialValue + bonuses->totalValue();
  205. valueCachedLast = treeVersion;
  206. }
  207. return value;
  208. }
  209. int CTotalsProxy::getValueAndList(TConstBonusListPtr & outBonusList) const
  210. {
  211. const auto treeVersion = target->getTreeVersion();
  212. outBonusList = getBonusList();
  213. if(treeVersion != valueCachedLast)
  214. {
  215. value = initialValue + outBonusList->totalValue();
  216. valueCachedLast = treeVersion;
  217. }
  218. return value;
  219. }
  220. int CTotalsProxy::getMeleeValue() const
  221. {
  222. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_MELEE_FIGHT));
  223. const auto treeVersion = target->getTreeVersion();
  224. if(treeVersion != meleeCachedLast)
  225. {
  226. auto bonuses = target->getBonuses(selector, limit);
  227. meleeValue = initialValue + bonuses->totalValue();
  228. meleeCachedLast = treeVersion;
  229. }
  230. return meleeValue;
  231. }
  232. int CTotalsProxy::getRangedValue() const
  233. {
  234. static const auto limit = Selector::effectRange()(Bonus::NO_LIMIT).Or(Selector::effectRange()(Bonus::ONLY_DISTANCE_FIGHT));
  235. const auto treeVersion = target->getTreeVersion();
  236. if(treeVersion != rangedCachedLast)
  237. {
  238. auto bonuses = target->getBonuses(selector, limit);
  239. rangedValue = initialValue + bonuses->totalValue();
  240. rangedCachedLast = treeVersion;
  241. }
  242. return rangedValue;
  243. }
  244. ///CCheckProxy
  245. CCheckProxy::CCheckProxy(const IBonusBearer * Target, CSelector Selector):
  246. target(Target),
  247. selector(std::move(Selector)),
  248. cachedLast(0),
  249. hasBonus(false)
  250. {
  251. }
  252. //This constructor should be placed here to avoid side effects
  253. CCheckProxy::CCheckProxy(const CCheckProxy & other) = default;
  254. bool CCheckProxy::getHasBonus() const
  255. {
  256. const auto treeVersion = target->getTreeVersion();
  257. if(treeVersion != cachedLast)
  258. {
  259. hasBonus = target->hasBonus(selector);
  260. cachedLast = treeVersion;
  261. }
  262. return hasBonus;
  263. }
  264. //This constructor should be placed here to avoid side effects
  265. CAddInfo::CAddInfo() = default;
  266. CAddInfo::CAddInfo(si32 value)
  267. {
  268. if(value != CAddInfo::NONE)
  269. push_back(value);
  270. }
  271. bool CAddInfo::operator==(si32 value) const
  272. {
  273. switch(size())
  274. {
  275. case 0:
  276. return value == CAddInfo::NONE;
  277. case 1:
  278. return operator[](0) == value;
  279. default:
  280. return false;
  281. }
  282. }
  283. bool CAddInfo::operator!=(si32 value) const
  284. {
  285. return !operator==(value);
  286. }
  287. si32 & CAddInfo::operator[](size_type pos)
  288. {
  289. if(pos >= size())
  290. resize(pos + 1, CAddInfo::NONE);
  291. return vector::operator[](pos);
  292. }
  293. si32 CAddInfo::operator[](size_type pos) const
  294. {
  295. return pos < size() ? vector::operator[](pos) : CAddInfo::NONE;
  296. }
  297. std::string CAddInfo::toString() const
  298. {
  299. return toJsonNode().toJson(true);
  300. }
  301. JsonNode CAddInfo::toJsonNode() const
  302. {
  303. if(size() < 2)
  304. {
  305. return JsonUtils::intNode(operator[](0));
  306. }
  307. else
  308. {
  309. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  310. for(si32 value : *this)
  311. node.Vector().push_back(JsonUtils::intNode(value));
  312. return node;
  313. }
  314. }
  315. std::atomic<int64_t> CBonusSystemNode::treeChanged(1);
  316. constexpr bool CBonusSystemNode::cachingEnabled = true;
  317. BonusList::BonusList(bool BelongsToTree) : belongsToTree(BelongsToTree)
  318. {
  319. }
  320. BonusList::BonusList(const BonusList & bonusList): belongsToTree(false)
  321. {
  322. bonuses.resize(bonusList.size());
  323. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  324. }
  325. BonusList::BonusList(BonusList && other) noexcept: belongsToTree(false)
  326. {
  327. std::swap(belongsToTree, other.belongsToTree);
  328. std::swap(bonuses, other.bonuses);
  329. }
  330. BonusList& BonusList::operator=(const BonusList &bonusList)
  331. {
  332. bonuses.resize(bonusList.size());
  333. std::copy(bonusList.begin(), bonusList.end(), bonuses.begin());
  334. belongsToTree = false;
  335. return *this;
  336. }
  337. void BonusList::changed() const
  338. {
  339. if(belongsToTree)
  340. CBonusSystemNode::treeHasChanged();
  341. }
  342. void BonusList::stackBonuses()
  343. {
  344. boost::sort(bonuses, [](const std::shared_ptr<Bonus> & b1, const std::shared_ptr<Bonus> & b2) -> bool
  345. {
  346. if(b1 == b2)
  347. return false;
  348. #define COMPARE_ATT(ATT) if(b1->ATT != b2->ATT) return b1->ATT < b2->ATT
  349. COMPARE_ATT(stacking);
  350. COMPARE_ATT(type);
  351. COMPARE_ATT(subtype);
  352. COMPARE_ATT(valType);
  353. #undef COMPARE_ATT
  354. return b1->val > b2->val;
  355. });
  356. // remove non-stacking
  357. size_t next = 1;
  358. while(next < bonuses.size())
  359. {
  360. bool remove = false;
  361. std::shared_ptr<Bonus> last = bonuses[next-1];
  362. std::shared_ptr<Bonus> current = bonuses[next];
  363. if(current->stacking.empty())
  364. remove = current == last;
  365. else if(current->stacking == "ALWAYS")
  366. remove = false;
  367. else
  368. remove = current->stacking == last->stacking
  369. && current->type == last->type
  370. && current->subtype == last->subtype
  371. && current->valType == last->valType;
  372. if(remove)
  373. bonuses.erase(bonuses.begin() + next);
  374. else
  375. next++;
  376. }
  377. }
  378. int BonusList::totalValue() const
  379. {
  380. struct BonusCollection
  381. {
  382. int base = 0;
  383. int percentToBase = 0;
  384. int percentToAll = 0;
  385. int additive = 0;
  386. int percentToSource = 0;
  387. int indepMin = std::numeric_limits<int>::max();
  388. int indepMax = std::numeric_limits<int>::min();
  389. };
  390. auto percent = [](int64_t base, int64_t percent) -> int {
  391. return static_cast<int>(vstd::clamp((base * (100 + percent)) / 100, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()));
  392. };
  393. std::array <BonusCollection, Bonus::BonusSource::NUM_BONUS_SOURCE> sources = {};
  394. BonusCollection any;
  395. bool hasIndepMax = false;
  396. bool hasIndepMin = false;
  397. for(const auto & b : bonuses)
  398. {
  399. switch(b->valType)
  400. {
  401. case Bonus::BASE_NUMBER:
  402. sources[b->source].base += b->val;
  403. break;
  404. case Bonus::PERCENT_TO_ALL:
  405. sources[b->source].percentToAll += b->val;
  406. break;
  407. case Bonus::PERCENT_TO_BASE:
  408. sources[b->source].percentToBase += b->val;
  409. break;
  410. case Bonus::PERCENT_TO_SOURCE:
  411. sources[b->source].percentToSource += b->val;
  412. break;
  413. case Bonus::PERCENT_TO_TARGET_TYPE:
  414. sources[b->targetSourceType].percentToSource += b->val;
  415. break;
  416. case Bonus::ADDITIVE_VALUE:
  417. sources[b->source].additive += b->val;
  418. break;
  419. case Bonus::INDEPENDENT_MAX:
  420. hasIndepMax = true;
  421. vstd::amax(sources[b->source].indepMax, b->val);
  422. break;
  423. case Bonus::INDEPENDENT_MIN:
  424. hasIndepMin = true;
  425. vstd::amin(sources[b->source].indepMin, b->val);
  426. break;
  427. }
  428. }
  429. for(const auto & src : sources)
  430. {
  431. any.base += percent(src.base, src.percentToSource);
  432. any.percentToBase += percent(src.percentToBase, src.percentToSource);
  433. any.percentToAll += percent(src.percentToAll, src.percentToSource);
  434. any.additive += percent(src.additive, src.percentToSource);
  435. if(hasIndepMin)
  436. vstd::amin(any.indepMin, percent(src.indepMin, src.percentToSource));
  437. if(hasIndepMax)
  438. vstd::amax(any.indepMax, percent(src.indepMax, src.percentToSource));
  439. }
  440. any.base = percent(any.base, any.percentToBase);
  441. any.base += any.additive;
  442. auto valFirst = percent(any.base ,any.percentToAll);
  443. if(hasIndepMin && hasIndepMax && any.indepMin < any.indepMax)
  444. any.indepMax = any.indepMin;
  445. const int notIndepBonuses = static_cast<int>(std::count_if(bonuses.cbegin(), bonuses.cend(), [](const std::shared_ptr<Bonus>& b)
  446. {
  447. return b->valType != Bonus::INDEPENDENT_MAX && b->valType != Bonus::INDEPENDENT_MIN;
  448. }));
  449. if(notIndepBonuses)
  450. return vstd::clamp(valFirst, any.indepMax, any.indepMin);
  451. return hasIndepMin ? any.indepMin : hasIndepMax ? any.indepMax : 0;
  452. }
  453. std::shared_ptr<Bonus> BonusList::getFirst(const CSelector &select)
  454. {
  455. for (auto & b : bonuses)
  456. {
  457. if(select(b.get()))
  458. return b;
  459. }
  460. return nullptr;
  461. }
  462. std::shared_ptr<const Bonus> BonusList::getFirst(const CSelector &selector) const
  463. {
  464. for(const auto & b : bonuses)
  465. {
  466. if(selector(b.get()))
  467. return b;
  468. }
  469. return nullptr;
  470. }
  471. void BonusList::getBonuses(BonusList & out, const CSelector &selector, const CSelector &limit) const
  472. {
  473. out.reserve(bonuses.size());
  474. for(const auto & b : bonuses)
  475. {
  476. //add matching bonuses that matches limit predicate or have NO_LIMIT if no given predicate
  477. auto noFightLimit = b->effectRange == Bonus::NO_LIMIT;
  478. if(selector(b.get()) && ((!limit && noFightLimit) || ((bool)limit && limit(b.get()))))
  479. out.push_back(b);
  480. }
  481. }
  482. void BonusList::getAllBonuses(BonusList &out) const
  483. {
  484. for(const auto & b : bonuses)
  485. out.push_back(b);
  486. }
  487. int BonusList::valOfBonuses(const CSelector &select) const
  488. {
  489. BonusList ret;
  490. CSelector limit = nullptr;
  491. getBonuses(ret, select, limit);
  492. return ret.totalValue();
  493. }
  494. JsonNode BonusList::toJsonNode() const
  495. {
  496. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  497. for(const std::shared_ptr<Bonus> & b : bonuses)
  498. node.Vector().push_back(b->toJsonNode());
  499. return node;
  500. }
  501. void BonusList::push_back(const std::shared_ptr<Bonus> & x)
  502. {
  503. bonuses.push_back(x);
  504. changed();
  505. }
  506. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  507. {
  508. changed();
  509. return bonuses.erase(bonuses.begin() + position);
  510. }
  511. void BonusList::clear()
  512. {
  513. bonuses.clear();
  514. changed();
  515. }
  516. std::vector<BonusList *>::size_type BonusList::operator-=(const std::shared_ptr<Bonus> & i)
  517. {
  518. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  519. if(itr == bonuses.end())
  520. return false;
  521. bonuses.erase(itr);
  522. changed();
  523. return true;
  524. }
  525. void BonusList::resize(BonusList::TInternalContainer::size_type sz, const std::shared_ptr<Bonus> & c)
  526. {
  527. bonuses.resize(sz, c);
  528. changed();
  529. }
  530. void BonusList::reserve(TInternalContainer::size_type sz)
  531. {
  532. bonuses.reserve(sz);
  533. }
  534. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, const std::shared_ptr<Bonus> & x)
  535. {
  536. bonuses.insert(position, n, x);
  537. changed();
  538. }
  539. CSelector IBonusBearer::anaffectedByMoraleSelector =
  540. Selector::type()(Bonus::NON_LIVING)
  541. .Or(Selector::type()(Bonus::UNDEAD))
  542. .Or(Selector::type()(Bonus::SIEGE_WEAPON))
  543. .Or(Selector::type()(Bonus::NO_MORALE));
  544. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  545. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  546. IBonusBearer::IBonusBearer()
  547. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  548. moraleValue(this, moraleSelector, 0),
  549. luckValue(this, luckSelector, 0)
  550. {
  551. }
  552. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  553. {
  554. return valOfBonuses(Selector::type()(type).And(selector));
  555. }
  556. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  557. {
  558. //This part is performance-critical
  559. std::string cachingStr = "type_" + std::to_string(static_cast<int>(type)) + "_" + std::to_string(subtype);
  560. CSelector s = Selector::type()(type);
  561. if(subtype != -1)
  562. s = s.And(Selector::subtype()(subtype));
  563. return valOfBonuses(s, cachingStr);
  564. }
  565. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  566. {
  567. CSelector limit = nullptr;
  568. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  569. return hlp->totalValue();
  570. }
  571. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  572. {
  573. //TODO: We don't need to count all bonuses and could break on first matching
  574. return getBonuses(selector, cachingStr)->size() > 0;
  575. }
  576. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  577. {
  578. return getBonuses(selector, limit, cachingStr)->size() > 0;
  579. }
  580. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  581. {
  582. //This part is performance-ciritcal
  583. std::string cachingStr = "type_" + std::to_string(static_cast<int>(type)) + "_" + std::to_string(subtype);
  584. CSelector s = Selector::type()(type);
  585. if(subtype != -1)
  586. s = s.And(Selector::subtype()(subtype));
  587. return hasBonus(s, cachingStr);
  588. }
  589. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  590. {
  591. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  592. }
  593. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  594. {
  595. return getAllBonuses(selector, limit, nullptr, cachingStr);
  596. }
  597. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  598. {
  599. boost::format fmt("source_%did_%d");
  600. fmt % static_cast<int>(source) % sourceID;
  601. return hasBonus(Selector::source(source,sourceID), fmt.str());
  602. }
  603. int IBonusBearer::MoraleVal() const
  604. {
  605. if(anaffectedByMorale.getHasBonus())
  606. return 0;
  607. int ret = moraleValue.getValue();
  608. return vstd::abetween(ret, -3, +3);
  609. }
  610. int IBonusBearer::LuckVal() const
  611. {
  612. if(hasBonusOfType(Bonus::NO_LUCK))
  613. return 0;
  614. int ret = luckValue.getValue();
  615. return vstd::abetween(ret, -3, +3);
  616. }
  617. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  618. {
  619. if(anaffectedByMorale.getHasBonus())
  620. {
  621. if(!bonusList->empty())
  622. bonusList = std::make_shared<const BonusList>();
  623. return 0;
  624. }
  625. int ret = moraleValue.getValueAndList(bonusList);
  626. return vstd::abetween(ret, -3, +3);
  627. }
  628. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  629. {
  630. if(hasBonusOfType(Bonus::NO_LUCK))
  631. {
  632. if(!bonusList->empty())
  633. bonusList = std::make_shared<const BonusList>();
  634. return 0;
  635. }
  636. int ret = luckValue.getValueAndList(bonusList);
  637. return vstd::abetween(ret, -3, +3);
  638. }
  639. ui32 IBonusBearer::MaxHealth() const
  640. {
  641. const std::string cachingStr = "type_STACK_HEALTH";
  642. static const auto selector = Selector::type()(Bonus::STACK_HEALTH);
  643. auto value = valOfBonuses(selector, cachingStr);
  644. return std::max(1, value); //never 0
  645. }
  646. int IBonusBearer::getAttack(bool ranged) const
  647. {
  648. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  649. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  650. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  651. }
  652. int IBonusBearer::getDefense(bool ranged) const
  653. {
  654. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  655. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  656. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  657. }
  658. int IBonusBearer::getMinDamage(bool ranged) const
  659. {
  660. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  661. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  662. return valOfBonuses(selector, cachingStr);
  663. }
  664. int IBonusBearer::getMaxDamage(bool ranged) const
  665. {
  666. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  667. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  668. return valOfBonuses(selector, cachingStr);
  669. }
  670. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  671. {
  672. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  673. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  674. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  675. auto ret = allSkills->valOfBonuses(Selector::subtype()(id));
  676. auto minSkillValue = (id == PrimarySkill::SPELL_POWER || id == PrimarySkill::KNOWLEDGE) ? 1 : 0;
  677. vstd::amax(ret, minSkillValue); //otherwise, some artifacts may cause negative skill value effect
  678. return ret; //sp=0 works in old saves
  679. }
  680. si32 IBonusBearer::magicResistance() const
  681. {
  682. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  683. }
  684. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  685. {
  686. //war machines cannot move
  687. if(hasBonus(Selector::type()(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  688. {
  689. return 0;
  690. }
  691. //bind effect check - doesn't influence stack initiative
  692. if(useBind && hasBonus(Selector::type()(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  693. {
  694. return 0;
  695. }
  696. return valOfBonuses(Selector::type()(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  697. }
  698. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  699. {
  700. static const std::string cachingStr = "IBonusBearer::isLiving";
  701. static const CSelector selector = Selector::type()(Bonus::UNDEAD)
  702. .Or(Selector::type()(Bonus::NON_LIVING))
  703. .Or(Selector::type()(Bonus::GARGOYLE))
  704. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  705. return !hasBonus(selector, cachingStr);
  706. }
  707. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  708. {
  709. auto bonuses = getAllBonuses(selector, Selector::all);
  710. return bonuses->getFirst(Selector::all);
  711. }
  712. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  713. {
  714. switch(node->getNodeType())
  715. {
  716. case CBonusSystemNode::STACK_BATTLE:
  717. return dynamic_cast<const CStack *>(node);
  718. default:
  719. return nullptr;
  720. }
  721. }
  722. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  723. {
  724. switch(node->getNodeType())
  725. {
  726. case CBonusSystemNode::STACK_INSTANCE:
  727. return (dynamic_cast<const CStackInstance *>(node));
  728. case CBonusSystemNode::STACK_BATTLE:
  729. return (dynamic_cast<const CStack *>(node))->base;
  730. default:
  731. return nullptr;
  732. }
  733. }
  734. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  735. {
  736. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  737. }
  738. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  739. {
  740. auto ret = bonuses.getFirst(selector);
  741. if(ret)
  742. return ret;
  743. FOREACH_PARENT(pname)
  744. {
  745. ret = pname->getBonusLocalFirst(selector);
  746. if (ret)
  747. return ret;
  748. }
  749. return nullptr;
  750. }
  751. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  752. {
  753. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  754. }
  755. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  756. {
  757. for(const auto & elem : parents)
  758. {
  759. const CBonusSystemNode *parent = elem;
  760. out.insert(parent);
  761. }
  762. }
  763. void CBonusSystemNode::getParents(TNodes &out)
  764. {
  765. for (auto & elem : parents)
  766. {
  767. const CBonusSystemNode *parent = elem;
  768. out.insert(const_cast<CBonusSystemNode*>(parent));
  769. }
  770. }
  771. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  772. {
  773. for(auto * parent : parents)
  774. {
  775. out.insert(parent);
  776. parent->getAllParents(out);
  777. }
  778. }
  779. void CBonusSystemNode::getAllBonusesRec(BonusList &out, const CSelector & selector) const
  780. {
  781. //out has been reserved sufficient capacity at getAllBonuses() call
  782. BonusList beforeUpdate;
  783. TCNodes lparents;
  784. getAllParents(lparents);
  785. if(!lparents.empty())
  786. {
  787. //estimate on how many bonuses are missing yet - must be positive
  788. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  789. }
  790. else
  791. {
  792. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  793. }
  794. for(const auto * parent : lparents)
  795. {
  796. parent->getAllBonusesRec(beforeUpdate, selector);
  797. }
  798. bonuses.getAllBonuses(beforeUpdate);
  799. for(const auto & b : beforeUpdate)
  800. {
  801. //We should not run updaters on non-selected bonuses
  802. auto updated = selector(b.get()) && b->updater
  803. ? getUpdatedBonus(b, b->updater)
  804. : b;
  805. //do not add bonus with updater
  806. bool bonusExists = false;
  807. for(const auto & bonus : out)
  808. {
  809. if (bonus == updated)
  810. bonusExists = true;
  811. if (bonus->updater && bonus->updater == updated->updater)
  812. bonusExists = true;
  813. }
  814. if (!bonusExists)
  815. out.push_back(updated);
  816. }
  817. }
  818. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  819. {
  820. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  821. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  822. {
  823. // Exclusive access for one thread
  824. boost::lock_guard<boost::mutex> lock(sync);
  825. // If the bonus system tree changes(state of a single node or the relations to each other) then
  826. // cache all bonus objects. Selector objects doesn't matter.
  827. if (cachedLast != treeChanged)
  828. {
  829. BonusList allBonuses;
  830. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  831. cachedBonuses.clear();
  832. cachedRequests.clear();
  833. getAllBonusesRec(allBonuses, Selector::all);
  834. limitBonuses(allBonuses, cachedBonuses);
  835. cachedBonuses.stackBonuses();
  836. cachedLast = treeChanged;
  837. }
  838. // If a bonus system request comes with a caching string then look up in the map if there are any
  839. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  840. if(!cachingStr.empty())
  841. {
  842. auto it = cachedRequests.find(cachingStr);
  843. if(it != cachedRequests.end())
  844. {
  845. //Cached list contains bonuses for our query with applied limiters
  846. return it->second;
  847. }
  848. }
  849. //We still don't have the bonuses (didn't returned them from cache)
  850. //Perform bonus selection
  851. auto ret = std::make_shared<BonusList>();
  852. cachedBonuses.getBonuses(*ret, selector, limit);
  853. // Save the results in the cache
  854. if(!cachingStr.empty())
  855. cachedRequests[cachingStr] = ret;
  856. return ret;
  857. }
  858. else
  859. {
  860. return getAllBonusesWithoutCaching(selector, limit, root);
  861. }
  862. }
  863. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  864. {
  865. auto ret = std::make_shared<BonusList>();
  866. // Get bonus results without caching enabled.
  867. BonusList beforeLimiting;
  868. BonusList afterLimiting;
  869. getAllBonusesRec(beforeLimiting, selector);
  870. if(!root || root == this)
  871. {
  872. limitBonuses(beforeLimiting, afterLimiting);
  873. }
  874. else if(root)
  875. {
  876. //We want to limit our query against an external node. We get all its bonuses,
  877. // add the ones we're considering and see if they're cut out by limiters
  878. BonusList rootBonuses;
  879. BonusList limitedRootBonuses;
  880. getAllBonusesRec(rootBonuses, selector);
  881. for(const auto & b : beforeLimiting)
  882. rootBonuses.push_back(b);
  883. root->limitBonuses(rootBonuses, limitedRootBonuses);
  884. for(const auto & b : beforeLimiting)
  885. if(vstd::contains(limitedRootBonuses, b))
  886. afterLimiting.push_back(b);
  887. }
  888. afterLimiting.getBonuses(*ret, selector, limit);
  889. ret->stackBonuses();
  890. return ret;
  891. }
  892. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr & updater) const
  893. {
  894. assert(updater);
  895. return updater->createUpdatedBonus(b, * this);
  896. }
  897. CBonusSystemNode::CBonusSystemNode()
  898. :CBonusSystemNode(false)
  899. {
  900. }
  901. CBonusSystemNode::CBonusSystemNode(bool isHypotetic):
  902. bonuses(true),
  903. exportedBonuses(true),
  904. nodeType(UNKNOWN),
  905. cachedLast(0),
  906. isHypotheticNode(isHypotetic)
  907. {
  908. }
  909. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType):
  910. bonuses(true),
  911. exportedBonuses(true),
  912. nodeType(NodeType),
  913. cachedLast(0),
  914. isHypotheticNode(false)
  915. {
  916. }
  917. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other) noexcept:
  918. bonuses(std::move(other.bonuses)),
  919. exportedBonuses(std::move(other.exportedBonuses)),
  920. nodeType(other.nodeType),
  921. description(other.description),
  922. cachedLast(0),
  923. isHypotheticNode(other.isHypotheticNode)
  924. {
  925. std::swap(parents, other.parents);
  926. std::swap(children, other.children);
  927. //fixing bonus tree without recalculation
  928. if(!isHypothetic())
  929. {
  930. for(CBonusSystemNode * n : parents)
  931. {
  932. n->children -= &other;
  933. n->children.push_back(this);
  934. }
  935. }
  936. for(CBonusSystemNode * n : children)
  937. {
  938. n->parents -= &other;
  939. n->parents.push_back(this);
  940. }
  941. //cache ignored
  942. //cachedBonuses
  943. //cachedRequests
  944. }
  945. CBonusSystemNode::~CBonusSystemNode()
  946. {
  947. detachFromAll();
  948. if(!children.empty())
  949. {
  950. while(!children.empty())
  951. children.front()->detachFrom(*this);
  952. }
  953. }
  954. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  955. {
  956. assert(!vstd::contains(parents, &parent));
  957. parents.push_back(&parent);
  958. if(!isHypothetic())
  959. {
  960. if(parent.actsAsBonusSourceOnly())
  961. parent.newRedDescendant(*this);
  962. else
  963. newRedDescendant(parent);
  964. parent.newChildAttached(*this);
  965. }
  966. CBonusSystemNode::treeHasChanged();
  967. }
  968. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  969. {
  970. assert(vstd::contains(parents, &parent));
  971. if(!isHypothetic())
  972. {
  973. if(parent.actsAsBonusSourceOnly())
  974. parent.removedRedDescendant(*this);
  975. else
  976. removedRedDescendant(parent);
  977. }
  978. if (vstd::contains(parents, &parent))
  979. {
  980. parents -= &parent;
  981. }
  982. else
  983. {
  984. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  985. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  986. }
  987. if(!isHypothetic())
  988. {
  989. parent.childDetached(*this);
  990. }
  991. CBonusSystemNode::treeHasChanged();
  992. }
  993. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  994. {
  995. removeBonuses(s);
  996. for(CBonusSystemNode * child : children)
  997. child->removeBonusesRecursive(s);
  998. }
  999. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  1000. {
  1001. BonusList bl;
  1002. exportedBonuses.getBonuses(bl, s, Selector::all);
  1003. for(const auto & b : bl)
  1004. {
  1005. b->turnsRemain--;
  1006. if(b->turnsRemain <= 0)
  1007. removeBonus(b);
  1008. }
  1009. for(CBonusSystemNode *child : children)
  1010. child->reduceBonusDurations(s);
  1011. }
  1012. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  1013. {
  1014. //turnsRemain shouldn't be zero for following durations
  1015. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  1016. {
  1017. assert(b->turnsRemain);
  1018. }
  1019. assert(!vstd::contains(exportedBonuses, b));
  1020. exportedBonuses.push_back(b);
  1021. exportBonus(b);
  1022. CBonusSystemNode::treeHasChanged();
  1023. }
  1024. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  1025. {
  1026. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  1027. if(bonus)
  1028. bonus->val += b->val;
  1029. else
  1030. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  1031. }
  1032. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  1033. {
  1034. exportedBonuses -= b;
  1035. if(b->propagator)
  1036. unpropagateBonus(b);
  1037. else
  1038. bonuses -= b;
  1039. CBonusSystemNode::treeHasChanged();
  1040. }
  1041. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  1042. {
  1043. BonusList toRemove;
  1044. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  1045. for(const auto & bonus : toRemove)
  1046. removeBonus(bonus);
  1047. }
  1048. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  1049. {
  1050. switch(nodeType)
  1051. {
  1052. case CREATURE:
  1053. case ARTIFACT:
  1054. case ARTIFACT_INSTANCE:
  1055. return true;
  1056. default:
  1057. return false;
  1058. }
  1059. }
  1060. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  1061. {
  1062. if(b->propagator->shouldBeAttached(this))
  1063. {
  1064. auto propagated = b->propagationUpdater
  1065. ? source.getUpdatedBonus(b, b->propagationUpdater)
  1066. : b;
  1067. bonuses.push_back(propagated);
  1068. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  1069. }
  1070. FOREACH_RED_CHILD(child)
  1071. child->propagateBonus(b, source);
  1072. }
  1073. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  1074. {
  1075. if(b->propagator->shouldBeAttached(this))
  1076. {
  1077. bonuses -= b;
  1078. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  1079. }
  1080. FOREACH_RED_CHILD(child)
  1081. child->unpropagateBonus(b);
  1082. }
  1083. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  1084. {
  1085. assert(!vstd::contains(children, &child));
  1086. children.push_back(&child);
  1087. }
  1088. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  1089. {
  1090. if(vstd::contains(children, &child))
  1091. children -= &child;
  1092. else
  1093. {
  1094. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  1095. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  1096. }
  1097. }
  1098. void CBonusSystemNode::detachFromAll()
  1099. {
  1100. while(!parents.empty())
  1101. detachFrom(*parents.front());
  1102. }
  1103. bool CBonusSystemNode::isIndependentNode() const
  1104. {
  1105. return parents.empty() && children.empty();
  1106. }
  1107. std::string CBonusSystemNode::nodeName() const
  1108. {
  1109. return !description.empty()
  1110. ? description
  1111. : std::string("Bonus system node of type ") + typeid(*this).name();
  1112. }
  1113. std::string CBonusSystemNode::nodeShortInfo() const
  1114. {
  1115. std::ostringstream str;
  1116. str << "'" << typeid(* this).name() << "'";
  1117. description.length() > 0
  1118. ? str << " (" << description << ")"
  1119. : str << " (no description)";
  1120. return str.str();
  1121. }
  1122. void CBonusSystemNode::deserializationFix()
  1123. {
  1124. exportBonuses();
  1125. }
  1126. void CBonusSystemNode::getRedParents(TNodes & out)
  1127. {
  1128. FOREACH_PARENT(pname)
  1129. {
  1130. if(pname->actsAsBonusSourceOnly())
  1131. {
  1132. out.insert(pname);
  1133. }
  1134. }
  1135. if(!actsAsBonusSourceOnly())
  1136. {
  1137. for(CBonusSystemNode *child : children)
  1138. {
  1139. out.insert(child);
  1140. }
  1141. }
  1142. }
  1143. void CBonusSystemNode::getRedChildren(TNodes &out)
  1144. {
  1145. FOREACH_PARENT(pname)
  1146. {
  1147. if(!pname->actsAsBonusSourceOnly())
  1148. {
  1149. out.insert(pname);
  1150. }
  1151. }
  1152. if(actsAsBonusSourceOnly())
  1153. {
  1154. for(CBonusSystemNode *child : children)
  1155. {
  1156. out.insert(child);
  1157. }
  1158. }
  1159. }
  1160. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  1161. {
  1162. for(const auto & b : exportedBonuses)
  1163. {
  1164. if(b->propagator)
  1165. descendant.propagateBonus(b, *this);
  1166. }
  1167. TNodes redParents;
  1168. getRedAncestors(redParents); //get all red parents recursively
  1169. for(auto * parent : redParents)
  1170. {
  1171. for(const auto & b : parent->exportedBonuses)
  1172. {
  1173. if(b->propagator)
  1174. descendant.propagateBonus(b, *this);
  1175. }
  1176. }
  1177. }
  1178. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  1179. {
  1180. for(const auto & b : exportedBonuses)
  1181. if(b->propagator)
  1182. descendant.unpropagateBonus(b);
  1183. TNodes redParents;
  1184. getRedAncestors(redParents); //get all red parents recursively
  1185. for(auto * parent : redParents)
  1186. {
  1187. for(const auto & b : parent->exportedBonuses)
  1188. if(b->propagator)
  1189. descendant.unpropagateBonus(b);
  1190. }
  1191. }
  1192. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1193. {
  1194. getRedParents(out);
  1195. TNodes redParents;
  1196. getRedParents(redParents);
  1197. for(CBonusSystemNode * parent : redParents)
  1198. parent->getRedAncestors(out);
  1199. }
  1200. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  1201. {
  1202. if(b->propagator)
  1203. propagateBonus(b, *this);
  1204. else
  1205. bonuses.push_back(b);
  1206. CBonusSystemNode::treeHasChanged();
  1207. }
  1208. void CBonusSystemNode::exportBonuses()
  1209. {
  1210. for(const auto & b : exportedBonuses)
  1211. exportBonus(b);
  1212. }
  1213. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1214. {
  1215. return nodeType;
  1216. }
  1217. const BonusList& CBonusSystemNode::getBonusList() const
  1218. {
  1219. return bonuses;
  1220. }
  1221. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1222. {
  1223. return parents;
  1224. }
  1225. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1226. {
  1227. return children;
  1228. }
  1229. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1230. {
  1231. nodeType = type;
  1232. }
  1233. BonusList & CBonusSystemNode::getExportedBonusList()
  1234. {
  1235. return exportedBonuses;
  1236. }
  1237. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1238. {
  1239. return exportedBonuses;
  1240. }
  1241. const std::string& CBonusSystemNode::getDescription() const
  1242. {
  1243. return description;
  1244. }
  1245. void CBonusSystemNode::setDescription(const std::string &description)
  1246. {
  1247. this->description = description;
  1248. }
  1249. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1250. {
  1251. assert(&allBonuses != &out); //todo should it work in-place?
  1252. BonusList undecided = allBonuses;
  1253. BonusList & accepted = out;
  1254. while(true)
  1255. {
  1256. int undecidedCount = static_cast<int>(undecided.size());
  1257. for(int i = 0; i < undecided.size(); i++)
  1258. {
  1259. auto b = undecided[i];
  1260. BonusLimitationContext context = {b, *this, out, undecided};
  1261. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  1262. if(decision == ILimiter::EDecision::DISCARD)
  1263. {
  1264. undecided.erase(i);
  1265. i--; continue;
  1266. }
  1267. else if(decision == ILimiter::EDecision::ACCEPT)
  1268. {
  1269. accepted.push_back(b);
  1270. undecided.erase(i);
  1271. i--; continue;
  1272. }
  1273. else
  1274. assert(decision == ILimiter::EDecision::NOT_SURE);
  1275. }
  1276. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1277. return;
  1278. }
  1279. }
  1280. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1281. {
  1282. auto ret = std::make_shared<BonusList>();
  1283. limitBonuses(allBonuses, *ret);
  1284. return ret;
  1285. }
  1286. void CBonusSystemNode::treeHasChanged()
  1287. {
  1288. treeChanged++;
  1289. }
  1290. int64_t CBonusSystemNode::getTreeVersion() const
  1291. {
  1292. return treeChanged;
  1293. }
  1294. std::string Bonus::Description(boost::optional<si32> customValue) const
  1295. {
  1296. std::ostringstream str;
  1297. if(description.empty())
  1298. {
  1299. if(stacking.empty() || stacking == "ALWAYS")
  1300. {
  1301. switch(source)
  1302. {
  1303. case ARTIFACT:
  1304. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getNameTranslated();
  1305. break;
  1306. case SPELL_EFFECT:
  1307. str << SpellID(sid).toSpell(VLC->spells())->getNameTranslated();
  1308. break;
  1309. case CREATURE_ABILITY:
  1310. str << VLC->creh->objects[sid]->getNamePluralTranslated();
  1311. break;
  1312. case SECONDARY_SKILL:
  1313. str << VLC->skillh->getByIndex(sid)->getNameTranslated();
  1314. break;
  1315. case HERO_SPECIAL:
  1316. str << VLC->heroh->objects[sid]->getNameTranslated();
  1317. break;
  1318. default:
  1319. //todo: handle all possible sources
  1320. str << "Unknown";
  1321. break;
  1322. }
  1323. }
  1324. else
  1325. str << stacking;
  1326. }
  1327. else
  1328. {
  1329. str << description;
  1330. }
  1331. if(auto value = customValue.value_or(val))
  1332. str << " " << std::showpos << value;
  1333. return str.str();
  1334. }
  1335. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1336. {
  1337. switch(type)
  1338. {
  1339. case Bonus::PRIMARY_SKILL:
  1340. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1341. case Bonus::SPECIAL_SPELL_LEV:
  1342. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1343. case Bonus::SPELL:
  1344. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1345. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1346. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1347. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1348. case Bonus::IMPROVED_NECROMANCY:
  1349. case Bonus::SPECIAL_UPGRADE:
  1350. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1351. case Bonus::GENERATE_RESOURCE:
  1352. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1353. default:
  1354. return JsonUtils::intNode(subtype);
  1355. }
  1356. }
  1357. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1358. {
  1359. switch(type)
  1360. {
  1361. case Bonus::SPECIAL_UPGRADE:
  1362. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1363. default:
  1364. return addInfo.toJsonNode();
  1365. }
  1366. }
  1367. JsonNode durationToJson(ui16 duration)
  1368. {
  1369. std::vector<std::string> durationNames;
  1370. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1371. {
  1372. if(duration & durBit)
  1373. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1374. }
  1375. if(durationNames.size() == 1)
  1376. {
  1377. return JsonUtils::stringNode(durationNames[0]);
  1378. }
  1379. else
  1380. {
  1381. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1382. for(const std::string & dur : durationNames)
  1383. node.Vector().push_back(JsonUtils::stringNode(dur));
  1384. return node;
  1385. }
  1386. }
  1387. JsonNode Bonus::toJsonNode() const
  1388. {
  1389. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1390. // only add values that might reasonably be found in config files
  1391. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1392. if(subtype != -1)
  1393. root["subtype"] = subtypeToJson(type, subtype);
  1394. if(additionalInfo != CAddInfo::NONE)
  1395. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1396. if(duration != 0)
  1397. {
  1398. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1399. for(const auto & kv : bonusDurationMap)
  1400. {
  1401. if(duration & kv.second)
  1402. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1403. }
  1404. root["duration"] = durationVec;
  1405. }
  1406. if(turnsRemain != 0)
  1407. root["turns"].Integer() = turnsRemain;
  1408. if(source != OTHER)
  1409. root["sourceType"].String() = vstd::findKey(bonusSourceMap, source);
  1410. if(targetSourceType != OTHER)
  1411. root["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetSourceType);
  1412. if(sid != 0)
  1413. root["sourceID"].Integer() = sid;
  1414. if(val != 0)
  1415. root["val"].Integer() = val;
  1416. if(valType != ADDITIVE_VALUE)
  1417. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1418. if(!stacking.empty())
  1419. root["stacking"].String() = stacking;
  1420. if(!description.empty())
  1421. root["description"].String() = description;
  1422. if(effectRange != NO_LIMIT)
  1423. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1424. if(duration != PERMANENT)
  1425. root["duration"] = durationToJson(duration);
  1426. if(turnsRemain)
  1427. root["turns"].Integer() = turnsRemain;
  1428. if(limiter)
  1429. root["limiters"] = limiter->toJsonNode();
  1430. if(updater)
  1431. root["updater"] = updater->toJsonNode();
  1432. if(propagator)
  1433. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1434. return root;
  1435. }
  1436. std::string Bonus::nameForBonus() const
  1437. {
  1438. switch(type)
  1439. {
  1440. case Bonus::PRIMARY_SKILL:
  1441. return PrimarySkill::names[subtype];
  1442. case Bonus::SPECIAL_SPELL_LEV:
  1443. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1444. case Bonus::SPELL:
  1445. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1446. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1447. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1448. return VLC->spells()->getByIndex(subtype)->getJsonKey();
  1449. case Bonus::SPECIAL_UPGRADE:
  1450. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1451. case Bonus::GENERATE_RESOURCE:
  1452. return GameConstants::RESOURCE_NAMES[subtype];
  1453. case Bonus::STACKS_SPEED:
  1454. return "speed";
  1455. default:
  1456. return vstd::findKey(bonusNameMap, type);
  1457. }
  1458. }
  1459. BonusParams::BonusParams(std::string deprecatedTypeStr, std::string deprecatedSubtypeStr, int deprecatedSubtype):
  1460. isConverted(true)
  1461. {
  1462. if(deprecatedTypeStr == "SECONDARY_SKILL_PREMY" || deprecatedTypeStr == "SPECIAL_SECONDARY_SKILL")
  1463. {
  1464. if(deprecatedSubtype == SecondarySkill::PATHFINDING || deprecatedSubtypeStr == "skill.pathfinding")
  1465. type = Bonus::ROUGH_TERRAIN_DISCOUNT;
  1466. else if(deprecatedSubtype == SecondarySkill::DIPLOMACY || deprecatedSubtypeStr == "skill.diplomacy")
  1467. type = Bonus::WANDERING_CREATURES_JOIN_BONUS;
  1468. else if(deprecatedSubtype == SecondarySkill::WISDOM || deprecatedSubtypeStr == "skill.wisdom")
  1469. type = Bonus::MAX_LEARNABLE_SPELL_LEVEL;
  1470. else if(deprecatedSubtype == SecondarySkill::MYSTICISM || deprecatedSubtypeStr == "skill.mysticism")
  1471. type = Bonus::MANA_REGENERATION;
  1472. else if(deprecatedSubtype == SecondarySkill::NECROMANCY || deprecatedSubtypeStr == "skill.necromancy")
  1473. type = Bonus::UNDEAD_RAISE_PERCENTAGE;
  1474. else if(deprecatedSubtype == SecondarySkill::LEARNING || deprecatedSubtypeStr == "skill.learning")
  1475. type = Bonus::HERO_EXPERIENCE_GAIN_PERCENT;
  1476. else if(deprecatedSubtype == SecondarySkill::RESISTANCE || deprecatedSubtypeStr == "skill.resistance")
  1477. type = Bonus::MAGIC_RESISTANCE;
  1478. else if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1479. type = Bonus::LEARN_BATTLE_SPELL_CHANCE;
  1480. else if(deprecatedSubtype == SecondarySkill::SCOUTING || deprecatedSubtypeStr == "skill.scouting")
  1481. type = Bonus::SIGHT_RADIUS;
  1482. else if(deprecatedSubtype == SecondarySkill::INTELLIGENCE || deprecatedSubtypeStr == "skill.intelligence")
  1483. {
  1484. type = Bonus::MANA_PER_KNOWLEDGE;
  1485. valueType = Bonus::PERCENT_TO_BASE;
  1486. valueTypeRelevant = true;
  1487. }
  1488. else if(deprecatedSubtype == SecondarySkill::SORCERY || deprecatedSubtypeStr == "skill.sorcery")
  1489. type = Bonus::SPELL_DAMAGE;
  1490. else if(deprecatedSubtype == SecondarySkill::SCHOLAR || deprecatedSubtypeStr == "skill.scholar")
  1491. type = Bonus::LEARN_MEETING_SPELL_LIMIT;
  1492. else if(deprecatedSubtype == SecondarySkill::ARCHERY|| deprecatedSubtypeStr == "skill.archery")
  1493. {
  1494. subtype = 1;
  1495. subtypeRelevant = true;
  1496. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1497. }
  1498. else if(deprecatedSubtype == SecondarySkill::OFFENCE || deprecatedSubtypeStr == "skill.offence")
  1499. {
  1500. subtype = 0;
  1501. subtypeRelevant = true;
  1502. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1503. }
  1504. else if(deprecatedSubtype == SecondarySkill::ARMORER || deprecatedSubtypeStr == "skill.armorer")
  1505. {
  1506. subtype = -1;
  1507. subtypeRelevant = true;
  1508. type = Bonus::GENERAL_DAMAGE_REDUCTION;
  1509. }
  1510. else if(deprecatedSubtype == SecondarySkill::NAVIGATION || deprecatedSubtypeStr == "skill.navigation")
  1511. {
  1512. subtype = 0;
  1513. subtypeRelevant = true;
  1514. valueType = Bonus::PERCENT_TO_BASE;
  1515. valueTypeRelevant = true;
  1516. type = Bonus::MOVEMENT;
  1517. }
  1518. else if(deprecatedSubtype == SecondarySkill::LOGISTICS || deprecatedSubtypeStr == "skill.logistics")
  1519. {
  1520. subtype = 0;
  1521. subtypeRelevant = true;
  1522. valueType = Bonus::PERCENT_TO_BASE;
  1523. valueTypeRelevant = true;
  1524. type = Bonus::MOVEMENT;
  1525. }
  1526. else if(deprecatedSubtype == SecondarySkill::ESTATES || deprecatedSubtypeStr == "skill.estates")
  1527. {
  1528. type = Bonus::GENERATE_RESOURCE;
  1529. subtype = GameResID(EGameResID::GOLD);
  1530. subtypeRelevant = true;
  1531. }
  1532. else if(deprecatedSubtype == SecondarySkill::AIR_MAGIC || deprecatedSubtypeStr == "skill.airMagic")
  1533. {
  1534. type = Bonus::MAGIC_SCHOOL_SKILL;
  1535. subtypeRelevant = true;
  1536. subtype = 4;
  1537. }
  1538. else if(deprecatedSubtype == SecondarySkill::WATER_MAGIC || deprecatedSubtypeStr == "skill.waterMagic")
  1539. {
  1540. type = Bonus::MAGIC_SCHOOL_SKILL;
  1541. subtypeRelevant = true;
  1542. subtype = 1;
  1543. }
  1544. else if(deprecatedSubtype == SecondarySkill::FIRE_MAGIC || deprecatedSubtypeStr == "skill.fireMagic")
  1545. {
  1546. type = Bonus::MAGIC_SCHOOL_SKILL;
  1547. subtypeRelevant = true;
  1548. subtype = 2;
  1549. }
  1550. else if(deprecatedSubtype == SecondarySkill::EARTH_MAGIC || deprecatedSubtypeStr == "skill.earthMagic")
  1551. {
  1552. type = Bonus::MAGIC_SCHOOL_SKILL;
  1553. subtypeRelevant = true;
  1554. subtype = 8;
  1555. }
  1556. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1557. {
  1558. type = Bonus::BONUS_DAMAGE_CHANCE;
  1559. subtypeRelevant = true;
  1560. subtypeStr = "core:creature.ballista";
  1561. }
  1562. else if (deprecatedSubtype == SecondarySkill::FIRST_AID || deprecatedSubtypeStr == "skill.firstAid")
  1563. {
  1564. type = Bonus::SPECIFIC_SPELL_POWER;
  1565. subtypeRelevant = true;
  1566. subtypeStr = "core:spell.firstAid";
  1567. }
  1568. else if (deprecatedSubtype == SecondarySkill::BALLISTICS || deprecatedSubtypeStr == "skill.ballistics")
  1569. {
  1570. type = Bonus::CATAPULT_EXTRA_SHOTS;
  1571. subtypeRelevant = true;
  1572. subtypeStr = "core:spell.catapultShot";
  1573. }
  1574. else
  1575. isConverted = false;
  1576. }
  1577. else if (deprecatedTypeStr == "SECONDARY_SKILL_VAL2")
  1578. {
  1579. if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1580. type = Bonus::LEARN_BATTLE_SPELL_LEVEL_LIMIT;
  1581. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1582. {
  1583. type = Bonus::HERO_GRANTS_ATTACKS;
  1584. subtypeRelevant = true;
  1585. subtypeStr = "core:creature.ballista";
  1586. }
  1587. else
  1588. isConverted = false;
  1589. }
  1590. else if (deprecatedTypeStr == "SEA_MOVEMENT")
  1591. {
  1592. subtype = 0;
  1593. subtypeRelevant = true;
  1594. valueType = Bonus::ADDITIVE_VALUE;
  1595. valueTypeRelevant = true;
  1596. type = Bonus::MOVEMENT;
  1597. }
  1598. else if (deprecatedTypeStr == "LAND_MOVEMENT")
  1599. {
  1600. subtype = 1;
  1601. subtypeRelevant = true;
  1602. valueType = Bonus::ADDITIVE_VALUE;
  1603. valueTypeRelevant = true;
  1604. type = Bonus::MOVEMENT;
  1605. }
  1606. else if (deprecatedTypeStr == "MAXED_SPELL")
  1607. {
  1608. type = Bonus::SPELL;
  1609. subtypeStr = deprecatedSubtypeStr;
  1610. subtypeRelevant = true;
  1611. valueType = Bonus::INDEPENDENT_MAX;
  1612. valueTypeRelevant = true;
  1613. val = 3;
  1614. valRelevant = true;
  1615. }
  1616. else if (deprecatedTypeStr == "FULL_HP_REGENERATION")
  1617. {
  1618. type = Bonus::HP_REGENERATION;
  1619. val = 100000; //very high value to always chose stack health
  1620. valRelevant = true;
  1621. }
  1622. else if (deprecatedTypeStr == "KING1")
  1623. {
  1624. type = Bonus::KING;
  1625. val = 0;
  1626. valRelevant = true;
  1627. }
  1628. else if (deprecatedTypeStr == "KING2")
  1629. {
  1630. type = Bonus::KING;
  1631. val = 2;
  1632. valRelevant = true;
  1633. }
  1634. else if (deprecatedTypeStr == "KING3")
  1635. {
  1636. type = Bonus::KING;
  1637. val = 3;
  1638. valRelevant = true;
  1639. }
  1640. else if (deprecatedTypeStr == "SIGHT_RADIOUS")
  1641. type = Bonus::SIGHT_RADIUS;
  1642. else if (deprecatedTypeStr == "SELF_MORALE")
  1643. {
  1644. type = Bonus::MORALE;
  1645. val = 1;
  1646. valRelevant = true;
  1647. valueType = Bonus::INDEPENDENT_MAX;
  1648. valueTypeRelevant = true;
  1649. }
  1650. else if (deprecatedTypeStr == "SELF_LUCK")
  1651. {
  1652. type = Bonus::LUCK;
  1653. val = 1;
  1654. valRelevant = true;
  1655. valueType = Bonus::INDEPENDENT_MAX;
  1656. valueTypeRelevant = true;
  1657. }
  1658. else
  1659. isConverted = false;
  1660. }
  1661. const JsonNode & BonusParams::toJson()
  1662. {
  1663. assert(isConverted);
  1664. if(ret.isNull())
  1665. {
  1666. ret["type"].String() = vstd::findKey(bonusNameMap, type);
  1667. if(subtypeRelevant && !subtypeStr.empty())
  1668. ret["subtype"].String() = subtypeStr;
  1669. else if(subtypeRelevant)
  1670. ret["subtype"].Integer() = subtype;
  1671. if(valueTypeRelevant)
  1672. ret["valueType"].String() = vstd::findKey(bonusValueMap, valueType);
  1673. if(valRelevant)
  1674. ret["val"].Float() = val;
  1675. if(targetTypeRelevant)
  1676. ret["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetType);
  1677. jsonCreated = true;
  1678. }
  1679. return ret;
  1680. };
  1681. CSelector BonusParams::toSelector()
  1682. {
  1683. assert(isConverted);
  1684. if(subtypeRelevant && !subtypeStr.empty())
  1685. JsonUtils::resolveIdentifier(subtype, toJson(), "subtype");
  1686. auto ret = Selector::type()(type);
  1687. if(subtypeRelevant)
  1688. ret = ret.And(Selector::subtype()(subtype));
  1689. if(valueTypeRelevant)
  1690. ret = ret.And(Selector::valueType(valueType));
  1691. if(targetTypeRelevant)
  1692. ret = ret.And(Selector::targetSourceType()(targetType));
  1693. return ret;
  1694. }
  1695. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype):
  1696. duration(static_cast<ui16>(Duration)),
  1697. type(Type),
  1698. subtype(Subtype),
  1699. source(Src),
  1700. val(Val),
  1701. sid(ID),
  1702. description(std::move(Desc))
  1703. {
  1704. boost::algorithm::trim(description);
  1705. targetSourceType = OTHER;
  1706. }
  1707. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType):
  1708. duration(static_cast<ui16>(Duration)),
  1709. type(Type),
  1710. subtype(Subtype),
  1711. source(Src),
  1712. val(Val),
  1713. sid(ID),
  1714. valType(ValType)
  1715. {
  1716. turnsRemain = 0;
  1717. effectRange = NO_LIMIT;
  1718. targetSourceType = OTHER;
  1719. }
  1720. std::shared_ptr<Bonus> Bonus::addPropagator(const TPropagatorPtr & Propagator)
  1721. {
  1722. propagator = Propagator;
  1723. return this->shared_from_this();
  1724. }
  1725. namespace Selector
  1726. {
  1727. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1728. {
  1729. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1730. return stype;
  1731. }
  1732. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1733. {
  1734. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1735. return ssubtype;
  1736. }
  1737. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1738. {
  1739. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1740. return sinfo;
  1741. }
  1742. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1743. {
  1744. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1745. return ssourceType;
  1746. }
  1747. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1748. {
  1749. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1750. return ssourceType;
  1751. }
  1752. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1753. {
  1754. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1755. return seffectRange;
  1756. }
  1757. DLL_LINKAGE CWillLastTurns turns;
  1758. DLL_LINKAGE CWillLastDays days;
  1759. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1760. {
  1761. return type()(Type).And(subtype()(Subtype));
  1762. }
  1763. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, const CAddInfo & info)
  1764. {
  1765. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1766. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1767. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1768. }
  1769. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1770. {
  1771. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1772. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1773. }
  1774. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1775. {
  1776. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1777. }
  1778. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1779. {
  1780. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1781. }
  1782. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1783. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1784. }
  1785. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1786. {
  1787. switch(node->getNodeType())
  1788. {
  1789. case CBonusSystemNode::CREATURE:
  1790. return (dynamic_cast<const CCreature *>(node));
  1791. case CBonusSystemNode::STACK_BATTLE:
  1792. return (dynamic_cast<const CStack *>(node))->type;
  1793. default:
  1794. const CStackInstance * csi = retrieveStackInstance(node);
  1795. if(csi)
  1796. return csi->type;
  1797. return nullptr;
  1798. }
  1799. }
  1800. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1801. {
  1802. for (ui32 i = 0; i < bonusList.size(); i++)
  1803. {
  1804. const auto & b = bonusList[i];
  1805. out << "Bonus " << i << "\n" << *b << std::endl;
  1806. }
  1807. return out;
  1808. }
  1809. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1810. {
  1811. for(const auto & i : bonusNameMap)
  1812. if(i.second == bonus.type)
  1813. out << "\tType: " << i.first << " \t";
  1814. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1815. printField(val);
  1816. printField(subtype);
  1817. printField(duration);
  1818. printField(source);
  1819. printField(sid);
  1820. if(bonus.additionalInfo != CAddInfo::NONE)
  1821. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1822. printField(turnsRemain);
  1823. printField(valType);
  1824. if(!bonus.stacking.empty())
  1825. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1826. printField(effectRange);
  1827. #undef printField
  1828. if(bonus.limiter)
  1829. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1830. if(bonus.updater)
  1831. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1832. return out;
  1833. }
  1834. std::shared_ptr<Bonus> Bonus::addLimiter(const TLimiterPtr & Limiter)
  1835. {
  1836. if (limiter)
  1837. {
  1838. //If we already have limiter list, retrieve it
  1839. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1840. if(!limiterList)
  1841. {
  1842. //Create a new limiter list with old limiter and the new one will be pushed later
  1843. limiterList = std::make_shared<AllOfLimiter>();
  1844. limiterList->add(limiter);
  1845. limiter = limiterList;
  1846. }
  1847. limiterList->add(Limiter);
  1848. }
  1849. else
  1850. {
  1851. limiter = Limiter;
  1852. }
  1853. return this->shared_from_this();
  1854. }
  1855. ILimiter::EDecision ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1856. {
  1857. return ILimiter::EDecision::ACCEPT;
  1858. }
  1859. std::string ILimiter::toString() const
  1860. {
  1861. return typeid(*this).name();
  1862. }
  1863. JsonNode ILimiter::toJsonNode() const
  1864. {
  1865. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1866. root["type"].String() = toString();
  1867. return root;
  1868. }
  1869. ILimiter::EDecision CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1870. {
  1871. const CCreature *c = retrieveCreature(&context.node);
  1872. if(!c)
  1873. return ILimiter::EDecision::DISCARD;
  1874. auto accept = c->getId() == creature->getId() || (includeUpgrades && creature->isMyUpgrade(c));
  1875. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  1876. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1877. }
  1878. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1879. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1880. {
  1881. }
  1882. void CCreatureTypeLimiter::setCreature(const CreatureID & id)
  1883. {
  1884. creature = VLC->creh->objects[id];
  1885. }
  1886. std::string CCreatureTypeLimiter::toString() const
  1887. {
  1888. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1889. fmt % creature->getJsonKey() % (includeUpgrades ? "true" : "false");
  1890. return fmt.str();
  1891. }
  1892. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1893. {
  1894. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1895. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1896. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->getJsonKey()));
  1897. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1898. return root;
  1899. }
  1900. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1901. : type(bonus), subtype(0), isSubtypeRelevant(false), isSourceRelevant(false), isSourceIDRelevant(false)
  1902. {
  1903. }
  1904. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1905. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), isSourceRelevant(false), isSourceIDRelevant(false)
  1906. {
  1907. }
  1908. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, Bonus::BonusSource src)
  1909. : type(bonus), source(src), isSubtypeRelevant(false), isSourceRelevant(true), isSourceIDRelevant(false)
  1910. {
  1911. }
  1912. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype, Bonus::BonusSource src)
  1913. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), source(src), isSourceRelevant(true), isSourceIDRelevant(false)
  1914. {
  1915. }
  1916. ILimiter::EDecision HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1917. {
  1918. //TODO: proper selector config with parsing of JSON
  1919. auto mySelector = Selector::type()(type);
  1920. if(isSubtypeRelevant)
  1921. mySelector = mySelector.And(Selector::subtype()(subtype));
  1922. if(isSourceRelevant && isSourceIDRelevant)
  1923. mySelector = mySelector.And(Selector::source(source, sid));
  1924. else if (isSourceRelevant)
  1925. mySelector = mySelector.And(Selector::sourceTypeSel(source));
  1926. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1927. if(context.alreadyAccepted.getFirst(mySelector))
  1928. return ILimiter::EDecision::ACCEPT;
  1929. //if there are no matching bonuses pending, we can (and must) reject right away
  1930. if(!context.stillUndecided.getFirst(mySelector))
  1931. return ILimiter::EDecision::DISCARD;
  1932. //do not accept for now but it may change if more bonuses gets included
  1933. return ILimiter::EDecision::NOT_SURE;
  1934. }
  1935. std::string HasAnotherBonusLimiter::toString() const
  1936. {
  1937. std::string typeName = vstd::findKey(bonusNameMap, type);
  1938. if(isSubtypeRelevant)
  1939. {
  1940. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1941. fmt % typeName % subtype;
  1942. return fmt.str();
  1943. }
  1944. else
  1945. {
  1946. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1947. fmt % typeName;
  1948. return fmt.str();
  1949. }
  1950. }
  1951. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1952. {
  1953. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1954. std::string typeName = vstd::findKey(bonusNameMap, type);
  1955. auto sourceTypeName = vstd::findKey(bonusSourceMap, source);
  1956. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1957. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1958. if(isSubtypeRelevant)
  1959. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1960. if(isSourceRelevant)
  1961. root["parameters"].Vector().push_back(JsonUtils::stringNode(sourceTypeName));
  1962. return root;
  1963. }
  1964. ILimiter::EDecision UnitOnHexLimiter::limit(const BonusLimitationContext &context) const
  1965. {
  1966. const auto * stack = retrieveStackBattle(&context.node);
  1967. if(!stack)
  1968. return ILimiter::EDecision::DISCARD;
  1969. auto accept = false;
  1970. for (const auto & hex : stack->getHexes())
  1971. accept |= !!applicableHexes.count(hex);
  1972. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  1973. }
  1974. UnitOnHexLimiter::UnitOnHexLimiter(const std::set<BattleHex> & applicableHexes):
  1975. applicableHexes(applicableHexes)
  1976. {
  1977. }
  1978. JsonNode UnitOnHexLimiter::toJsonNode() const
  1979. {
  1980. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1981. root["type"].String() = "UNIT_ON_HEXES";
  1982. for(const auto & hex : applicableHexes)
  1983. root["parameters"].Vector().push_back(JsonUtils::intNode(hex));
  1984. return root;
  1985. }
  1986. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1987. {
  1988. return false;
  1989. }
  1990. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1991. {
  1992. return CBonusSystemNode::ENodeTypes::NONE;
  1993. }
  1994. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1995. : nodeType(NodeType)
  1996. {
  1997. }
  1998. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1999. {
  2000. return nodeType;
  2001. }
  2002. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  2003. {
  2004. return nodeType == dest->getNodeType();
  2005. }
  2006. CreatureTerrainLimiter::CreatureTerrainLimiter()
  2007. : terrainType(ETerrainId::NATIVE_TERRAIN)
  2008. {
  2009. }
  2010. CreatureTerrainLimiter::CreatureTerrainLimiter(TerrainId terrain):
  2011. terrainType(terrain)
  2012. {
  2013. }
  2014. ILimiter::EDecision CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  2015. {
  2016. const CStack *stack = retrieveStackBattle(&context.node);
  2017. if(stack)
  2018. {
  2019. if (terrainType == ETerrainId::NATIVE_TERRAIN && stack->isOnNativeTerrain())//terrainType not specified = native
  2020. return ILimiter::EDecision::ACCEPT;
  2021. if(terrainType != ETerrainId::NATIVE_TERRAIN && stack->isOnTerrain(terrainType))
  2022. return ILimiter::EDecision::ACCEPT;
  2023. }
  2024. return ILimiter::EDecision::DISCARD;
  2025. //TODO neutral creatues
  2026. }
  2027. std::string CreatureTerrainLimiter::toString() const
  2028. {
  2029. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  2030. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2031. fmt % (terrainType == ETerrainId::NATIVE_TERRAIN ? "native" : terrainName);
  2032. return fmt.str();
  2033. }
  2034. JsonNode CreatureTerrainLimiter::toJsonNode() const
  2035. {
  2036. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2037. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  2038. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2039. root["parameters"].Vector().push_back(JsonUtils::stringNode(terrainName));
  2040. return root;
  2041. }
  2042. FactionLimiter::FactionLimiter(FactionID creatureFaction)
  2043. : faction(creatureFaction)
  2044. {
  2045. }
  2046. ILimiter::EDecision FactionLimiter::limit(const BonusLimitationContext &context) const
  2047. {
  2048. const auto * bearer = dynamic_cast<const INativeTerrainProvider*>(&context.node);
  2049. if(bearer)
  2050. {
  2051. if(faction != FactionID::DEFAULT)
  2052. return bearer->getFaction() == faction ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  2053. switch(context.b->source)
  2054. {
  2055. case Bonus::CREATURE_ABILITY:
  2056. return faction == CreatureID(context.b->sid).toCreature()->getFaction() ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  2057. case Bonus::TOWN_STRUCTURE:
  2058. return faction == FactionID(Bonus::getHighFromSid32(context.b->sid)) ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  2059. //TODO: other sources of bonuses
  2060. }
  2061. }
  2062. return ILimiter::EDecision::DISCARD; //Discard by default
  2063. }
  2064. std::string FactionLimiter::toString() const
  2065. {
  2066. boost::format fmt("FactionLimiter(faction=%s)");
  2067. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  2068. return fmt.str();
  2069. }
  2070. JsonNode FactionLimiter::toJsonNode() const
  2071. {
  2072. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2073. root["type"].String() = "FACTION_LIMITER";
  2074. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  2075. return root;
  2076. }
  2077. CreatureLevelLimiter::CreatureLevelLimiter(uint32_t minLevel, uint32_t maxLevel) :
  2078. minLevel(minLevel),
  2079. maxLevel(maxLevel)
  2080. {
  2081. }
  2082. ILimiter::EDecision CreatureLevelLimiter::limit(const BonusLimitationContext &context) const
  2083. {
  2084. const auto *c = retrieveCreature(&context.node);
  2085. auto accept = c && (c->getLevel() < maxLevel && c->getLevel() >= minLevel);
  2086. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD; //drop bonus for non-creatures or non-native residents
  2087. }
  2088. std::string CreatureLevelLimiter::toString() const
  2089. {
  2090. boost::format fmt("CreatureLevelLimiter(minLevel=%d,maxLevel=%d)");
  2091. fmt % minLevel % maxLevel;
  2092. return fmt.str();
  2093. }
  2094. JsonNode CreatureLevelLimiter::toJsonNode() const
  2095. {
  2096. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2097. root["type"].String() = "CREATURE_LEVEL_LIMITER";
  2098. root["parameters"].Vector().push_back(JsonUtils::intNode(minLevel));
  2099. root["parameters"].Vector().push_back(JsonUtils::intNode(maxLevel));
  2100. return root;
  2101. }
  2102. CreatureAlignmentLimiter::CreatureAlignmentLimiter(EAlignment Alignment)
  2103. : alignment(Alignment)
  2104. {
  2105. }
  2106. ILimiter::EDecision CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  2107. {
  2108. const auto * c = retrieveCreature(&context.node);
  2109. if(c) {
  2110. if(alignment == EAlignment::GOOD && c->isGood())
  2111. return ILimiter::EDecision::ACCEPT;
  2112. if(alignment == EAlignment::EVIL && c->isEvil())
  2113. return ILimiter::EDecision::ACCEPT;
  2114. if(alignment == EAlignment::NEUTRAL && !c->isEvil() && !c->isGood())
  2115. return ILimiter::EDecision::ACCEPT;
  2116. }
  2117. return ILimiter::EDecision::DISCARD;
  2118. }
  2119. std::string CreatureAlignmentLimiter::toString() const
  2120. {
  2121. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  2122. fmt % GameConstants::ALIGNMENT_NAMES[vstd::to_underlying(alignment)];
  2123. return fmt.str();
  2124. }
  2125. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  2126. {
  2127. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2128. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  2129. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::ALIGNMENT_NAMES[vstd::to_underlying(alignment)]));
  2130. return root;
  2131. }
  2132. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  2133. :minRank(Min), maxRank(Max)
  2134. {
  2135. }
  2136. RankRangeLimiter::RankRangeLimiter()
  2137. {
  2138. minRank = maxRank = -1;
  2139. }
  2140. ILimiter::EDecision RankRangeLimiter::limit(const BonusLimitationContext &context) const
  2141. {
  2142. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2143. if(csi)
  2144. {
  2145. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  2146. return ILimiter::EDecision::DISCARD;
  2147. if (csi->getExpRank() > minRank && csi->getExpRank() < maxRank)
  2148. return ILimiter::EDecision::ACCEPT;
  2149. }
  2150. return ILimiter::EDecision::DISCARD;
  2151. }
  2152. OppositeSideLimiter::OppositeSideLimiter(PlayerColor Owner):
  2153. owner(std::move(Owner))
  2154. {
  2155. }
  2156. ILimiter::EDecision OppositeSideLimiter::limit(const BonusLimitationContext & context) const
  2157. {
  2158. auto contextOwner = CBonusSystemNode::retrieveNodeOwner(& context.node);
  2159. auto decision = (owner == contextOwner || owner == PlayerColor::CANNOT_DETERMINE) ? ILimiter::EDecision::DISCARD : ILimiter::EDecision::ACCEPT;
  2160. return decision;
  2161. }
  2162. // Aggregate/Boolean Limiters
  2163. AggregateLimiter::AggregateLimiter(std::vector<TLimiterPtr> limiters):
  2164. limiters(std::move(limiters))
  2165. {
  2166. }
  2167. void AggregateLimiter::add(const TLimiterPtr & limiter)
  2168. {
  2169. if(limiter)
  2170. limiters.push_back(limiter);
  2171. }
  2172. JsonNode AggregateLimiter::toJsonNode() const
  2173. {
  2174. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  2175. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  2176. for(const auto & l : limiters)
  2177. result.Vector().push_back(l->toJsonNode());
  2178. return result;
  2179. }
  2180. const std::string AllOfLimiter::aggregator = "allOf";
  2181. const std::string & AllOfLimiter::getAggregator() const
  2182. {
  2183. return aggregator;
  2184. }
  2185. AllOfLimiter::AllOfLimiter(std::vector<TLimiterPtr> limiters):
  2186. AggregateLimiter(limiters)
  2187. {
  2188. }
  2189. ILimiter::EDecision AllOfLimiter::limit(const BonusLimitationContext & context) const
  2190. {
  2191. bool wasntSure = false;
  2192. for(const auto & limiter : limiters)
  2193. {
  2194. auto result = limiter->limit(context);
  2195. if(result == ILimiter::EDecision::DISCARD)
  2196. return result;
  2197. if(result == ILimiter::EDecision::NOT_SURE)
  2198. wasntSure = true;
  2199. }
  2200. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::ACCEPT;
  2201. }
  2202. const std::string AnyOfLimiter::aggregator = "anyOf";
  2203. const std::string & AnyOfLimiter::getAggregator() const
  2204. {
  2205. return aggregator;
  2206. }
  2207. AnyOfLimiter::AnyOfLimiter(std::vector<TLimiterPtr> limiters):
  2208. AggregateLimiter(limiters)
  2209. {
  2210. }
  2211. ILimiter::EDecision AnyOfLimiter::limit(const BonusLimitationContext & context) const
  2212. {
  2213. bool wasntSure = false;
  2214. for(const auto & limiter : limiters)
  2215. {
  2216. auto result = limiter->limit(context);
  2217. if(result == ILimiter::EDecision::ACCEPT)
  2218. return result;
  2219. if(result == ILimiter::EDecision::NOT_SURE)
  2220. wasntSure = true;
  2221. }
  2222. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::DISCARD;
  2223. }
  2224. const std::string NoneOfLimiter::aggregator = "noneOf";
  2225. const std::string & NoneOfLimiter::getAggregator() const
  2226. {
  2227. return aggregator;
  2228. }
  2229. NoneOfLimiter::NoneOfLimiter(std::vector<TLimiterPtr> limiters):
  2230. AggregateLimiter(limiters)
  2231. {
  2232. }
  2233. ILimiter::EDecision NoneOfLimiter::limit(const BonusLimitationContext & context) const
  2234. {
  2235. bool wasntSure = false;
  2236. for(const auto & limiter : limiters)
  2237. {
  2238. auto result = limiter->limit(context);
  2239. if(result == ILimiter::EDecision::ACCEPT)
  2240. return ILimiter::EDecision::DISCARD;
  2241. if(result == ILimiter::EDecision::NOT_SURE)
  2242. wasntSure = true;
  2243. }
  2244. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::ACCEPT;
  2245. }
  2246. // Updaters
  2247. std::shared_ptr<Bonus> Bonus::addUpdater(const TUpdaterPtr & Updater)
  2248. {
  2249. updater = Updater;
  2250. return this->shared_from_this();
  2251. }
  2252. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2253. {
  2254. return b;
  2255. }
  2256. std::string IUpdater::toString() const
  2257. {
  2258. return typeid(*this).name();
  2259. }
  2260. JsonNode IUpdater::toJsonNode() const
  2261. {
  2262. return JsonNode(JsonNode::JsonType::DATA_NULL);
  2263. }
  2264. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  2265. {
  2266. }
  2267. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2268. {
  2269. if(context.getNodeType() == CBonusSystemNode::HERO)
  2270. {
  2271. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  2272. int steps = stepSize ? level / stepSize : level;
  2273. //rounding follows format for HMM3 creature specialty bonus
  2274. int newVal = (valPer20 * steps + 19) / 20;
  2275. //return copy of bonus with updated val
  2276. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2277. newBonus->val = newVal;
  2278. return newBonus;
  2279. }
  2280. return b;
  2281. }
  2282. std::string GrowsWithLevelUpdater::toString() const
  2283. {
  2284. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  2285. }
  2286. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  2287. {
  2288. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2289. root["type"].String() = "GROWS_WITH_LEVEL";
  2290. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  2291. if(stepSize > 1)
  2292. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  2293. return root;
  2294. }
  2295. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2296. {
  2297. if(context.getNodeType() == CBonusSystemNode::HERO)
  2298. {
  2299. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  2300. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2301. newBonus->val *= level;
  2302. return newBonus;
  2303. }
  2304. return b;
  2305. }
  2306. std::string TimesHeroLevelUpdater::toString() const
  2307. {
  2308. return "TimesHeroLevelUpdater";
  2309. }
  2310. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  2311. {
  2312. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  2313. }
  2314. ArmyMovementUpdater::ArmyMovementUpdater():
  2315. base(20),
  2316. divider(3),
  2317. multiplier(10),
  2318. max(700)
  2319. {
  2320. }
  2321. ArmyMovementUpdater::ArmyMovementUpdater(int base, int divider, int multiplier, int max):
  2322. base(base),
  2323. divider(divider),
  2324. multiplier(multiplier),
  2325. max(max)
  2326. {
  2327. }
  2328. std::shared_ptr<Bonus> ArmyMovementUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2329. {
  2330. if(b->type == Bonus::MOVEMENT && context.getNodeType() == CBonusSystemNode::HERO)
  2331. {
  2332. auto speed = static_cast<const CGHeroInstance &>(context).getLowestCreatureSpeed();
  2333. si32 armySpeed = speed * base / divider;
  2334. auto counted = armySpeed * multiplier;
  2335. auto newBonus = std::make_shared<Bonus>(*b);
  2336. newBonus->source = Bonus::ARMY;
  2337. newBonus->val += vstd::amin(counted, max);
  2338. return newBonus;
  2339. }
  2340. if(b->type != Bonus::MOVEMENT)
  2341. logGlobal->error("ArmyMovementUpdater should only be used for MOVEMENT bonus!");
  2342. return b;
  2343. }
  2344. std::string ArmyMovementUpdater::toString() const
  2345. {
  2346. return "ArmyMovementUpdater";
  2347. }
  2348. JsonNode ArmyMovementUpdater::toJsonNode() const
  2349. {
  2350. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2351. root["type"].String() = "ARMY_MOVEMENT";
  2352. root["parameters"].Vector().push_back(JsonUtils::intNode(base));
  2353. root["parameters"].Vector().push_back(JsonUtils::intNode(divider));
  2354. root["parameters"].Vector().push_back(JsonUtils::intNode(multiplier));
  2355. root["parameters"].Vector().push_back(JsonUtils::intNode(max));
  2356. return root;
  2357. }
  2358. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2359. {
  2360. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  2361. {
  2362. int level = dynamic_cast<const CStackInstance &>(context).getLevel();
  2363. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2364. newBonus->val *= level;
  2365. return newBonus;
  2366. }
  2367. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  2368. {
  2369. const auto & stack = dynamic_cast<const CStack &>(context);
  2370. //only update if stack doesn't have an instance (summons, war machines)
  2371. //otherwise we'd end up multiplying twice
  2372. if(stack.base == nullptr)
  2373. {
  2374. int level = stack.type->getLevel();
  2375. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2376. newBonus->val *= level;
  2377. return newBonus;
  2378. }
  2379. }
  2380. return b;
  2381. }
  2382. std::string TimesStackLevelUpdater::toString() const
  2383. {
  2384. return "TimesStackLevelUpdater";
  2385. }
  2386. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2387. {
  2388. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2389. }
  2390. std::string OwnerUpdater::toString() const
  2391. {
  2392. return "OwnerUpdater";
  2393. }
  2394. JsonNode OwnerUpdater::toJsonNode() const
  2395. {
  2396. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  2397. }
  2398. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2399. {
  2400. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  2401. if(owner == PlayerColor::UNFLAGGABLE)
  2402. owner = PlayerColor::NEUTRAL;
  2403. std::shared_ptr<Bonus> updated =
  2404. std::make_shared<Bonus>(static_cast<Bonus::BonusDuration>(b->duration), b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  2405. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  2406. return updated;
  2407. }
  2408. VCMI_LIB_NAMESPACE_END