2
0

CSpellHandler.cpp 25 KB

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