CSpellHandler.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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. if(air)
  285. ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
  286. else if(fire) //only one type of bonus for Magic Arrow
  287. ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
  288. else if(water)
  289. ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
  290. else if(earth)
  291. ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
  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. if(air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  310. {
  311. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  312. ret /= 100;
  313. }
  314. else if(fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  315. {
  316. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  317. ret /= 100;
  318. }
  319. else if(water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  320. {
  321. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  322. ret /= 100;
  323. }
  324. else if (earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  325. {
  326. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  327. ret /= 100;
  328. }
  329. //general spell dmg reduction
  330. //FIXME?
  331. if(air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  332. {
  333. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  334. ret /= 100;
  335. }
  336. //dmg increasing
  337. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  338. {
  339. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  340. ret /= 100;
  341. }
  342. }
  343. ret = calculateBonus(ret, caster, affectedCreature);
  344. return ret;
  345. }
  346. ui32 CSpell::calculateHealedHP(const CGHeroInstance* caster, const CStack* stack, const CStack* sacrificedStack) const
  347. {
  348. //todo: use Mechanics class
  349. int healedHealth;
  350. if(!isHealingSpell())
  351. {
  352. logGlobal->errorStream() << "calculateHealedHP called for nonhealing spell "<< name;
  353. return 0;
  354. }
  355. const int spellPowerSkill = caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER);
  356. const int levelPower = getPower(caster->getSpellSchoolLevel(this));
  357. if (id == SpellID::SACRIFICE && sacrificedStack)
  358. healedHealth = (spellPowerSkill + sacrificedStack->MaxHealth() + levelPower) * sacrificedStack->count;
  359. else
  360. healedHealth = spellPowerSkill * power + levelPower; //???
  361. healedHealth = calculateBonus(healedHealth, caster, stack);
  362. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + (isRisingSpell() ? stack->baseAmount * stack->MaxHealth() : 0));
  363. }
  364. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  365. {
  366. using namespace SRSLPraserHelpers;
  367. std::vector<BattleHex> ret;
  368. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  369. {
  370. //Special case - shape of obstacle depends on caster's side
  371. //TODO make it possible through spell_info config
  372. BattleHex::EDir firstStep, secondStep;
  373. if(side)
  374. {
  375. firstStep = BattleHex::TOP_LEFT;
  376. secondStep = BattleHex::TOP_RIGHT;
  377. }
  378. else
  379. {
  380. firstStep = BattleHex::TOP_RIGHT;
  381. secondStep = BattleHex::TOP_LEFT;
  382. }
  383. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  384. auto addIfValid = [&](BattleHex hex)
  385. {
  386. if(hex.isValid())
  387. ret.push_back(hex);
  388. else if(outDroppedHexes)
  389. *outDroppedHexes = true;
  390. };
  391. ret.push_back(centralHex);
  392. addIfValid(centralHex.moveInDir(firstStep, false));
  393. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  394. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  395. return ret;
  396. }
  397. std::string rng = getLevelInfo(schoolLvl).range + ','; //copy + artificial comma for easier handling
  398. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  399. {
  400. std::string number1, number2;
  401. int beg, end;
  402. bool readingFirst = true;
  403. for(auto & elem : rng)
  404. {
  405. if(std::isdigit(elem) ) //reading number
  406. {
  407. if(readingFirst)
  408. number1 += elem;
  409. else
  410. number2 += elem;
  411. }
  412. else if(elem == ',') //comma
  413. {
  414. //calculating variables
  415. if(readingFirst)
  416. {
  417. beg = atoi(number1.c_str());
  418. number1 = "";
  419. }
  420. else
  421. {
  422. end = atoi(number2.c_str());
  423. number2 = "";
  424. }
  425. //obtaining new hexes
  426. std::set<ui16> curLayer;
  427. if(readingFirst)
  428. {
  429. curLayer = getInRange(centralHex, beg, beg);
  430. }
  431. else
  432. {
  433. curLayer = getInRange(centralHex, beg, end);
  434. readingFirst = true;
  435. }
  436. //adding abtained hexes
  437. for(auto & curLayer_it : curLayer)
  438. {
  439. ret.push_back(curLayer_it);
  440. }
  441. }
  442. else if(elem == '-') //dash
  443. {
  444. beg = atoi(number1.c_str());
  445. number1 = "";
  446. readingFirst = false;
  447. }
  448. }
  449. }
  450. //remove duplicates (TODO check if actually needed)
  451. range::unique(ret);
  452. return ret;
  453. }
  454. CSpell::ETargetType CSpell::getTargetType() const
  455. {
  456. return targetType;
  457. }
  458. const CSpell::TargetInfo CSpell::getTargetInfo(const int level) const
  459. {
  460. TargetInfo info;
  461. auto & levelInfo = getLevelInfo(level);
  462. info.type = getTargetType();
  463. info.smart = levelInfo.smartTarget;
  464. info.massive = levelInfo.range == "X";
  465. info.onlyAlive = !isRisingSpell();
  466. return info;
  467. }
  468. bool CSpell::isCombatSpell() const
  469. {
  470. return combatSpell;
  471. }
  472. bool CSpell::isAdventureSpell() const
  473. {
  474. return !combatSpell;
  475. }
  476. bool CSpell::isCreatureAbility() const
  477. {
  478. return creatureAbility;
  479. }
  480. bool CSpell::isPositive() const
  481. {
  482. return positiveness == POSITIVE;
  483. }
  484. bool CSpell::isNegative() const
  485. {
  486. return positiveness == NEGATIVE;
  487. }
  488. bool CSpell::isNeutral() const
  489. {
  490. return positiveness == NEUTRAL;
  491. }
  492. bool CSpell::isHealingSpell() const
  493. {
  494. return isRisingSpell() || (id == SpellID::CURE);
  495. }
  496. bool CSpell::isRisingSpell() const
  497. {
  498. return isRising;
  499. }
  500. bool CSpell::isDamageSpell() const
  501. {
  502. return isDamage;
  503. }
  504. bool CSpell::isOffensiveSpell() const
  505. {
  506. return isOffensive;
  507. }
  508. bool CSpell::isSpecialSpell() const
  509. {
  510. return isSpecial;
  511. }
  512. bool CSpell::hasEffects() const
  513. {
  514. return !levels[0].effects.empty();
  515. }
  516. const std::string& CSpell::getIconImmune() const
  517. {
  518. return iconImmune;
  519. }
  520. const std::string& CSpell::getCastSound() const
  521. {
  522. return castSound;
  523. }
  524. si32 CSpell::getCost(const int skillLevel) const
  525. {
  526. return getLevelInfo(skillLevel).cost;
  527. }
  528. si32 CSpell::getPower(const int skillLevel) const
  529. {
  530. return getLevelInfo(skillLevel).power;
  531. }
  532. //si32 CSpell::calculatePower(const int skillLevel) const
  533. //{
  534. // return power + getPower(skillLevel);
  535. //}
  536. si32 CSpell::getProbability(const TFaction factionId) const
  537. {
  538. if(!vstd::contains(probabilities,factionId))
  539. {
  540. return defaultProbability;
  541. }
  542. return probabilities.at(factionId);
  543. }
  544. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  545. {
  546. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  547. {
  548. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  549. return;
  550. }
  551. const std::vector<Bonus> & effects = levels[level].effects;
  552. if(effects.empty())
  553. {
  554. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  555. return;
  556. }
  557. lst.reserve(lst.size() + effects.size());
  558. for(const Bonus & b : effects)
  559. {
  560. lst.push_back(Bonus(b));
  561. }
  562. }
  563. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneBy(const IBonusBearer* obj) const
  564. {
  565. //0. check receptivity
  566. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  567. return ESpellCastProblem::OK;
  568. //todo: use new bonus API
  569. //1. Check absolute limiters
  570. for(auto b : absoluteLimiters)
  571. {
  572. if (!obj->hasBonusOfType(b))
  573. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  574. }
  575. //2. Check absolute immunities
  576. for(auto b : absoluteImmunities)
  577. {
  578. if (obj->hasBonusOfType(b))
  579. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  580. }
  581. //3. Check negation
  582. //FIXME: Orb of vulnerability mechanics is not such trivial
  583. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  584. return ESpellCastProblem::NOT_DECIDED;
  585. //4. Check negatable limit
  586. for(auto b : limiters)
  587. {
  588. if (!obj->hasBonusOfType(b))
  589. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  590. }
  591. //5. Check negatable immunities
  592. for(auto b : immunities)
  593. {
  594. if (obj->hasBonusOfType(b))
  595. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  596. }
  597. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  598. {
  599. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  600. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  601. else if(!isPositive()) //negative or indifferent
  602. {
  603. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  604. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  605. }
  606. return ESpellCastProblem::NOT_DECIDED;
  607. };
  608. //6. Check elemental immunities
  609. if(fire)
  610. {
  611. if(battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  612. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  613. }
  614. if(water)
  615. {
  616. if(battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  617. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  618. }
  619. if(earth)
  620. {
  621. if(battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  622. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  623. }
  624. if(air)
  625. {
  626. if(battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  627. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  628. }
  629. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  630. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  631. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  632. {
  633. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  634. }
  635. return ESpellCastProblem::NOT_DECIDED;
  636. }
  637. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const CGHeroInstance* caster, ECastingMode::ECastingMode mode, const CStack* obj) const
  638. {
  639. const auto immuneResult = mechanics->isImmuneByStack(caster,mode,obj);
  640. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  641. return immuneResult;
  642. return ESpellCastProblem::OK;
  643. }
  644. void CSpell::setIsOffensive(const bool val)
  645. {
  646. isOffensive = val;
  647. if(val)
  648. {
  649. positiveness = CSpell::NEGATIVE;
  650. isDamage = true;
  651. }
  652. }
  653. void CSpell::setIsRising(const bool val)
  654. {
  655. isRising = val;
  656. if(val)
  657. {
  658. positiveness = CSpell::POSITIVE;
  659. }
  660. }
  661. void CSpell::setupMechanics()
  662. {
  663. if(nullptr != mechanics)
  664. {
  665. logGlobal->errorStream() << "Spell " << this->name << " mechanics already set";
  666. delete mechanics;
  667. mechanics = nullptr;
  668. }
  669. switch (id)
  670. {
  671. case SpellID::CLONE:
  672. mechanics = new CloneMechnics(this);
  673. break;
  674. case SpellID::DISPEL_HELPFUL_SPELLS:
  675. mechanics = new DispellHelpfulMechanics(this);
  676. break;
  677. case SpellID::SACRIFICE:
  678. mechanics = new SacrificeMechanics(this);
  679. break;
  680. default:
  681. if(isRisingSpell())
  682. mechanics = new SpecialRisingSpellMechanics(this);
  683. else
  684. mechanics = new CSpellMechanics(this);
  685. break;
  686. }
  687. }
  688. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  689. {
  690. int3 diff = pos - center;
  691. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  692. return true;
  693. else
  694. return false;
  695. }
  696. ///CSpellHandler
  697. CSpellHandler::CSpellHandler()
  698. {
  699. }
  700. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  701. {
  702. using namespace SpellConfig;
  703. std::vector<JsonNode> legacyData;
  704. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  705. auto readSchool = [&](JsonMap& schools, const std::string& name)
  706. {
  707. if (parser.readString() == "x")
  708. {
  709. schools[name].Bool() = true;
  710. }
  711. };
  712. auto read = [&,this](bool combat, bool ability)
  713. {
  714. do
  715. {
  716. JsonNode lineNode(JsonNode::DATA_STRUCT);
  717. const si32 id = legacyData.size();
  718. lineNode["index"].Float() = id;
  719. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  720. lineNode["name"].String() = parser.readString();
  721. parser.readString(); //ignored unused abbreviated name
  722. lineNode["level"].Float() = parser.readNumber();
  723. auto& schools = lineNode["school"].Struct();
  724. readSchool(schools, "earth");
  725. readSchool(schools, "water");
  726. readSchool(schools, "fire");
  727. readSchool(schools, "air");
  728. auto& levels = lineNode["levels"].Struct();
  729. auto getLevel = [&](const size_t idx)->JsonMap&
  730. {
  731. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  732. return levels[LEVEL_NAMES[idx]].Struct();
  733. };
  734. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  735. lineNode["power"].Float() = parser.readNumber();
  736. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  737. auto& chances = lineNode["gainChance"].Struct();
  738. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  739. chances[ETownType::names[i]].Float() = parser.readNumber();
  740. }
  741. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  742. std::vector<std::string> descriptions;
  743. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  744. descriptions.push_back(parser.readString());
  745. std::string attributes = parser.readString();
  746. std::string targetType = "NO_TARGET";
  747. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  748. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  749. targetType = "CREATURE_EXPERT_MASSIVE";
  750. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  751. targetType = "CREATURE";
  752. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  753. targetType = "OBSTACLE";
  754. //save parsed level specific data
  755. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  756. {
  757. auto& level = getLevel(i);
  758. level["description"].String() = descriptions[i];
  759. level["cost"].Float() = costs[i];
  760. level["power"].Float() = powers[i];
  761. level["aiValue"].Float() = AIVals[i];
  762. }
  763. if(targetType == "CREATURE_EXPERT_MASSIVE")
  764. {
  765. lineNode["targetType"].String() = "CREATURE";
  766. getLevel(3)["range"].String() = "X";
  767. }
  768. else
  769. {
  770. lineNode["targetType"].String() = targetType;
  771. }
  772. legacyData.push_back(lineNode);
  773. }
  774. while (parser.endLine() && !parser.isNextEntryEmpty());
  775. };
  776. auto skip = [&](int cnt)
  777. {
  778. for(int i=0; i<cnt; i++)
  779. parser.endLine();
  780. };
  781. skip(5);// header
  782. read(false,false); //read adventure map spells
  783. skip(3);
  784. read(true,false); //read battle spells
  785. skip(3);
  786. read(true,true);//read creature abilities
  787. //TODO: maybe move to config
  788. //clone Acid Breath attributes for Acid Breath damage effect
  789. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  790. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  791. legacyData.push_back(temp);
  792. objects.resize(legacyData.size());
  793. return legacyData;
  794. }
  795. const std::string CSpellHandler::getTypeName() const
  796. {
  797. return "spell";
  798. }
  799. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  800. {
  801. using namespace SpellConfig;
  802. CSpell * spell = new CSpell();
  803. const auto type = json["type"].String();
  804. if(type == "ability")
  805. {
  806. spell->creatureAbility = true;
  807. spell->combatSpell = true;
  808. }
  809. else
  810. {
  811. spell->creatureAbility = false;
  812. spell->combatSpell = type == "combat";
  813. }
  814. spell->name = json["name"].String();
  815. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  816. const auto schoolNames = json["school"];
  817. spell->air = schoolNames["air"].Bool();
  818. spell->earth = schoolNames["earth"].Bool();
  819. spell->fire = schoolNames["fire"].Bool();
  820. spell->water = schoolNames["water"].Bool();
  821. spell->level = json["level"].Float();
  822. spell->power = json["power"].Float();
  823. spell->defaultProbability = json["defaultGainChance"].Float();
  824. for(const auto & node : json["gainChance"].Struct())
  825. {
  826. const int chance = node.second.Float();
  827. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  828. {
  829. spell->probabilities[factionID] = chance;
  830. });
  831. }
  832. const std::string targetType = json["targetType"].String();
  833. if(targetType == "NO_TARGET")
  834. spell->targetType = CSpell::NO_TARGET;
  835. else if(targetType == "CREATURE")
  836. spell->targetType = CSpell::CREATURE;
  837. else if(targetType == "OBSTACLE")
  838. spell->targetType = CSpell::OBSTACLE;
  839. else
  840. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  841. spell->mainEffectAnim = json["anim"].Float();
  842. for(const auto & counteredSpell: json["counters"].Struct())
  843. if (counteredSpell.second.Bool())
  844. {
  845. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  846. {
  847. spell->counteredSpells.push_back(SpellID(id));
  848. });
  849. }
  850. //TODO: more error checking - f.e. conflicting flags
  851. const auto flags = json["flags"];
  852. //by default all flags are set to false in constructor
  853. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  854. if(flags["offensive"].Bool())
  855. {
  856. spell->setIsOffensive(true);
  857. }
  858. if(flags["rising"].Bool())
  859. {
  860. spell->setIsRising(true);
  861. }
  862. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  863. if(flags["indifferent"].Bool())
  864. {
  865. spell->positiveness = CSpell::NEUTRAL;
  866. }
  867. else if(flags["negative"].Bool())
  868. {
  869. spell->positiveness = CSpell::NEGATIVE;
  870. }
  871. else if(flags["positive"].Bool())
  872. {
  873. spell->positiveness = CSpell::POSITIVE;
  874. }
  875. else if(!implicitPositiveness)
  876. {
  877. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  878. logGlobal->warnStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL";
  879. }
  880. spell->isSpecial = flags["special"].Bool();
  881. auto findBonus = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  882. {
  883. auto it = bonusNameMap.find(name);
  884. if(it == bonusNameMap.end())
  885. {
  886. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  887. }
  888. else
  889. {
  890. vec.push_back((Bonus::BonusType)it->second);
  891. }
  892. };
  893. auto readBonusStruct = [&](const std::string & name, std::vector<Bonus::BonusType> &vec)
  894. {
  895. for(auto bonusData: json[name].Struct())
  896. {
  897. const std::string bonusId = bonusData.first;
  898. const bool flag = bonusData.second.Bool();
  899. if(flag)
  900. findBonus(bonusId, vec);
  901. }
  902. };
  903. readBonusStruct("immunity", spell->immunities);
  904. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  905. readBonusStruct("limit", spell->limiters);
  906. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  907. const JsonNode & graphicsNode = json["graphics"];
  908. spell->iconImmune = graphicsNode["iconImmune"].String();
  909. spell->iconBook = graphicsNode["iconBook"].String();
  910. spell->iconEffect = graphicsNode["iconEffect"].String();
  911. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  912. spell->iconScroll = graphicsNode["iconScroll"].String();
  913. const JsonNode & soundsNode = json["sounds"];
  914. spell->castSound = soundsNode["cast"].String();
  915. //load level attributes
  916. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  917. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  918. {
  919. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  920. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  921. const si32 levelPower = levelNode["power"].Float();
  922. levelObject.description = levelNode["description"].String();
  923. levelObject.cost = levelNode["cost"].Float();
  924. levelObject.power = levelPower;
  925. levelObject.AIValue = levelNode["aiValue"].Float();
  926. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  927. levelObject.range = levelNode["range"].String();
  928. for(const auto & elem : levelNode["effects"].Struct())
  929. {
  930. const JsonNode & bonusNode = elem.second;
  931. Bonus * b = JsonUtils::parseBonus(bonusNode);
  932. const bool usePowerAsValue = bonusNode["val"].isNull();
  933. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  934. //b->sid = spell->id; //for all
  935. b->source = Bonus::SPELL_EFFECT;//for all
  936. if(usePowerAsValue)
  937. b->val = levelPower;
  938. levelObject.effects.push_back(*b);
  939. }
  940. }
  941. return spell;
  942. }
  943. void CSpellHandler::afterLoadFinalization()
  944. {
  945. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  946. for(auto spell: objects)
  947. {
  948. for(auto & level: spell->levels)
  949. for(auto & bonus: level.effects)
  950. bonus.sid = spell->id;
  951. spell->setupMechanics();
  952. }
  953. }
  954. void CSpellHandler::beforeValidate(JsonNode & object)
  955. {
  956. //handle "base" level info
  957. JsonNode& levels = object["levels"];
  958. JsonNode& base = levels["base"];
  959. auto inheritNode = [&](const std::string & name){
  960. JsonUtils::inherit(levels[name],base);
  961. };
  962. inheritNode("none");
  963. inheritNode("basic");
  964. inheritNode("advanced");
  965. inheritNode("expert");
  966. }
  967. CSpellHandler::~CSpellHandler()
  968. {
  969. }
  970. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  971. {
  972. std::vector<bool> allowedSpells;
  973. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  974. return allowedSpells;
  975. }