HeroBonus.cpp 76 KB

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