HeroBonus.cpp 76 KB

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