HeroBonus.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328
  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 "StringConstants.h"
  23. #include "battle/BattleInfo.h"
  24. #define FOREACH_PARENT(pname) TNodes lparents; getParents(lparents); for(CBonusSystemNode *pname : lparents)
  25. #define FOREACH_CPARENT(pname) TCNodes lparents; getParents(lparents); for(const CBonusSystemNode *pname : lparents)
  26. #define FOREACH_RED_CHILD(pname) TNodes lchildren; getRedChildren(lchildren); for(CBonusSystemNode *pname : lchildren)
  27. #define FOREACH_RED_PARENT(pname) TNodes lparents; getRedParents(lparents); for(CBonusSystemNode *pname : lparents)
  28. #define BONUS_NAME(x) { #x, Bonus::x },
  29. const std::map<std::string, Bonus::BonusType> bonusNameMap = { BONUS_LIST };
  30. #undef BONUS_NAME
  31. #define BONUS_VALUE(x) { #x, Bonus::x },
  32. const std::map<std::string, Bonus::ValueType> bonusValueMap = { BONUS_VALUE_LIST };
  33. #undef BONUS_VALUE
  34. #define BONUS_SOURCE(x) { #x, Bonus::x },
  35. const std::map<std::string, Bonus::BonusSource> bonusSourceMap = { BONUS_SOURCE_LIST };
  36. #undef BONUS_SOURCE
  37. #define BONUS_ITEM(x) { #x, Bonus::x },
  38. const std::map<std::string, ui16> bonusDurationMap =
  39. {
  40. BONUS_ITEM(PERMANENT)
  41. BONUS_ITEM(ONE_BATTLE)
  42. BONUS_ITEM(ONE_DAY)
  43. BONUS_ITEM(ONE_WEEK)
  44. BONUS_ITEM(N_TURNS)
  45. BONUS_ITEM(N_DAYS)
  46. BONUS_ITEM(UNTIL_BEING_ATTACKED)
  47. BONUS_ITEM(UNTIL_ATTACK)
  48. BONUS_ITEM(STACK_GETS_TURN)
  49. BONUS_ITEM(COMMANDER_KILLED)
  50. { "UNITL_BEING_ATTACKED", Bonus::UNTIL_BEING_ATTACKED }//typo, but used in some mods
  51. };
  52. const std::map<std::string, Bonus::LimitEffect> bonusLimitEffect =
  53. {
  54. BONUS_ITEM(NO_LIMIT)
  55. BONUS_ITEM(ONLY_DISTANCE_FIGHT)
  56. BONUS_ITEM(ONLY_MELEE_FIGHT)
  57. BONUS_ITEM(ONLY_ENEMY_ARMY)
  58. };
  59. const std::map<std::string, TLimiterPtr> bonusLimiterMap =
  60. {
  61. {"SHOOTER_ONLY", std::make_shared<HasAnotherBonusLimiter>(Bonus::SHOOTER)},
  62. {"DRAGON_NATURE", std::make_shared<HasAnotherBonusLimiter>(Bonus::DRAGON_NATURE)},
  63. {"IS_UNDEAD", std::make_shared<HasAnotherBonusLimiter>(Bonus::UNDEAD)},
  64. {"CREATURE_NATIVE_TERRAIN", std::make_shared<CreatureTerrainLimiter>()},
  65. {"CREATURE_FACTION", std::make_shared<CreatureFactionLimiter>()}
  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. if(selector(b.get()) && ((!limit && b->effectRange == Bonus::NO_LIMIT) || ((bool)limit && limit(b.get()))))
  458. out.push_back(b);
  459. }
  460. }
  461. void BonusList::getAllBonuses(BonusList &out) const
  462. {
  463. for(auto & b : bonuses)
  464. out.push_back(b);
  465. }
  466. int BonusList::valOfBonuses(const CSelector &select) const
  467. {
  468. BonusList ret;
  469. CSelector limit = nullptr;
  470. getBonuses(ret, select, limit);
  471. return ret.totalValue();
  472. }
  473. JsonNode BonusList::toJsonNode() const
  474. {
  475. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  476. for(std::shared_ptr<Bonus> b : bonuses)
  477. node.Vector().push_back(b->toJsonNode());
  478. return node;
  479. }
  480. void BonusList::push_back(std::shared_ptr<Bonus> x)
  481. {
  482. bonuses.push_back(x);
  483. changed();
  484. }
  485. BonusList::TInternalContainer::iterator BonusList::erase(const int position)
  486. {
  487. changed();
  488. return bonuses.erase(bonuses.begin() + position);
  489. }
  490. void BonusList::clear()
  491. {
  492. bonuses.clear();
  493. changed();
  494. }
  495. std::vector<BonusList*>::size_type BonusList::operator-=(std::shared_ptr<Bonus> const &i)
  496. {
  497. auto itr = std::find(bonuses.begin(), bonuses.end(), i);
  498. if(itr == bonuses.end())
  499. return false;
  500. bonuses.erase(itr);
  501. changed();
  502. return true;
  503. }
  504. void BonusList::resize(BonusList::TInternalContainer::size_type sz, std::shared_ptr<Bonus> c )
  505. {
  506. bonuses.resize(sz, c);
  507. changed();
  508. }
  509. void BonusList::insert(BonusList::TInternalContainer::iterator position, BonusList::TInternalContainer::size_type n, std::shared_ptr<Bonus> const &x)
  510. {
  511. bonuses.insert(position, n, x);
  512. changed();
  513. }
  514. CSelector IBonusBearer::anaffectedByMoraleSelector
  515. = Selector::type()(Bonus::NON_LIVING)
  516. .Or(Selector::type()(Bonus::UNDEAD))
  517. .Or(Selector::type()(Bonus::NO_MORALE))
  518. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  519. CSelector IBonusBearer::moraleSelector = Selector::type()(Bonus::MORALE);
  520. CSelector IBonusBearer::luckSelector = Selector::type()(Bonus::LUCK);
  521. CSelector IBonusBearer::selfMoraleSelector = Selector::type()(Bonus::SELF_MORALE);
  522. CSelector IBonusBearer::selfLuckSelector = Selector::type()(Bonus::SELF_LUCK);
  523. IBonusBearer::IBonusBearer()
  524. :anaffectedByMorale(this, anaffectedByMoraleSelector),
  525. moraleValue(this, moraleSelector, 0),
  526. luckValue(this, luckSelector, 0),
  527. selfMorale(this, selfMoraleSelector),
  528. selfLuck(this, selfLuckSelector)
  529. {
  530. }
  531. int IBonusBearer::valOfBonuses(Bonus::BonusType type, const CSelector &selector) const
  532. {
  533. return valOfBonuses(Selector::type()(type).And(selector));
  534. }
  535. int IBonusBearer::valOfBonuses(Bonus::BonusType type, int subtype) const
  536. {
  537. boost::format fmt("type_%ds_%d");
  538. fmt % (int)type % subtype;
  539. CSelector s = Selector::type()(type);
  540. if(subtype != -1)
  541. s = s.And(Selector::subtype()(subtype));
  542. return valOfBonuses(s, fmt.str());
  543. }
  544. int IBonusBearer::valOfBonuses(const CSelector &selector, const std::string &cachingStr) const
  545. {
  546. CSelector limit = nullptr;
  547. TConstBonusListPtr hlp = getAllBonuses(selector, limit, nullptr, cachingStr);
  548. return hlp->totalValue();
  549. }
  550. bool IBonusBearer::hasBonus(const CSelector &selector, const std::string &cachingStr) const
  551. {
  552. return getBonuses(selector, cachingStr)->size() > 0;
  553. }
  554. bool IBonusBearer::hasBonus(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  555. {
  556. return getBonuses(selector, limit, cachingStr)->size() > 0;
  557. }
  558. bool IBonusBearer::hasBonusOfType(Bonus::BonusType type, int subtype) const
  559. {
  560. boost::format fmt("type_%ds_%d");
  561. fmt % (int)type % subtype;
  562. CSelector s = Selector::type()(type);
  563. if(subtype != -1)
  564. s = s.And(Selector::subtype()(subtype));
  565. return hasBonus(s, fmt.str());
  566. }
  567. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const std::string &cachingStr) const
  568. {
  569. return getAllBonuses(selector, nullptr, nullptr, cachingStr);
  570. }
  571. TConstBonusListPtr IBonusBearer::getBonuses(const CSelector &selector, const CSelector &limit, const std::string &cachingStr) const
  572. {
  573. return getAllBonuses(selector, limit, nullptr, cachingStr);
  574. }
  575. bool IBonusBearer::hasBonusFrom(Bonus::BonusSource source, ui32 sourceID) const
  576. {
  577. boost::format fmt("source_%did_%d");
  578. fmt % (int)source % sourceID;
  579. return hasBonus(Selector::source(source,sourceID), fmt.str());
  580. }
  581. int IBonusBearer::MoraleVal() const
  582. {
  583. if(anaffectedByMorale.getHasBonus())
  584. return 0;
  585. int ret = moraleValue.getValue();
  586. if(selfMorale.getHasBonus()) //eg. minotaur
  587. vstd::amax(ret, +1);
  588. return vstd::abetween(ret, -3, +3);
  589. }
  590. int IBonusBearer::LuckVal() const
  591. {
  592. if(hasBonusOfType(Bonus::NO_LUCK))
  593. return 0;
  594. int ret = luckValue.getValue();
  595. if(selfLuck.getHasBonus()) //eg. halfling
  596. vstd::amax(ret, +1);
  597. return vstd::abetween(ret, -3, +3);
  598. }
  599. int IBonusBearer::MoraleValAndBonusList(TConstBonusListPtr & bonusList) const
  600. {
  601. if(anaffectedByMorale.getHasBonus())
  602. {
  603. if(!bonusList->empty())
  604. bonusList = std::make_shared<const BonusList>();
  605. return 0;
  606. }
  607. int ret = moraleValue.getValueAndList(bonusList);
  608. if(selfMorale.getHasBonus()) //eg. minotaur
  609. vstd::amax(ret, +1);
  610. return vstd::abetween(ret, -3, +3);
  611. }
  612. int IBonusBearer::LuckValAndBonusList(TConstBonusListPtr & bonusList) const
  613. {
  614. if(hasBonusOfType(Bonus::NO_LUCK))
  615. {
  616. if(!bonusList->empty())
  617. bonusList = std::make_shared<const BonusList>();
  618. return 0;
  619. }
  620. int ret = luckValue.getValueAndList(bonusList);
  621. if(selfLuck.getHasBonus()) //eg. halfling
  622. vstd::amax(ret, +1);
  623. return vstd::abetween(ret, -3, +3);
  624. }
  625. ui32 IBonusBearer::MaxHealth() const
  626. {
  627. const std::string cachingStr = "type_STACK_HEALTH";
  628. static const auto selector = Selector::type()(Bonus::STACK_HEALTH);
  629. auto value = valOfBonuses(selector, cachingStr);
  630. return std::max(1, value); //never 0
  631. }
  632. int IBonusBearer::getAttack(bool ranged) const
  633. {
  634. const std::string cachingStr = "type_PRIMARY_SKILLs_ATTACK";
  635. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  636. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  637. }
  638. int IBonusBearer::getDefence(bool ranged) const
  639. {
  640. const std::string cachingStr = "type_PRIMARY_SKILLs_DEFENSE";
  641. static const auto selector = Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  642. return getBonuses(selector, nullptr, cachingStr)->totalValue();
  643. }
  644. int IBonusBearer::getMinDamage(bool ranged) const
  645. {
  646. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_1";
  647. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 1));
  648. return valOfBonuses(selector, cachingStr);
  649. }
  650. int IBonusBearer::getMaxDamage(bool ranged) const
  651. {
  652. const std::string cachingStr = "type_CREATURE_DAMAGEs_0Otype_CREATURE_DAMAGEs_2";
  653. static const auto selector = Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 0).Or(Selector::typeSubtype(Bonus::CREATURE_DAMAGE, 2));
  654. return valOfBonuses(selector, cachingStr);
  655. }
  656. si32 IBonusBearer::manaLimit() const
  657. {
  658. return si32(getPrimSkillLevel(PrimarySkill::KNOWLEDGE)
  659. * (100.0 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::INTELLIGENCE))
  660. / 10.0);
  661. }
  662. int IBonusBearer::getPrimSkillLevel(PrimarySkill::PrimarySkill id) const
  663. {
  664. static const CSelector selectorAllSkills = Selector::type()(Bonus::PRIMARY_SKILL);
  665. static const std::string keyAllSkills = "type_PRIMARY_SKILL";
  666. auto allSkills = getBonuses(selectorAllSkills, keyAllSkills);
  667. auto ret = allSkills->valOfBonuses(Selector::subtype()(id));
  668. return ret; //sp=0 works in old saves
  669. }
  670. si32 IBonusBearer::magicResistance() const
  671. {
  672. return valOfBonuses(Bonus::MAGIC_RESISTANCE);
  673. }
  674. ui32 IBonusBearer::Speed(int turn, bool useBind) const
  675. {
  676. //war machines cannot move
  677. if(hasBonus(Selector::type()(Bonus::SIEGE_WEAPON).And(Selector::turns(turn))))
  678. {
  679. return 0;
  680. }
  681. //bind effect check - doesn't influence stack initiative
  682. if(useBind && hasBonus(Selector::type()(Bonus::BIND_EFFECT).And(Selector::turns(turn))))
  683. {
  684. return 0;
  685. }
  686. return valOfBonuses(Selector::type()(Bonus::STACKS_SPEED).And(Selector::turns(turn)));
  687. }
  688. bool IBonusBearer::isLiving() const //TODO: theoreticaly there exists "LIVING" bonus in stack experience documentation
  689. {
  690. static const std::string cachingStr = "IBonusBearer::isLiving";
  691. static const CSelector selector = Selector::type()(Bonus::UNDEAD)
  692. .Or(Selector::type()(Bonus::NON_LIVING))
  693. .Or(Selector::type()(Bonus::GARGOYLE))
  694. .Or(Selector::type()(Bonus::SIEGE_WEAPON));
  695. return !hasBonus(selector, cachingStr);
  696. }
  697. std::shared_ptr<const Bonus> IBonusBearer::getBonus(const CSelector &selector) const
  698. {
  699. auto bonuses = getAllBonuses(selector, Selector::all);
  700. return bonuses->getFirst(Selector::all);
  701. }
  702. std::shared_ptr<Bonus> CBonusSystemNode::getBonusLocalFirst(const CSelector &selector)
  703. {
  704. auto ret = bonuses.getFirst(selector);
  705. if(ret)
  706. return ret;
  707. FOREACH_PARENT(pname)
  708. {
  709. ret = pname->getBonusLocalFirst(selector);
  710. if (ret)
  711. return ret;
  712. }
  713. return nullptr;
  714. }
  715. std::shared_ptr<const Bonus> CBonusSystemNode::getBonusLocalFirst( const CSelector &selector ) const
  716. {
  717. return (const_cast<CBonusSystemNode*>(this))->getBonusLocalFirst(selector);
  718. }
  719. void CBonusSystemNode::getParents(TCNodes & out) const /*retrieves list of parent nodes (nodes to inherit bonuses from) */
  720. {
  721. for (auto & elem : parents)
  722. {
  723. const CBonusSystemNode *parent = elem;
  724. out.insert(parent);
  725. }
  726. }
  727. void CBonusSystemNode::getParents(TNodes &out)
  728. {
  729. for (auto & elem : parents)
  730. {
  731. const CBonusSystemNode *parent = elem;
  732. out.insert(const_cast<CBonusSystemNode*>(parent));
  733. }
  734. }
  735. void CBonusSystemNode::getBonusesRec(BonusList &out, const CSelector &selector, const CSelector &limit) const
  736. {
  737. BonusList beforeUpdate;
  738. FOREACH_CPARENT(p)
  739. {
  740. p->getBonusesRec(beforeUpdate, selector, limit);
  741. }
  742. bonuses.getBonuses(beforeUpdate, selector, limit);
  743. for(auto b : beforeUpdate)
  744. out.push_back(update(b));
  745. }
  746. void CBonusSystemNode::getAllBonusesRec(BonusList &out) const
  747. {
  748. BonusList beforeUpdate;
  749. FOREACH_CPARENT(p)
  750. {
  751. p->getAllBonusesRec(beforeUpdate);
  752. }
  753. bonuses.getAllBonuses(beforeUpdate);
  754. for(auto b : beforeUpdate)
  755. out.push_back(update(b));
  756. }
  757. TConstBonusListPtr CBonusSystemNode::getAllBonuses(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root, const std::string &cachingStr) const
  758. {
  759. bool limitOnUs = (!root || root == this); //caching won't work when we want to limit bonuses against an external node
  760. if (CBonusSystemNode::cachingEnabled && limitOnUs)
  761. {
  762. // Exclusive access for one thread
  763. static boost::mutex m;
  764. boost::mutex::scoped_lock lock(m);
  765. // If the bonus system tree changes(state of a single node or the relations to each other) then
  766. // cache all bonus objects. Selector objects doesn't matter.
  767. if (cachedLast != treeChanged)
  768. {
  769. cachedBonuses.clear();
  770. cachedRequests.clear();
  771. BonusList allBonuses;
  772. getAllBonusesRec(allBonuses);
  773. limitBonuses(allBonuses, cachedBonuses);
  774. cachedBonuses.stackBonuses();
  775. cachedLast = treeChanged;
  776. }
  777. // If a bonus system request comes with a caching string then look up in the map if there are any
  778. // pre-calculated bonus results. Limiters can't be cached so they have to be calculated.
  779. if (cachingStr != "")
  780. {
  781. auto it = cachedRequests.find(cachingStr);
  782. if(it != cachedRequests.end())
  783. {
  784. //Cached list contains bonuses for our query with applied limiters
  785. return it->second;
  786. }
  787. }
  788. //We still don't have the bonuses (didn't returned them from cache)
  789. //Perform bonus selection
  790. auto ret = std::make_shared<BonusList>();
  791. cachedBonuses.getBonuses(*ret, selector, limit);
  792. // Save the results in the cache
  793. if(cachingStr != "")
  794. cachedRequests[cachingStr] = ret;
  795. return ret;
  796. }
  797. else
  798. {
  799. return getAllBonusesWithoutCaching(selector, limit, root);
  800. }
  801. }
  802. TConstBonusListPtr CBonusSystemNode::getAllBonusesWithoutCaching(const CSelector &selector, const CSelector &limit, const CBonusSystemNode *root) const
  803. {
  804. auto ret = std::make_shared<BonusList>();
  805. // Get bonus results without caching enabled.
  806. BonusList beforeLimiting, afterLimiting;
  807. getAllBonusesRec(beforeLimiting);
  808. if(!root || root == this)
  809. {
  810. limitBonuses(beforeLimiting, afterLimiting);
  811. }
  812. else if(root)
  813. {
  814. //We want to limit our query against an external node. We get all its bonuses,
  815. // add the ones we're considering and see if they're cut out by limiters
  816. BonusList rootBonuses, limitedRootBonuses;
  817. getAllBonusesRec(rootBonuses);
  818. for(auto b : beforeLimiting)
  819. rootBonuses.push_back(b);
  820. root->limitBonuses(rootBonuses, limitedRootBonuses);
  821. for(auto b : beforeLimiting)
  822. if(vstd::contains(limitedRootBonuses, b))
  823. afterLimiting.push_back(b);
  824. }
  825. afterLimiting.getBonuses(*ret, selector, limit);
  826. ret->stackBonuses();
  827. return ret;
  828. }
  829. std::shared_ptr<Bonus> CBonusSystemNode::update(const std::shared_ptr<Bonus> & b) const
  830. {
  831. if(b->updater)
  832. return b->updater->update(b, *this);
  833. return b;
  834. }
  835. CBonusSystemNode::CBonusSystemNode()
  836. : bonuses(true),
  837. exportedBonuses(true),
  838. nodeType(UNKNOWN),
  839. cachedLast(0)
  840. {
  841. }
  842. CBonusSystemNode::CBonusSystemNode(ENodeTypes NodeType)
  843. : bonuses(true),
  844. exportedBonuses(true),
  845. nodeType(NodeType),
  846. cachedLast(0)
  847. {
  848. }
  849. CBonusSystemNode::CBonusSystemNode(CBonusSystemNode && other):
  850. bonuses(std::move(other.bonuses)),
  851. exportedBonuses(std::move(other.exportedBonuses)),
  852. nodeType(other.nodeType),
  853. description(other.description),
  854. cachedLast(0)
  855. {
  856. std::swap(parents, other.parents);
  857. std::swap(children, other.children);
  858. //fixing bonus tree without recalculation
  859. for(CBonusSystemNode * n : parents)
  860. {
  861. n->children -= &other;
  862. n->children.push_back(this);
  863. }
  864. for(CBonusSystemNode * n : children)
  865. {
  866. n->parents -= &other;
  867. n->parents.push_back(this);
  868. }
  869. //cache ignored
  870. //cachedBonuses
  871. //cachedRequests
  872. }
  873. CBonusSystemNode::~CBonusSystemNode()
  874. {
  875. detachFromAll();
  876. if(children.size())
  877. {
  878. while(children.size())
  879. children.front()->detachFrom(this);
  880. }
  881. }
  882. void CBonusSystemNode::attachTo(CBonusSystemNode *parent)
  883. {
  884. assert(!vstd::contains(parents, parent));
  885. parents.push_back(parent);
  886. if(parent->actsAsBonusSourceOnly())
  887. parent->newRedDescendant(this);
  888. else
  889. newRedDescendant(parent);
  890. parent->newChildAttached(this);
  891. CBonusSystemNode::treeHasChanged();
  892. }
  893. void CBonusSystemNode::detachFrom(CBonusSystemNode *parent)
  894. {
  895. assert(vstd::contains(parents, parent));
  896. if(parent->actsAsBonusSourceOnly())
  897. parent->removedRedDescendant(this);
  898. else
  899. removedRedDescendant(parent);
  900. parents -= parent;
  901. parent->childDetached(this);
  902. CBonusSystemNode::treeHasChanged();
  903. }
  904. void CBonusSystemNode::removeBonusesRecursive(const CSelector & s)
  905. {
  906. removeBonuses(s);
  907. for(CBonusSystemNode * child : children)
  908. child->removeBonusesRecursive(s);
  909. }
  910. void CBonusSystemNode::reduceBonusDurations(const CSelector &s)
  911. {
  912. BonusList bl;
  913. exportedBonuses.getBonuses(bl, s, Selector::all);
  914. for(auto b : bl)
  915. {
  916. b->turnsRemain--;
  917. if(b->turnsRemain <= 0)
  918. removeBonus(b);
  919. }
  920. for(CBonusSystemNode *child : children)
  921. child->reduceBonusDurations(s);
  922. }
  923. void CBonusSystemNode::addNewBonus(const std::shared_ptr<Bonus>& b)
  924. {
  925. //turnsRemain shouldn't be zero for following durations
  926. if(Bonus::NTurns(b.get()) || Bonus::NDays(b.get()) || Bonus::OneWeek(b.get()))
  927. {
  928. assert(b->turnsRemain);
  929. }
  930. assert(!vstd::contains(exportedBonuses, b));
  931. exportedBonuses.push_back(b);
  932. exportBonus(b);
  933. CBonusSystemNode::treeHasChanged();
  934. }
  935. void CBonusSystemNode::accumulateBonus(const std::shared_ptr<Bonus>& b)
  936. {
  937. auto bonus = exportedBonuses.getFirst(Selector::typeSubtype(b->type, b->subtype)); //only local bonuses are interesting //TODO: what about value type?
  938. if(bonus)
  939. bonus->val += b->val;
  940. else
  941. addNewBonus(std::make_shared<Bonus>(*b)); //duplicate needed, original may get destroyed
  942. }
  943. void CBonusSystemNode::removeBonus(const std::shared_ptr<Bonus>& b)
  944. {
  945. exportedBonuses -= b;
  946. if(b->propagator)
  947. unpropagateBonus(b);
  948. else
  949. bonuses -= b;
  950. CBonusSystemNode::treeHasChanged();
  951. }
  952. void CBonusSystemNode::removeBonuses(const CSelector & selector)
  953. {
  954. BonusList toRemove;
  955. exportedBonuses.getBonuses(toRemove, selector, Selector::all);
  956. for(auto bonus : toRemove)
  957. removeBonus(bonus);
  958. }
  959. bool CBonusSystemNode::actsAsBonusSourceOnly() const
  960. {
  961. switch(nodeType)
  962. {
  963. case CREATURE:
  964. case ARTIFACT:
  965. case ARTIFACT_INSTANCE:
  966. return true;
  967. default:
  968. return false;
  969. }
  970. }
  971. void CBonusSystemNode::propagateBonus(std::shared_ptr<Bonus> b)
  972. {
  973. if(b->propagator->shouldBeAttached(this))
  974. {
  975. bonuses.push_back(b);
  976. logBonus->trace("#$# %s #propagated to# %s", b->Description(), nodeName());
  977. }
  978. FOREACH_RED_CHILD(child)
  979. child->propagateBonus(b);
  980. }
  981. void CBonusSystemNode::unpropagateBonus(std::shared_ptr<Bonus> b)
  982. {
  983. if(b->propagator->shouldBeAttached(this))
  984. {
  985. bonuses -= b;
  986. logBonus->trace("#$# %s #is no longer propagated to# %s", b->Description(), nodeName());
  987. }
  988. FOREACH_RED_CHILD(child)
  989. child->unpropagateBonus(b);
  990. }
  991. void CBonusSystemNode::newChildAttached(CBonusSystemNode *child)
  992. {
  993. assert(!vstd::contains(children, child));
  994. children.push_back(child);
  995. }
  996. void CBonusSystemNode::childDetached(CBonusSystemNode *child)
  997. {
  998. if (vstd::contains(children, child))
  999. children -= child;
  1000. else
  1001. {
  1002. logBonus->error("Error! %s #cannot be detached from# %s", child->nodeName(), nodeName());
  1003. throw std::runtime_error("internal error");
  1004. }
  1005. }
  1006. void CBonusSystemNode::detachFromAll()
  1007. {
  1008. while(parents.size())
  1009. detachFrom(parents.front());
  1010. }
  1011. bool CBonusSystemNode::isIndependentNode() const
  1012. {
  1013. return parents.empty() && children.empty();
  1014. }
  1015. std::string CBonusSystemNode::nodeName() const
  1016. {
  1017. return description.size()
  1018. ? description
  1019. : std::string("Bonus system node of type ") + typeid(*this).name();
  1020. }
  1021. void CBonusSystemNode::deserializationFix()
  1022. {
  1023. exportBonuses();
  1024. }
  1025. void CBonusSystemNode::getRedParents(TNodes &out)
  1026. {
  1027. FOREACH_PARENT(pname)
  1028. {
  1029. if(pname->actsAsBonusSourceOnly())
  1030. {
  1031. out.insert(pname);
  1032. }
  1033. }
  1034. if(!actsAsBonusSourceOnly())
  1035. {
  1036. for(CBonusSystemNode *child : children)
  1037. {
  1038. out.insert(child);
  1039. }
  1040. }
  1041. }
  1042. void CBonusSystemNode::getRedChildren(TNodes &out)
  1043. {
  1044. FOREACH_PARENT(pname)
  1045. {
  1046. if(!pname->actsAsBonusSourceOnly())
  1047. {
  1048. out.insert(pname);
  1049. }
  1050. }
  1051. if(actsAsBonusSourceOnly())
  1052. {
  1053. for(CBonusSystemNode *child : children)
  1054. {
  1055. out.insert(child);
  1056. }
  1057. }
  1058. }
  1059. void CBonusSystemNode::newRedDescendant(CBonusSystemNode *descendant)
  1060. {
  1061. for(auto b : exportedBonuses)
  1062. if(b->propagator)
  1063. descendant->propagateBonus(b);
  1064. FOREACH_RED_PARENT(parent)
  1065. parent->newRedDescendant(descendant);
  1066. }
  1067. void CBonusSystemNode::removedRedDescendant(CBonusSystemNode *descendant)
  1068. {
  1069. for(auto b : exportedBonuses)
  1070. if(b->propagator)
  1071. descendant->unpropagateBonus(b);
  1072. FOREACH_RED_PARENT(parent)
  1073. parent->removedRedDescendant(descendant);
  1074. }
  1075. void CBonusSystemNode::getRedAncestors(TNodes &out)
  1076. {
  1077. getRedParents(out);
  1078. FOREACH_RED_PARENT(p)
  1079. p->getRedAncestors(out);
  1080. }
  1081. void CBonusSystemNode::getRedDescendants(TNodes &out)
  1082. {
  1083. getRedChildren(out);
  1084. FOREACH_RED_CHILD(c)
  1085. c->getRedChildren(out);
  1086. }
  1087. void CBonusSystemNode::exportBonus(std::shared_ptr<Bonus> b)
  1088. {
  1089. if(b->propagator)
  1090. propagateBonus(b);
  1091. else
  1092. bonuses.push_back(b);
  1093. CBonusSystemNode::treeHasChanged();
  1094. }
  1095. void CBonusSystemNode::exportBonuses()
  1096. {
  1097. for(auto b : exportedBonuses)
  1098. exportBonus(b);
  1099. }
  1100. CBonusSystemNode::ENodeTypes CBonusSystemNode::getNodeType() const
  1101. {
  1102. return nodeType;
  1103. }
  1104. const BonusList& CBonusSystemNode::getBonusList() const
  1105. {
  1106. return bonuses;
  1107. }
  1108. const TNodesVector& CBonusSystemNode::getParentNodes() const
  1109. {
  1110. return parents;
  1111. }
  1112. const TNodesVector& CBonusSystemNode::getChildrenNodes() const
  1113. {
  1114. return children;
  1115. }
  1116. void CBonusSystemNode::setNodeType(CBonusSystemNode::ENodeTypes type)
  1117. {
  1118. nodeType = type;
  1119. }
  1120. BonusList& CBonusSystemNode::getExportedBonusList()
  1121. {
  1122. return exportedBonuses;
  1123. }
  1124. const std::string& CBonusSystemNode::getDescription() const
  1125. {
  1126. return description;
  1127. }
  1128. void CBonusSystemNode::setDescription(const std::string &description)
  1129. {
  1130. this->description = description;
  1131. }
  1132. void CBonusSystemNode::limitBonuses(const BonusList &allBonuses, BonusList &out) const
  1133. {
  1134. assert(&allBonuses != &out); //todo should it work in-place?
  1135. BonusList undecided = allBonuses,
  1136. &accepted = out;
  1137. while(true)
  1138. {
  1139. int undecidedCount = static_cast<int>(undecided.size());
  1140. for(int i = 0; i < undecided.size(); i++)
  1141. {
  1142. auto b = undecided[i];
  1143. BonusLimitationContext context = {b, *this, out, undecided};
  1144. int decision = b->limiter ? b->limiter->limit(context) : ILimiter::ACCEPT; //bonuses without limiters will be accepted by default
  1145. if(decision == ILimiter::DISCARD)
  1146. {
  1147. undecided.erase(i);
  1148. i--; continue;
  1149. }
  1150. else if(decision == ILimiter::ACCEPT)
  1151. {
  1152. accepted.push_back(b);
  1153. undecided.erase(i);
  1154. i--; continue;
  1155. }
  1156. else
  1157. assert(decision == ILimiter::NOT_SURE);
  1158. }
  1159. if(undecided.size() == undecidedCount) //we haven't moved a single bonus -> limiters reached a stable state
  1160. return;
  1161. }
  1162. }
  1163. TBonusListPtr CBonusSystemNode::limitBonuses(const BonusList &allBonuses) const
  1164. {
  1165. auto ret = std::make_shared<BonusList>();
  1166. limitBonuses(allBonuses, *ret);
  1167. return ret;
  1168. }
  1169. void CBonusSystemNode::treeHasChanged()
  1170. {
  1171. treeChanged++;
  1172. }
  1173. int64_t CBonusSystemNode::getTreeVersion() const
  1174. {
  1175. int64_t ret = treeChanged;
  1176. return ret << 32;
  1177. }
  1178. int NBonus::valOf(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1179. {
  1180. if(obj)
  1181. return obj->valOfBonuses(type, subtype);
  1182. return 0;
  1183. }
  1184. bool NBonus::hasOfType(const CBonusSystemNode *obj, Bonus::BonusType type, int subtype)
  1185. {
  1186. if(obj)
  1187. return obj->hasBonusOfType(type, subtype);
  1188. return false;
  1189. }
  1190. std::string Bonus::Description() const
  1191. {
  1192. std::ostringstream str;
  1193. if(description.empty())
  1194. {
  1195. if(stacking.empty() || stacking == "ALWAYS")
  1196. {
  1197. switch(source)
  1198. {
  1199. case ARTIFACT:
  1200. str << VLC->arth->artifacts[sid]->Name();
  1201. break;
  1202. case SPELL_EFFECT:
  1203. str << SpellID(sid).toSpell()->name;
  1204. break;
  1205. case CREATURE_ABILITY:
  1206. str << VLC->creh->creatures[sid]->namePl;
  1207. break;
  1208. case SECONDARY_SKILL:
  1209. str << VLC->skillh->skillName(sid);
  1210. break;
  1211. case HERO_SPECIAL:
  1212. str << VLC->heroh->heroes[sid]->name;
  1213. break;
  1214. default:
  1215. //todo: handle all possible sources
  1216. str << "Unknown";
  1217. break;
  1218. }
  1219. }
  1220. else
  1221. str << stacking;
  1222. }
  1223. else
  1224. {
  1225. str << description;
  1226. }
  1227. if(val != 0)
  1228. str << " " << std::showpos << val;
  1229. return str.str();
  1230. }
  1231. JsonNode subtypeToJson(Bonus::BonusType type, int subtype)
  1232. {
  1233. switch(type)
  1234. {
  1235. case Bonus::PRIMARY_SKILL:
  1236. return JsonUtils::stringNode("primSkill." + PrimarySkill::names[subtype]);
  1237. case Bonus::SECONDARY_SKILL_PREMY:
  1238. return JsonUtils::stringNode(CSkillHandler::encodeSkillWithType(subtype));
  1239. case Bonus::SPECIAL_SPELL_LEV:
  1240. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1241. case Bonus::SPECIAL_BLESS_DAMAGE:
  1242. case Bonus::MAXED_SPELL:
  1243. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1244. return JsonUtils::stringNode("spell." + (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier);
  1245. case Bonus::IMPROVED_NECROMANCY:
  1246. case Bonus::SPECIAL_UPGRADE:
  1247. return JsonUtils::stringNode("creature." + CreatureID::encode(subtype));
  1248. case Bonus::GENERATE_RESOURCE:
  1249. return JsonUtils::stringNode("resource." + GameConstants::RESOURCE_NAMES[subtype]);
  1250. default:
  1251. return JsonUtils::intNode(subtype);
  1252. }
  1253. }
  1254. JsonNode additionalInfoToJson(Bonus::BonusType type, CAddInfo addInfo)
  1255. {
  1256. switch(type)
  1257. {
  1258. case Bonus::SPECIAL_UPGRADE:
  1259. return JsonUtils::stringNode("creature." + CreatureID::encode(addInfo[0]));
  1260. default:
  1261. return addInfo.toJsonNode();
  1262. }
  1263. }
  1264. JsonNode durationToJson(ui16 duration)
  1265. {
  1266. std::vector<std::string> durationNames;
  1267. for(ui16 durBit = 1; durBit; durBit = durBit << 1)
  1268. {
  1269. if(duration & durBit)
  1270. durationNames.push_back(vstd::findKey(bonusDurationMap, durBit));
  1271. }
  1272. if(durationNames.size() == 1)
  1273. {
  1274. return JsonUtils::stringNode(durationNames[0]);
  1275. }
  1276. else
  1277. {
  1278. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  1279. for(std::string dur : durationNames)
  1280. node.Vector().push_back(JsonUtils::stringNode(dur));
  1281. return node;
  1282. }
  1283. }
  1284. JsonNode Bonus::toJsonNode() const
  1285. {
  1286. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1287. // only add values that might reasonably be found in config files
  1288. root["type"].String() = vstd::findKey(bonusNameMap, type);
  1289. if(subtype != -1)
  1290. root["subtype"] = subtypeToJson(type, subtype);
  1291. if(additionalInfo != CAddInfo::NONE)
  1292. root["addInfo"] = additionalInfoToJson(type, additionalInfo);
  1293. if(val != 0)
  1294. root["val"].Integer() = val;
  1295. if(valType != ADDITIVE_VALUE)
  1296. root["valueType"].String() = vstd::findKey(bonusValueMap, valType);
  1297. if(stacking != "")
  1298. root["stacking"].String() = stacking;
  1299. if(description != "")
  1300. root["description"].String() = description;
  1301. if(effectRange != NO_LIMIT)
  1302. root["effectRange"].String() = vstd::findKey(bonusLimitEffect, effectRange);
  1303. if(duration != PERMANENT)
  1304. root["duration"] = durationToJson(duration);
  1305. if(turnsRemain)
  1306. root["turns"].Integer() = turnsRemain;
  1307. if(limiter)
  1308. root["limiters"] = limiter->toJsonNode();
  1309. if(updater)
  1310. root["updater"] = updater->toJsonNode();
  1311. if(propagator)
  1312. root["propagator"].String() = vstd::findKey(bonusPropagatorMap, propagator);
  1313. return root;
  1314. }
  1315. std::string Bonus::nameForBonus() const
  1316. {
  1317. switch(type)
  1318. {
  1319. case Bonus::PRIMARY_SKILL:
  1320. return PrimarySkill::names[subtype];
  1321. case Bonus::SECONDARY_SKILL_PREMY:
  1322. return CSkillHandler::encodeSkill(subtype);
  1323. case Bonus::SPECIAL_SPELL_LEV:
  1324. case Bonus::SPECIFIC_SPELL_DAMAGE:
  1325. case Bonus::SPECIAL_BLESS_DAMAGE:
  1326. case Bonus::MAXED_SPELL:
  1327. case Bonus::SPECIAL_PECULIAR_ENCHANT:
  1328. return (*VLC->spellh)[SpellID::ESpellID(subtype)]->identifier;
  1329. case Bonus::SPECIAL_UPGRADE:
  1330. return CreatureID::encode(subtype) + "2" + CreatureID::encode(additionalInfo[0]);
  1331. case Bonus::GENERATE_RESOURCE:
  1332. return GameConstants::RESOURCE_NAMES[subtype];
  1333. case Bonus::STACKS_SPEED:
  1334. return "speed";
  1335. default:
  1336. return vstd::findKey(bonusNameMap, type);
  1337. }
  1338. }
  1339. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, std::string Desc, si32 Subtype)
  1340. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), description(Desc)
  1341. {
  1342. turnsRemain = 0;
  1343. valType = ADDITIVE_VALUE;
  1344. effectRange = NO_LIMIT;
  1345. boost::algorithm::trim(description);
  1346. }
  1347. Bonus::Bonus(Bonus::BonusDuration Duration, BonusType Type, BonusSource Src, si32 Val, ui32 ID, si32 Subtype, ValueType ValType)
  1348. : duration((ui16)Duration), type(Type), subtype(Subtype), source(Src), val(Val), sid(ID), valType(ValType)
  1349. {
  1350. turnsRemain = 0;
  1351. effectRange = NO_LIMIT;
  1352. }
  1353. Bonus::Bonus()
  1354. {
  1355. duration = PERMANENT;
  1356. turnsRemain = 0;
  1357. type = NONE;
  1358. subtype = -1;
  1359. valType = ADDITIVE_VALUE;
  1360. effectRange = NO_LIMIT;
  1361. val = 0;
  1362. source = OTHER;
  1363. sid = 0;
  1364. }
  1365. std::shared_ptr<Bonus> Bonus::addPropagator(TPropagatorPtr Propagator)
  1366. {
  1367. propagator = Propagator;
  1368. return this->shared_from_this();
  1369. }
  1370. namespace Selector
  1371. {
  1372. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusType> & type()
  1373. {
  1374. static CSelectFieldEqual<Bonus::BonusType> stype(&Bonus::type);
  1375. return stype;
  1376. }
  1377. DLL_LINKAGE CSelectFieldEqual<TBonusSubtype> & subtype()
  1378. {
  1379. static CSelectFieldEqual<TBonusSubtype> ssubtype(&Bonus::subtype);
  1380. return ssubtype;
  1381. }
  1382. DLL_LINKAGE CSelectFieldEqual<CAddInfo> & info()
  1383. {
  1384. static CSelectFieldEqual<CAddInfo> sinfo(&Bonus::additionalInfo);
  1385. return sinfo;
  1386. }
  1387. DLL_LINKAGE CSelectFieldEqual<Bonus::BonusSource> & sourceType()
  1388. {
  1389. static CSelectFieldEqual<Bonus::BonusSource> ssourceType(&Bonus::source);
  1390. return ssourceType;
  1391. }
  1392. DLL_LINKAGE CSelectFieldEqual<Bonus::LimitEffect> & effectRange()
  1393. {
  1394. static CSelectFieldEqual<Bonus::LimitEffect> seffectRange(&Bonus::effectRange);
  1395. return seffectRange;
  1396. }
  1397. DLL_LINKAGE CWillLastTurns turns;
  1398. DLL_LINKAGE CWillLastDays days;
  1399. CSelector DLL_LINKAGE typeSubtype(Bonus::BonusType Type, TBonusSubtype Subtype)
  1400. {
  1401. return type()(Type).And(subtype()(Subtype));
  1402. }
  1403. CSelector DLL_LINKAGE typeSubtypeInfo(Bonus::BonusType type, TBonusSubtype subtype, CAddInfo info)
  1404. {
  1405. return CSelectFieldEqual<Bonus::BonusType>(&Bonus::type)(type)
  1406. .And(CSelectFieldEqual<TBonusSubtype>(&Bonus::subtype)(subtype))
  1407. .And(CSelectFieldEqual<CAddInfo>(&Bonus::additionalInfo)(info));
  1408. }
  1409. CSelector DLL_LINKAGE source(Bonus::BonusSource source, ui32 sourceID)
  1410. {
  1411. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source)
  1412. .And(CSelectFieldEqual<ui32>(&Bonus::sid)(sourceID));
  1413. }
  1414. CSelector DLL_LINKAGE sourceTypeSel(Bonus::BonusSource source)
  1415. {
  1416. return CSelectFieldEqual<Bonus::BonusSource>(&Bonus::source)(source);
  1417. }
  1418. CSelector DLL_LINKAGE valueType(Bonus::ValueType valType)
  1419. {
  1420. return CSelectFieldEqual<Bonus::ValueType>(&Bonus::valType)(valType);
  1421. }
  1422. DLL_LINKAGE CSelector all([](const Bonus * b){return true;});
  1423. DLL_LINKAGE CSelector none([](const Bonus * b){return false;});
  1424. bool DLL_LINKAGE matchesType(const CSelector &sel, Bonus::BonusType type)
  1425. {
  1426. Bonus dummy;
  1427. dummy.type = type;
  1428. return sel(&dummy);
  1429. }
  1430. bool DLL_LINKAGE matchesTypeSubtype(const CSelector &sel, Bonus::BonusType type, TBonusSubtype subtype)
  1431. {
  1432. Bonus dummy;
  1433. dummy.type = type;
  1434. dummy.subtype = subtype;
  1435. return sel(&dummy);
  1436. }
  1437. }
  1438. const CStack * retrieveStackBattle(const CBonusSystemNode * node)
  1439. {
  1440. switch(node->getNodeType())
  1441. {
  1442. case CBonusSystemNode::STACK_BATTLE:
  1443. return static_cast<const CStack*>(node);
  1444. default:
  1445. return nullptr;
  1446. }
  1447. }
  1448. const CStackInstance * retrieveStackInstance(const CBonusSystemNode * node)
  1449. {
  1450. switch(node->getNodeType())
  1451. {
  1452. case CBonusSystemNode::STACK_INSTANCE:
  1453. return (static_cast<const CStackInstance *>(node));
  1454. case CBonusSystemNode::STACK_BATTLE:
  1455. return (static_cast<const CStack*>(node))->base;
  1456. default:
  1457. return nullptr;
  1458. }
  1459. }
  1460. const CCreature * retrieveCreature(const CBonusSystemNode *node)
  1461. {
  1462. switch(node->getNodeType())
  1463. {
  1464. case CBonusSystemNode::CREATURE:
  1465. return (static_cast<const CCreature *>(node));
  1466. case CBonusSystemNode::STACK_BATTLE:
  1467. return (static_cast<const CStack*>(node))->type;
  1468. default:
  1469. const CStackInstance * csi = retrieveStackInstance(node);
  1470. if(csi)
  1471. return csi->type;
  1472. return nullptr;
  1473. }
  1474. }
  1475. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const BonusList &bonusList)
  1476. {
  1477. for (ui32 i = 0; i < bonusList.size(); i++)
  1478. {
  1479. auto b = bonusList[i];
  1480. out << "Bonus " << i << "\n" << *b << std::endl;
  1481. }
  1482. return out;
  1483. }
  1484. DLL_LINKAGE std::ostream & operator<<(std::ostream &out, const Bonus &bonus)
  1485. {
  1486. for(auto i = bonusNameMap.cbegin(); i != bonusNameMap.cend(); i++)
  1487. if(i->second == bonus.type)
  1488. out << "\tType: " << i->first << " \t";
  1489. #define printField(field) out << "\t" #field ": " << (int)bonus.field << "\n"
  1490. printField(val);
  1491. printField(subtype);
  1492. printField(duration);
  1493. printField(source);
  1494. printField(sid);
  1495. if(bonus.additionalInfo != CAddInfo::NONE)
  1496. out << "\taddInfo: " << bonus.additionalInfo.toString() << "\n";
  1497. printField(turnsRemain);
  1498. printField(valType);
  1499. if(!bonus.stacking.empty())
  1500. out << "\tstacking: \"" << bonus.stacking << "\"\n";
  1501. printField(effectRange);
  1502. #undef printField
  1503. if(bonus.limiter)
  1504. out << "\tLimiter: " << bonus.limiter->toString() << "\n";
  1505. if(bonus.updater)
  1506. out << "\tUpdater: " << bonus.updater->toString() << "\n";
  1507. return out;
  1508. }
  1509. std::shared_ptr<Bonus> Bonus::addLimiter(TLimiterPtr Limiter)
  1510. {
  1511. if (limiter)
  1512. {
  1513. //If we already have limiter list, retrieve it
  1514. auto limiterList = std::dynamic_pointer_cast<AllOfLimiter>(limiter);
  1515. if(!limiterList)
  1516. {
  1517. //Create a new limiter list with old limiter and the new one will be pushed later
  1518. limiterList = std::make_shared<AllOfLimiter>();
  1519. limiterList->add(limiter);
  1520. limiter = limiterList;
  1521. }
  1522. limiterList->add(Limiter);
  1523. }
  1524. else
  1525. {
  1526. limiter = Limiter;
  1527. }
  1528. return this->shared_from_this();
  1529. }
  1530. ILimiter::~ILimiter()
  1531. {
  1532. }
  1533. int ILimiter::limit(const BonusLimitationContext &context) const /*return true to drop the bonus */
  1534. {
  1535. return false;
  1536. }
  1537. std::string ILimiter::toString() const
  1538. {
  1539. return typeid(*this).name();
  1540. }
  1541. JsonNode ILimiter::toJsonNode() const
  1542. {
  1543. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1544. root["type"].String() = toString();
  1545. return root;
  1546. }
  1547. int CCreatureTypeLimiter::limit(const BonusLimitationContext &context) const
  1548. {
  1549. const CCreature *c = retrieveCreature(&context.node);
  1550. if(!c)
  1551. return true;
  1552. return c != creature && (!includeUpgrades || !creature->isMyUpgrade(c));
  1553. //drop bonus if it's not our creature and (we don`t check upgrades or its not our upgrade)
  1554. }
  1555. CCreatureTypeLimiter::CCreatureTypeLimiter(const CCreature &Creature, bool IncludeUpgrades)
  1556. :creature(&Creature), includeUpgrades(IncludeUpgrades)
  1557. {
  1558. }
  1559. CCreatureTypeLimiter::CCreatureTypeLimiter()
  1560. {
  1561. creature = nullptr;
  1562. includeUpgrades = false;
  1563. }
  1564. void CCreatureTypeLimiter::setCreature (CreatureID id)
  1565. {
  1566. creature = VLC->creh->creatures[id];
  1567. }
  1568. std::string CCreatureTypeLimiter::toString() const
  1569. {
  1570. boost::format fmt("CCreatureTypeLimiter(creature=%s, includeUpgrades=%s)");
  1571. fmt % creature->identifier % (includeUpgrades ? "true" : "false");
  1572. return fmt.str();
  1573. }
  1574. JsonNode CCreatureTypeLimiter::toJsonNode() const
  1575. {
  1576. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1577. root["type"].String() = "CREATURE_TYPE_LIMITER";
  1578. root["parameters"].Vector().push_back(JsonUtils::stringNode(creature->identifier));
  1579. root["parameters"].Vector().push_back(JsonUtils::boolNode(includeUpgrades));
  1580. return root;
  1581. }
  1582. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus )
  1583. : type(bonus), subtype(0), isSubtypeRelevant(false)
  1584. {
  1585. }
  1586. HasAnotherBonusLimiter::HasAnotherBonusLimiter( Bonus::BonusType bonus, TBonusSubtype _subtype )
  1587. : type(bonus), subtype(_subtype), isSubtypeRelevant(true)
  1588. {
  1589. }
  1590. int HasAnotherBonusLimiter::limit(const BonusLimitationContext &context) const
  1591. {
  1592. CSelector mySelector = isSubtypeRelevant
  1593. ? Selector::typeSubtype(type, subtype)
  1594. : Selector::type()(type);
  1595. //if we have a bonus of required type accepted, limiter should accept also this bonus
  1596. if(context.alreadyAccepted.getFirst(mySelector))
  1597. return ACCEPT;
  1598. //if there are no matching bonuses pending, we can (and must) reject right away
  1599. if(!context.stillUndecided.getFirst(mySelector))
  1600. return DISCARD;
  1601. //do not accept for now but it may change if more bonuses gets included
  1602. return NOT_SURE;
  1603. }
  1604. std::string HasAnotherBonusLimiter::toString() const
  1605. {
  1606. std::string typeName = vstd::findKey(bonusNameMap, type);
  1607. if(isSubtypeRelevant)
  1608. {
  1609. boost::format fmt("HasAnotherBonusLimiter(type=%s, subtype=%d)");
  1610. fmt % typeName % subtype;
  1611. return fmt.str();
  1612. }
  1613. else
  1614. {
  1615. boost::format fmt("HasAnotherBonusLimiter(type=%s)");
  1616. fmt % typeName;
  1617. return fmt.str();
  1618. }
  1619. }
  1620. JsonNode HasAnotherBonusLimiter::toJsonNode() const
  1621. {
  1622. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1623. std::string typeName = vstd::findKey(bonusNameMap, type);
  1624. root["type"].String() = "HAS_ANOTHER_BONUS_LIMITER";
  1625. root["parameters"].Vector().push_back(JsonUtils::stringNode(typeName));
  1626. if(isSubtypeRelevant)
  1627. root["parameters"].Vector().push_back(JsonUtils::intNode(subtype));
  1628. return root;
  1629. }
  1630. IPropagator::~IPropagator()
  1631. {
  1632. }
  1633. bool IPropagator::shouldBeAttached(CBonusSystemNode *dest)
  1634. {
  1635. return false;
  1636. }
  1637. CBonusSystemNode::ENodeTypes IPropagator::getPropagatorType() const
  1638. {
  1639. return CBonusSystemNode::ENodeTypes::NONE;
  1640. }
  1641. CPropagatorNodeType::CPropagatorNodeType()
  1642. :nodeType(CBonusSystemNode::ENodeTypes::UNKNOWN)
  1643. {
  1644. }
  1645. CPropagatorNodeType::CPropagatorNodeType(CBonusSystemNode::ENodeTypes NodeType)
  1646. : nodeType(NodeType)
  1647. {
  1648. }
  1649. CBonusSystemNode::ENodeTypes CPropagatorNodeType::getPropagatorType() const
  1650. {
  1651. return nodeType;
  1652. }
  1653. bool CPropagatorNodeType::shouldBeAttached(CBonusSystemNode *dest)
  1654. {
  1655. return nodeType == dest->getNodeType();
  1656. }
  1657. CreatureTerrainLimiter::CreatureTerrainLimiter(int TerrainType)
  1658. : terrainType(TerrainType)
  1659. {
  1660. }
  1661. CreatureTerrainLimiter::CreatureTerrainLimiter()
  1662. : terrainType(-1)
  1663. {
  1664. }
  1665. int CreatureTerrainLimiter::limit(const BonusLimitationContext &context) const
  1666. {
  1667. const CStack *stack = retrieveStackBattle(&context.node);
  1668. if(stack)
  1669. {
  1670. if(terrainType == -1)//terrainType not specified = native
  1671. return !stack->isOnNativeTerrain();
  1672. return !stack->isOnTerrain(terrainType);
  1673. }
  1674. return true;
  1675. //TODO neutral creatues
  1676. }
  1677. std::string CreatureTerrainLimiter::toString() const
  1678. {
  1679. boost::format fmt("CreatureTerrainLimiter(terrainType=%s)");
  1680. fmt % (terrainType >= 0 ? GameConstants::TERRAIN_NAMES[terrainType] : "native");
  1681. return fmt.str();
  1682. }
  1683. JsonNode CreatureTerrainLimiter::toJsonNode() const
  1684. {
  1685. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1686. root["type"].String() = "CREATURE_TERRAIN_LIMITER";
  1687. if(terrainType >= 0)
  1688. root["parameters"].Vector().push_back(JsonUtils::stringNode(GameConstants::TERRAIN_NAMES[terrainType]));
  1689. return root;
  1690. }
  1691. CreatureFactionLimiter::CreatureFactionLimiter(TFaction creatureFaction)
  1692. : faction(creatureFaction)
  1693. {
  1694. }
  1695. CreatureFactionLimiter::CreatureFactionLimiter()
  1696. : faction((TFaction)-1)
  1697. {
  1698. }
  1699. int CreatureFactionLimiter::limit(const BonusLimitationContext &context) const
  1700. {
  1701. const CCreature *c = retrieveCreature(&context.node);
  1702. return !c || c->faction != faction; //drop bonus for non-creatures or non-native residents
  1703. }
  1704. std::string CreatureFactionLimiter::toString() const
  1705. {
  1706. boost::format fmt("CreatureFactionLimiter(faction=%s)");
  1707. fmt % VLC->townh->factions[faction]->identifier;
  1708. return fmt.str();
  1709. }
  1710. JsonNode CreatureFactionLimiter::toJsonNode() const
  1711. {
  1712. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1713. root["type"].String() = "CREATURE_FACTION_LIMITER";
  1714. root["parameters"].Vector().push_back(JsonUtils::stringNode(VLC->townh->factions[faction]->identifier));
  1715. return root;
  1716. }
  1717. CreatureAlignmentLimiter::CreatureAlignmentLimiter()
  1718. : alignment(-1)
  1719. {
  1720. }
  1721. CreatureAlignmentLimiter::CreatureAlignmentLimiter(si8 Alignment)
  1722. : alignment(Alignment)
  1723. {
  1724. }
  1725. int CreatureAlignmentLimiter::limit(const BonusLimitationContext &context) const
  1726. {
  1727. const CCreature *c = retrieveCreature(&context.node);
  1728. if(!c)
  1729. return true;
  1730. switch(alignment)
  1731. {
  1732. case EAlignment::GOOD:
  1733. return !c->isGood(); //if not good -> return true (drop bonus)
  1734. case EAlignment::NEUTRAL:
  1735. return c->isEvil() || c->isGood();
  1736. case EAlignment::EVIL:
  1737. return !c->isEvil();
  1738. default:
  1739. logBonus->warn("Warning: illegal alignment in limiter!");
  1740. return true;
  1741. }
  1742. }
  1743. std::string CreatureAlignmentLimiter::toString() const
  1744. {
  1745. boost::format fmt("CreatureAlignmentLimiter(alignment=%s)");
  1746. fmt % EAlignment::names[alignment];
  1747. return fmt.str();
  1748. }
  1749. JsonNode CreatureAlignmentLimiter::toJsonNode() const
  1750. {
  1751. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1752. root["type"].String() = "CREATURE_ALIGNMENT_LIMITER";
  1753. root["parameters"].Vector().push_back(JsonUtils::stringNode(EAlignment::names[alignment]));
  1754. return root;
  1755. }
  1756. RankRangeLimiter::RankRangeLimiter(ui8 Min, ui8 Max)
  1757. :minRank(Min), maxRank(Max)
  1758. {
  1759. }
  1760. RankRangeLimiter::RankRangeLimiter()
  1761. {
  1762. minRank = maxRank = -1;
  1763. }
  1764. int RankRangeLimiter::limit(const BonusLimitationContext &context) const
  1765. {
  1766. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1767. if(csi)
  1768. {
  1769. if (csi->getNodeType() == CBonusSystemNode::COMMANDER) //no stack exp bonuses for commander creatures
  1770. return true;
  1771. return csi->getExpRank() < minRank || csi->getExpRank() > maxRank;
  1772. }
  1773. return true;
  1774. }
  1775. int StackOwnerLimiter::limit(const BonusLimitationContext &context) const
  1776. {
  1777. const CStack * s = retrieveStackBattle(&context.node);
  1778. if(s)
  1779. return s->owner != owner;
  1780. const CStackInstance * csi = retrieveStackInstance(&context.node);
  1781. if(csi && csi->armyObj)
  1782. return csi->armyObj->tempOwner != owner;
  1783. return true;
  1784. }
  1785. StackOwnerLimiter::StackOwnerLimiter()
  1786. : owner(-1)
  1787. {
  1788. }
  1789. StackOwnerLimiter::StackOwnerLimiter(PlayerColor Owner)
  1790. : owner(Owner)
  1791. {
  1792. }
  1793. // Aggregate/Boolean Limiters
  1794. void AggregateLimiter::add(TLimiterPtr limiter)
  1795. {
  1796. if(limiter)
  1797. limiters.push_back(limiter);
  1798. }
  1799. JsonNode AggregateLimiter::toJsonNode() const
  1800. {
  1801. JsonNode result(JsonNode::JsonType::DATA_VECTOR);
  1802. result.Vector().push_back(JsonUtils::stringNode(getAggregator()));
  1803. for(auto l : limiters)
  1804. result.Vector().push_back(l->toJsonNode());
  1805. return result;
  1806. }
  1807. const std::string AllOfLimiter::aggregator = "allOf";
  1808. const std::string & AllOfLimiter::getAggregator() const
  1809. {
  1810. return aggregator;
  1811. }
  1812. int AllOfLimiter::limit(const BonusLimitationContext & context) const
  1813. {
  1814. bool wasntSure = false;
  1815. for(auto limiter : limiters)
  1816. {
  1817. auto result = limiter->limit(context);
  1818. if(result == ILimiter::DISCARD)
  1819. return result;
  1820. if(result == ILimiter::NOT_SURE)
  1821. wasntSure = true;
  1822. }
  1823. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1824. }
  1825. const std::string AnyOfLimiter::aggregator = "anyOf";
  1826. const std::string & AnyOfLimiter::getAggregator() const
  1827. {
  1828. return aggregator;
  1829. }
  1830. int AnyOfLimiter::limit(const BonusLimitationContext & context) const
  1831. {
  1832. bool wasntSure = false;
  1833. for(auto limiter : limiters)
  1834. {
  1835. auto result = limiter->limit(context);
  1836. if(result == ILimiter::ACCEPT)
  1837. return result;
  1838. if(result == ILimiter::NOT_SURE)
  1839. wasntSure = true;
  1840. }
  1841. return wasntSure ? ILimiter::NOT_SURE : ILimiter::DISCARD;
  1842. }
  1843. const std::string NoneOfLimiter::aggregator = "noneOf";
  1844. const std::string & NoneOfLimiter::getAggregator() const
  1845. {
  1846. return aggregator;
  1847. }
  1848. int NoneOfLimiter::limit(const BonusLimitationContext & context) const
  1849. {
  1850. bool wasntSure = false;
  1851. for(auto limiter : limiters)
  1852. {
  1853. auto result = limiter->limit(context);
  1854. if(result == ILimiter::ACCEPT)
  1855. return ILimiter::DISCARD;
  1856. if(result == ILimiter::NOT_SURE)
  1857. wasntSure = true;
  1858. }
  1859. return wasntSure ? ILimiter::NOT_SURE : ILimiter::ACCEPT;
  1860. }
  1861. // Updaters
  1862. std::shared_ptr<Bonus> Bonus::addUpdater(TUpdaterPtr Updater)
  1863. {
  1864. updater = Updater;
  1865. return this->shared_from_this();
  1866. }
  1867. IUpdater::~IUpdater()
  1868. {
  1869. }
  1870. std::shared_ptr<Bonus> IUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1871. {
  1872. return b;
  1873. }
  1874. std::string IUpdater::toString() const
  1875. {
  1876. return typeid(*this).name();
  1877. }
  1878. JsonNode IUpdater::toJsonNode() const
  1879. {
  1880. return JsonNode(JsonNode::JsonType::DATA_NULL);
  1881. }
  1882. GrowsWithLevelUpdater::GrowsWithLevelUpdater() : valPer20(0), stepSize(1)
  1883. {
  1884. }
  1885. GrowsWithLevelUpdater::GrowsWithLevelUpdater(int valPer20, int stepSize) : valPer20(valPer20), stepSize(stepSize)
  1886. {
  1887. }
  1888. std::shared_ptr<Bonus> GrowsWithLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1889. {
  1890. if(context.getNodeType() == CBonusSystemNode::HERO)
  1891. {
  1892. int level = static_cast<const CGHeroInstance &>(context).level;
  1893. int steps = stepSize ? level / stepSize : level;
  1894. //rounding follows format for HMM3 creature specialty bonus
  1895. int newVal = (valPer20 * steps + 19) / 20;
  1896. //return copy of bonus with updated val
  1897. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1898. newBonus->val = newVal;
  1899. return newBonus;
  1900. }
  1901. return b;
  1902. }
  1903. std::string GrowsWithLevelUpdater::toString() const
  1904. {
  1905. return boost::str(boost::format("GrowsWithLevelUpdater(valPer20=%d, stepSize=%d)") % valPer20 % stepSize);
  1906. }
  1907. JsonNode GrowsWithLevelUpdater::toJsonNode() const
  1908. {
  1909. JsonNode root(JsonNode::JsonType::DATA_STRUCT);
  1910. root["type"].String() = "GROWS_WITH_LEVEL";
  1911. root["parameters"].Vector().push_back(JsonUtils::intNode(valPer20));
  1912. if(stepSize > 1)
  1913. root["parameters"].Vector().push_back(JsonUtils::intNode(stepSize));
  1914. return root;
  1915. }
  1916. TimesHeroLevelUpdater::TimesHeroLevelUpdater()
  1917. {
  1918. }
  1919. std::shared_ptr<Bonus> TimesHeroLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1920. {
  1921. if(context.getNodeType() == CBonusSystemNode::HERO)
  1922. {
  1923. int level = static_cast<const CGHeroInstance &>(context).level;
  1924. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1925. newBonus->val *= level;
  1926. return newBonus;
  1927. }
  1928. return b;
  1929. }
  1930. std::string TimesHeroLevelUpdater::toString() const
  1931. {
  1932. return "TimesHeroLevelUpdater";
  1933. }
  1934. JsonNode TimesHeroLevelUpdater::toJsonNode() const
  1935. {
  1936. return JsonUtils::stringNode("TIMES_HERO_LEVEL");
  1937. }
  1938. TimesStackLevelUpdater::TimesStackLevelUpdater()
  1939. {
  1940. }
  1941. std::shared_ptr<Bonus> TimesStackLevelUpdater::update(const std::shared_ptr<Bonus> & b, const CBonusSystemNode & context) const
  1942. {
  1943. if(context.getNodeType() == CBonusSystemNode::STACK_INSTANCE)
  1944. {
  1945. int level = static_cast<const CStackInstance &>(context).getLevel();
  1946. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1947. newBonus->val *= level;
  1948. return newBonus;
  1949. }
  1950. else if(context.getNodeType() == CBonusSystemNode::STACK_BATTLE)
  1951. {
  1952. const CStack & stack = static_cast<const CStack &>(context);
  1953. //only update if stack doesn't have an instance (summons, war machines)
  1954. //otherwise we'd end up multiplying twice
  1955. if(stack.base == nullptr)
  1956. {
  1957. int level = stack.type->level;
  1958. std::shared_ptr<Bonus> newBonus = std::make_shared<Bonus>(*b);
  1959. newBonus->val *= level;
  1960. return newBonus;
  1961. }
  1962. }
  1963. return b;
  1964. }
  1965. std::string TimesStackLevelUpdater::toString() const
  1966. {
  1967. return "TimesStackLevelUpdater";
  1968. }
  1969. JsonNode TimesStackLevelUpdater::toJsonNode() const
  1970. {
  1971. return JsonUtils::stringNode("TIMES_STACK_LEVEL");
  1972. }