CSpellHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  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(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. }
  439. mechanics = ISpellMechanics::createMechanics(this);
  440. }
  441. ///CSpell::TargetInfo
  442. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  443. {
  444. init(spell, level);
  445. }
  446. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  447. {
  448. init(spell, level);
  449. if(mode == ECastingMode::ENCHANTER_CASTING)
  450. {
  451. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  452. massive = true;
  453. }
  454. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  455. {
  456. alwaysHitDirectly = true;
  457. }
  458. }
  459. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  460. {
  461. auto & levelInfo = spell->getLevelInfo(level);
  462. type = spell->getTargetType();
  463. smart = levelInfo.smartTarget;
  464. massive = levelInfo.range == "X";
  465. onlyAlive = !spell->isRisingSpell();
  466. alwaysHitDirectly = false;
  467. clearAffected = levelInfo.clearAffected;
  468. clearTarget = levelInfo.clearTarget;
  469. }
  470. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  471. {
  472. int3 diff = pos - center;
  473. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  474. return true;
  475. else
  476. return false;
  477. }
  478. ///CSpellHandler
  479. CSpellHandler::CSpellHandler()
  480. {
  481. }
  482. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  483. {
  484. using namespace SpellConfig;
  485. std::vector<JsonNode> legacyData;
  486. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  487. auto readSchool = [&](JsonMap& schools, const std::string& name)
  488. {
  489. if (parser.readString() == "x")
  490. {
  491. schools[name].Bool() = true;
  492. }
  493. };
  494. auto read = [&,this](bool combat, bool ability)
  495. {
  496. do
  497. {
  498. JsonNode lineNode(JsonNode::DATA_STRUCT);
  499. const si32 id = legacyData.size();
  500. lineNode["index"].Float() = id;
  501. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  502. lineNode["name"].String() = parser.readString();
  503. parser.readString(); //ignored unused abbreviated name
  504. lineNode["level"].Float() = parser.readNumber();
  505. auto& schools = lineNode["school"].Struct();
  506. readSchool(schools, "earth");
  507. readSchool(schools, "water");
  508. readSchool(schools, "fire");
  509. readSchool(schools, "air");
  510. auto& levels = lineNode["levels"].Struct();
  511. auto getLevel = [&](const size_t idx)->JsonMap&
  512. {
  513. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  514. return levels[LEVEL_NAMES[idx]].Struct();
  515. };
  516. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  517. lineNode["power"].Float() = parser.readNumber();
  518. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  519. auto& chances = lineNode["gainChance"].Struct();
  520. for(size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  521. chances[ETownType::names[i]].Float() = parser.readNumber();
  522. }
  523. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  524. std::vector<std::string> descriptions;
  525. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  526. descriptions.push_back(parser.readString());
  527. parser.readString(); //ignore attributes. All data present in JSON
  528. //save parsed level specific data
  529. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  530. {
  531. auto& level = getLevel(i);
  532. level["description"].String() = descriptions[i];
  533. level["cost"].Float() = costs[i];
  534. level["power"].Float() = powers[i];
  535. level["aiValue"].Float() = AIVals[i];
  536. }
  537. legacyData.push_back(lineNode);
  538. }
  539. while (parser.endLine() && !parser.isNextEntryEmpty());
  540. };
  541. auto skip = [&](int cnt)
  542. {
  543. for(int i=0; i<cnt; i++)
  544. parser.endLine();
  545. };
  546. skip(5);// header
  547. read(false,false); //read adventure map spells
  548. skip(3);
  549. read(true,false); //read battle spells
  550. skip(3);
  551. read(true,true);//read creature abilities
  552. //TODO: maybe move to config
  553. //clone Acid Breath attributes for Acid Breath damage effect
  554. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  555. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  556. legacyData.push_back(temp);
  557. objects.resize(legacyData.size());
  558. return legacyData;
  559. }
  560. const std::string CSpellHandler::getTypeName() const
  561. {
  562. return "spell";
  563. }
  564. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  565. {
  566. using namespace SpellConfig;
  567. CSpell * spell = new CSpell();
  568. const auto type = json["type"].String();
  569. if(type == "ability")
  570. {
  571. spell->creatureAbility = true;
  572. spell->combatSpell = true;
  573. }
  574. else
  575. {
  576. spell->creatureAbility = false;
  577. spell->combatSpell = type == "combat";
  578. }
  579. spell->name = json["name"].String();
  580. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  581. const auto schoolNames = json["school"];
  582. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  583. {
  584. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  585. }
  586. spell->level = json["level"].Float();
  587. spell->power = json["power"].Float();
  588. spell->defaultProbability = json["defaultGainChance"].Float();
  589. for(const auto & node : json["gainChance"].Struct())
  590. {
  591. const int chance = node.second.Float();
  592. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  593. {
  594. spell->probabilities[factionID] = chance;
  595. });
  596. }
  597. auto targetType = json["targetType"].String();
  598. if(targetType == "NO_TARGET")
  599. spell->targetType = CSpell::NO_TARGET;
  600. else if(targetType == "CREATURE")
  601. spell->targetType = CSpell::CREATURE;
  602. else if(targetType == "OBSTACLE")
  603. spell->targetType = CSpell::OBSTACLE;
  604. else if(targetType == "LOCATION")
  605. spell->targetType = CSpell::LOCATION;
  606. else
  607. logGlobal->warnStream() << "Spell " << spell->name << ". Target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ". Assumed NO_TARGET.";
  608. spell->mainEffectAnim = json["anim"].Float();
  609. for(const auto & counteredSpell: json["counters"].Struct())
  610. if (counteredSpell.second.Bool())
  611. {
  612. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  613. {
  614. spell->counteredSpells.push_back(SpellID(id));
  615. });
  616. }
  617. //TODO: more error checking - f.e. conflicting flags
  618. const auto flags = json["flags"];
  619. //by default all flags are set to false in constructor
  620. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  621. if(flags["offensive"].Bool())
  622. {
  623. spell->setIsOffensive(true);
  624. }
  625. if(flags["rising"].Bool())
  626. {
  627. spell->setIsRising(true);
  628. }
  629. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  630. if(flags["indifferent"].Bool())
  631. {
  632. spell->positiveness = CSpell::NEUTRAL;
  633. }
  634. else if(flags["negative"].Bool())
  635. {
  636. spell->positiveness = CSpell::NEGATIVE;
  637. }
  638. else if(flags["positive"].Bool())
  639. {
  640. spell->positiveness = CSpell::POSITIVE;
  641. }
  642. else if(!implicitPositiveness)
  643. {
  644. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  645. logGlobal->errorStream() << "No positiveness specified, assumed NEUTRAL";
  646. }
  647. spell->isSpecial = flags["special"].Bool();
  648. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  649. {
  650. auto it = bonusNameMap.find(name);
  651. if(it == bonusNameMap.end())
  652. {
  653. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  654. }
  655. else
  656. {
  657. vec.push_back((Bonus::BonusType)it->second);
  658. }
  659. };
  660. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  661. {
  662. for(auto bonusData: json[name].Struct())
  663. {
  664. const std::string bonusId = bonusData.first;
  665. const bool flag = bonusData.second.Bool();
  666. if(flag)
  667. findBonus(bonusId, vec);
  668. }
  669. };
  670. readBonusStruct("immunity", spell->immunities);
  671. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  672. readBonusStruct("limit", spell->limiters);
  673. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  674. const JsonNode & graphicsNode = json["graphics"];
  675. spell->iconImmune = graphicsNode["iconImmune"].String();
  676. spell->iconBook = graphicsNode["iconBook"].String();
  677. spell->iconEffect = graphicsNode["iconEffect"].String();
  678. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  679. spell->iconScroll = graphicsNode["iconScroll"].String();
  680. const JsonNode & soundsNode = json["sounds"];
  681. spell->castSound = soundsNode["cast"].String();
  682. //load level attributes
  683. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  684. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  685. {
  686. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  687. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  688. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  689. levelObject.description = levelNode["description"].String();
  690. levelObject.cost = levelNode["cost"].Float();
  691. levelObject.AIValue = levelNode["aiValue"].Float();
  692. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  693. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  694. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  695. levelObject.range = levelNode["range"].String();
  696. for(const auto & elem : levelNode["effects"].Struct())
  697. {
  698. const JsonNode & bonusNode = elem.second;
  699. Bonus * b = JsonUtils::parseBonus(bonusNode);
  700. const bool usePowerAsValue = bonusNode["val"].isNull();
  701. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  702. //b->sid = spell->id; //for all
  703. b->source = Bonus::SPELL_EFFECT;//for all
  704. if(usePowerAsValue)
  705. b->val = levelPower;
  706. levelObject.effects.push_back(*b);
  707. }
  708. }
  709. return spell;
  710. }
  711. void CSpellHandler::afterLoadFinalization()
  712. {
  713. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  714. for(auto spell: objects)
  715. {
  716. for(auto & level: spell->levels)
  717. for(auto & bonus: level.effects)
  718. bonus.sid = spell->id;
  719. spell->setup();
  720. }
  721. }
  722. void CSpellHandler::beforeValidate(JsonNode & object)
  723. {
  724. //handle "base" level info
  725. JsonNode& levels = object["levels"];
  726. JsonNode& base = levels["base"];
  727. auto inheritNode = [&](const std::string & name){
  728. JsonUtils::inherit(levels[name],base);
  729. };
  730. inheritNode("none");
  731. inheritNode("basic");
  732. inheritNode("advanced");
  733. inheritNode("expert");
  734. }
  735. CSpellHandler::~CSpellHandler()
  736. {
  737. }
  738. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  739. {
  740. std::vector<bool> allowedSpells;
  741. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  742. return allowedSpells;
  743. }