CSpellHandler.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. /*
  2. * CSpellHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <cctype>
  12. #include "CSpellHandler.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../JsonNode.h"
  16. #include "../CModHandler.h"
  17. #include "../StringConstants.h"
  18. #include "../BattleState.h"
  19. #include "../CBattleCallback.h"
  20. #include "../CGameState.h" //todo: remove
  21. #include "../NetPacks.h" //todo: remove
  22. #include "ISpellMechanics.h"
  23. namespace SpellConfig
  24. {
  25. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  26. static const SpellSchoolInfo SCHOOL[4] =
  27. {
  28. {
  29. ESpellSchool::AIR,
  30. Bonus::AIR_SPELL_DMG_PREMY,
  31. Bonus::AIR_IMMUNITY,
  32. "air",
  33. SecondarySkill::AIR_MAGIC,
  34. Bonus::AIR_SPELLS
  35. },
  36. {
  37. ESpellSchool::FIRE,
  38. Bonus::FIRE_SPELL_DMG_PREMY,
  39. Bonus::FIRE_IMMUNITY,
  40. "fire",
  41. SecondarySkill::FIRE_MAGIC,
  42. Bonus::FIRE_SPELLS
  43. },
  44. {
  45. ESpellSchool::WATER,
  46. Bonus::WATER_SPELL_DMG_PREMY,
  47. Bonus::WATER_IMMUNITY,
  48. "water",
  49. SecondarySkill::WATER_MAGIC,
  50. Bonus::WATER_SPELLS
  51. },
  52. {
  53. ESpellSchool::EARTH,
  54. Bonus::EARTH_SPELL_DMG_PREMY,
  55. Bonus::EARTH_IMMUNITY,
  56. "earth",
  57. SecondarySkill::EARTH_MAGIC,
  58. Bonus::EARTH_SPELLS
  59. }
  60. };
  61. }
  62. ///CSpell::LevelInfo
  63. CSpell::LevelInfo::LevelInfo()
  64. :description(""),cost(0),power(0),AIValue(0),smartTarget(true), clearTarget(false), clearAffected(false), range("0")
  65. {
  66. }
  67. CSpell::LevelInfo::~LevelInfo()
  68. {
  69. }
  70. ///CSpell
  71. CSpell::CSpell():
  72. id(SpellID::NONE), level(0),
  73. combatSpell(false), creatureAbility(false),
  74. positiveness(ESpellPositiveness::NEUTRAL),
  75. defaultProbability(0),
  76. isRising(false), isDamage(false), isOffensive(false),
  77. targetType(ETargetType::NO_TARGET),
  78. mechanics(),
  79. adventureMechanics()
  80. {
  81. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  82. }
  83. CSpell::~CSpell()
  84. {
  85. }
  86. void CSpell::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  87. {
  88. mechanics->applyBattle(battle, packet);
  89. }
  90. bool CSpell::adventureCast(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  91. {
  92. assert(env);
  93. if(!adventureMechanics.get())
  94. {
  95. env->complain("Invalid adventure spell cast attempt!");
  96. return false;
  97. }
  98. return adventureMechanics->adventureCast(env, parameters);
  99. }
  100. void CSpell::battleCast(const SpellCastEnvironment * env, const BattleSpellCastParameters & parameters) const
  101. {
  102. assert(env);
  103. if(parameters.destinations.size()<1)
  104. {
  105. env->complain("Spell must have at least one destination");
  106. return;
  107. }
  108. mechanics->battleCast(env, parameters);
  109. }
  110. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  111. {
  112. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  113. {
  114. logGlobal->error("CSpell::getLevelInfo invalid school level %d", level);
  115. throw new std::runtime_error("Invalid school level");
  116. }
  117. return levels.at(level);
  118. }
  119. ui32 CSpell::calculateDamage(const ISpellCaster * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  120. {
  121. //check if spell really does damage - if not, return 0
  122. if(!isDamageSpell())
  123. return 0;
  124. return adjustRawDamage(caster, affectedCreature, calculateRawEffectValue(spellSchoolLevel, usedSpellPower));
  125. }
  126. ESpellCastProblem::ESpellCastProblem CSpell::canBeCast(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster) const
  127. {
  128. const ESpellCastProblem::ESpellCastProblem generalProblem = mechanics->canBeCast(cb, mode, caster);
  129. if(generalProblem != ESpellCastProblem::OK)
  130. return generalProblem;
  131. //check for creature target existence
  132. if(mechanics->requiresCreatureTarget())
  133. {
  134. switch(mode)
  135. {
  136. case ECastingMode::HERO_CASTING:
  137. case ECastingMode::CREATURE_ACTIVE_CASTING:
  138. case ECastingMode::ENCHANTER_CASTING:
  139. case ECastingMode::PASSIVE_CASTING:
  140. {
  141. TargetInfo tinfo(this, caster->getSpellSchoolLevel(this), mode);
  142. bool targetExists = false;
  143. for(const CStack * stack : cb->battleGetAllStacks())
  144. {
  145. bool immune = !(stack->isValidTarget(!tinfo.onlyAlive) && ESpellCastProblem::OK == isImmuneByStack(caster, stack));
  146. bool casterStack = stack->owner == caster->getOwner();
  147. if(!immune)
  148. {
  149. switch (positiveness)
  150. {
  151. case CSpell::POSITIVE:
  152. if(casterStack || !tinfo.smart)
  153. targetExists = true;
  154. break;
  155. case CSpell::NEUTRAL:
  156. targetExists = true;
  157. break;
  158. case CSpell::NEGATIVE:
  159. if(!casterStack || !tinfo.smart)
  160. targetExists = true;
  161. break;
  162. }
  163. }
  164. if(targetExists)
  165. break;
  166. }
  167. if(!targetExists)
  168. {
  169. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  170. }
  171. }
  172. break;
  173. }
  174. }
  175. return ESpellCastProblem::OK;
  176. }
  177. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  178. {
  179. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  180. }
  181. std::vector<const CStack *> CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, const ISpellCaster * caster, int spellLvl, BattleHex destination) const
  182. {
  183. SpellTargetingContext ctx(this, mode, caster, spellLvl, destination);
  184. return mechanics->getAffectedStacks(cb, ctx);;
  185. }
  186. CSpell::ETargetType CSpell::getTargetType() const
  187. {
  188. return targetType;
  189. }
  190. void CSpell::forEachSchool(const std::function<void(const SpellSchoolInfo &, bool &)>& cb) const
  191. {
  192. bool stop = false;
  193. for(const SpellSchoolInfo & cnf : SpellConfig::SCHOOL)
  194. {
  195. if(school.at(cnf.id))
  196. {
  197. cb(cnf, stop);
  198. if(stop)
  199. break;
  200. }
  201. }
  202. }
  203. bool CSpell::isCombatSpell() const
  204. {
  205. return combatSpell;
  206. }
  207. bool CSpell::isAdventureSpell() const
  208. {
  209. return !combatSpell;
  210. }
  211. bool CSpell::isCreatureAbility() const
  212. {
  213. return creatureAbility;
  214. }
  215. bool CSpell::isPositive() const
  216. {
  217. return positiveness == POSITIVE;
  218. }
  219. bool CSpell::isNegative() const
  220. {
  221. return positiveness == NEGATIVE;
  222. }
  223. bool CSpell::isNeutral() const
  224. {
  225. return positiveness == NEUTRAL;
  226. }
  227. bool CSpell::isRisingSpell() const
  228. {
  229. return isRising;
  230. }
  231. bool CSpell::isDamageSpell() const
  232. {
  233. return isDamage;
  234. }
  235. bool CSpell::isOffensiveSpell() const
  236. {
  237. return isOffensive;
  238. }
  239. bool CSpell::isSpecialSpell() const
  240. {
  241. return isSpecial;
  242. }
  243. bool CSpell::hasEffects() const
  244. {
  245. return !levels[0].effects.empty();
  246. }
  247. const std::string & CSpell::getIconImmune() const
  248. {
  249. return iconImmune;
  250. }
  251. const std::string & CSpell::getCastSound() const
  252. {
  253. return castSound;
  254. }
  255. si32 CSpell::getCost(const int skillLevel) const
  256. {
  257. return getLevelInfo(skillLevel).cost;
  258. }
  259. si32 CSpell::getPower(const int skillLevel) const
  260. {
  261. return getLevelInfo(skillLevel).power;
  262. }
  263. si32 CSpell::getProbability(const TFaction factionId) const
  264. {
  265. if(!vstd::contains(probabilities,factionId))
  266. {
  267. return defaultProbability;
  268. }
  269. return probabilities.at(factionId);
  270. }
  271. void CSpell::getEffects(std::vector<Bonus> & lst, const int level) const
  272. {
  273. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  274. {
  275. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  276. return;
  277. }
  278. const std::vector<Bonus> & effects = levels[level].effects;
  279. if(effects.empty())
  280. {
  281. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  282. return;
  283. }
  284. lst.reserve(lst.size() + effects.size());
  285. for(const Bonus & b : effects)
  286. {
  287. lst.push_back(Bonus(b));
  288. }
  289. }
  290. ESpellCastProblem::ESpellCastProblem CSpell::canBeCastAt(const CBattleInfoCallback * cb, const ISpellCaster * caster, ECastingMode::ECastingMode mode, BattleHex destination) const
  291. {
  292. SpellTargetingContext ctx(this, mode, caster, caster->getSpellSchoolLevel(this), destination);
  293. ESpellCastProblem::ESpellCastProblem specific = mechanics->canBeCast(cb, ctx);
  294. if(specific != ESpellCastProblem::OK)
  295. return specific;
  296. //todo: this should be moved to mechanics
  297. //rising spells handled by mechanics
  298. if(ctx.ti.onlyAlive && getTargetType() == CSpell::CREATURE)
  299. {
  300. const CStack * aliveStack = cb->getStackIf([destination](const CStack * s)
  301. {
  302. return s->isValidTarget(false) && s->coversPos(destination);
  303. });
  304. if(!aliveStack)
  305. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  306. if(ctx.ti.smart && isNegative() && aliveStack->owner == caster->getOwner())
  307. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  308. if(ctx.ti.smart && isPositive() && aliveStack->owner != caster->getOwner())
  309. return ESpellCastProblem::NO_APPROPRIATE_TARGET;
  310. }
  311. return isImmuneAt(cb, caster, mode, destination);
  312. }
  313. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneAt(const CBattleInfoCallback * cb, const ISpellCaster * caster, ECastingMode::ECastingMode mode, BattleHex destination) const
  314. {
  315. // Get all stacks at destination hex. only alive if not rising spell
  316. TStacks stacks = cb->battleGetStacksIf([=](const CStack * s)
  317. {
  318. return s->coversPos(destination) && s->isValidTarget(isRisingSpell());
  319. });
  320. if(!stacks.empty())
  321. {
  322. bool allImmune = true;
  323. ESpellCastProblem::ESpellCastProblem problem = ESpellCastProblem::INVALID;
  324. for(auto s : stacks)
  325. {
  326. ESpellCastProblem::ESpellCastProblem res = isImmuneByStack(caster,s);
  327. if(res == ESpellCastProblem::OK)
  328. {
  329. allImmune = false;
  330. }
  331. else
  332. {
  333. problem = res;
  334. }
  335. }
  336. if(allImmune)
  337. return problem;
  338. }
  339. else //no target stack on this tile
  340. {
  341. if(getTargetType() == CSpell::CREATURE)
  342. {
  343. if(caster && mode == ECastingMode::HERO_CASTING) //TODO why???
  344. {
  345. const CSpell::TargetInfo ti(this, caster->getSpellSchoolLevel(this), mode);
  346. if(!ti.massive)
  347. return ESpellCastProblem::WRONG_SPELL_TARGET;
  348. }
  349. else
  350. {
  351. return ESpellCastProblem::WRONG_SPELL_TARGET;
  352. }
  353. }
  354. }
  355. return ESpellCastProblem::OK;
  356. }
  357. int CSpell::adjustRawDamage(const ISpellCaster * caster, const CStack * affectedCreature, int rawDamage) const
  358. {
  359. int ret = rawDamage;
  360. //affected creature-specific part
  361. if(nullptr != affectedCreature)
  362. {
  363. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  364. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  365. {
  366. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  367. {
  368. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  369. ret /= 100;
  370. stop = true;//only bonus from one school is used
  371. }
  372. });
  373. //general spell dmg reduction
  374. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  375. {
  376. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  377. ret /= 100;
  378. }
  379. //dmg increasing
  380. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  381. {
  382. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  383. ret /= 100;
  384. }
  385. }
  386. if(caster != nullptr)
  387. ret = caster->getSpellBonus(this, ret, affectedCreature);
  388. return ret;
  389. }
  390. int CSpell::calculateRawEffectValue(int effectLevel, int effectPower) const
  391. {
  392. return effectPower * power + getPower(effectLevel);
  393. }
  394. ESpellCastProblem::ESpellCastProblem CSpell::internalIsImmune(const ISpellCaster * caster, const CStack *obj) const
  395. {
  396. //todo: use new bonus API
  397. //1. Check absolute limiters
  398. for(auto b : absoluteLimiters)
  399. {
  400. if (!obj->hasBonusOfType(b))
  401. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  402. }
  403. //2. Check absolute immunities
  404. for(auto b : absoluteImmunities)
  405. {
  406. if (obj->hasBonusOfType(b))
  407. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  408. }
  409. {
  410. //spell-based spell immunity (only ANTIMAGIC in OH3) is treated as absolute
  411. std::stringstream cachingStr;
  412. cachingStr << "type_" << Bonus::LEVEL_SPELL_IMMUNITY << "source_" << Bonus::SPELL_EFFECT;
  413. TBonusListPtr levelImmunitiesFromSpell = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY).And(Selector::sourceType(Bonus::SPELL_EFFECT)), cachingStr.str());
  414. if(levelImmunitiesFromSpell->size() > 0 && levelImmunitiesFromSpell->totalValue() >= level && level)
  415. {
  416. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  417. }
  418. }
  419. {
  420. //SPELL_IMMUNITY absolute case
  421. std::stringstream cachingStr;
  422. cachingStr << "type_" << Bonus::SPELL_IMMUNITY << "subtype_" << id.toEnum() << "addInfo_1";
  423. if(obj->hasBonus(Selector::typeSubtypeInfo(Bonus::SPELL_IMMUNITY, id.toEnum(), 1), cachingStr.str()))
  424. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  425. }
  426. //check receptivity
  427. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  428. return ESpellCastProblem::OK;
  429. //3. Check negation
  430. //Orb of vulnerability
  431. //FIXME: Orb of vulnerability mechanics is not such trivial (issue 1791)
  432. const bool battleWideNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 0);
  433. const bool heroNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 1);
  434. //anyone can cast on artifact holder`s stacks
  435. if(heroNegation)
  436. return ESpellCastProblem::NOT_DECIDED;
  437. //this stack is from other player
  438. //todo: check that caster is always present (not trivial is this case)
  439. //todo: NEGATE_ALL_NATURAL_IMMUNITIES special cases: dispell, chain lightning
  440. else if(battleWideNegation && caster)
  441. {
  442. if(obj->owner != caster->getOwner())
  443. return ESpellCastProblem::NOT_DECIDED;
  444. }
  445. //4. Check negatable limit
  446. for(auto b : limiters)
  447. {
  448. if (!obj->hasBonusOfType(b))
  449. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  450. }
  451. //5. Check negatable immunities
  452. for(auto b : immunities)
  453. {
  454. if (obj->hasBonusOfType(b))
  455. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  456. }
  457. //6. Check elemental immunities
  458. ESpellCastProblem::ESpellCastProblem tmp = ESpellCastProblem::NOT_DECIDED;
  459. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  460. {
  461. auto element = cnf.immunityBonus;
  462. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  463. {
  464. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  465. stop = true;
  466. }
  467. else if(!isPositive()) //negative or indifferent
  468. {
  469. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  470. {
  471. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  472. stop = true;
  473. }
  474. }
  475. });
  476. if(tmp != ESpellCastProblem::NOT_DECIDED)
  477. return tmp;
  478. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  479. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  480. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  481. {
  482. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  483. }
  484. return ESpellCastProblem::NOT_DECIDED;
  485. }
  486. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const ISpellCaster * caster, const CStack * obj) const
  487. {
  488. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  489. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  490. return immuneResult;
  491. return ESpellCastProblem::OK;
  492. }
  493. void CSpell::setIsOffensive(const bool val)
  494. {
  495. isOffensive = val;
  496. if(val)
  497. {
  498. positiveness = CSpell::NEGATIVE;
  499. isDamage = true;
  500. }
  501. }
  502. void CSpell::setIsRising(const bool val)
  503. {
  504. isRising = val;
  505. if(val)
  506. {
  507. positiveness = CSpell::POSITIVE;
  508. }
  509. }
  510. void CSpell::setup()
  511. {
  512. setupMechanics();
  513. }
  514. void CSpell::setupMechanics()
  515. {
  516. mechanics = ISpellMechanics::createMechanics(this);
  517. adventureMechanics = IAdventureSpellMechanics::createMechanics(this);
  518. }
  519. ///CSpell::AnimationInfo
  520. CSpell::AnimationItem::AnimationItem()
  521. :resourceName(""),verticalPosition(VerticalPosition::TOP),pause(0)
  522. {
  523. }
  524. ///CSpell::AnimationInfo
  525. CSpell::AnimationInfo::AnimationInfo()
  526. {
  527. }
  528. CSpell::AnimationInfo::~AnimationInfo()
  529. {
  530. }
  531. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  532. {
  533. std::string res;
  534. double maximum = 0.0;
  535. for(const auto & info : projectile)
  536. {
  537. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  538. {
  539. maximum = info.minimumAngle;
  540. res = info.resourceName;
  541. }
  542. }
  543. return res;
  544. }
  545. ///CSpell::TargetInfo
  546. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  547. {
  548. init(spell, level);
  549. }
  550. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  551. {
  552. init(spell, level);
  553. if(mode == ECastingMode::ENCHANTER_CASTING)
  554. {
  555. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  556. massive = true;
  557. }
  558. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  559. {
  560. alwaysHitDirectly = true;
  561. }
  562. else if(mode == ECastingMode::CREATURE_ACTIVE_CASTING)
  563. {
  564. massive = false;//FIXME: find better solution for Commander spells
  565. }
  566. }
  567. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  568. {
  569. auto & levelInfo = spell->getLevelInfo(level);
  570. type = spell->getTargetType();
  571. smart = levelInfo.smartTarget;
  572. massive = levelInfo.range == "X";
  573. onlyAlive = !spell->isRisingSpell();
  574. alwaysHitDirectly = false;
  575. clearAffected = levelInfo.clearAffected;
  576. clearTarget = levelInfo.clearTarget;
  577. }
  578. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  579. {
  580. int3 diff = pos - center;
  581. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  582. return true;
  583. else
  584. return false;
  585. }
  586. ///CSpellHandler
  587. CSpellHandler::CSpellHandler()
  588. {
  589. }
  590. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  591. {
  592. using namespace SpellConfig;
  593. std::vector<JsonNode> legacyData;
  594. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  595. auto readSchool = [&](JsonMap & schools, const std::string & name)
  596. {
  597. if (parser.readString() == "x")
  598. {
  599. schools[name].Bool() = true;
  600. }
  601. };
  602. auto read = [&,this](bool combat, bool ability)
  603. {
  604. do
  605. {
  606. JsonNode lineNode(JsonNode::DATA_STRUCT);
  607. const si32 id = legacyData.size();
  608. lineNode["index"].Float() = id;
  609. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  610. lineNode["name"].String() = parser.readString();
  611. parser.readString(); //ignored unused abbreviated name
  612. lineNode["level"].Float() = parser.readNumber();
  613. auto& schools = lineNode["school"].Struct();
  614. readSchool(schools, "earth");
  615. readSchool(schools, "water");
  616. readSchool(schools, "fire");
  617. readSchool(schools, "air");
  618. auto& levels = lineNode["levels"].Struct();
  619. auto getLevel = [&](const size_t idx)->JsonMap&
  620. {
  621. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  622. return levels[LEVEL_NAMES[idx]].Struct();
  623. };
  624. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  625. lineNode["power"].Float() = parser.readNumber();
  626. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  627. auto& chances = lineNode["gainChance"].Struct();
  628. for(size_t i = 0; i < GameConstants::F_NUMBER; i++){
  629. chances[ETownType::names[i]].Float() = parser.readNumber();
  630. }
  631. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  632. std::vector<std::string> descriptions;
  633. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  634. descriptions.push_back(parser.readString());
  635. parser.readString(); //ignore attributes. All data present in JSON
  636. //save parsed level specific data
  637. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  638. {
  639. auto& level = getLevel(i);
  640. level["description"].String() = descriptions[i];
  641. level["cost"].Float() = costs[i];
  642. level["power"].Float() = powers[i];
  643. level["aiValue"].Float() = AIVals[i];
  644. }
  645. legacyData.push_back(lineNode);
  646. }
  647. while (parser.endLine() && !parser.isNextEntryEmpty());
  648. };
  649. auto skip = [&](int cnt)
  650. {
  651. for(int i=0; i<cnt; i++)
  652. parser.endLine();
  653. };
  654. skip(5);// header
  655. read(false,false); //read adventure map spells
  656. skip(3);
  657. read(true,false); //read battle spells
  658. skip(3);
  659. read(true,true);//read creature abilities
  660. //TODO: maybe move to config
  661. //clone Acid Breath attributes for Acid Breath damage effect
  662. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  663. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  664. legacyData.push_back(temp);
  665. objects.resize(legacyData.size());
  666. return legacyData;
  667. }
  668. const std::string CSpellHandler::getTypeName() const
  669. {
  670. return "spell";
  671. }
  672. CSpell * CSpellHandler::loadFromJson(const JsonNode & json, const std::string & identifier)
  673. {
  674. using namespace SpellConfig;
  675. CSpell * spell = new CSpell();
  676. spell->identifier = identifier;
  677. const auto type = json["type"].String();
  678. if(type == "ability")
  679. {
  680. spell->creatureAbility = true;
  681. spell->combatSpell = true;
  682. }
  683. else
  684. {
  685. spell->creatureAbility = false;
  686. spell->combatSpell = type == "combat";
  687. }
  688. spell->name = json["name"].String();
  689. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  690. const auto schoolNames = json["school"];
  691. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  692. {
  693. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  694. }
  695. spell->level = json["level"].Float();
  696. spell->power = json["power"].Float();
  697. spell->defaultProbability = json["defaultGainChance"].Float();
  698. for(const auto & node : json["gainChance"].Struct())
  699. {
  700. const int chance = node.second.Float();
  701. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  702. {
  703. spell->probabilities[factionID] = chance;
  704. });
  705. }
  706. auto targetType = json["targetType"].String();
  707. if(targetType == "NO_TARGET")
  708. spell->targetType = CSpell::NO_TARGET;
  709. else if(targetType == "CREATURE")
  710. spell->targetType = CSpell::CREATURE;
  711. else if(targetType == "OBSTACLE")
  712. spell->targetType = CSpell::OBSTACLE;
  713. else if(targetType == "LOCATION")
  714. spell->targetType = CSpell::LOCATION;
  715. else
  716. logGlobal->warnStream() << "Spell " << spell->name << ": target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ", assumed NO_TARGET.";
  717. for(const auto & counteredSpell: json["counters"].Struct())
  718. if (counteredSpell.second.Bool())
  719. {
  720. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  721. {
  722. spell->counteredSpells.push_back(SpellID(id));
  723. });
  724. }
  725. //TODO: more error checking - f.e. conflicting flags
  726. const auto flags = json["flags"];
  727. //by default all flags are set to false in constructor
  728. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  729. if(flags["offensive"].Bool())
  730. {
  731. spell->setIsOffensive(true);
  732. }
  733. if(flags["rising"].Bool())
  734. {
  735. spell->setIsRising(true);
  736. }
  737. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  738. if(flags["indifferent"].Bool())
  739. {
  740. spell->positiveness = CSpell::NEUTRAL;
  741. }
  742. else if(flags["negative"].Bool())
  743. {
  744. spell->positiveness = CSpell::NEGATIVE;
  745. }
  746. else if(flags["positive"].Bool())
  747. {
  748. spell->positiveness = CSpell::POSITIVE;
  749. }
  750. else if(!implicitPositiveness)
  751. {
  752. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  753. logGlobal->errorStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL.";
  754. }
  755. spell->isSpecial = flags["special"].Bool();
  756. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  757. {
  758. auto it = bonusNameMap.find(name);
  759. if(it == bonusNameMap.end())
  760. {
  761. logGlobal->errorStream() << "Spell " << spell->name << ": invalid bonus name " << name;
  762. }
  763. else
  764. {
  765. vec.push_back((Bonus::BonusType)it->second);
  766. }
  767. };
  768. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  769. {
  770. for(auto bonusData: json[name].Struct())
  771. {
  772. const std::string bonusId = bonusData.first;
  773. const bool flag = bonusData.second.Bool();
  774. if(flag)
  775. findBonus(bonusId, vec);
  776. }
  777. };
  778. readBonusStruct("immunity", spell->immunities);
  779. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  780. readBonusStruct("limit", spell->limiters);
  781. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  782. const JsonNode & graphicsNode = json["graphics"];
  783. spell->iconImmune = graphicsNode["iconImmune"].String();
  784. spell->iconBook = graphicsNode["iconBook"].String();
  785. spell->iconEffect = graphicsNode["iconEffect"].String();
  786. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  787. spell->iconScroll = graphicsNode["iconScroll"].String();
  788. const JsonNode & animationNode = json["animation"];
  789. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  790. {
  791. auto queueNode = animationNode[jsonName].Vector();
  792. for(const JsonNode & item : queueNode)
  793. {
  794. CSpell::TAnimation newItem;
  795. if(item.getType() == JsonNode::DATA_STRING)
  796. newItem.resourceName = item.String();
  797. else if(item.getType() == JsonNode::DATA_STRUCT)
  798. {
  799. newItem.resourceName = item["defName"].String();
  800. auto vPosStr = item["verticalPosition"].String();
  801. if("bottom" == vPosStr)
  802. newItem.verticalPosition = VerticalPosition::BOTTOM;
  803. }
  804. else if(item.getType() == JsonNode::DATA_FLOAT)
  805. {
  806. newItem.pause = item.Float();
  807. }
  808. q.push_back(newItem);
  809. }
  810. };
  811. loadAnimationQueue("affect", spell->animationInfo.affect);
  812. loadAnimationQueue("cast", spell->animationInfo.cast);
  813. loadAnimationQueue("hit", spell->animationInfo.hit);
  814. const JsonVector & projectile = animationNode["projectile"].Vector();
  815. for(const JsonNode & item : projectile)
  816. {
  817. CSpell::ProjectileInfo info;
  818. info.resourceName = item["defName"].String();
  819. info.minimumAngle = item["minimumAngle"].Float();
  820. spell->animationInfo.projectile.push_back(info);
  821. }
  822. const JsonNode & soundsNode = json["sounds"];
  823. spell->castSound = soundsNode["cast"].String();
  824. //load level attributes
  825. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  826. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  827. {
  828. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  829. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  830. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  831. levelObject.description = levelNode["description"].String();
  832. levelObject.cost = levelNode["cost"].Float();
  833. levelObject.AIValue = levelNode["aiValue"].Float();
  834. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  835. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  836. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  837. levelObject.range = levelNode["range"].String();
  838. for(const auto & elem : levelNode["effects"].Struct())
  839. {
  840. const JsonNode & bonusNode = elem.second;
  841. auto b = JsonUtils::parseBonus(bonusNode);
  842. const bool usePowerAsValue = bonusNode["val"].isNull();
  843. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  844. //b->sid = spell->id; //for all
  845. b->source = Bonus::SPELL_EFFECT;//for all
  846. if(usePowerAsValue)
  847. b->val = levelPower;
  848. levelObject.effectsTmp.push_back(b);
  849. }
  850. }
  851. return spell;
  852. }
  853. void CSpellHandler::afterLoadFinalization()
  854. {
  855. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  856. for(auto spell: objects)
  857. {
  858. for(auto & level: spell->levels)
  859. {
  860. for(auto bonus : level.effectsTmp)
  861. {
  862. level.effects.push_back(*bonus);
  863. }
  864. level.effectsTmp.clear();
  865. for(auto & bonus: level.effects)
  866. bonus.sid = spell->id;
  867. }
  868. spell->setup();
  869. }
  870. }
  871. void CSpellHandler::beforeValidate(JsonNode & object)
  872. {
  873. //handle "base" level info
  874. JsonNode & levels = object["levels"];
  875. JsonNode & base = levels["base"];
  876. auto inheritNode = [&](const std::string & name){
  877. JsonUtils::inherit(levels[name],base);
  878. };
  879. inheritNode("none");
  880. inheritNode("basic");
  881. inheritNode("advanced");
  882. inheritNode("expert");
  883. }
  884. CSpellHandler::~CSpellHandler()
  885. {
  886. }
  887. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  888. {
  889. std::vector<bool> allowedSpells;
  890. allowedSpells.reserve(objects.size());
  891. for(const CSpell * s : objects)
  892. {
  893. allowedSpells.push_back( !(s->isSpecialSpell() || s->isCreatureAbility()));
  894. }
  895. return allowedSpells;
  896. }
  897. si32 CSpellHandler::decodeSpell(const std::string& identifier)
  898. {
  899. auto rawId = VLC->modh->identifiers.getIdentifier("core", "spell", identifier);
  900. if(rawId)
  901. return rawId.get();
  902. else
  903. return -1;
  904. }
  905. std::string CSpellHandler::encodeSpell(const si32 index)
  906. {
  907. return VLC->spellh->objects[index]->identifier;
  908. }