CSpellHandler.cpp 24 KB

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