HeroBonus.cpp 59 KB

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