HeroBonus.cpp 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776
  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::exportBonus(const std::shared_ptr<Bonus> & b)
  1205. {
  1206. if(b->propagator)
  1207. propagateBonus(b, *this);
  1208. else
  1209. bonuses.push_back(b);
  1210. CBonusSystemNode::treeHasChanged();
  1211. }
  1212. void CBonusSystemNode::exportBonuses()
  1213. {
  1214. for(const auto & b : exportedBonuses)
  1215. exportBonus(b);
  1216. }
  1217. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1218. {
  1219. return nodeType;
  1220. }
  1221. const BonusList& CBonusSystemNode::getBonusList() const
  1222. {
  1223. return bonuses;
  1224. }
  1225. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1226. {
  1227. return parents;
  1228. }
  1229. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1230. {
  1231. return children;
  1232. }
  1233. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1234. {
  1235. nodeType = type;
  1236. }
  1237. BonusList & CBonusSystemNode::getExportedBonusList()
  1238. {
  1239. return exportedBonuses;
  1240. }
  1241. const BonusList & CBonusSystemNode::getExportedBonusList() const
  1242. {
  1243. return exportedBonuses;
  1244. }
  1245. const std::string& CBonusSystemNode::getDescription() const
  1246. {
  1247. return description;
  1248. }
  1249. void CBonusSystemNode::setDescription(const std::string &description)
  1250. {
  1251. this->description = description;
  1252. }
  1253. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1254. {
  1255. assert(&allBonuses != &out); //todo should it work in-place?
  1256. BonusList undecided = allBonuses;
  1257. BonusList & accepted = out;
  1258. while(true)
  1259. {
  1260. int undecidedCount = static_cast<int>(undecided.size());
  1261. for(int i = 0; i < undecided.size(); i++)
  1262. {
  1263. auto b = undecided[i];
  1264. BonusLimitationContext context = {b, *this, out, undecided};
  1265. auto decision = b->limiter ? b->limiter->limit(context) : ILimiter::EDecision::ACCEPT; //bonuses without limiters will be accepted by default
  1266. if(decision == ILimiter::EDecision::DISCARD)
  1267. {
  1268. undecided.erase(i);
  1269. i--; continue;
  1270. }
  1271. else if(decision == ILimiter::EDecision::ACCEPT)
  1272. {
  1273. accepted.push_back(b);
  1274. undecided.erase(i);
  1275. i--; continue;
  1276. }
  1277. else
  1278. assert(decision == ILimiter::EDecision::NOT_SURE);
  1279. }
  1280. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1281. return;
  1282. }
  1283. }
  1284. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1285. {
  1286. auto ret = std::make_shared<BonusList>();
  1287. limitBonuses(allBonuses, *ret);
  1288. return ret;
  1289. }
  1290. void CBonusSystemNode::treeHasChanged()
  1291. {
  1292. treeChanged++;
  1293. }
  1294. int64_t CBonusSystemNode::getTreeVersion() const
  1295. {
  1296. return treeChanged;
  1297. }
  1298. std::string Bonus::Description(boost::optional<si32> customValue) const
  1299. {
  1300. std::ostringstream str;
  1301. if(description.empty())
  1302. {
  1303. if(stacking.empty() || stacking == "ALWAYS")
  1304. {
  1305. switch(source)
  1306. {
  1307. case ARTIFACT:
  1308. str << ArtifactID(sid).toArtifact(VLC->artifacts())->getNameTranslated();
  1309. break;
  1310. case SPELL_EFFECT:
  1311. str << SpellID(sid).toSpell(VLC->spells())->getNameTranslated();
  1312. break;
  1313. case CREATURE_ABILITY:
  1314. str << VLC->creh->objects[sid]->getNamePluralTranslated();
  1315. break;
  1316. case SECONDARY_SKILL:
  1317. str << VLC->skillh->getByIndex(sid)->getNameTranslated();
  1318. break;
  1319. case HERO_SPECIAL:
  1320. str << VLC->heroh->objects[sid]->getNameTranslated();
  1321. break;
  1322. default:
  1323. //todo: handle all possible sources
  1324. str << "Unknown";
  1325. break;
  1326. }
  1327. }
  1328. else
  1329. str << stacking;
  1330. }
  1331. else
  1332. {
  1333. str << description;
  1334. }
  1335. if(auto value = customValue.value_or(val))
  1336. str << " " << std::showpos << value;
  1337. return str.str();
  1338. }
  1339. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1340. {
  1341. switch(type)
  1342. {
  1343. case Bonus::PRIMARY_SKILL:
  1344. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1345. case Bonus::SPECIAL_SPELL_LEV:
  1346. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1347. case Bonus::SPELL:
  1348. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1349. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1350. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1351. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "spell", SpellID::encode(subtype)));
  1352. case Bonus::IMPROVED_NECROMANCY:
  1353. case Bonus::SPECIAL_UPGRADE:
  1354. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(subtype)));
  1355. case Bonus::GENERATE_RESOURCE:
  1356. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1357. default:
  1358. return JsonUtils::intNode(subtype);
  1359. }
  1360. }
  1361. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1362. {
  1363. switch(type)
  1364. {
  1365. case Bonus::SPECIAL_UPGRADE:
  1366. return JsonUtils::stringNode(CModHandler::makeFullIdentifier("", "creature", CreatureID::encode(addInfo[0])));
  1367. default:
  1368. return addInfo.toJsonNode();
  1369. }
  1370. }
  1371. JsonNode durationToJson(ui16 duration)
  1372. {
  1373. std::vector<std::string> durationNames;
  1374. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1375. {
  1376. if(duration & durBit)
  1377. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1378. }
  1379. if(durationNames.size() == 1)
  1380. {
  1381. return JsonUtils::stringNode(durationNames[0]);
  1382. }
  1383. else
  1384. {
  1385. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1386. for(const std::string & dur : durationNames)
  1387. node.Vector().push_back(JsonUtils::stringNode(dur));
  1388. return node;
  1389. }
  1390. }
  1391. JsonNode Bonus::toJsonNode() const
  1392. {
  1393. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1394. // only add values that might reasonably be found in config files
  1395. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1396. if(subtype != -1)
  1397. root["subtype"] = subtypeToJson(type, subtype);
  1398. if(additionalInfo != CAddInfo::NONE)
  1399. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1400. if(duration != 0)
  1401. {
  1402. JsonNode durationVec(JsonNode::JsonType::DATA_VECTOR);
  1403. for(const auto & kv : bonusDurationMap)
  1404. {
  1405. if(duration & kv.second)
  1406. durationVec.Vector().push_back(JsonUtils::stringNode(kv.first));
  1407. }
  1408. root["duration"] = durationVec;
  1409. }
  1410. if(turnsRemain != 0)
  1411. root["turns"].Integer() = turnsRemain;
  1412. if(source != OTHER)
  1413. root["sourceType"].String() = vstd::findKey(bonusSourceMap, source);
  1414. if(targetSourceType != OTHER)
  1415. root["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetSourceType);
  1416. if(sid != 0)
  1417. root["sourceID"].Integer() = sid;
  1418. if(val != 0)
  1419. root["val"].Integer() = val;
  1420. if(valType != ADDITIVE_VALUE)
  1421. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1422. if(!stacking.empty())
  1423. root["stacking"].String() = stacking;
  1424. if(!description.empty())
  1425. root["description"].String() = description;
  1426. if(effectRange != NO_LIMIT)
  1427. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1428. if(duration != PERMANENT)
  1429. root["duration"] = durationToJson(duration);
  1430. if(turnsRemain)
  1431. root["turns"].Integer() = turnsRemain;
  1432. if(limiter)
  1433. root["limiters"] = limiter->toJsonNode();
  1434. if(updater)
  1435. root["updater"] = updater->toJsonNode();
  1436. if(propagator)
  1437. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1438. return root;
  1439. }
  1440. std::string Bonus::nameForBonus() const
  1441. {
  1442. switch(type)
  1443. {
  1444. case Bonus::PRIMARY_SKILL:
  1445. return PrimarySkill::names[subtype];
  1446. case Bonus::SPECIAL_SPELL_LEV:
  1447. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1448. case Bonus::SPELL:
  1449. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1450. case Bonus::SPECIAL_ADD_VALUE_ENCHANT:
  1451. case Bonus::SPECIAL_FIXED_VALUE_ENCHANT:
  1452. return VLC->spells()->getByIndex(subtype)->getJsonKey();
  1453. case Bonus::SPECIAL_UPGRADE:
  1454. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1455. case Bonus::GENERATE_RESOURCE:
  1456. return GameConstants::RESOURCE_NAMES[subtype];
  1457. case Bonus::STACKS_SPEED:
  1458. return "speed";
  1459. default:
  1460. return vstd::findKey(bonusNameMap, type);
  1461. }
  1462. }
  1463. BonusParams::BonusParams(std::string deprecatedTypeStr, std::string deprecatedSubtypeStr, int deprecatedSubtype):
  1464. isConverted(true)
  1465. {
  1466. if(deprecatedTypeStr == "SECONDARY_SKILL_PREMY" || deprecatedTypeStr == "SPECIAL_SECONDARY_SKILL")
  1467. {
  1468. if(deprecatedSubtype == SecondarySkill::PATHFINDING || deprecatedSubtypeStr == "skill.pathfinding")
  1469. type = Bonus::ROUGH_TERRAIN_DISCOUNT;
  1470. else if(deprecatedSubtype == SecondarySkill::DIPLOMACY || deprecatedSubtypeStr == "skill.diplomacy")
  1471. type = Bonus::WANDERING_CREATURES_JOIN_BONUS;
  1472. else if(deprecatedSubtype == SecondarySkill::WISDOM || deprecatedSubtypeStr == "skill.wisdom")
  1473. type = Bonus::MAX_LEARNABLE_SPELL_LEVEL;
  1474. else if(deprecatedSubtype == SecondarySkill::MYSTICISM || deprecatedSubtypeStr == "skill.mysticism")
  1475. type = Bonus::MANA_REGENERATION;
  1476. else if(deprecatedSubtype == SecondarySkill::NECROMANCY || deprecatedSubtypeStr == "skill.necromancy")
  1477. type = Bonus::UNDEAD_RAISE_PERCENTAGE;
  1478. else if(deprecatedSubtype == SecondarySkill::LEARNING || deprecatedSubtypeStr == "skill.learning")
  1479. type = Bonus::HERO_EXPERIENCE_GAIN_PERCENT;
  1480. else if(deprecatedSubtype == SecondarySkill::RESISTANCE || deprecatedSubtypeStr == "skill.resistance")
  1481. type = Bonus::MAGIC_RESISTANCE;
  1482. else if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1483. type = Bonus::LEARN_BATTLE_SPELL_CHANCE;
  1484. else if(deprecatedSubtype == SecondarySkill::SCOUTING || deprecatedSubtypeStr == "skill.scouting")
  1485. type = Bonus::SIGHT_RADIUS;
  1486. else if(deprecatedSubtype == SecondarySkill::INTELLIGENCE || deprecatedSubtypeStr == "skill.intelligence")
  1487. {
  1488. type = Bonus::MANA_PER_KNOWLEDGE;
  1489. valueType = Bonus::PERCENT_TO_BASE;
  1490. valueTypeRelevant = true;
  1491. }
  1492. else if(deprecatedSubtype == SecondarySkill::SORCERY || deprecatedSubtypeStr == "skill.sorcery")
  1493. type = Bonus::SPELL_DAMAGE;
  1494. else if(deprecatedSubtype == SecondarySkill::SCHOLAR || deprecatedSubtypeStr == "skill.scholar")
  1495. type = Bonus::LEARN_MEETING_SPELL_LIMIT;
  1496. else if(deprecatedSubtype == SecondarySkill::ARCHERY|| deprecatedSubtypeStr == "skill.archery")
  1497. {
  1498. subtype = 1;
  1499. subtypeRelevant = true;
  1500. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1501. }
  1502. else if(deprecatedSubtype == SecondarySkill::OFFENCE || deprecatedSubtypeStr == "skill.offence")
  1503. {
  1504. subtype = 0;
  1505. subtypeRelevant = true;
  1506. type = Bonus::PERCENTAGE_DAMAGE_BOOST;
  1507. }
  1508. else if(deprecatedSubtype == SecondarySkill::ARMORER || deprecatedSubtypeStr == "skill.armorer")
  1509. {
  1510. subtype = -1;
  1511. subtypeRelevant = true;
  1512. type = Bonus::GENERAL_DAMAGE_REDUCTION;
  1513. }
  1514. else if(deprecatedSubtype == SecondarySkill::NAVIGATION || deprecatedSubtypeStr == "skill.navigation")
  1515. {
  1516. subtype = 0;
  1517. subtypeRelevant = true;
  1518. valueType = Bonus::PERCENT_TO_BASE;
  1519. valueTypeRelevant = true;
  1520. type = Bonus::MOVEMENT;
  1521. }
  1522. else if(deprecatedSubtype == SecondarySkill::LOGISTICS || deprecatedSubtypeStr == "skill.logistics")
  1523. {
  1524. subtype = 0;
  1525. subtypeRelevant = true;
  1526. valueType = Bonus::PERCENT_TO_BASE;
  1527. valueTypeRelevant = true;
  1528. type = Bonus::MOVEMENT;
  1529. }
  1530. else if(deprecatedSubtype == SecondarySkill::ESTATES || deprecatedSubtypeStr == "skill.estates")
  1531. {
  1532. type = Bonus::GENERATE_RESOURCE;
  1533. subtype = GameResID(EGameResID::GOLD);
  1534. subtypeRelevant = true;
  1535. }
  1536. else if(deprecatedSubtype == SecondarySkill::AIR_MAGIC || deprecatedSubtypeStr == "skill.airMagic")
  1537. {
  1538. type = Bonus::MAGIC_SCHOOL_SKILL;
  1539. subtypeRelevant = true;
  1540. subtype = 4;
  1541. }
  1542. else if(deprecatedSubtype == SecondarySkill::WATER_MAGIC || deprecatedSubtypeStr == "skill.waterMagic")
  1543. {
  1544. type = Bonus::MAGIC_SCHOOL_SKILL;
  1545. subtypeRelevant = true;
  1546. subtype = 1;
  1547. }
  1548. else if(deprecatedSubtype == SecondarySkill::FIRE_MAGIC || deprecatedSubtypeStr == "skill.fireMagic")
  1549. {
  1550. type = Bonus::MAGIC_SCHOOL_SKILL;
  1551. subtypeRelevant = true;
  1552. subtype = 2;
  1553. }
  1554. else if(deprecatedSubtype == SecondarySkill::EARTH_MAGIC || deprecatedSubtypeStr == "skill.earthMagic")
  1555. {
  1556. type = Bonus::MAGIC_SCHOOL_SKILL;
  1557. subtypeRelevant = true;
  1558. subtype = 8;
  1559. }
  1560. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1561. {
  1562. type = Bonus::BONUS_DAMAGE_CHANCE;
  1563. subtypeRelevant = true;
  1564. subtypeStr = "core:creature.ballista";
  1565. }
  1566. else if (deprecatedSubtype == SecondarySkill::FIRST_AID || deprecatedSubtypeStr == "skill.firstAid")
  1567. {
  1568. type = Bonus::SPECIFIC_SPELL_POWER;
  1569. subtypeRelevant = true;
  1570. subtypeStr = "core:spell.firstAid";
  1571. }
  1572. else if (deprecatedSubtype == SecondarySkill::BALLISTICS || deprecatedSubtypeStr == "skill.ballistics")
  1573. {
  1574. type = Bonus::CATAPULT_EXTRA_SHOTS;
  1575. subtypeRelevant = true;
  1576. subtypeStr = "core:spell.catapultShot";
  1577. }
  1578. else
  1579. isConverted = false;
  1580. }
  1581. else if (deprecatedTypeStr == "SECONDARY_SKILL_VAL2")
  1582. {
  1583. if(deprecatedSubtype == SecondarySkill::EAGLE_EYE || deprecatedSubtypeStr == "skill.eagleEye")
  1584. type = Bonus::LEARN_BATTLE_SPELL_LEVEL_LIMIT;
  1585. else if (deprecatedSubtype == SecondarySkill::ARTILLERY || deprecatedSubtypeStr == "skill.artillery")
  1586. {
  1587. type = Bonus::HERO_GRANTS_ATTACKS;
  1588. subtypeRelevant = true;
  1589. subtypeStr = "core:creature.ballista";
  1590. }
  1591. else
  1592. isConverted = false;
  1593. }
  1594. else if (deprecatedTypeStr == "SEA_MOVEMENT")
  1595. {
  1596. subtype = 0;
  1597. subtypeRelevant = true;
  1598. valueType = Bonus::ADDITIVE_VALUE;
  1599. valueTypeRelevant = true;
  1600. type = Bonus::MOVEMENT;
  1601. }
  1602. else if (deprecatedTypeStr == "LAND_MOVEMENT")
  1603. {
  1604. subtype = 1;
  1605. subtypeRelevant = true;
  1606. valueType = Bonus::ADDITIVE_VALUE;
  1607. valueTypeRelevant = true;
  1608. type = Bonus::MOVEMENT;
  1609. }
  1610. else if (deprecatedTypeStr == "MAXED_SPELL")
  1611. {
  1612. type = Bonus::SPELL;
  1613. subtypeStr = deprecatedSubtypeStr;
  1614. subtypeRelevant = true;
  1615. valueType = Bonus::INDEPENDENT_MAX;
  1616. valueTypeRelevant = true;
  1617. val = 3;
  1618. valRelevant = true;
  1619. }
  1620. else if (deprecatedTypeStr == "FULL_HP_REGENERATION")
  1621. {
  1622. type = Bonus::HP_REGENERATION;
  1623. val = 100000; //very high value to always chose stack health
  1624. valRelevant = true;
  1625. }
  1626. else if (deprecatedTypeStr == "KING1")
  1627. {
  1628. type = Bonus::KING;
  1629. val = 0;
  1630. valRelevant = true;
  1631. }
  1632. else if (deprecatedTypeStr == "KING2")
  1633. {
  1634. type = Bonus::KING;
  1635. val = 2;
  1636. valRelevant = true;
  1637. }
  1638. else if (deprecatedTypeStr == "KING3")
  1639. {
  1640. type = Bonus::KING;
  1641. val = 3;
  1642. valRelevant = true;
  1643. }
  1644. else if (deprecatedTypeStr == "SIGHT_RADIOUS")
  1645. type = Bonus::SIGHT_RADIUS;
  1646. else if (deprecatedTypeStr == "SELF_MORALE")
  1647. {
  1648. type = Bonus::MORALE;
  1649. val = 1;
  1650. valRelevant = true;
  1651. valueType = Bonus::INDEPENDENT_MAX;
  1652. valueTypeRelevant = true;
  1653. }
  1654. else if (deprecatedTypeStr == "SELF_LUCK")
  1655. {
  1656. type = Bonus::LUCK;
  1657. val = 1;
  1658. valRelevant = true;
  1659. valueType = Bonus::INDEPENDENT_MAX;
  1660. valueTypeRelevant = true;
  1661. }
  1662. else
  1663. isConverted = false;
  1664. }
  1665. const JsonNode & BonusParams::toJson()
  1666. {
  1667. assert(isConverted);
  1668. if(ret.isNull())
  1669. {
  1670. ret["type"].String() = vstd::findKey(bonusNameMap, type);
  1671. if(subtypeRelevant && !subtypeStr.empty())
  1672. ret["subtype"].String() = subtypeStr;
  1673. else if(subtypeRelevant)
  1674. ret["subtype"].Integer() = subtype;
  1675. if(valueTypeRelevant)
  1676. ret["valueType"].String() = vstd::findKey(bonusValueMap, valueType);
  1677. if(valRelevant)
  1678. ret["val"].Float() = val;
  1679. if(targetTypeRelevant)
  1680. ret["targetSourceType"].String() = vstd::findKey(bonusSourceMap, targetType);
  1681. jsonCreated = true;
  1682. }
  1683. return ret;
  1684. };
  1685. CSelector BonusParams::toSelector()
  1686. {
  1687. assert(isConverted);
  1688. if(subtypeRelevant && !subtypeStr.empty())
  1689. JsonUtils::resolveIdentifier(subtype, toJson(), "subtype");
  1690. auto ret = Selector::type()(type);
  1691. if(subtypeRelevant)
  1692. ret = ret.And(Selector::subtype()(subtype));
  1693. if(valueTypeRelevant)
  1694. ret = ret.And(Selector::valueType(valueType));
  1695. if(targetTypeRelevant)
  1696. ret = ret.And(Selector::targetSourceType()(targetType));
  1697. return ret;
  1698. }
  1699. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype):
  1700. duration(static_cast<ui16>(Duration)),
  1701. type(Type),
  1702. subtype(Subtype),
  1703. source(Src),
  1704. val(Val),
  1705. sid(ID),
  1706. description(std::move(Desc))
  1707. {
  1708. boost::algorithm::trim(description);
  1709. targetSourceType = OTHER;
  1710. }
  1711. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType):
  1712. duration(static_cast<ui16>(Duration)),
  1713. type(Type),
  1714. subtype(Subtype),
  1715. source(Src),
  1716. val(Val),
  1717. sid(ID),
  1718. valType(ValType)
  1719. {
  1720. turnsRemain = 0;
  1721. effectRange = NO_LIMIT;
  1722. targetSourceType = OTHER;
  1723. }
  1724. std::shared_ptr<Bonus> Bonus::addPropagator(const TPropagatorPtr & Propagator)
  1725. {
  1726. propagator = Propagator;
  1727. return this->shared_from_this();
  1728. }
  1729. namespace Selector
  1730. {
  1731. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1732. {
  1733. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1734. return stype;
  1735. }
  1736. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1737. {
  1738. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1739. return ssubtype;
  1740. }
  1741. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1742. {
  1743. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1744. return sinfo;
  1745. }
  1746. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1747. {
  1748. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1749. return ssourceType;
  1750. }
  1751. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & targetSourceType()
  1752. {
  1753. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::targetSourceType);
  1754. return ssourceType;
  1755. }
  1756. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1757. {
  1758. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1759. return seffectRange;
  1760. }
  1761. DLL_LINKAGE CWillLastTurns turns;
  1762. DLL_LINKAGE CWillLastDays days;
  1763. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1764. {
  1765. return type()(Type).And(subtype()(Subtype));
  1766. }
  1767. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, const CAddInfo & info)
  1768. {
  1769. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1770. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1771. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1772. }
  1773. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1774. {
  1775. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1776. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1777. }
  1778. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1779. {
  1780. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1781. }
  1782. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1783. {
  1784. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1785. }
  1786. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1787. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1788. }
  1789. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1790. {
  1791. switch(node->getNodeType())
  1792. {
  1793. case CBonusSystemNode::CREATURE:
  1794. return (dynamic_cast<const CCreature *>(node));
  1795. case CBonusSystemNode::STACK_BATTLE:
  1796. return (dynamic_cast<const CStack *>(node))->type;
  1797. default:
  1798. const CStackInstance * csi = retrieveStackInstance(node);
  1799. if(csi)
  1800. return csi->type;
  1801. return nullptr;
  1802. }
  1803. }
  1804. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1805. {
  1806. for (ui32 i = 0; i < bonusList.size(); i++)
  1807. {
  1808. const auto & b = bonusList[i];
  1809. out << "Bonus " << i << "\n" << *b << std::endl;
  1810. }
  1811. return out;
  1812. }
  1813. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1814. {
  1815. for(const auto & i : bonusNameMap)
  1816. if(i.second == bonus.type)
  1817. out << "\tType: " << i.first << " \t";
  1818. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1819. printField(val);
  1820. printField(subtype);
  1821. printField(duration);
  1822. printField(source);
  1823. printField(sid);
  1824. if(bonus.additionalInfo != CAddInfo::NONE)
  1825. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1826. printField(turnsRemain);
  1827. printField(valType);
  1828. if(!bonus.stacking.empty())
  1829. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1830. printField(effectRange);
  1831. #undef printField
  1832. if(bonus.limiter)
  1833. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1834. if(bonus.updater)
  1835. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1836. return out;
  1837. }
  1838. std::shared_ptr<Bonus> Bonus::addLimiter(const TLimiterPtr & Limiter)
  1839. {
  1840. if (limiter)
  1841. {
  1842. //If we already have limiter list, retrieve it
  1843. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1844. if(!limiterList)
  1845. {
  1846. //Create a new limiter list with old limiter and the new one will be pushed later
  1847. limiterList = std::make_shared<AllOfLimiter>();
  1848. limiterList->add(limiter);
  1849. limiter = limiterList;
  1850. }
  1851. limiterList->add(Limiter);
  1852. }
  1853. else
  1854. {
  1855. limiter = Limiter;
  1856. }
  1857. return this->shared_from_this();
  1858. }
  1859. ILimiter::EDecision ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1860. {
  1861. return ILimiter::EDecision::ACCEPT;
  1862. }
  1863. std::string ILimiter::toString() const
  1864. {
  1865. return typeid(*this).name();
  1866. }
  1867. JsonNode ILimiter::toJsonNode() const
  1868. {
  1869. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1870. root["type"].String() = toString();
  1871. return root;
  1872. }
  1873. ILimiter::EDecision CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1874. {
  1875. const CCreature *c = retrieveCreature(&context.node);
  1876. if(!c)
  1877. return ILimiter::EDecision::DISCARD;
  1878. auto accept = c->getId() == creature->getId() || (includeUpgrades && creature->isMyUpgrade(c));
  1879. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  1880. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1881. }
  1882. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature & creature_, bool IncludeUpgrades)
  1883. : creature(&creature_), includeUpgrades(IncludeUpgrades)
  1884. {
  1885. }
  1886. void CCreatureTypeLimiter::setCreature(const CreatureID & id)
  1887. {
  1888. creature = VLC->creh->objects[id];
  1889. }
  1890. std::string CCreatureTypeLimiter::toString() const
  1891. {
  1892. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1893. fmt % creature->getJsonKey() % (includeUpgrades ? "true" : "false");
  1894. return fmt.str();
  1895. }
  1896. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1897. {
  1898. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1899. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1900. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->getJsonKey()));
  1901. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1902. return root;
  1903. }
  1904. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1905. : type(bonus), subtype(0), isSubtypeRelevant(false), isSourceRelevant(false), isSourceIDRelevant(false)
  1906. {
  1907. }
  1908. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1909. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), isSourceRelevant(false), isSourceIDRelevant(false)
  1910. {
  1911. }
  1912. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, Bonus::BonusSource src)
  1913. : type(bonus), source(src), isSubtypeRelevant(false), isSourceRelevant(true), isSourceIDRelevant(false)
  1914. {
  1915. }
  1916. HasAnotherBonusLimiter::HasAnotherBonusLimiter(Bonus::BonusType bonus, TBonusSubtype _subtype, Bonus::BonusSource src)
  1917. : type(bonus), subtype(_subtype), isSubtypeRelevant(true), source(src), isSourceRelevant(true), isSourceIDRelevant(false)
  1918. {
  1919. }
  1920. ILimiter::EDecision HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1921. {
  1922. //TODO: proper selector config with parsing of JSON
  1923. auto mySelector = Selector::type()(type);
  1924. if(isSubtypeRelevant)
  1925. mySelector = mySelector.And(Selector::subtype()(subtype));
  1926. if(isSourceRelevant && isSourceIDRelevant)
  1927. mySelector = mySelector.And(Selector::source(source, sid));
  1928. else if (isSourceRelevant)
  1929. mySelector = mySelector.And(Selector::sourceTypeSel(source));
  1930. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1931. if(context.alreadyAccepted.getFirst(mySelector))
  1932. return ILimiter::EDecision::ACCEPT;
  1933. //if there are no matching bonuses pending, we can (and must) reject right away
  1934. if(!context.stillUndecided.getFirst(mySelector))
  1935. return ILimiter::EDecision::DISCARD;
  1936. //do not accept for now but it may change if more bonuses gets included
  1937. return ILimiter::EDecision::NOT_SURE;
  1938. }
  1939. std::string HasAnotherBonusLimiter::toString() const
  1940. {
  1941. std::string typeName = vstd::findKey(bonusNameMap, type);
  1942. if(isSubtypeRelevant)
  1943. {
  1944. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1945. fmt % typeName % subtype;
  1946. return fmt.str();
  1947. }
  1948. else
  1949. {
  1950. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1951. fmt % typeName;
  1952. return fmt.str();
  1953. }
  1954. }
  1955. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1956. {
  1957. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1958. std::string typeName = vstd::findKey(bonusNameMap, type);
  1959. auto sourceTypeName = vstd::findKey(bonusSourceMap, source);
  1960. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1961. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1962. if(isSubtypeRelevant)
  1963. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1964. if(isSourceRelevant)
  1965. root["parameters"].Vector().push_back(JsonUtils::stringNode(sourceTypeName));
  1966. return root;
  1967. }
  1968. ILimiter::EDecision UnitOnHexLimiter::limit(const BonusLimitationContext &context) const
  1969. {
  1970. const auto * stack = retrieveStackBattle(&context.node);
  1971. if(!stack)
  1972. return ILimiter::EDecision::DISCARD;
  1973. auto accept = false;
  1974. for (const auto & hex : stack->getHexes())
  1975. accept |= !!applicableHexes.count(hex);
  1976. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD;
  1977. }
  1978. UnitOnHexLimiter::UnitOnHexLimiter(const std::set<BattleHex> & applicableHexes):
  1979. applicableHexes(applicableHexes)
  1980. {
  1981. }
  1982. JsonNode UnitOnHexLimiter::toJsonNode() const
  1983. {
  1984. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1985. root["type"].String() = "UNIT_ON_HEXES";
  1986. for(const auto & hex : applicableHexes)
  1987. root["parameters"].Vector().push_back(JsonUtils::intNode(hex));
  1988. return root;
  1989. }
  1990. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1991. {
  1992. return false;
  1993. }
  1994. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1995. {
  1996. return CBonusSystemNode::ENodeTypes::NONE;
  1997. }
  1998. CPropagatorNodeType::CPropagatorNodeType()
  1999. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  2000. {
  2001. }
  2002. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  2003. : nodeType(NodeType)
  2004. {
  2005. }
  2006. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  2007. {
  2008. return nodeType;
  2009. }
  2010. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  2011. {
  2012. return nodeType == dest->getNodeType();
  2013. }
  2014. CreatureTerrainLimiter::CreatureTerrainLimiter()
  2015. : terrainType(ETerrainId::NATIVE_TERRAIN)
  2016. {
  2017. }
  2018. CreatureTerrainLimiter::CreatureTerrainLimiter(TerrainId terrain):
  2019. terrainType(terrain)
  2020. {
  2021. }
  2022. ILimiter::EDecision CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  2023. {
  2024. const CStack *stack = retrieveStackBattle(&context.node);
  2025. if(stack)
  2026. {
  2027. if (terrainType == ETerrainId::NATIVE_TERRAIN && stack->isOnNativeTerrain())//terrainType not specified = native
  2028. return ILimiter::EDecision::ACCEPT;
  2029. if(terrainType != ETerrainId::NATIVE_TERRAIN && stack->isOnTerrain(terrainType))
  2030. return ILimiter::EDecision::ACCEPT;
  2031. }
  2032. return ILimiter::EDecision::DISCARD;
  2033. //TODO neutral creatues
  2034. }
  2035. std::string CreatureTerrainLimiter::toString() const
  2036. {
  2037. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  2038. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2039. fmt % (terrainType == ETerrainId::NATIVE_TERRAIN ? "native" : terrainName);
  2040. return fmt.str();
  2041. }
  2042. JsonNode CreatureTerrainLimiter::toJsonNode() const
  2043. {
  2044. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2045. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  2046. auto terrainName = VLC->terrainTypeHandler->getById(terrainType)->getJsonKey();
  2047. root["parameters"].Vector().push_back(JsonUtils::stringNode(terrainName));
  2048. return root;
  2049. }
  2050. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  2051. : faction(creatureFaction)
  2052. {
  2053. }
  2054. CreatureFactionLimiter::CreatureFactionLimiter():
  2055. faction(static_cast<TFaction>(-1))
  2056. {
  2057. }
  2058. ILimiter::EDecision CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  2059. {
  2060. const CCreature *c = retrieveCreature(&context.node);
  2061. auto accept = c && c->getFactionIndex() == faction;
  2062. return accept ? ILimiter::EDecision::ACCEPT : ILimiter::EDecision::DISCARD; //drop bonus for non-creatures or non-native residents
  2063. }
  2064. std::string CreatureFactionLimiter::toString() const
  2065. {
  2066. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  2067. fmt % VLC->factions()->getByIndex(faction)->getJsonKey();
  2068. return fmt.str();
  2069. }
  2070. JsonNode CreatureFactionLimiter::toJsonNode() const
  2071. {
  2072. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2073. root["type"].String() = "CREATURE_FACTION_LIMITER";
  2074. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->factions()->getByIndex(faction)->getJsonKey()));
  2075. return root;
  2076. }
  2077. CreatureAlignmentLimiter::CreatureAlignmentLimiter(EAlignment Alignment)
  2078. : alignment(Alignment)
  2079. {
  2080. }
  2081. ILimiter::EDecision CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  2082. {
  2083. const auto * c = retrieveCreature(&context.node);
  2084. if(c) {
  2085. if(alignment == EAlignment::GOOD && c->isGood())
  2086. return ILimiter::EDecision::ACCEPT;
  2087. if(alignment == EAlignment::EVIL && c->isEvil())
  2088. return ILimiter::EDecision::ACCEPT;
  2089. if(alignment == EAlignment::NEUTRAL && !c->isEvil() && !c->isGood())
  2090. return ILimiter::EDecision::ACCEPT;
  2091. }
  2092. return ILimiter::EDecision::DISCARD;
  2093. }
  2094. std::string CreatureAlignmentLimiter::toString() const
  2095. {
  2096. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  2097. fmt % GameConstants::ALIGNMENT_NAMES[vstd::to_underlying(alignment)];
  2098. return fmt.str();
  2099. }
  2100. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  2101. {
  2102. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2103. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  2104. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::ALIGNMENT_NAMES[vstd::to_underlying(alignment)]));
  2105. return root;
  2106. }
  2107. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  2108. :minRank(Min), maxRank(Max)
  2109. {
  2110. }
  2111. RankRangeLimiter::RankRangeLimiter()
  2112. {
  2113. minRank = maxRank = -1;
  2114. }
  2115. ILimiter::EDecision RankRangeLimiter::limit(const BonusLimitationContext &context) const
  2116. {
  2117. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2118. if(csi)
  2119. {
  2120. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  2121. return ILimiter::EDecision::DISCARD;
  2122. if (csi->getExpRank() > minRank && csi->getExpRank() < maxRank)
  2123. return ILimiter::EDecision::ACCEPT;
  2124. }
  2125. return ILimiter::EDecision::DISCARD;
  2126. }
  2127. ILimiter::EDecision StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  2128. {
  2129. const CStack * s = retrieveStackBattle(&context.node);
  2130. if(s && s->owner == owner)
  2131. return ILimiter::EDecision::ACCEPT;
  2132. const CStackInstance * csi = retrieveStackInstance(&context.node);
  2133. if(csi && csi->armyObj && csi->armyObj->tempOwner == owner)
  2134. return ILimiter::EDecision::ACCEPT;
  2135. return ILimiter::EDecision::DISCARD;
  2136. }
  2137. StackOwnerLimiter::StackOwnerLimiter()
  2138. : owner(-1)
  2139. {
  2140. }
  2141. StackOwnerLimiter::StackOwnerLimiter(const PlayerColor & Owner):
  2142. owner(Owner)
  2143. {
  2144. }
  2145. OppositeSideLimiter::OppositeSideLimiter():
  2146. owner(PlayerColor::CANNOT_DETERMINE)
  2147. {
  2148. }
  2149. OppositeSideLimiter::OppositeSideLimiter(const PlayerColor & Owner):
  2150. owner(Owner)
  2151. {
  2152. }
  2153. ILimiter::EDecision OppositeSideLimiter::limit(const BonusLimitationContext & context) const
  2154. {
  2155. auto contextOwner = CBonusSystemNode::retrieveNodeOwner(& context.node);
  2156. auto decision = (owner == contextOwner || owner == PlayerColor::CANNOT_DETERMINE) ? ILimiter::EDecision::DISCARD : ILimiter::EDecision::ACCEPT;
  2157. return decision;
  2158. }
  2159. // Aggregate/Boolean Limiters
  2160. void AggregateLimiter::add(const TLimiterPtr & limiter)
  2161. {
  2162. if(limiter)
  2163. limiters.push_back(limiter);
  2164. }
  2165. JsonNode AggregateLimiter::toJsonNode() const
  2166. {
  2167. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  2168. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  2169. for(const auto & l : limiters)
  2170. result.Vector().push_back(l->toJsonNode());
  2171. return result;
  2172. }
  2173. const std::string AllOfLimiter::aggregator = "allOf";
  2174. const std::string & AllOfLimiter::getAggregator() const
  2175. {
  2176. return aggregator;
  2177. }
  2178. ILimiter::EDecision AllOfLimiter::limit(const BonusLimitationContext & context) const
  2179. {
  2180. bool wasntSure = false;
  2181. for(const auto & limiter : limiters)
  2182. {
  2183. auto result = limiter->limit(context);
  2184. if(result == ILimiter::EDecision::DISCARD)
  2185. return result;
  2186. if(result == ILimiter::EDecision::NOT_SURE)
  2187. wasntSure = true;
  2188. }
  2189. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::ACCEPT;
  2190. }
  2191. const std::string AnyOfLimiter::aggregator = "anyOf";
  2192. const std::string & AnyOfLimiter::getAggregator() const
  2193. {
  2194. return aggregator;
  2195. }
  2196. ILimiter::EDecision AnyOfLimiter::limit(const BonusLimitationContext & context) const
  2197. {
  2198. bool wasntSure = false;
  2199. for(const auto & limiter : limiters)
  2200. {
  2201. auto result = limiter->limit(context);
  2202. if(result == ILimiter::EDecision::ACCEPT)
  2203. return result;
  2204. if(result == ILimiter::EDecision::NOT_SURE)
  2205. wasntSure = true;
  2206. }
  2207. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::DISCARD;
  2208. }
  2209. const std::string NoneOfLimiter::aggregator = "noneOf";
  2210. const std::string & NoneOfLimiter::getAggregator() const
  2211. {
  2212. return aggregator;
  2213. }
  2214. ILimiter::EDecision NoneOfLimiter::limit(const BonusLimitationContext & context) const
  2215. {
  2216. bool wasntSure = false;
  2217. for(const auto & limiter : limiters)
  2218. {
  2219. auto result = limiter->limit(context);
  2220. if(result == ILimiter::EDecision::ACCEPT)
  2221. return ILimiter::EDecision::DISCARD;
  2222. if(result == ILimiter::EDecision::NOT_SURE)
  2223. wasntSure = true;
  2224. }
  2225. return wasntSure ? ILimiter::EDecision::NOT_SURE : ILimiter::EDecision::ACCEPT;
  2226. }
  2227. // Updaters
  2228. std::shared_ptr<Bonus> Bonus::addUpdater(const TUpdaterPtr & Updater)
  2229. {
  2230. updater = Updater;
  2231. return this->shared_from_this();
  2232. }
  2233. std::shared_ptr<Bonus> IUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2234. {
  2235. return b;
  2236. }
  2237. std::string IUpdater::toString() const
  2238. {
  2239. return typeid(*this).name();
  2240. }
  2241. JsonNode IUpdater::toJsonNode() const
  2242. {
  2243. return JsonNode(JsonNode::JsonType::DATA_NULL);
  2244. }
  2245. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  2246. {
  2247. }
  2248. std::shared_ptr<Bonus> GrowsWithLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2249. {
  2250. if(context.getNodeType() == CBonusSystemNode::HERO)
  2251. {
  2252. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  2253. int steps = stepSize ? level / stepSize : level;
  2254. //rounding follows format for HMM3 creature specialty bonus
  2255. int newVal = (valPer20 * steps + 19) / 20;
  2256. //return copy of bonus with updated val
  2257. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2258. newBonus->val = newVal;
  2259. return newBonus;
  2260. }
  2261. return b;
  2262. }
  2263. std::string GrowsWithLevelUpdater::toString() const
  2264. {
  2265. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  2266. }
  2267. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  2268. {
  2269. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2270. root["type"].String() = "GROWS_WITH_LEVEL";
  2271. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  2272. if(stepSize > 1)
  2273. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  2274. return root;
  2275. }
  2276. std::shared_ptr<Bonus> TimesHeroLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2277. {
  2278. if(context.getNodeType() == CBonusSystemNode::HERO)
  2279. {
  2280. int level = dynamic_cast<const CGHeroInstance &>(context).level;
  2281. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2282. newBonus->val *= level;
  2283. return newBonus;
  2284. }
  2285. return b;
  2286. }
  2287. std::string TimesHeroLevelUpdater::toString() const
  2288. {
  2289. return "TimesHeroLevelUpdater";
  2290. }
  2291. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  2292. {
  2293. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  2294. }
  2295. ArmyMovementUpdater::ArmyMovementUpdater():
  2296. base(20),
  2297. divider(3),
  2298. multiplier(10),
  2299. max(700)
  2300. {
  2301. }
  2302. ArmyMovementUpdater::ArmyMovementUpdater(int base, int divider, int multiplier, int max):
  2303. base(base),
  2304. divider(divider),
  2305. multiplier(multiplier),
  2306. max(max)
  2307. {
  2308. }
  2309. std::shared_ptr<Bonus> ArmyMovementUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2310. {
  2311. if(b->type == Bonus::MOVEMENT && context.getNodeType() == CBonusSystemNode::HERO)
  2312. {
  2313. auto speed = static_cast<const CGHeroInstance &>(context).getLowestCreatureSpeed();
  2314. si32 armySpeed = speed * base / divider;
  2315. auto counted = armySpeed * multiplier;
  2316. auto newBonus = std::make_shared<Bonus>(*b);
  2317. newBonus->source = Bonus::ARMY;
  2318. newBonus->val += vstd::amin(counted, max);
  2319. return newBonus;
  2320. }
  2321. if(b->type != Bonus::MOVEMENT)
  2322. logGlobal->error("ArmyMovementUpdater should only be used for MOVEMENT bonus!");
  2323. return b;
  2324. }
  2325. std::string ArmyMovementUpdater::toString() const
  2326. {
  2327. return "ArmyMovementUpdater";
  2328. }
  2329. JsonNode ArmyMovementUpdater::toJsonNode() const
  2330. {
  2331. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  2332. root["type"].String() = "ARMY_MOVEMENT";
  2333. root["parameters"].Vector().push_back(JsonUtils::intNode(base));
  2334. root["parameters"].Vector().push_back(JsonUtils::intNode(divider));
  2335. root["parameters"].Vector().push_back(JsonUtils::intNode(multiplier));
  2336. root["parameters"].Vector().push_back(JsonUtils::intNode(max));
  2337. return root;
  2338. }
  2339. std::shared_ptr<Bonus> TimesStackLevelUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2340. {
  2341. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  2342. {
  2343. int level = dynamic_cast<const CStackInstance &>(context).getLevel();
  2344. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2345. newBonus->val *= level;
  2346. return newBonus;
  2347. }
  2348. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  2349. {
  2350. const auto & stack = dynamic_cast<const CStack &>(context);
  2351. //only update if stack doesn't have an instance (summons, war machines)
  2352. //otherwise we'd end up multiplying twice
  2353. if(stack.base == nullptr)
  2354. {
  2355. int level = stack.type->getLevel();
  2356. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  2357. newBonus->val *= level;
  2358. return newBonus;
  2359. }
  2360. }
  2361. return b;
  2362. }
  2363. std::string TimesStackLevelUpdater::toString() const
  2364. {
  2365. return "TimesStackLevelUpdater";
  2366. }
  2367. JsonNode TimesStackLevelUpdater::toJsonNode() const
  2368. {
  2369. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  2370. }
  2371. std::string OwnerUpdater::toString() const
  2372. {
  2373. return "OwnerUpdater";
  2374. }
  2375. JsonNode OwnerUpdater::toJsonNode() const
  2376. {
  2377. return JsonUtils::stringNode("BONUS_OWNER_UPDATER");
  2378. }
  2379. std::shared_ptr<Bonus> OwnerUpdater::createUpdatedBonus(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  2380. {
  2381. auto owner = CBonusSystemNode::retrieveNodeOwner(&context);
  2382. if(owner == PlayerColor::UNFLAGGABLE)
  2383. owner = PlayerColor::NEUTRAL;
  2384. std::shared_ptr<Bonus> updated =
  2385. std::make_shared<Bonus>(static_cast<Bonus::BonusDuration>(b->duration), b->type, b->source, b->val, b->sid, b->subtype, b->valType);
  2386. updated->limiter = std::make_shared<OppositeSideLimiter>(owner);
  2387. return updated;
  2388. }
  2389. VCMI_LIB_NAMESPACE_END