CSpellHandler.cpp 26 KB

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