HeroBonus.cpp 75 KB

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