CSpellHandler.cpp 26 KB

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