CSpellHandler.cpp 26 KB

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