HeroBonus.cpp 77 KB

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