CSpellHandler.cpp 28 KB

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