CSpellHandler.cpp 26 KB

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