CSpellHandler.cpp 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  1. #include "StdInc.h"
  2. #include "CSpellHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "JsonNode.h"
  6. #include <cctype>
  7. #include "BattleHex.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. #include "mapObjects/CGHeroInstance.h"
  11. #include "BattleState.h"
  12. /*
  13. * CSpellHandler.cpp, part of VCMI engine
  14. *
  15. * Authors: listed in file AUTHORS in main folder
  16. *
  17. * License: GNU General Public License v2.0 or later
  18. * Full text of license available in license.txt file, in main folder
  19. *
  20. */
  21. namespace SpellConfig
  22. {
  23. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  24. }
  25. namespace SRSLPraserHelpers
  26. {
  27. static int XYToHex(int x, int y)
  28. {
  29. return x + 17 * y;
  30. }
  31. static int XYToHex(std::pair<int, int> xy)
  32. {
  33. return XYToHex(xy.first, xy.second);
  34. }
  35. static int hexToY(int battleFieldPosition)
  36. {
  37. return battleFieldPosition/17;
  38. }
  39. static int hexToX(int battleFieldPosition)
  40. {
  41. int pos = battleFieldPosition - hexToY(battleFieldPosition) * 17;
  42. return pos;
  43. }
  44. static std::pair<int, int> hexToPair(int battleFieldPosition)
  45. {
  46. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  47. }
  48. //moves hex by one hex in given direction
  49. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  50. static std::pair<int, int> gotoDir(int x, int y, int direction)
  51. {
  52. switch(direction)
  53. {
  54. case 0: //top left
  55. return std::make_pair((y%2) ? x-1 : x, y-1);
  56. case 1: //top right
  57. return std::make_pair((y%2) ? x : x+1, y-1);
  58. case 2: //right
  59. return std::make_pair(x+1, y);
  60. case 3: //right bottom
  61. return std::make_pair((y%2) ? x : x+1, y+1);
  62. case 4: //left bottom
  63. return std::make_pair((y%2) ? x-1 : x, y+1);
  64. case 5: //left
  65. return std::make_pair(x-1, y);
  66. default:
  67. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  68. }
  69. }
  70. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  71. {
  72. return gotoDir(xy.first, xy.second, direction);
  73. }
  74. static bool isGoodHex(std::pair<int, int> xy)
  75. {
  76. return xy.first >=0 && xy.first < 17 && xy.second >= 0 && xy.second < 11;
  77. }
  78. //helper function for std::set<ui16> CSpell::rangeInHexes(unsigned int centralHex, ui8 schoolLvl ) const
  79. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  80. {
  81. std::set<ui16> ret;
  82. if(low == 0)
  83. {
  84. ret.insert(center);
  85. }
  86. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  87. for(auto & elem : mainPointForLayer)
  88. elem = hexToPair(center);
  89. for(int it=1; it<=high; ++it) //it - distance to the center
  90. {
  91. for(int b=0; b<6; ++b)
  92. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  93. if(it>=low)
  94. {
  95. std::pair<int, int> curHex;
  96. //adding lines (A-b, B-c, C-d, etc)
  97. for(int v=0; v<6; ++v)
  98. {
  99. curHex = mainPointForLayer[v];
  100. for(int h=0; h<it; ++h)
  101. {
  102. if(isGoodHex(curHex))
  103. ret.insert(XYToHex(curHex));
  104. curHex = gotoDir(curHex, (v+2)%6);
  105. }
  106. }
  107. } //if(it>=low)
  108. }
  109. return ret;
  110. }
  111. }
  112. ///CSpellMechanics
  113. CSpellMechanics::CSpellMechanics(CSpell * s):
  114. owner(s)
  115. {
  116. }
  117. CSpellMechanics::~CSpellMechanics()
  118. {
  119. }
  120. ESpellCastProblem::ESpellCastProblem CSpellMechanics::isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj)
  121. {
  122. //by default use general algorithm
  123. return owner->isImmuneBy(obj);
  124. }
  125. namespace
  126. {
  127. class CloneMechnics: public CSpellMechanics
  128. {
  129. public:
  130. CloneMechnics(CSpell * s): CSpellMechanics(s){};
  131. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  132. };
  133. class DispellHelpfulMechanics: public CSpellMechanics
  134. {
  135. public:
  136. DispellHelpfulMechanics(CSpell * s): CSpellMechanics(s){};
  137. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  138. };
  139. ///all rising spells
  140. class RisingSpellMechanics: public CSpellMechanics
  141. {
  142. public:
  143. RisingSpellMechanics(CSpell * s): CSpellMechanics(s){};
  144. };
  145. ///all rising spells but SACRIFICE
  146. class SpecialRisingSpellMechanics: public RisingSpellMechanics
  147. {
  148. public:
  149. SpecialRisingSpellMechanics(CSpell * s): RisingSpellMechanics(s){};
  150. ESpellCastProblem::ESpellCastProblem isImmuneByStack(const CGHeroInstance * caster, ECastingMode::ECastingMode mode, const CStack * obj) override;
  151. };
  152. class SacrificeMechanics: public RisingSpellMechanics
  153. {
  154. public:
  155. };
  156. ///CloneMechanics
  157. ESpellCastProblem::ESpellCastProblem CloneMechnics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack * obj)
  158. {
  159. //can't clone already cloned creature
  160. if (vstd::contains(obj->state, EBattleStackState::CLONED))
  161. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  162. //TODO: how about stacks casting Clone?
  163. //currently Clone casted by stack is assumed Expert level
  164. ui8 schoolLevel;
  165. if (caster)
  166. {
  167. schoolLevel = caster->getSpellSchoolLevel(owner);
  168. }
  169. else
  170. {
  171. schoolLevel = 3;
  172. }
  173. if (schoolLevel < 3)
  174. {
  175. int maxLevel = (std::max(schoolLevel, (ui8)1) + 4);
  176. int creLevel = obj->getCreature()->level;
  177. if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, any level for expert
  178. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  179. }
  180. //use default algorithm only if there is no mechanics-related problem
  181. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  182. }
  183. ///DispellHelpfulMechanics
  184. ESpellCastProblem::ESpellCastProblem DispellHelpfulMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  185. {
  186. TBonusListPtr spellBon = obj->getSpellBonuses();
  187. bool hasPositiveSpell = false;
  188. for(const Bonus * b : *spellBon)
  189. {
  190. if(SpellID(b->sid).toSpell()->isPositive())
  191. {
  192. hasPositiveSpell = true;
  193. break;
  194. }
  195. }
  196. if(!hasPositiveSpell)
  197. {
  198. return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
  199. }
  200. //use default algorithm only if there is no mechanics-related problem
  201. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  202. }
  203. ///SpecialRisingSpellMechanics
  204. ESpellCastProblem::ESpellCastProblem SpecialRisingSpellMechanics::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj)
  205. {
  206. // following does apply to resurrect and animate dead(?) only
  207. // for sacrifice health calculation and health limit check don't matter
  208. if(obj->count >= obj->baseAmount)
  209. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  210. if (caster) //FIXME: Archangels can cast immune stack
  211. {
  212. auto maxHealth = calculateHealedHP (caster, obj);
  213. if (maxHealth < obj->MaxHealth()) //must be able to rise at least one full creature
  214. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  215. }
  216. return CSpellMechanics::isImmuneByStack(caster,mode,obj);
  217. }
  218. }
  219. ///CSpell::LevelInfo
  220. CSpell::LevelInfo::LevelInfo()
  221. :description(""),cost(0),power(0),AIValue(0),smartTarget(true),range("0")
  222. {
  223. }
  224. CSpell::LevelInfo::~LevelInfo()
  225. {
  226. }
  227. ///CSpell
  228. CSpell::CSpell():
  229. id(SpellID::NONE), level(0),
  230. earth(false), water(false), fire(false), air(false),
  231. combatSpell(false), creatureAbility(false),
  232. positiveness(ESpellPositiveness::NEUTRAL),
  233. mainEffectAnim(-1),
  234. defaultProbability(0),
  235. isRising(false), isDamage(false), isOffensive(false),
  236. targetType(ETargetType::NO_TARGET),
  237. mechanics(nullptr)
  238. {
  239. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  240. }
  241. CSpell::~CSpell()
  242. {
  243. delete mechanics;
  244. }
  245. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  246. {
  247. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  248. {
  249. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  250. throw new std::runtime_error("Invalid school level");
  251. }
  252. return levels.at(level);
  253. }
  254. ui32 CSpell::calculateBonus(ui32 baseDamage, const CGHeroInstance* caster, const CStack* affectedCreature) const
  255. {
  256. ui32 ret = baseDamage;
  257. //applying sorcery secondary skill
  258. if(caster)
  259. {
  260. ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
  261. ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, id.toEnum())) / 100.0;
  262. if(air)
  263. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  264. else if(fire) //only one type of bonus for Magic Arrow
  265. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  266. else if(water)
  267. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  268. else if(earth)
  269. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  270. if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
  271. ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
  272. }
  273. return ret;
  274. }
  275. ui32 CSpell::calculateHealedHP(const CGHeroInstance* caster, const CStack* stack, const CStack* sacrificedStack) const
  276. {
  277. //todo: use Mechanics class
  278. int healedHealth;
  279. if(!isHealingSpell())
  280. {
  281. logGlobal->errorStream() << "calculateHealedHP called for nonhealing spell "<< name;
  282. return 0;
  283. }
  284. const int spellPowerSkill = caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  285. const int levelPower = getPower(caster->getSpellSchoolLevel(this));
  286. if (id == SpellID::SACRIFICE && sacrificedStack)
  287. healedHealth = (spellPowerSkill + sacrificedStack->MaxHealth() + levelPower) * sacrificedStack->count;
  288. else
  289. healedHealth = spellPowerSkill * power + levelPower); //???
  290. healedHealth = calculateBonus(healedHealth, caster, stack);
  291. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (isRisingSpell() ? stack->baseAmount * stack->MaxHealth() : 0));
  292. }
  293. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  294. {
  295. using namespace SRSLPraserHelpers;
  296. std::vector<BattleHex> ret;
  297. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  298. {
  299. //Special case - shape of obstacle depends on caster's side
  300. //TODO make it possible through spell_info config
  301. BattleHex::EDir firstStep, secondStep;
  302. if(side)
  303. {
  304. firstStep = BattleHex::TOP_LEFT;
  305. secondStep = BattleHex::TOP_RIGHT;
  306. }
  307. else
  308. {
  309. firstStep = BattleHex::TOP_RIGHT;
  310. secondStep = BattleHex::TOP_LEFT;
  311. }
  312. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  313. auto addIfValid = [&](BattleHex hex)
  314. {
  315. if(hex.isValid())
  316. ret.push_back(hex);
  317. else if(outDroppedHexes)
  318. *outDroppedHexes = true;
  319. };
  320. ret.push_back(centralHex);
  321. addIfValid(centralHex.moveInDir(firstStep, false));
  322. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  323. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  324. return ret;
  325. }
  326. std::string rng = getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  327. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  328. {
  329. std::string number1, number2;
  330. int beg, end;
  331. bool readingFirst = true;
  332. for(auto & elem : rng)
  333. {
  334. if(std::isdigit(elem) ) //reading number
  335. {
  336. if(readingFirst)
  337. number1 += elem;
  338. else
  339. number2 += elem;
  340. }
  341. else if(elem == ',') //comma
  342. {
  343. //calculating variables
  344. if(readingFirst)
  345. {
  346. beg = atoi(number1.c_str());
  347. number1 = "";
  348. }
  349. else
  350. {
  351. end = atoi(number2.c_str());
  352. number2 = "";
  353. }
  354. //obtaining new hexes
  355. std::set<ui16> curLayer;
  356. if(readingFirst)
  357. {
  358. curLayer = getInRange(centralHex, beg, beg);
  359. }
  360. else
  361. {
  362. curLayer = getInRange(centralHex, beg, end);
  363. readingFirst = true;
  364. }
  365. //adding abtained hexes
  366. for(auto & curLayer_it : curLayer)
  367. {
  368. ret.push_back(curLayer_it);
  369. }
  370. }
  371. else if(elem == '-') //dash
  372. {
  373. beg = atoi(number1.c_str());
  374. number1 = "";
  375. readingFirst = false;
  376. }
  377. }
  378. }
  379. //remove duplicates (TODO check if actually needed)
  380. range::unique(ret);
  381. return ret;
  382. }
  383. CSpell::ETargetType CSpell::getTargetType() const
  384. {
  385. return targetType;
  386. }
  387. const CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  388. {
  389. TargetInfo info;
  390. auto & levelInfo = getLevelInfo(level);
  391. info.type = getTargetType();
  392. info.smart = levelInfo.smartTarget;
  393. info.massive = levelInfo.range == "X";
  394. info.onlyAlive = !isRisingSpell();
  395. return info;
  396. }
  397. bool CSpell::isCombatSpell() const
  398. {
  399. return combatSpell;
  400. }
  401. bool CSpell::isAdventureSpell() const
  402. {
  403. return !combatSpell;
  404. }
  405. bool CSpell::isCreatureAbility() const
  406. {
  407. return creatureAbility;
  408. }
  409. bool CSpell::isPositive() const
  410. {
  411. return positiveness == POSITIVE;
  412. }
  413. bool CSpell::isNegative() const
  414. {
  415. return positiveness == NEGATIVE;
  416. }
  417. bool CSpell::isNeutral() const
  418. {
  419. return positiveness == NEUTRAL;
  420. }
  421. bool CSpell::isHealingSpell() const
  422. {
  423. return isRisingSpell() || (id == SpellID::CURE);
  424. }
  425. bool CSpell::isRisingSpell() const
  426. {
  427. return isRising;
  428. }
  429. bool CSpell::isDamageSpell() const
  430. {
  431. return isDamage;
  432. }
  433. bool CSpell::isOffensiveSpell() const
  434. {
  435. return isOffensive;
  436. }
  437. bool CSpell::isSpecialSpell() const
  438. {
  439. return isSpecial;
  440. }
  441. bool CSpell::hasEffects() const
  442. {
  443. return !levels[0].effects.empty();
  444. }
  445. const std::string& CSpell::getIconImmune() const
  446. {
  447. return iconImmune;
  448. }
  449. const std::string& CSpell::getCastSound() const
  450. {
  451. return castSound;
  452. }
  453. si32 CSpell::getCost(const int skillLevel) const
  454. {
  455. return getLevelInfo(skillLevel).cost;
  456. }
  457. si32 CSpell::getPower(const int skillLevel) const
  458. {
  459. return getLevelInfo(skillLevel).power;
  460. }
  461. //si32 CSpell::calculatePower(const int skillLevel) const
  462. //{
  463. // return power + getPower(skillLevel);
  464. //}
  465. si32 CSpell::getProbability(const TFaction factionId) const
  466. {
  467. if(!vstd::contains(probabilities,factionId))
  468. {
  469. return defaultProbability;
  470. }
  471. return probabilities.at(factionId);
  472. }
  473. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  474. {
  475. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  476. {
  477. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  478. return;
  479. }
  480. const std::vector<Bonus> & effects = levels[level].effects;
  481. if(effects.empty())
  482. {
  483. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  484. return;
  485. }
  486. lst.reserve(lst.size() + effects.size());
  487. for(const Bonus & b : effects)
  488. {
  489. lst.push_back(Bonus(b));
  490. }
  491. }
  492. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  493. {
  494. //0. check receptivity
  495. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  496. return ESpellCastProblem::OK;
  497. //todo: use new bonus API
  498. //1. Check absolute limiters
  499. for(auto b : absoluteLimiters)
  500. {
  501. if (!obj->hasBonusOfType(b))
  502. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  503. }
  504. //2. Check absolute immunities
  505. for(auto b : absoluteImmunities)
  506. {
  507. if (obj->hasBonusOfType(b))
  508. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  509. }
  510. //3. Check negation
  511. //FIXME: Orb of vulnerability mechanics is not such trivial
  512. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  513. return ESpellCastProblem::NOT_DECIDED;
  514. //4. Check negatable limit
  515. for(auto b : limiters)
  516. {
  517. if (!obj->hasBonusOfType(b))
  518. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  519. }
  520. //5. Check negatable immunities
  521. for(auto b : immunities)
  522. {
  523. if (obj->hasBonusOfType(b))
  524. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  525. }
  526. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  527. {
  528. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  529. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  530. else if(!isPositive()) //negative or indifferent
  531. {
  532. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  533. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  534. }
  535. return ESpellCastProblem::NOT_DECIDED;
  536. };
  537. //6. Check elemental immunities
  538. if(fire)
  539. {
  540. if(battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  541. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  542. }
  543. if(water)
  544. {
  545. if(battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  546. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  547. }
  548. if(earth)
  549. {
  550. if(battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  551. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  552. }
  553. if(air)
  554. {
  555. if(battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  556. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  557. }
  558. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  559. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  560. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  561. {
  562. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  563. }
  564. return ESpellCastProblem::NOT_DECIDED;
  565. }
  566. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj) const
  567. {
  568. return mechanics->isImmuneByStack(caster,mode,obj);
  569. }
  570. void CSpell::setIsOffensive(const bool val)
  571. {
  572. isOffensive = val;
  573. if(val)
  574. {
  575. positiveness = CSpell::NEGATIVE;
  576. isDamage = true;
  577. }
  578. }
  579. void CSpell::setIsRising(const bool val)
  580. {
  581. isRising = val;
  582. if(val)
  583. {
  584. positiveness = CSpell::POSITIVE;
  585. }
  586. }
  587. void CSpell::setupMechanics()
  588. {
  589. if(nullptr != mechanics)
  590. {
  591. logGlobal->errorStream() << "Spell " << this->name << " mechanics already set";
  592. delete mechanics;
  593. mechanics = nullptr;
  594. }
  595. switch (id)
  596. {
  597. case SpellID::CLONE:
  598. mechanics = new CloneMechnics(this);
  599. break;
  600. case SpellID::DISPEL_HELPFUL_SPELLS:
  601. mechanics = new DispellHelpfulMechanics(this);
  602. break;
  603. case SpellID::SACRIFICE:
  604. mechanics = new SacrificeMechanics(this);
  605. break
  606. default:
  607. if(isRisingSpell())
  608. mechanics = new SpecialRisingSpellMechanics(this);
  609. else
  610. mechanics = new CSpellMechanics(this);
  611. break;
  612. }
  613. }
  614. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  615. {
  616. int3 diff = pos - center;
  617. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  618. return true;
  619. else
  620. return false;
  621. }
  622. ///CSpellHandler
  623. CSpellHandler::CSpellHandler()
  624. {
  625. }
  626. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  627. {
  628. using namespace SpellConfig;
  629. std::vector<JsonNode> legacyData;
  630. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  631. auto readSchool = [&](JsonMap& schools, const std::string& name)
  632. {
  633. if (parser.readString() == "x")
  634. {
  635. schools[name].Bool() = true;
  636. }
  637. };
  638. auto read = [&,this](bool combat, bool ability)
  639. {
  640. do
  641. {
  642. JsonNode lineNode(JsonNode::DATA_STRUCT);
  643. const si32 id = legacyData.size();
  644. lineNode["index"].Float() = id;
  645. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  646. lineNode["name"].String() = parser.readString();
  647. parser.readString(); //ignored unused abbreviated name
  648. lineNode["level"].Float() = parser.readNumber();
  649. auto& schools = lineNode["school"].Struct();
  650. readSchool(schools, "earth");
  651. readSchool(schools, "water");
  652. readSchool(schools, "fire");
  653. readSchool(schools, "air");
  654. auto& levels = lineNode["levels"].Struct();
  655. auto getLevel = [&](const size_t idx)->JsonMap&
  656. {
  657. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  658. return levels[LEVEL_NAMES[idx]].Struct();
  659. };
  660. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  661. lineNode["power"].Float() = parser.readNumber();
  662. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  663. auto& chances = lineNode["gainChance"].Struct();
  664. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  665. chances[ETownType::names[i]].Float() = parser.readNumber();
  666. }
  667. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  668. std::vector<std::string> descriptions;
  669. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  670. descriptions.push_back(parser.readString());
  671. std::string attributes = parser.readString();
  672. std::string targetType = "NO_TARGET";
  673. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  674. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  675. targetType = "CREATURE_EXPERT_MASSIVE";
  676. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  677. targetType = "CREATURE";
  678. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  679. targetType = "OBSTACLE";
  680. //save parsed level specific data
  681. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  682. {
  683. auto& level = getLevel(i);
  684. level["description"].String() = descriptions[i];
  685. level["cost"].Float() = costs[i];
  686. level["power"].Float() = powers[i];
  687. level["aiValue"].Float() = AIVals[i];
  688. }
  689. if(targetType == "CREATURE_EXPERT_MASSIVE")
  690. {
  691. lineNode["targetType"].String() = "CREATURE";
  692. getLevel(3)["range"].String() = "X";
  693. }
  694. else
  695. {
  696. lineNode["targetType"].String() = targetType;
  697. }
  698. legacyData.push_back(lineNode);
  699. }
  700. while (parser.endLine() && !parser.isNextEntryEmpty());
  701. };
  702. auto skip = [&](int cnt)
  703. {
  704. for(int i=0; i<cnt; i++)
  705. parser.endLine();
  706. };
  707. skip(5);// header
  708. read(false,false); //read adventure map spells
  709. skip(3);
  710. read(true,false); //read battle spells
  711. skip(3);
  712. read(true,true);//read creature abilities
  713. //TODO: maybe move to config
  714. //clone Acid Breath attributes for Acid Breath damage effect
  715. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  716. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  717. legacyData.push_back(temp);
  718. objects.resize(legacyData.size());
  719. return legacyData;
  720. }
  721. const std::string CSpellHandler::getTypeName() const
  722. {
  723. return "spell";
  724. }
  725. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  726. {
  727. using namespace SpellConfig;
  728. CSpell * spell = new CSpell();
  729. const auto type = json["type"].String();
  730. if(type == "ability")
  731. {
  732. spell->creatureAbility = true;
  733. spell->combatSpell = true;
  734. }
  735. else
  736. {
  737. spell->creatureAbility = false;
  738. spell->combatSpell = type == "combat";
  739. }
  740. spell->name = json["name"].String();
  741. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  742. const auto schoolNames = json["school"];
  743. spell->air = schoolNames["air"].Bool();
  744. spell->earth = schoolNames["earth"].Bool();
  745. spell->fire = schoolNames["fire"].Bool();
  746. spell->water = schoolNames["water"].Bool();
  747. spell->level = json["level"].Float();
  748. spell->power = json["power"].Float();
  749. spell->defaultProbability = json["defaultGainChance"].Float();
  750. for(const auto & node : json["gainChance"].Struct())
  751. {
  752. const int chance = node.second.Float();
  753. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  754. {
  755. spell->probabilities[factionID] = chance;
  756. });
  757. }
  758. const std::string targetType = json["targetType"].String();
  759. if(targetType == "NO_TARGET")
  760. spell->targetType = CSpell::NO_TARGET;
  761. else if(targetType == "CREATURE")
  762. spell->targetType = CSpell::CREATURE;
  763. else if(targetType == "OBSTACLE")
  764. spell->targetType = CSpell::OBSTACLE;
  765. else
  766. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  767. spell->mainEffectAnim = json["anim"].Float();
  768. for(const auto & counteredSpell: json["counters"].Struct())
  769. if (counteredSpell.second.Bool())
  770. {
  771. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  772. {
  773. spell->counteredSpells.push_back(SpellID(id));
  774. });
  775. }
  776. //TODO: more error checking - f.e. conflicting flags
  777. const auto flags = json["flags"];
  778. //by default all flags are set to false in constructor
  779. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  780. if(flags["offensive"].Bool())
  781. {
  782. spell->setIsOffensive(true);
  783. }
  784. if(flags["rising"].Bool())
  785. {
  786. spell->setIsRising(true);
  787. }
  788. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  789. if(flags["indifferent"].Bool())
  790. {
  791. spell->positiveness = CSpell::NEUTRAL;
  792. }
  793. else if(flags["negative"].Bool())
  794. {
  795. spell->positiveness = CSpell::NEGATIVE;
  796. }
  797. else if(flags["positive"].Bool())
  798. {
  799. spell->positiveness = CSpell::POSITIVE;
  800. }
  801. else if(!implicitPositiveness)
  802. {
  803. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  804. logGlobal->warnStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL";
  805. }
  806. spell->isSpecial = flags["special"].Bool();
  807. auto findBonus = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  808. {
  809. auto it = bonusNameMap.find(name);
  810. if(it == bonusNameMap.end())
  811. {
  812. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  813. }
  814. else
  815. {
  816. vec.push_back((Bonus::BonusType)it->second);
  817. }
  818. };
  819. auto readBonusStruct = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  820. {
  821. for(auto bonusData: json[name].Struct())
  822. {
  823. const std::string bonusId = bonusData.first;
  824. const bool flag = bonusData.second.Bool();
  825. if(flag)
  826. findBonus(bonusId, vec);
  827. }
  828. };
  829. readBonusStruct("immunity", spell->immunities);
  830. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  831. readBonusStruct("limit", spell->limiters);
  832. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  833. const JsonNode & graphicsNode = json["graphics"];
  834. spell->iconImmune = graphicsNode["iconImmune"].String();
  835. spell->iconBook = graphicsNode["iconBook"].String();
  836. spell->iconEffect = graphicsNode["iconEffect"].String();
  837. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  838. spell->iconScroll = graphicsNode["iconScroll"].String();
  839. const JsonNode & soundsNode = json["sounds"];
  840. spell->castSound = soundsNode["cast"].String();
  841. //load level attributes
  842. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  843. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  844. {
  845. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  846. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  847. const si32 levelPower = levelNode["power"].Float();
  848. levelObject.description = levelNode["description"].String();
  849. levelObject.cost = levelNode["cost"].Float();
  850. levelObject.power = levelPower;
  851. levelObject.AIValue = levelNode["aiValue"].Float();
  852. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  853. levelObject.range = levelNode["range"].String();
  854. for(const auto & elem : levelNode["effects"].Struct())
  855. {
  856. const JsonNode & bonusNode = elem.second;
  857. Bonus * b = JsonUtils::parseBonus(bonusNode);
  858. const bool usePowerAsValue = bonusNode["val"].isNull();
  859. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  860. //b->sid = spell->id; //for all
  861. b->source = Bonus::SPELL_EFFECT;//for all
  862. if(usePowerAsValue)
  863. b->val = levelPower;
  864. levelObject.effects.push_back(*b);
  865. }
  866. }
  867. return spell;
  868. }
  869. void CSpellHandler::afterLoadFinalization()
  870. {
  871. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  872. for(auto spell: objects)
  873. {
  874. for(auto & level: spell->levels)
  875. for(auto & bonus: level.effects)
  876. bonus.sid = spell->id;
  877. spell->setupMechanics();
  878. }
  879. }
  880. void CSpellHandler::beforeValidate(JsonNode & object)
  881. {
  882. //handle "base" level info
  883. JsonNode& levels = object["levels"];
  884. JsonNode& base = levels["base"];
  885. auto inheritNode = [&](const std::string & name){
  886. JsonUtils::inherit(levels[name],base);
  887. };
  888. inheritNode("none");
  889. inheritNode("basic");
  890. inheritNode("advanced");
  891. inheritNode("expert");
  892. }
  893. CSpellHandler::~CSpellHandler()
  894. {
  895. }
  896. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  897. {
  898. std::vector<bool> allowedSpells;
  899. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  900. return allowedSpells;
  901. }