CSpellHandler.cpp 24 KB

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