HeroBonus.cpp 76 KB

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