HeroBonus.cpp 60 KB

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