HeroBonus.cpp 74 KB

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