HeroBonus.cpp 63 KB

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