HeroBonus.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788
  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<CreatureFactionLimiter>()},
  68. {"OPPOSITE_SIDE", std::make_shared<OppositeSideLimiter>()},
  69. {"UNIT_ON_HEXES", std::make_shared<UnitOnHexLimiter>()}
  70. };
  71. const std::map<std::string, TPropagatorPtr> bonusPropagatorMap =
  72. {
  73. {"BATTLE_WIDE", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::BATTLE)},
  74. {"VISITED_TOWN_AND_VISITOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TOWN_AND_VISITOR)},
  75. {"PLAYER_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::PLAYER)},
  76. {"HERO", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::HERO)},
  77. {"TEAM_PROPAGATOR", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::TEAM)}, //untested
  78. {"GLOBAL_EFFECT", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::GLOBAL_EFFECTS)},
  79. {"ALL_CREATURES", std::make_shared<CPropagatorNodeType>(CBonusSystemNode::ALL_CREATURES)}
  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. si32 IBonusBearer::manaLimit() const
  671. {
  672. return 0;
  673. }
  674. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  675. {
  676. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  677. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  678. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  679. auto ret = allSkills->valOfBonuses(Selector::subtype()(id));
  680. auto minSkillValue = (id == PrimarySkill::SPELL_POWER || id == PrimarySkill::KNOWLEDGE) ? 1 : 0;
  681. vstd::amax(ret, minSkillValue); //otherwise, some artifacts may cause negative skill value effect
  682. return ret; //sp=0 works in old saves
  683. }
  684. si32 IBonusBearer::magicResistance() const
  685. {
  686. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  687. }
  688. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  689. {
  690. //war machines cannot move
  691. if(hasBonus(Selector::type()(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  692. {
  693. return 0;
  694. }
  695. //bind effect check - doesn't influence stack initiative
  696. if(useBind && hasBonus(Selector::type()(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  697. {
  698. return 0;
  699. }
  700. return valOfBonuses(Selector::type()(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  701. }
  702. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  703. {
  704. static const std::string cachingStr = "IBonusBearer::isLiving";
  705. static const CSelector selector = Selector::type()(Bonus::UNDEAD)
  706. .Or(Selector::type()(Bonus::NON_LIVING))
  707. .Or(Selector::type()(Bonus::GARGOYLE))
  708. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  709. return !hasBonus(selector, cachingStr);
  710. }
  711. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  712. {
  713. auto bonuses = getAllBonuses(selector, Selector::all);
  714. return bonuses->getFirst(Selector::all);
  715. }
  716. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  717. {
  718. switch(node->getNodeType())
  719. {
  720. case CBonusSystemNode::STACK_BATTLE:
  721. return dynamic_cast<const CStack *>(node);
  722. default:
  723. return nullptr;
  724. }
  725. }
  726. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  727. {
  728. switch(node->getNodeType())
  729. {
  730. case CBonusSystemNode::STACK_INSTANCE:
  731. return (dynamic_cast<const CStackInstance *>(node));
  732. case CBonusSystemNode::STACK_BATTLE:
  733. return (dynamic_cast<const CStack *>(node))->base;
  734. default:
  735. return nullptr;
  736. }
  737. }
  738. PlayerColor CBonusSystemNode::retrieveNodeOwner(const CBonusSystemNode * node)
  739. {
  740. return node ? node->getOwner() : PlayerColor::CANNOT_DETERMINE;
  741. }
  742. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector)
  743. {
  744. auto ret = bonuses.getFirst(selector);
  745. if(ret)
  746. return ret;
  747. FOREACH_PARENT(pname)
  748. {
  749. ret = pname->getBonusLocalFirst(selector);
  750. if (ret)
  751. return ret;
  752. }
  753. return nullptr;
  754. }
  755. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector & selector) const
  756. {
  757. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  758. }
  759. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  760. {
  761. for(const auto & elem : parents)
  762. {
  763. const CBonusSystemNode *parent = elem;
  764. out.insert(parent);
  765. }
  766. }
  767. void CBonusSystemNode::getParents(TNodes &out)
  768. {
  769. for (auto & elem : parents)
  770. {
  771. const CBonusSystemNode *parent = elem;
  772. out.insert(const_cast<CBonusSystemNode*>(parent));
  773. }
  774. }
  775. void CBonusSystemNode::getAllParents(TCNodes & out) const //retrieves list of parent nodes (nodes to inherit bonuses from)
  776. {
  777. for(auto * parent : parents)
  778. {
  779. out.insert(parent);
  780. parent->getAllParents(out);
  781. }
  782. }
  783. void CBonusSystemNode::getAllBonusesRec(BonusList &out, const CSelector & selector) const
  784. {
  785. //out has been reserved sufficient capacity at getAllBonuses() call
  786. BonusList beforeUpdate;
  787. TCNodes lparents;
  788. getAllParents(lparents);
  789. if(!lparents.empty())
  790. {
  791. //estimate on how many bonuses are missing yet - must be positive
  792. beforeUpdate.reserve(std::max(out.capacity() - out.size(), bonuses.size()));
  793. }
  794. else
  795. {
  796. beforeUpdate.reserve(bonuses.size()); //at most all local bonuses
  797. }
  798. for(const auto * parent : lparents)
  799. {
  800. parent->getAllBonusesRec(beforeUpdate, selector);
  801. }
  802. bonuses.getAllBonuses(beforeUpdate);
  803. for(const auto & b : beforeUpdate)
  804. {
  805. //We should not run updaters on non-selected bonuses
  806. auto updated = selector(b.get()) && b->updater
  807. ? getUpdatedBonus(b, b->updater)
  808. : b;
  809. //do not add bonus with updater
  810. bool bonusExists = false;
  811. for(const auto & bonus : out)
  812. {
  813. if (bonus == updated)
  814. bonusExists = true;
  815. if (bonus->updater && bonus->updater == updated->updater)
  816. bonusExists = true;
  817. }
  818. if (!bonusExists)
  819. out.push_back(updated);
  820. }
  821. }
  822. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  823. {
  824. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  825. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  826. {
  827. // Exclusive access for one thread
  828. boost::lock_guard<boost::mutex> lock(sync);
  829. // If the bonus system tree changes(state of a single node or the relations to each other) then
  830. // cache all bonus objects. Selector objects doesn't matter.
  831. if (cachedLast != treeChanged)
  832. {
  833. BonusList allBonuses;
  834. allBonuses.reserve(cachedBonuses.capacity()); //we assume we'll get about the same number of bonuses
  835. cachedBonuses.clear();
  836. cachedRequests.clear();
  837. getAllBonusesRec(allBonuses, Selector::all);
  838. limitBonuses(allBonuses, cachedBonuses);
  839. cachedBonuses.stackBonuses();
  840. cachedLast = treeChanged;
  841. }
  842. // If a bonus system request comes with a caching string then look up in the map if there are any
  843. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  844. if(!cachingStr.empty())
  845. {
  846. auto it = cachedRequests.find(cachingStr);
  847. if(it != cachedRequests.end())
  848. {
  849. //Cached list contains bonuses for our query with applied limiters
  850. return it->second;
  851. }
  852. }
  853. //We still don't have the bonuses (didn't returned them from cache)
  854. //Perform bonus selection
  855. auto ret = std::make_shared<BonusList>();
  856. cachedBonuses.getBonuses(*ret, selector, limit);
  857. // Save the results in the cache
  858. if(!cachingStr.empty())
  859. cachedRequests[cachingStr] = ret;
  860. return ret;
  861. }
  862. else
  863. {
  864. return getAllBonusesWithoutCaching(selector, limit, root);
  865. }
  866. }
  867. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  868. {
  869. auto ret = std::make_shared<BonusList>();
  870. // Get bonus results without caching enabled.
  871. BonusList beforeLimiting;
  872. BonusList afterLimiting;
  873. getAllBonusesRec(beforeLimiting, selector);
  874. if(!root || root == this)
  875. {
  876. limitBonuses(beforeLimiting, afterLimiting);
  877. }
  878. else if(root)
  879. {
  880. //We want to limit our query against an external node. We get all its bonuses,
  881. // add the ones we're considering and see if they're cut out by limiters
  882. BonusList rootBonuses;
  883. BonusList limitedRootBonuses;
  884. getAllBonusesRec(rootBonuses, selector);
  885. for(const auto & b : beforeLimiting)
  886. rootBonuses.push_back(b);
  887. root->limitBonuses(rootBonuses, limitedRootBonuses);
  888. for(const auto & b : beforeLimiting)
  889. if(vstd::contains(limitedRootBonuses, b))
  890. afterLimiting.push_back(b);
  891. }
  892. afterLimiting.getBonuses(*ret, selector, limit);
  893. ret->stackBonuses();
  894. return ret;
  895. }
  896. std::shared_ptr<Bonus> CBonusSystemNode::getUpdatedBonus(const std::shared_ptr<Bonus> & b, const TUpdaterPtr & updater) const
  897. {
  898. assert(updater);
  899. return updater->createUpdatedBonus(b, * this);
  900. }
  901. CBonusSystemNode::CBonusSystemNode()
  902. :CBonusSystemNode(false)
  903. {
  904. }
  905. CBonusSystemNode::CBonusSystemNode(bool isHypotetic):
  906. bonuses(true),
  907. exportedBonuses(true),
  908. nodeType(UNKNOWN),
  909. cachedLast(0),
  910. isHypotheticNode(isHypotetic)
  911. {
  912. }
  913. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType):
  914. bonuses(true),
  915. exportedBonuses(true),
  916. nodeType(NodeType),
  917. cachedLast(0),
  918. isHypotheticNode(false)
  919. {
  920. }
  921. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other) noexcept:
  922. bonuses(std::move(other.bonuses)),
  923. exportedBonuses(std::move(other.exportedBonuses)),
  924. nodeType(other.nodeType),
  925. description(other.description),
  926. cachedLast(0),
  927. isHypotheticNode(other.isHypotheticNode)
  928. {
  929. std::swap(parents, other.parents);
  930. std::swap(children, other.children);
  931. //fixing bonus tree without recalculation
  932. if(!isHypothetic())
  933. {
  934. for(CBonusSystemNode * n : parents)
  935. {
  936. n->children -= &other;
  937. n->children.push_back(this);
  938. }
  939. }
  940. for(CBonusSystemNode * n : children)
  941. {
  942. n->parents -= &other;
  943. n->parents.push_back(this);
  944. }
  945. //cache ignored
  946. //cachedBonuses
  947. //cachedRequests
  948. }
  949. CBonusSystemNode::~CBonusSystemNode()
  950. {
  951. detachFromAll();
  952. if(!children.empty())
  953. {
  954. while(!children.empty())
  955. children.front()->detachFrom(*this);
  956. }
  957. }
  958. void CBonusSystemNode::attachTo(CBonusSystemNode & parent)
  959. {
  960. assert(!vstd::contains(parents, &parent));
  961. parents.push_back(&parent);
  962. if(!isHypothetic())
  963. {
  964. if(parent.actsAsBonusSourceOnly())
  965. parent.newRedDescendant(*this);
  966. else
  967. newRedDescendant(parent);
  968. parent.newChildAttached(*this);
  969. }
  970. CBonusSystemNode::treeHasChanged();
  971. }
  972. void CBonusSystemNode::detachFrom(CBonusSystemNode & parent)
  973. {
  974. assert(vstd::contains(parents, &parent));
  975. if(!isHypothetic())
  976. {
  977. if(parent.actsAsBonusSourceOnly())
  978. parent.removedRedDescendant(*this);
  979. else
  980. removedRedDescendant(parent);
  981. }
  982. if (vstd::contains(parents, &parent))
  983. {
  984. parents -= &parent;
  985. }
  986. else
  987. {
  988. logBonus->error("Error on Detach. Node %s (nodeType=%d) has not parent %s (nodeType=%d)"
  989. , nodeShortInfo(), nodeType, parent.nodeShortInfo(), parent.nodeType);
  990. }
  991. if(!isHypothetic())
  992. {
  993. parent.childDetached(*this);
  994. }
  995. CBonusSystemNode::treeHasChanged();
  996. }
  997. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  998. {
  999. removeBonuses(s);
  1000. for(CBonusSystemNode * child : children)
  1001. child->removeBonusesRecursive(s);
  1002. }
  1003. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  1004. {
  1005. BonusList bl;
  1006. exportedBonuses.getBonuses(bl, s, Selector::all);
  1007. for(const auto & b : bl)
  1008. {
  1009. b->turnsRemain--;
  1010. if(b->turnsRemain <= 0)
  1011. removeBonus(b);
  1012. }
  1013. for(CBonusSystemNode *child : children)
  1014. child->reduceBonusDurations(s);
  1015. }
  1016. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  1017. {
  1018. //turnsRemain shouldn't be zero for following durations
  1019. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  1020. {
  1021. assert(b->turnsRemain);
  1022. }
  1023. assert(!vstd::contains(exportedBonuses, b));
  1024. exportedBonuses.push_back(b);
  1025. exportBonus(b);
  1026. CBonusSystemNode::treeHasChanged();
  1027. }
  1028. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  1029. {
  1030. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  1031. if(bonus)
  1032. bonus->val += b->val;
  1033. else
  1034. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  1035. }
  1036. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  1037. {
  1038. exportedBonuses -= b;
  1039. if(b->propagator)
  1040. unpropagateBonus(b);
  1041. else
  1042. bonuses -= b;
  1043. CBonusSystemNode::treeHasChanged();
  1044. }
  1045. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  1046. {
  1047. BonusList toRemove;
  1048. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  1049. for(const auto & bonus : toRemove)
  1050. removeBonus(bonus);
  1051. }
  1052. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  1053. {
  1054. switch(nodeType)
  1055. {
  1056. case CREATURE:
  1057. case ARTIFACT:
  1058. case ARTIFACT_INSTANCE:
  1059. return true;
  1060. default:
  1061. return false;
  1062. }
  1063. }
  1064. void CBonusSystemNode::propagateBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & source)
  1065. {
  1066. if(b->propagator->shouldBeAttached(this))
  1067. {
  1068. auto propagated = b->propagationUpdater
  1069. ? source.getUpdatedBonus(b, b->propagationUpdater)
  1070. : b;
  1071. bonuses.push_back(propagated);
  1072. logBonus->trace("#$# %s #propagated to# %s", propagated->Description(), nodeName());
  1073. }
  1074. FOREACH_RED_CHILD(child)
  1075. child->propagateBonus(b, source);
  1076. }
  1077. void CBonusSystemNode::unpropagateBonus(const std::shared_ptr<Bonus> & b)
  1078. {
  1079. if(b->propagator->shouldBeAttached(this))
  1080. {
  1081. bonuses -= b;
  1082. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  1083. }
  1084. FOREACH_RED_CHILD(child)
  1085. child->unpropagateBonus(b);
  1086. }
  1087. void CBonusSystemNode::newChildAttached(CBonusSystemNode & child)
  1088. {
  1089. assert(!vstd::contains(children, &child));
  1090. children.push_back(&child);
  1091. }
  1092. void CBonusSystemNode::childDetached(CBonusSystemNode & child)
  1093. {
  1094. if(vstd::contains(children, &child))
  1095. children -= &child;
  1096. else
  1097. {
  1098. logBonus->error("Error on Detach. Node %s (nodeType=%d) is not a child of %s (nodeType=%d)"
  1099. , child.nodeShortInfo(), child.nodeType, nodeShortInfo(), nodeType);
  1100. }
  1101. }
  1102. void CBonusSystemNode::detachFromAll()
  1103. {
  1104. while(!parents.empty())
  1105. detachFrom(*parents.front());
  1106. }
  1107. bool CBonusSystemNode::isIndependentNode() const
  1108. {
  1109. return parents.empty() && children.empty();
  1110. }
  1111. std::string CBonusSystemNode::nodeName() const
  1112. {
  1113. return !description.empty()
  1114. ? description
  1115. : std::string("Bonus system node of type ") + typeid(*this).name();
  1116. }
  1117. std::string CBonusSystemNode::nodeShortInfo() const
  1118. {
  1119. std::ostringstream str;
  1120. str << "'" << typeid(* this).name() << "'";
  1121. description.length() > 0
  1122. ? str << " (" << description << ")"
  1123. : str << " (no description)";
  1124. return str.str();
  1125. }
  1126. void CBonusSystemNode::deserializationFix()
  1127. {
  1128. exportBonuses();
  1129. }
  1130. void CBonusSystemNode::getRedParents(TNodes & out)
  1131. {
  1132. FOREACH_PARENT(pname)
  1133. {
  1134. if(pname->actsAsBonusSourceOnly())
  1135. {
  1136. out.insert(pname);
  1137. }
  1138. }
  1139. if(!actsAsBonusSourceOnly())
  1140. {
  1141. for(CBonusSystemNode *child : children)
  1142. {
  1143. out.insert(child);
  1144. }
  1145. }
  1146. }
  1147. void CBonusSystemNode::getRedChildren(TNodes &out)
  1148. {
  1149. FOREACH_PARENT(pname)
  1150. {
  1151. if(!pname->actsAsBonusSourceOnly())
  1152. {
  1153. out.insert(pname);
  1154. }
  1155. }
  1156. if(actsAsBonusSourceOnly())
  1157. {
  1158. for(CBonusSystemNode *child : children)
  1159. {
  1160. out.insert(child);
  1161. }
  1162. }
  1163. }
  1164. void CBonusSystemNode::newRedDescendant(CBonusSystemNode & descendant)
  1165. {
  1166. for(const auto & b : exportedBonuses)
  1167. {
  1168. if(b->propagator)
  1169. descendant.propagateBonus(b, *this);
  1170. }
  1171. TNodes redParents;
  1172. getRedAncestors(redParents); //get all red parents recursively
  1173. for(auto * parent : redParents)
  1174. {
  1175. for(const auto & b : parent->exportedBonuses)
  1176. {
  1177. if(b->propagator)
  1178. descendant.propagateBonus(b, *this);
  1179. }
  1180. }
  1181. }
  1182. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode & descendant)
  1183. {
  1184. for(const auto & b : exportedBonuses)
  1185. if(b->propagator)
  1186. descendant.unpropagateBonus(b);
  1187. TNodes redParents;
  1188. getRedAncestors(redParents); //get all red parents recursively
  1189. for(auto * parent : redParents)
  1190. {
  1191. for(const auto & b : parent->exportedBonuses)
  1192. if(b->propagator)
  1193. descendant.unpropagateBonus(b);
  1194. }
  1195. }
  1196. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1197. {
  1198. getRedParents(out);
  1199. TNodes redParents;
  1200. getRedParents(redParents);
  1201. for(CBonusSystemNode * parent : redParents)
  1202. parent->getRedAncestors(out);
  1203. }
  1204. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1205. {
  1206. getRedChildren(out);
  1207. FOREACH_RED_CHILD(c)
  1208. c->getRedChildren(out);
  1209. }
  1210. void CBonusSystemNode::exportBonus(const std::shared_ptr<Bonus> & b)
  1211. {
  1212. if(b->propagator)
  1213. propagateBonus(b, *this);
  1214. else
  1215. bonuses.push_back(b);
  1216. CBonusSystemNode::treeHasChanged();
  1217. }
  1218. void CBonusSystemNode::exportBonuses()
  1219. {
  1220. for(const auto & b : exportedBonuses)
  1221. exportBonus(b);
  1222. }
  1223. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1224. {
  1225. return nodeType;
  1226. }
  1227. const BonusList& CBonusSystemNode::getBonusList() const
  1228. {
  1229. return bonuses;
  1230. }
  1231. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1232. {
  1233. return parents;
  1234. }
  1235. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1236. {
  1237. return children;
  1238. }
  1239. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1240. {
  1241. nodeType = type;
  1242. }
  1243. BonusList & CBonusSystemNode::getExportedBonusList()
  1244. {
  1245. return exportedBonuses;
  1246. }
  1247. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1248. {
  1249. return exportedBonuses;
  1250. }
  1251. const std::string& CBonusSystemNode::getDescription() const
  1252. {
  1253. return description;
  1254. }
  1255. void CBonusSystemNode::setDescription(const std::string &description)
  1256. {
  1257. this->description = description;
  1258. }
  1259. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1260. {
  1261. assert(&allBonuses != &out); //todo should it work in-place?
  1262. BonusList undecided = allBonuses;
  1263. BonusList & accepted = out;
  1264. while(true)
  1265. {
  1266. int undecidedCount = static_cast<int>(undecided.size());
  1267. for(int i = 0; i < undecided.size(); i++)
  1268. {
  1269. auto b = undecided[i];
  1270. BonusLimitationContext context = {b, *this, out, undecided};
  1271. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  1272. if(decision == ILimiter::EDecision::DISCARD)
  1273. {
  1274. undecided.erase(i);
  1275. i--; continue;
  1276. }
  1277. else if(decision == ILimiter::EDecision::ACCEPT)
  1278. {
  1279. accepted.push_back(b);
  1280. undecided.erase(i);
  1281. i--; continue;
  1282. }
  1283. else
  1284. assert(decision == ILimiter::EDecision::NOT_SURE);
  1285. }
  1286. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1287. return;
  1288. }
  1289. }
  1290. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1291. {
  1292. auto ret = std::make_shared<BonusList>();
  1293. limitBonuses(allBonuses, *ret);
  1294. return ret;
  1295. }
  1296. void CBonusSystemNode::treeHasChanged()
  1297. {
  1298. treeChanged++;
  1299. }
  1300. int64_t CBonusSystemNode::getTreeVersion() const
  1301. {
  1302. return treeChanged;
  1303. }
  1304. std::string Bonus::Description(boost::optional<si32> customValue) const
  1305. {
  1306. std::ostringstream str;
  1307. if(description.empty())
  1308. {
  1309. if(stacking.empty() || stacking == "ALWAYS")
  1310. {
  1311. switch(source)
  1312. {
  1313. case ARTIFACT:
  1314. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getNameTranslated();
  1315. break;
  1316. case SPELL_EFFECT:
  1317. str << SpellID(sid).toSpell(VLC->spells())->getNameTranslated();
  1318. break;
  1319. case CREATURE_ABILITY:
  1320. str << VLC->creh->objects[sid]->getNamePluralTranslated();
  1321. break;
  1322. case SECONDARY_SKILL:
  1323. str << VLC->skillh->getByIndex(sid)->getNameTranslated();
  1324. break;
  1325. case HERO_SPECIAL:
  1326. str << VLC->heroh->objects[sid]->getNameTranslated();
  1327. break;
  1328. default:
  1329. //todo: handle all possible sources
  1330. str << "Unknown";
  1331. break;
  1332. }
  1333. }
  1334. else
  1335. str << stacking;
  1336. }
  1337. else
  1338. {
  1339. str << description;
  1340. }
  1341. if(auto value = customValue.value_or(val))
  1342. str << " " << std::showpos << value;
  1343. return str.str();
  1344. }
  1345. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1346. {
  1347. switch(type)
  1348. {
  1349. case Bonus::PRIMARY_SKILL:
  1350. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1351. case Bonus::SPECIAL_SPELL_LEV:
  1352. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1353. case Bonus::SPELL:
  1354. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1355. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1356. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1357. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1358. case Bonus::IMPROVED_NECROMANCY:
  1359. case Bonus::SPECIAL_UPGRADE:
  1360. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1361. case Bonus::GENERATE_RESOURCE:
  1362. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1363. default:
  1364. return JsonUtils::intNode(subtype);
  1365. }
  1366. }
  1367. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1368. {
  1369. switch(type)
  1370. {
  1371. case Bonus::SPECIAL_UPGRADE:
  1372. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1373. default:
  1374. return addInfo.toJsonNode();
  1375. }
  1376. }
  1377. JsonNode durationToJson(ui16 duration)
  1378. {
  1379. std::vector<std::string> durationNames;
  1380. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1381. {
  1382. if(duration & durBit)
  1383. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1384. }
  1385. if(durationNames.size() == 1)
  1386. {
  1387. return JsonUtils::stringNode(durationNames[0]);
  1388. }
  1389. else
  1390. {
  1391. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1392. for(const std::string & dur : durationNames)
  1393. node.Vector().push_back(JsonUtils::stringNode(dur));
  1394. return node;
  1395. }
  1396. }
  1397. JsonNode Bonus::toJsonNode() const
  1398. {
  1399. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1400. // only add values that might reasonably be found in config files
  1401. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1402. if(subtype != -1)
  1403. root["subtype"] = subtypeToJson(type, subtype);
  1404. if(additionalInfo != CAddInfo::NONE)
  1405. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1406. if(duration != 0)
  1407. {
  1408. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1409. for(const auto & kv : bonusDurationMap)
  1410. {
  1411. if(duration & kv.second)
  1412. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1413. }
  1414. root["duration"] = durationVec;
  1415. }
  1416. if(turnsRemain != 0)
  1417. root["turns"].Integer() = turnsRemain;
  1418. if(source != OTHER)
  1419. root["sourceType"].String() = vstd::findKey(bonusSourceMap, source);
  1420. if(targetSourceType != OTHER)
  1421. root["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetSourceType);
  1422. if(sid != 0)
  1423. root["sourceID"].Integer() = sid;
  1424. if(val != 0)
  1425. root["val"].Integer() = val;
  1426. if(valType != ADDITIVE_VALUE)
  1427. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1428. if(!stacking.empty())
  1429. root["stacking"].String() = stacking;
  1430. if(!description.empty())
  1431. root["description"].String() = description;
  1432. if(effectRange != NO_LIMIT)
  1433. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1434. if(duration != PERMANENT)
  1435. root["duration"] = durationToJson(duration);
  1436. if(turnsRemain)
  1437. root["turns"].Integer() = turnsRemain;
  1438. if(limiter)
  1439. root["limiters"] = limiter->toJsonNode();
  1440. if(updater)
  1441. root["updater"] = updater->toJsonNode();
  1442. if(propagator)
  1443. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1444. return root;
  1445. }
  1446. std::string Bonus::nameForBonus() const
  1447. {
  1448. switch(type)
  1449. {
  1450. case Bonus::PRIMARY_SKILL:
  1451. return PrimarySkill::names[subtype];
  1452. case Bonus::SPECIAL_SPELL_LEV:
  1453. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1454. case Bonus::SPELL:
  1455. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1456. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1457. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1458. return (*VLC->spellh)[static_cast<SpellID::ESpellID>(subtype)]->identifier;
  1459. case Bonus::SPECIAL_UPGRADE:
  1460. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1461. case Bonus::GENERATE_RESOURCE:
  1462. return GameConstants::RESOURCE_NAMES[subtype];
  1463. case Bonus::STACKS_SPEED:
  1464. return "speed";
  1465. default:
  1466. return vstd::findKey(bonusNameMap, type);
  1467. }
  1468. }
  1469. BonusParams::BonusParams(std::string deprecatedTypeStr, std::string deprecatedSubtypeStr, int deprecatedSubtype):
  1470. isConverted(true)
  1471. {
  1472. if(deprecatedTypeStr == "SECONDARY_SKILL_PREMY" || deprecatedTypeStr == "SPECIAL_SECONDARY_SKILL")
  1473. {
  1474. if(deprecatedSubtype == SecondarySkill::PATHFINDING || deprecatedSubtypeStr == "skill.pathfinding")
  1475. type = Bonus::ROUGH_TERRAIN_DISCOUNT;
  1476. else if(deprecatedSubtype == SecondarySkill::DIPLOMACY || deprecatedSubtypeStr == "skill.diplomacy")
  1477. type = Bonus::WANDERING_CREATURES_JOIN_BONUS;
  1478. else if(deprecatedSubtype == SecondarySkill::WISDOM || deprecatedSubtypeStr == "skill.wisdom")
  1479. type = Bonus::MAX_LEARNABLE_SPELL_LEVEL;
  1480. else if(deprecatedSubtype == SecondarySkill::MYSTICISM || deprecatedSubtypeStr == "skill.mysticism")
  1481. type = Bonus::MANA_REGENERATION;
  1482. else if(deprecatedSubtype == SecondarySkill::NECROMANCY || deprecatedSubtypeStr == "skill.necromancy")
  1483. type = Bonus::UNDEAD_RAISE_PERCENTAGE;
  1484. else if(deprecatedSubtype == SecondarySkill::LEARNING || deprecatedSubtypeStr == "skill.learning")
  1485. type = Bonus::HERO_EXPERIENCE_GAIN_PERCENT;
  1486. else if(deprecatedSubtype == SecondarySkill::RESISTANCE || deprecatedSubtypeStr == "skill.resistance")
  1487. type = Bonus::MAGIC_RESISTANCE;
  1488. else if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1489. type = Bonus::LEARN_BATTLE_SPELL_CHANCE;
  1490. else if(deprecatedSubtype == SecondarySkill::SCOUTING || deprecatedSubtypeStr == "skill.scouting")
  1491. type = Bonus::SIGHT_RADIUS;
  1492. else if(deprecatedSubtype == SecondarySkill::INTELLIGENCE || deprecatedSubtypeStr == "skill.intelligence")
  1493. {
  1494. type = Bonus::MANA_PER_KNOWLEDGE;
  1495. valueType = Bonus::PERCENT_TO_BASE;
  1496. valueTypeRelevant = true;
  1497. }
  1498. else if(deprecatedSubtype == SecondarySkill::SORCERY || deprecatedSubtypeStr == "skill.sorcery")
  1499. type = Bonus::SPELL_DAMAGE;
  1500. else if(deprecatedSubtype == SecondarySkill::SCHOLAR || deprecatedSubtypeStr == "skill.scholar")
  1501. type = Bonus::LEARN_MEETING_SPELL_LIMIT;
  1502. else if(deprecatedSubtype == SecondarySkill::ARCHERY|| deprecatedSubtypeStr == "skill.archery")
  1503. {
  1504. subtype = 1;
  1505. subtypeRelevant = true;
  1506. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1507. }
  1508. else if(deprecatedSubtype == SecondarySkill::OFFENCE || deprecatedSubtypeStr == "skill.offence")
  1509. {
  1510. subtype = 0;
  1511. subtypeRelevant = true;
  1512. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1513. }
  1514. else if(deprecatedSubtype == SecondarySkill::ARMORER || deprecatedSubtypeStr == "skill.armorer")
  1515. {
  1516. subtype = -1;
  1517. subtypeRelevant = true;
  1518. type = Bonus::GENERAL_DAMAGE_REDUCTION;
  1519. }
  1520. else if(deprecatedSubtype == SecondarySkill::NAVIGATION || deprecatedSubtypeStr == "skill.navigation")
  1521. {
  1522. subtype = 0;
  1523. subtypeRelevant = true;
  1524. valueType = Bonus::PERCENT_TO_BASE;
  1525. valueTypeRelevant = true;
  1526. type = Bonus::MOVEMENT;
  1527. }
  1528. else if(deprecatedSubtype == SecondarySkill::LOGISTICS || deprecatedSubtypeStr == "skill.logistics")
  1529. {
  1530. subtype = 0;
  1531. subtypeRelevant = true;
  1532. valueType = Bonus::PERCENT_TO_BASE;
  1533. valueTypeRelevant = true;
  1534. type = Bonus::MOVEMENT;
  1535. }
  1536. else if(deprecatedSubtype == SecondarySkill::ESTATES || deprecatedSubtypeStr == "skill.estates")
  1537. {
  1538. type = Bonus::GENERATE_RESOURCE;
  1539. subtype = Res::GOLD;
  1540. subtypeRelevant = true;
  1541. }
  1542. else if(deprecatedSubtype == SecondarySkill::AIR_MAGIC || deprecatedSubtypeStr == "skill.airMagic")
  1543. {
  1544. type = Bonus::MAGIC_SCHOOL_SKILL;
  1545. subtypeRelevant = true;
  1546. subtype = 4;
  1547. }
  1548. else if(deprecatedSubtype == SecondarySkill::WATER_MAGIC || deprecatedSubtypeStr == "skill.waterMagic")
  1549. {
  1550. type = Bonus::MAGIC_SCHOOL_SKILL;
  1551. subtypeRelevant = true;
  1552. subtype = 1;
  1553. }
  1554. else if(deprecatedSubtype == SecondarySkill::FIRE_MAGIC || deprecatedSubtypeStr == "skill.fireMagic")
  1555. {
  1556. type = Bonus::MAGIC_SCHOOL_SKILL;
  1557. subtypeRelevant = true;
  1558. subtype = 2;
  1559. }
  1560. else if(deprecatedSubtype == SecondarySkill::EARTH_MAGIC || deprecatedSubtypeStr == "skill.earthMagic")
  1561. {
  1562. type = Bonus::MAGIC_SCHOOL_SKILL;
  1563. subtypeRelevant = true;
  1564. subtype = 8;
  1565. }
  1566. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1567. {
  1568. type = Bonus::BONUS_DAMAGE_CHANCE;
  1569. subtypeRelevant = true;
  1570. subtypeStr = "core:creature.ballista";
  1571. }
  1572. else if (deprecatedSubtype == SecondarySkill::FIRST_AID || deprecatedSubtypeStr == "skill.firstAid")
  1573. {
  1574. type = Bonus::SPECIFIC_SPELL_POWER;
  1575. subtypeRelevant = true;
  1576. subtypeStr = "core:spell.firstAid";
  1577. }
  1578. else if (deprecatedSubtype == SecondarySkill::BALLISTICS || deprecatedSubtypeStr == "skill.ballistics")
  1579. {
  1580. type = Bonus::CATAPULT_EXTRA_SHOTS;
  1581. subtypeRelevant = true;
  1582. subtypeStr = "core:spell.catapultShot";
  1583. }
  1584. else
  1585. isConverted = false;
  1586. }
  1587. else if (deprecatedTypeStr == "SECONDARY_SKILL_VAL2")
  1588. {
  1589. if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1590. type = Bonus::LEARN_BATTLE_SPELL_LEVEL_LIMIT;
  1591. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1592. {
  1593. type = Bonus::HERO_GRANTS_ATTACKS;
  1594. subtypeRelevant = true;
  1595. subtypeStr = "core:creature.ballista";
  1596. }
  1597. else
  1598. isConverted = false;
  1599. }
  1600. else if (deprecatedTypeStr == "SEA_MOVEMENT")
  1601. {
  1602. subtype = 0;
  1603. subtypeRelevant = true;
  1604. valueType = Bonus::ADDITIVE_VALUE;
  1605. valueTypeRelevant = true;
  1606. type = Bonus::MOVEMENT;
  1607. }
  1608. else if (deprecatedTypeStr == "LAND_MOVEMENT")
  1609. {
  1610. subtype = 1;
  1611. subtypeRelevant = true;
  1612. valueType = Bonus::ADDITIVE_VALUE;
  1613. valueTypeRelevant = true;
  1614. type = Bonus::MOVEMENT;
  1615. }
  1616. else if (deprecatedTypeStr == "MAXED_SPELL")
  1617. {
  1618. type = Bonus::SPELL;
  1619. subtypeStr = deprecatedSubtypeStr;
  1620. subtypeRelevant = true;
  1621. valueType = Bonus::INDEPENDENT_MAX;
  1622. valueTypeRelevant = true;
  1623. val = 3;
  1624. valRelevant = true;
  1625. }
  1626. else if (deprecatedTypeStr == "FULL_HP_REGENERATION")
  1627. {
  1628. type = Bonus::HP_REGENERATION;
  1629. val = 100000; //very high value to always chose stack health
  1630. valRelevant = true;
  1631. }
  1632. else if (deprecatedTypeStr == "KING1")
  1633. {
  1634. type = Bonus::KING;
  1635. val = 0;
  1636. valRelevant = true;
  1637. }
  1638. else if (deprecatedTypeStr == "KING2")
  1639. {
  1640. type = Bonus::KING;
  1641. val = 2;
  1642. valRelevant = true;
  1643. }
  1644. else if (deprecatedTypeStr == "KING3")
  1645. {
  1646. type = Bonus::KING;
  1647. val = 3;
  1648. valRelevant = true;
  1649. }
  1650. else if (deprecatedTypeStr == "SIGHT_RADIOUS")
  1651. type = Bonus::SIGHT_RADIUS;
  1652. else if (deprecatedTypeStr == "SELF_MORALE")
  1653. {
  1654. type = Bonus::MORALE;
  1655. val = 1;
  1656. valRelevant = true;
  1657. valueType = Bonus::INDEPENDENT_MAX;
  1658. valueTypeRelevant = true;
  1659. }
  1660. else if (deprecatedTypeStr == "SELF_LUCK")
  1661. {
  1662. type = Bonus::LUCK;
  1663. val = 1;
  1664. valRelevant = true;
  1665. valueType = Bonus::INDEPENDENT_MAX;
  1666. valueTypeRelevant = true;
  1667. }
  1668. else
  1669. isConverted = false;
  1670. }
  1671. const JsonNode & BonusParams::toJson()
  1672. {
  1673. assert(isConverted);
  1674. if(ret.isNull())
  1675. {
  1676. ret["type"].String() = vstd::findKey(bonusNameMap, type);
  1677. if(subtypeRelevant && !subtypeStr.empty())
  1678. ret["subtype"].String() = subtypeStr;
  1679. else if(subtypeRelevant)
  1680. ret["subtype"].Integer() = subtype;
  1681. if(valueTypeRelevant)
  1682. ret["valueType"].String() = vstd::findKey(bonusValueMap, valueType);
  1683. if(valRelevant)
  1684. ret["val"].Float() = val;
  1685. if(targetTypeRelevant)
  1686. ret["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetType);
  1687. jsonCreated = true;
  1688. }
  1689. return ret;
  1690. };
  1691. CSelector BonusParams::toSelector()
  1692. {
  1693. assert(isConverted);
  1694. if(subtypeRelevant && !subtypeStr.empty())
  1695. JsonUtils::resolveIdentifier(subtype, toJson(), "subtype");
  1696. auto ret = Selector::type()(type);
  1697. if(subtypeRelevant)
  1698. ret = ret.And(Selector::subtype()(subtype));
  1699. if(valueTypeRelevant)
  1700. ret = ret.And(Selector::valueType(valueType));
  1701. if(targetTypeRelevant)
  1702. ret = ret.And(Selector::targetSourceType()(targetType));
  1703. return ret;
  1704. }
  1705. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype):
  1706. duration(static_cast<ui16>(Duration)),
  1707. type(Type),
  1708. subtype(Subtype),
  1709. source(Src),
  1710. val(Val),
  1711. sid(ID),
  1712. description(std::move(Desc))
  1713. {
  1714. boost::algorithm::trim(description);
  1715. targetSourceType = OTHER;
  1716. }
  1717. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType):
  1718. duration(static_cast<ui16>(Duration)),
  1719. type(Type),
  1720. subtype(Subtype),
  1721. source(Src),
  1722. val(Val),
  1723. sid(ID),
  1724. valType(ValType)
  1725. {
  1726. turnsRemain = 0;
  1727. effectRange = NO_LIMIT;
  1728. targetSourceType = OTHER;
  1729. }
  1730. std::shared_ptr<Bonus> Bonus::addPropagator(const TPropagatorPtr & Propagator)
  1731. {
  1732. propagator = Propagator;
  1733. return this->shared_from_this();
  1734. }
  1735. namespace Selector
  1736. {
  1737. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1738. {
  1739. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1740. return stype;
  1741. }
  1742. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1743. {
  1744. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1745. return ssubtype;
  1746. }
  1747. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1748. {
  1749. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1750. return sinfo;
  1751. }
  1752. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1753. {
  1754. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1755. return ssourceType;
  1756. }
  1757. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1758. {
  1759. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1760. return ssourceType;
  1761. }
  1762. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1763. {
  1764. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1765. return seffectRange;
  1766. }
  1767. DLL_LINKAGE CWillLastTurns turns;
  1768. DLL_LINKAGE CWillLastDays days;
  1769. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1770. {
  1771. return type()(Type).And(subtype()(Subtype));
  1772. }
  1773. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, const CAddInfo & info)
  1774. {
  1775. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1776. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1777. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1778. }
  1779. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1780. {
  1781. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1782. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1783. }
  1784. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1785. {
  1786. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1787. }
  1788. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1789. {
  1790. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1791. }
  1792. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1793. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1794. }
  1795. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1796. {
  1797. switch(node->getNodeType())
  1798. {
  1799. case CBonusSystemNode::CREATURE:
  1800. return (dynamic_cast<const CCreature *>(node));
  1801. case CBonusSystemNode::STACK_BATTLE:
  1802. return (dynamic_cast<const CStack *>(node))->type;
  1803. default:
  1804. const CStackInstance * csi = retrieveStackInstance(node);
  1805. if(csi)
  1806. return csi->type;
  1807. return nullptr;
  1808. }
  1809. }
  1810. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1811. {
  1812. for (ui32 i = 0; i < bonusList.size(); i++)
  1813. {
  1814. const auto & b = bonusList[i];
  1815. out << "Bonus " << i << "\n" << *b << std::endl;
  1816. }
  1817. return out;
  1818. }
  1819. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1820. {
  1821. for(const auto & i : bonusNameMap)
  1822. if(i.second == bonus.type)
  1823. out << "\tType: " << i.first << " \t";
  1824. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1825. printField(val);
  1826. printField(subtype);
  1827. printField(duration);
  1828. printField(source);
  1829. printField(sid);
  1830. if(bonus.additionalInfo != CAddInfo::NONE)
  1831. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1832. printField(turnsRemain);
  1833. printField(valType);
  1834. if(!bonus.stacking.empty())
  1835. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1836. printField(effectRange);
  1837. #undef printField
  1838. if(bonus.limiter)
  1839. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1840. if(bonus.updater)
  1841. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1842. return out;
  1843. }
  1844. std::shared_ptr<Bonus> Bonus::addLimiter(const TLimiterPtr & Limiter)
  1845. {
  1846. if (limiter)
  1847. {
  1848. //If we already have limiter list, retrieve it
  1849. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1850. if(!limiterList)
  1851. {
  1852. //Create a new limiter list with old limiter and the new one will be pushed later
  1853. limiterList = std::make_shared<AllOfLimiter>();
  1854. limiterList->add(limiter);
  1855. limiter = limiterList;
  1856. }
  1857. limiterList->add(Limiter);
  1858. }
  1859. else
  1860. {
  1861. limiter = Limiter;
  1862. }
  1863. return this->shared_from_this();
  1864. }
  1865. ILimiter::EDecision ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1866. {
  1867. return ILimiter::EDecision::ACCEPT;
  1868. }
  1869. std::string ILimiter::toString() const
  1870. {
  1871. return typeid(*this).name();
  1872. }
  1873. JsonNode ILimiter::toJsonNode() const
  1874. {
  1875. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1876. root["type"].String() = toString();
  1877. return root;
  1878. }
  1879. ILimiter::EDecision CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1880. {
  1881. const CCreature *c = retrieveCreature(&context.node);
  1882. if(!c)
  1883. return ILimiter::EDecision::DISCARD;
  1884. auto accept = c->getId() == creature->getId() || (includeUpgrades && creature->isMyUpgrade(c));
  1885. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  1886. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1887. }
  1888. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1889. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1890. {
  1891. }
  1892. void CCreatureTypeLimiter::setCreature(const CreatureID & id)
  1893. {
  1894. creature = VLC->creh->objects[id];
  1895. }
  1896. std::string CCreatureTypeLimiter::toString() const
  1897. {
  1898. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1899. fmt % creature->getJsonKey() % (includeUpgrades ? "true" : "false");
  1900. return fmt.str();
  1901. }
  1902. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1903. {
  1904. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1905. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1906. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->getJsonKey()));
  1907. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1908. return root;
  1909. }
  1910. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1911. : type(bonus), subtype(0), isSubtypeRelevant(false), isSourceRelevant(false), isSourceIDRelevant(false)
  1912. {
  1913. }
  1914. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1915. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), isSourceRelevant(false), isSourceIDRelevant(false)
  1916. {
  1917. }
  1918. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, Bonus::BonusSource src)
  1919. : type(bonus), source(src), isSubtypeRelevant(false), isSourceRelevant(true), isSourceIDRelevant(false)
  1920. {
  1921. }
  1922. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype, Bonus::BonusSource src)
  1923. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), source(src), isSourceRelevant(true), isSourceIDRelevant(false)
  1924. {
  1925. }
  1926. ILimiter::EDecision HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1927. {
  1928. //TODO: proper selector config with parsing of JSON
  1929. auto mySelector = Selector::type()(type);
  1930. if(isSubtypeRelevant)
  1931. mySelector = mySelector.And(Selector::subtype()(subtype));
  1932. if(isSourceRelevant && isSourceIDRelevant)
  1933. mySelector = mySelector.And(Selector::source(source, sid));
  1934. else if (isSourceRelevant)
  1935. mySelector = mySelector.And(Selector::sourceTypeSel(source));
  1936. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1937. if(context.alreadyAccepted.getFirst(mySelector))
  1938. return ILimiter::EDecision::ACCEPT;
  1939. //if there are no matching bonuses pending, we can (and must) reject right away
  1940. if(!context.stillUndecided.getFirst(mySelector))
  1941. return ILimiter::EDecision::DISCARD;
  1942. //do not accept for now but it may change if more bonuses gets included
  1943. return ILimiter::EDecision::NOT_SURE;
  1944. }
  1945. std::string HasAnotherBonusLimiter::toString() const
  1946. {
  1947. std::string typeName = vstd::findKey(bonusNameMap, type);
  1948. if(isSubtypeRelevant)
  1949. {
  1950. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1951. fmt % typeName % subtype;
  1952. return fmt.str();
  1953. }
  1954. else
  1955. {
  1956. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1957. fmt % typeName;
  1958. return fmt.str();
  1959. }
  1960. }
  1961. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1962. {
  1963. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1964. std::string typeName = vstd::findKey(bonusNameMap, type);
  1965. auto sourceTypeName = vstd::findKey(bonusSourceMap, source);
  1966. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1967. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1968. if(isSubtypeRelevant)
  1969. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1970. if(isSourceRelevant)
  1971. root["parameters"].Vector().push_back(JsonUtils::stringNode(sourceTypeName));
  1972. return root;
  1973. }
  1974. ILimiter::EDecision UnitOnHexLimiter::limit(const BonusLimitationContext &context) const
  1975. {
  1976. const auto * stack = retrieveStackBattle(&context.node);
  1977. if(!stack)
  1978. return ILimiter::EDecision::DISCARD;
  1979. auto accept = false;
  1980. for (const auto & hex : stack->getHexes())
  1981. accept |= !!applicableHexes.count(hex);
  1982. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  1983. }
  1984. UnitOnHexLimiter::UnitOnHexLimiter(const std::set<BattleHex> & applicableHexes):
  1985. applicableHexes(applicableHexes)
  1986. {
  1987. }
  1988. JsonNode UnitOnHexLimiter::toJsonNode() const
  1989. {
  1990. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1991. root["type"].String() = "UNIT_ON_HEXES";
  1992. for(const auto & hex : applicableHexes)
  1993. root["parameters"].Vector().push_back(JsonUtils::intNode(hex));
  1994. return root;
  1995. }
  1996. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1997. {
  1998. return false;
  1999. }
  2000. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  2001. {
  2002. return CBonusSystemNode::ENodeTypes::NONE;
  2003. }
  2004. CPropagatorNodeType::CPropagatorNodeType()
  2005. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  2006. {
  2007. }
  2008. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  2009. : nodeType(NodeType)
  2010. {
  2011. }
  2012. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  2013. {
  2014. return nodeType;
  2015. }
  2016. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  2017. {
  2018. return nodeType == dest->getNodeType();
  2019. }
  2020. CreatureTerrainLimiter::CreatureTerrainLimiter()
  2021. : terrainType(ETerrainId::NATIVE_TERRAIN)
  2022. {
  2023. }
  2024. CreatureTerrainLimiter::CreatureTerrainLimiter(TerrainId terrain):
  2025. terrainType(terrain)
  2026. {
  2027. }
  2028. ILimiter::EDecision CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  2029. {
  2030. const CStack *stack = retrieveStackBattle(&context.node);
  2031. if(stack)
  2032. {
  2033. if (terrainType == ETerrainId::NATIVE_TERRAIN && stack->isOnNativeTerrain())//terrainType not specified = native
  2034. return ILimiter::EDecision::ACCEPT;
  2035. if(terrainType != ETerrainId::NATIVE_TERRAIN && stack->isOnTerrain(terrainType))
  2036. return ILimiter::EDecision::ACCEPT;
  2037. }
  2038. return ILimiter::EDecision::DISCARD;
  2039. //TODO neutral creatues
  2040. }
  2041. std::string CreatureTerrainLimiter::toString() const
  2042. {
  2043. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  2044. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2045. fmt % (terrainType == ETerrainId::NATIVE_TERRAIN ? "native" : terrainName);
  2046. return fmt.str();
  2047. }
  2048. JsonNode CreatureTerrainLimiter::toJsonNode() const
  2049. {
  2050. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2051. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  2052. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2053. root["parameters"].Vector().push_back(JsonUtils::stringNode(terrainName));
  2054. return root;
  2055. }
  2056. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  2057. : faction(creatureFaction)
  2058. {
  2059. }
  2060. CreatureFactionLimiter::CreatureFactionLimiter():
  2061. faction(static_cast<TFaction>(-1))
  2062. {
  2063. }
  2064. ILimiter::EDecision CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  2065. {
  2066. const CCreature *c = retrieveCreature(&context.node);
  2067. auto accept = c && c->faction == faction;
  2068. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD; //drop bonus for non-creatures or non-native residents
  2069. }
  2070. std::string CreatureFactionLimiter::toString() const
  2071. {
  2072. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  2073. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  2074. return fmt.str();
  2075. }
  2076. JsonNode CreatureFactionLimiter::toJsonNode() const
  2077. {
  2078. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2079. root["type"].String() = "CREATURE_FACTION_LIMITER";
  2080. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  2081. return root;
  2082. }
  2083. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  2084. : alignment(-1)
  2085. {
  2086. }
  2087. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  2088. : alignment(Alignment)
  2089. {
  2090. }
  2091. ILimiter::EDecision CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  2092. {
  2093. const auto * c = retrieveCreature(&context.node);
  2094. if(c) {
  2095. if(alignment == EAlignment::GOOD && c->isGood())
  2096. return ILimiter::EDecision::ACCEPT;
  2097. if(alignment == EAlignment::EVIL && c->isEvil())
  2098. return ILimiter::EDecision::ACCEPT;
  2099. if(alignment == EAlignment::NEUTRAL && !c->isEvil() && !c->isGood())
  2100. return ILimiter::EDecision::ACCEPT;
  2101. }
  2102. return ILimiter::EDecision::DISCARD;
  2103. }
  2104. std::string CreatureAlignmentLimiter::toString() const
  2105. {
  2106. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  2107. fmt % EAlignment::names[alignment];
  2108. return fmt.str();
  2109. }
  2110. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  2111. {
  2112. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2113. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  2114. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  2115. return root;
  2116. }
  2117. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  2118. :minRank(Min), maxRank(Max)
  2119. {
  2120. }
  2121. RankRangeLimiter::RankRangeLimiter()
  2122. {
  2123. minRank = maxRank = -1;
  2124. }
  2125. ILimiter::EDecision RankRangeLimiter::limit(const BonusLimitationContext &context) const
  2126. {
  2127. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2128. if(csi)
  2129. {
  2130. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  2131. return ILimiter::EDecision::DISCARD;
  2132. if (csi->getExpRank() > minRank && csi->getExpRank() < maxRank)
  2133. return ILimiter::EDecision::ACCEPT;
  2134. }
  2135. return ILimiter::EDecision::DISCARD;
  2136. }
  2137. ILimiter::EDecision StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  2138. {
  2139. const CStack * s = retrieveStackBattle(&context.node);
  2140. if(s && s->owner == owner)
  2141. return ILimiter::EDecision::ACCEPT;
  2142. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2143. if(csi && csi->armyObj && csi->armyObj->tempOwner == owner)
  2144. return ILimiter::EDecision::ACCEPT;
  2145. return ILimiter::EDecision::DISCARD;
  2146. }
  2147. StackOwnerLimiter::StackOwnerLimiter()
  2148. : owner(-1)
  2149. {
  2150. }
  2151. StackOwnerLimiter::StackOwnerLimiter(const PlayerColor & Owner):
  2152. owner(Owner)
  2153. {
  2154. }
  2155. OppositeSideLimiter::OppositeSideLimiter():
  2156. owner(PlayerColor::CANNOT_DETERMINE)
  2157. {
  2158. }
  2159. OppositeSideLimiter::OppositeSideLimiter(const PlayerColor & Owner):
  2160. owner(Owner)
  2161. {
  2162. }
  2163. ILimiter::EDecision OppositeSideLimiter::limit(const BonusLimitationContext & context) const
  2164. {
  2165. auto contextOwner = CBonusSystemNode::retrieveNodeOwner(& context.node);
  2166. auto decision = (owner == contextOwner || owner == PlayerColor::CANNOT_DETERMINE) ? ILimiter::EDecision::DISCARD : ILimiter::EDecision::ACCEPT;
  2167. return decision;
  2168. }
  2169. // Aggregate/Boolean Limiters
  2170. void AggregateLimiter::add(const TLimiterPtr & limiter)
  2171. {
  2172. if(limiter)
  2173. limiters.push_back(limiter);
  2174. }
  2175. JsonNode AggregateLimiter::toJsonNode() const
  2176. {
  2177. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  2178. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  2179. for(const auto & l : limiters)
  2180. result.Vector().push_back(l->toJsonNode());
  2181. return result;
  2182. }
  2183. const std::string AllOfLimiter::aggregator = "allOf";
  2184. const std::string & AllOfLimiter::getAggregator() const
  2185. {
  2186. return aggregator;
  2187. }
  2188. ILimiter::EDecision AllOfLimiter::limit(const BonusLimitationContext & context) const
  2189. {
  2190. bool wasntSure = false;
  2191. for(const auto & limiter : limiters)
  2192. {
  2193. auto result = limiter->limit(context);
  2194. if(result == ILimiter::EDecision::DISCARD)
  2195. return result;
  2196. if(result == ILimiter::EDecision::NOT_SURE)
  2197. wasntSure = true;
  2198. }
  2199. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::ACCEPT;
  2200. }
  2201. const std::string AnyOfLimiter::aggregator = "anyOf";
  2202. const std::string & AnyOfLimiter::getAggregator() const
  2203. {
  2204. return aggregator;
  2205. }
  2206. ILimiter::EDecision AnyOfLimiter::limit(const BonusLimitationContext & context) const
  2207. {
  2208. bool wasntSure = false;
  2209. for(const auto & limiter : limiters)
  2210. {
  2211. auto result = limiter->limit(context);
  2212. if(result == ILimiter::EDecision::ACCEPT)
  2213. return result;
  2214. if(result == ILimiter::EDecision::NOT_SURE)
  2215. wasntSure = true;
  2216. }
  2217. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::DISCARD;
  2218. }
  2219. const std::string NoneOfLimiter::aggregator = "noneOf";
  2220. const std::string & NoneOfLimiter::getAggregator() const
  2221. {
  2222. return aggregator;
  2223. }
  2224. ILimiter::EDecision NoneOfLimiter::limit(const BonusLimitationContext & context) const
  2225. {
  2226. bool wasntSure = false;
  2227. for(const auto & limiter : limiters)
  2228. {
  2229. auto result = limiter->limit(context);
  2230. if(result == ILimiter::EDecision::ACCEPT)
  2231. return ILimiter::EDecision::DISCARD;
  2232. if(result == ILimiter::EDecision::NOT_SURE)
  2233. wasntSure = true;
  2234. }
  2235. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::ACCEPT;
  2236. }
  2237. // Updaters
  2238. std::shared_ptr<Bonus> Bonus::addUpdater(const TUpdaterPtr & Updater)
  2239. {
  2240. updater = Updater;
  2241. return this->shared_from_this();
  2242. }
  2243. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2244. {
  2245. return b;
  2246. }
  2247. std::string IUpdater::toString() const
  2248. {
  2249. return typeid(*this).name();
  2250. }
  2251. JsonNode IUpdater::toJsonNode() const
  2252. {
  2253. return JsonNode(JsonNode::JsonType::DATA_NULL);
  2254. }
  2255. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  2256. {
  2257. }
  2258. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2259. {
  2260. if(context.getNodeType() == CBonusSystemNode::HERO)
  2261. {
  2262. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  2263. int steps = stepSize ? level / stepSize : level;
  2264. //rounding follows format for HMM3 creature specialty bonus
  2265. int newVal = (valPer20 * steps + 19) / 20;
  2266. //return copy of bonus with updated val
  2267. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2268. newBonus->val = newVal;
  2269. return newBonus;
  2270. }
  2271. return b;
  2272. }
  2273. std::string GrowsWithLevelUpdater::toString() const
  2274. {
  2275. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  2276. }
  2277. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  2278. {
  2279. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2280. root["type"].String() = "GROWS_WITH_LEVEL";
  2281. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  2282. if(stepSize > 1)
  2283. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  2284. return root;
  2285. }
  2286. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2287. {
  2288. if(context.getNodeType() == CBonusSystemNode::HERO)
  2289. {
  2290. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  2291. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2292. newBonus->val *= level;
  2293. return newBonus;
  2294. }
  2295. return b;
  2296. }
  2297. std::string TimesHeroLevelUpdater::toString() const
  2298. {
  2299. return "TimesHeroLevelUpdater";
  2300. }
  2301. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  2302. {
  2303. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  2304. }
  2305. ArmyMovementUpdater::ArmyMovementUpdater():
  2306. base(20),
  2307. divider(3),
  2308. multiplier(10),
  2309. max(700)
  2310. {
  2311. }
  2312. ArmyMovementUpdater::ArmyMovementUpdater(int base, int divider, int multiplier, int max):
  2313. base(base),
  2314. divider(divider),
  2315. multiplier(multiplier),
  2316. max(max)
  2317. {
  2318. }
  2319. std::shared_ptr<Bonus> ArmyMovementUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2320. {
  2321. if(b->type == Bonus::MOVEMENT && context.getNodeType() == CBonusSystemNode::HERO)
  2322. {
  2323. auto speed = static_cast<const CGHeroInstance &>(context).getLowestCreatureSpeed();
  2324. si32 armySpeed = speed * base / divider;
  2325. auto counted = armySpeed * multiplier;
  2326. auto newBonus = std::make_shared<Bonus>(*b);
  2327. newBonus->source = Bonus::ARMY;
  2328. newBonus->val += vstd::amin(counted, max);
  2329. return newBonus;
  2330. }
  2331. if(b->type != Bonus::MOVEMENT)
  2332. logGlobal->error("ArmyMovementUpdater should only be used for MOVEMENT bonus!");
  2333. return b;
  2334. }
  2335. std::string ArmyMovementUpdater::toString() const
  2336. {
  2337. return "ArmyMovementUpdater";
  2338. }
  2339. JsonNode ArmyMovementUpdater::toJsonNode() const
  2340. {
  2341. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2342. root["type"].String() = "ARMY_MOVEMENT";
  2343. root["parameters"].Vector().push_back(JsonUtils::intNode(base));
  2344. root["parameters"].Vector().push_back(JsonUtils::intNode(divider));
  2345. root["parameters"].Vector().push_back(JsonUtils::intNode(multiplier));
  2346. root["parameters"].Vector().push_back(JsonUtils::intNode(max));
  2347. return root;
  2348. }
  2349. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2350. {
  2351. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  2352. {
  2353. int level = dynamic_cast<const CStackInstance &>(context).getLevel();
  2354. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2355. newBonus->val *= level;
  2356. return newBonus;
  2357. }
  2358. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  2359. {
  2360. const auto & stack = dynamic_cast<const CStack &>(context);
  2361. //only update if stack doesn't have an instance (summons, war machines)
  2362. //otherwise we'd end up multiplying twice
  2363. if(stack.base == nullptr)
  2364. {
  2365. int level = stack.type->level;
  2366. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2367. newBonus->val *= level;
  2368. return newBonus;
  2369. }
  2370. }
  2371. return b;
  2372. }
  2373. std::string TimesStackLevelUpdater::toString() const
  2374. {
  2375. return "TimesStackLevelUpdater";
  2376. }
  2377. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2378. {
  2379. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2380. }
  2381. std::string OwnerUpdater::toString() const
  2382. {
  2383. return "OwnerUpdater";
  2384. }
  2385. JsonNode OwnerUpdater::toJsonNode() const
  2386. {
  2387. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  2388. }
  2389. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2390. {
  2391. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  2392. if(owner == PlayerColor::UNFLAGGABLE)
  2393. owner = PlayerColor::NEUTRAL;
  2394. std::shared_ptr<Bonus> updated =
  2395. std::make_shared<Bonus>(static_cast<Bonus::BonusDuration>(b->duration), b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  2396. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  2397. return updated;
  2398. }
  2399. VCMI_LIB_NAMESPACE_END