CSpellHandler.cpp 26 KB

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