CSpellHandler.cpp 22 KB

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