CSpellHandler.cpp 31 KB

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