CSpellHandler.cpp 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. /*
  2. * CSpellHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include <cctype>
  12. #include "CSpellHandler.h"
  13. #include "Problem.h"
  14. #include <vcmi/spells/Caster.h>
  15. #include "../CGeneralTextHandler.h"
  16. #include "../filesystem/Filesystem.h"
  17. #include "../CModHandler.h"
  18. #include "../StringConstants.h"
  19. #include "../battle/BattleInfo.h"
  20. #include "../battle/CBattleInfoCallback.h"
  21. #include "../battle/Unit.h"
  22. #include "../mapObjects/CGHeroInstance.h" //todo: remove
  23. #include "../serializer/CSerializer.h"
  24. #include "ISpellMechanics.h"
  25. VCMI_LIB_NAMESPACE_BEGIN
  26. namespace SpellConfig
  27. {
  28. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  29. static const spells::SchoolInfo SCHOOL[4] =
  30. {
  31. {
  32. ESpellSchool::AIR,
  33. Bonus::AIR_SPELL_DMG_PREMY,
  34. Bonus::AIR_IMMUNITY,
  35. "air",
  36. SecondarySkill::AIR_MAGIC,
  37. Bonus::AIR_SPELLS
  38. },
  39. {
  40. ESpellSchool::FIRE,
  41. Bonus::FIRE_SPELL_DMG_PREMY,
  42. Bonus::FIRE_IMMUNITY,
  43. "fire",
  44. SecondarySkill::FIRE_MAGIC,
  45. Bonus::FIRE_SPELLS
  46. },
  47. {
  48. ESpellSchool::WATER,
  49. Bonus::WATER_SPELL_DMG_PREMY,
  50. Bonus::WATER_IMMUNITY,
  51. "water",
  52. SecondarySkill::WATER_MAGIC,
  53. Bonus::WATER_SPELLS
  54. },
  55. {
  56. ESpellSchool::EARTH,
  57. Bonus::EARTH_SPELL_DMG_PREMY,
  58. Bonus::EARTH_IMMUNITY,
  59. "earth",
  60. SecondarySkill::EARTH_MAGIC,
  61. Bonus::EARTH_SPELLS
  62. }
  63. };
  64. //order as described in http://bugs.vcmi.eu/view.php?id=91
  65. static const ESpellSchool SCHOOL_ORDER[4] =
  66. {
  67. ESpellSchool::AIR, //=0
  68. ESpellSchool::FIRE, //=1
  69. ESpellSchool::EARTH,//=3(!)
  70. ESpellSchool::WATER //=2(!)
  71. };
  72. } //namespace SpellConfig
  73. ///CSpell
  74. CSpell::CSpell():
  75. id(SpellID::NONE),
  76. level(0),
  77. power(0),
  78. combat(false),
  79. creatureAbility(false),
  80. positiveness(ESpellPositiveness::NEUTRAL),
  81. defaultProbability(0),
  82. rising(false),
  83. damage(false),
  84. offensive(false),
  85. special(true),
  86. targetType(spells::AimType::NO_TARGET)
  87. {
  88. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  89. }
  90. //must be instantiated in .cpp file for access to complete types of all member fields
  91. CSpell::~CSpell() = default;
  92. bool CSpell::adventureCast(SpellCastEnvironment * env, const AdventureSpellCastParameters & parameters) const
  93. {
  94. assert(env);
  95. if(!adventureMechanics)
  96. {
  97. env->complain("Invalid adventure spell cast attempt!");
  98. return false;
  99. }
  100. return adventureMechanics->adventureCast(env, parameters);
  101. }
  102. const CSpell::LevelInfo & CSpell::getLevelInfo(const int32_t level) const
  103. {
  104. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  105. {
  106. logGlobal->error("CSpell::getLevelInfo: invalid school level %d", level);
  107. return levels.at(0);
  108. }
  109. return levels.at(level);
  110. }
  111. int64_t CSpell::calculateDamage(const spells::Caster * caster) const
  112. {
  113. //check if spell really does damage - if not, return 0
  114. if(!isDamage())
  115. return 0;
  116. auto rawDamage = calculateRawEffectValue(caster->getEffectLevel(this), caster->getEffectPower(this), 1);
  117. return caster->getSpellBonus(this, rawDamage, nullptr);
  118. }
  119. bool CSpell::canBeCast(const CBattleInfoCallback * cb, spells::Mode mode, const spells::Caster * caster) const
  120. {
  121. //if caller do not interested in description just discard it and do not pollute even debug log
  122. spells::detail::ProblemImpl problem;
  123. return canBeCast(problem, cb, mode, caster);
  124. }
  125. bool CSpell::canBeCast(spells::Problem & problem, const CBattleInfoCallback * cb, spells::Mode mode, const spells::Caster * caster) const
  126. {
  127. spells::BattleCast event(cb, caster, mode, this);
  128. auto mechanics = battleMechanics(&event);
  129. return mechanics->canBeCast(problem);
  130. }
  131. spells::AimType CSpell::getTargetType() const
  132. {
  133. return targetType;
  134. }
  135. void CSpell::forEachSchool(const std::function<void(const spells::SchoolInfo &, bool &)>& cb) const
  136. {
  137. bool stop = false;
  138. for(ESpellSchool iter : SpellConfig::SCHOOL_ORDER)
  139. {
  140. const spells::SchoolInfo & cnf = SpellConfig::SCHOOL[static_cast<ui8>(iter)];
  141. if(school.at(cnf.id))
  142. {
  143. cb(cnf, stop);
  144. if(stop)
  145. break;
  146. }
  147. }
  148. }
  149. SpellID CSpell::getId() const
  150. {
  151. return id;
  152. }
  153. std::string CSpell::getNameTextID() const
  154. {
  155. TextIdentifier id("spell", modScope, identifier, "name");
  156. return id.get();
  157. }
  158. std::string CSpell::getNameTranslated() const
  159. {
  160. return VLC->generaltexth->translate(getNameTextID());
  161. }
  162. std::string CSpell::getDescriptionTextID(int32_t level) const
  163. {
  164. TextIdentifier id("spell", modScope, identifier, "description", SpellConfig::LEVEL_NAMES[level]);
  165. return id.get();
  166. }
  167. std::string CSpell::getDescriptionTranslated(int32_t level) const
  168. {
  169. return VLC->generaltexth->translate(getDescriptionTextID(level));
  170. }
  171. std::string CSpell::getJsonKey() const
  172. {
  173. return modScope + ':' + identifier;;
  174. }
  175. int32_t CSpell::getIndex() const
  176. {
  177. return id.toEnum();
  178. }
  179. int32_t CSpell::getIconIndex() const
  180. {
  181. return getIndex();
  182. }
  183. int32_t CSpell::getLevel() const
  184. {
  185. return level;
  186. }
  187. bool CSpell::isCombat() const
  188. {
  189. return combat;
  190. }
  191. bool CSpell::isAdventure() const
  192. {
  193. return !combat;
  194. }
  195. bool CSpell::isCreatureAbility() const
  196. {
  197. return creatureAbility;
  198. }
  199. bool CSpell::isPositive() const
  200. {
  201. return positiveness == POSITIVE;
  202. }
  203. bool CSpell::isNegative() const
  204. {
  205. return positiveness == NEGATIVE;
  206. }
  207. bool CSpell::isNeutral() const
  208. {
  209. return positiveness == NEUTRAL;
  210. }
  211. boost::logic::tribool CSpell::getPositiveness() const
  212. {
  213. switch (positiveness)
  214. {
  215. case CSpell::POSITIVE:
  216. return true;
  217. case CSpell::NEGATIVE:
  218. return false;
  219. default:
  220. return boost::logic::indeterminate;
  221. }
  222. }
  223. bool CSpell::isDamage() const
  224. {
  225. return damage;
  226. }
  227. bool CSpell::isOffensive() const
  228. {
  229. return offensive;
  230. }
  231. bool CSpell::isSpecial() const
  232. {
  233. return special;
  234. }
  235. bool CSpell::hasEffects() const
  236. {
  237. return !levels[0].effects.empty() || !levels[0].cumulativeEffects.empty();
  238. }
  239. bool CSpell::hasBattleEffects() const
  240. {
  241. return levels[0].battleEffects.getType() == JsonNode::JsonType::DATA_STRUCT && !levels[0].battleEffects.Struct().empty();
  242. }
  243. const std::string & CSpell::getIconImmune() const
  244. {
  245. return iconImmune;
  246. }
  247. const std::string & CSpell::getIconBook() const
  248. {
  249. return iconBook;
  250. }
  251. const std::string & CSpell::getIconEffect() const
  252. {
  253. return iconEffect;
  254. }
  255. const std::string & CSpell::getIconScenarioBonus() const
  256. {
  257. return iconScenarioBonus;
  258. }
  259. const std::string & CSpell::getIconScroll() const
  260. {
  261. return iconScroll;
  262. }
  263. const std::string & CSpell::getCastSound() const
  264. {
  265. return castSound;
  266. }
  267. int32_t CSpell::getCost(const int32_t skillLevel) const
  268. {
  269. return getLevelInfo(skillLevel).cost;
  270. }
  271. int32_t CSpell::getBasePower() const
  272. {
  273. return power;
  274. }
  275. int32_t CSpell::getLevelPower(const int32_t skillLevel) const
  276. {
  277. return getLevelInfo(skillLevel).power;
  278. }
  279. si32 CSpell::getProbability(const TFaction factionId) const
  280. {
  281. if(!vstd::contains(probabilities,factionId))
  282. {
  283. return defaultProbability;
  284. }
  285. return probabilities.at(factionId);
  286. }
  287. void CSpell::getEffects(std::vector<Bonus> & lst, const int level, const bool cumulative, const si32 duration, boost::optional<si32 *> maxDuration) const
  288. {
  289. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  290. {
  291. logGlobal->error("invalid school level %d", level);
  292. return;
  293. }
  294. const auto & levelObject = levels.at(level);
  295. if(levelObject.effects.empty() && levelObject.cumulativeEffects.empty())
  296. {
  297. logGlobal->error("This spell (%s) has no effects for level %d", getNameTranslated(), level);
  298. return;
  299. }
  300. const auto & effects = cumulative ? levelObject.cumulativeEffects : levelObject.effects;
  301. lst.reserve(lst.size() + effects.size());
  302. for(const auto& b : effects)
  303. {
  304. Bonus nb(*b);
  305. //use configured duration if present
  306. if(nb.turnsRemain == 0)
  307. nb.turnsRemain = duration;
  308. if(maxDuration)
  309. vstd::amax(*(maxDuration.get()), nb.turnsRemain);
  310. lst.push_back(nb);
  311. }
  312. }
  313. int64_t CSpell::adjustRawDamage(const spells::Caster * caster, const battle::Unit * affectedCreature, int64_t rawDamage) const
  314. {
  315. auto ret = rawDamage;
  316. //affected creature-specific part
  317. if(nullptr != affectedCreature)
  318. {
  319. const auto * bearer = affectedCreature;
  320. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  321. forEachSchool([&](const spells::SchoolInfo & cnf, bool & stop)
  322. {
  323. if(bearer->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, static_cast<ui8>(cnf.id)))
  324. {
  325. ret *= 100 - bearer->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, static_cast<ui8>(cnf.id));
  326. ret /= 100;
  327. stop = true; //only bonus from one school is used
  328. }
  329. });
  330. CSelector selector = Selector::type()(Bonus::SPELL_DAMAGE_REDUCTION).And(Selector::subtype()(-1));
  331. //general spell dmg reduction
  332. if(bearer->hasBonus(selector))
  333. {
  334. ret *= 100 - bearer->valOfBonuses(selector);
  335. ret /= 100;
  336. }
  337. //dmg increasing
  338. if(bearer->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  339. {
  340. ret *= 100 + bearer->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  341. ret /= 100;
  342. }
  343. }
  344. ret = caster->getSpellBonus(this, ret, affectedCreature);
  345. return ret;
  346. }
  347. int64_t CSpell::calculateRawEffectValue(int32_t effectLevel, int32_t basePowerMultiplier, int32_t levelPowerMultiplier) const
  348. {
  349. return static_cast<int64_t>(basePowerMultiplier) * getBasePower() + levelPowerMultiplier * getLevelPower(effectLevel);
  350. }
  351. void CSpell::setIsOffensive(const bool val)
  352. {
  353. offensive = val;
  354. if(val)
  355. {
  356. positiveness = CSpell::NEGATIVE;
  357. damage = true;
  358. }
  359. }
  360. void CSpell::setIsRising(const bool val)
  361. {
  362. rising = val;
  363. if(val)
  364. {
  365. positiveness = CSpell::POSITIVE;
  366. }
  367. }
  368. JsonNode CSpell::convertTargetCondition(const BTVector & immunity, const BTVector & absImmunity, const BTVector & limit, const BTVector & absLimit) const
  369. {
  370. static const std::string CONDITION_NORMAL = "normal";
  371. static const std::string CONDITION_ABSOLUTE = "absolute";
  372. #define BONUS_NAME(x) { Bonus::x, #x },
  373. static const std::map<Bonus::BonusType, std::string> bonusNameRMap = { BONUS_LIST };
  374. #undef BONUS_NAME
  375. JsonNode res;
  376. auto convertVector = [&](const std::string & targetName, const BTVector & source, const std::string & value)
  377. {
  378. for(auto bonusType : source)
  379. {
  380. auto iter = bonusNameRMap.find(bonusType);
  381. if(iter != bonusNameRMap.end())
  382. {
  383. auto fullId = CModHandler::makeFullIdentifier("", "bonus", iter->second);
  384. res[targetName][fullId].String() = value;
  385. }
  386. else
  387. {
  388. logGlobal->error("Invalid bonus type %d", static_cast<int32_t>(bonusType));
  389. }
  390. }
  391. };
  392. auto convertSection = [&](const std::string & targetName, const BTVector & normal, const BTVector & absolute)
  393. {
  394. convertVector(targetName, normal, CONDITION_NORMAL);
  395. convertVector(targetName, absolute, CONDITION_ABSOLUTE);
  396. };
  397. convertSection("allOf", limit, absLimit);
  398. convertSection("noneOf", immunity, absImmunity);
  399. return res;
  400. }
  401. void CSpell::setupMechanics()
  402. {
  403. mechanics = spells::ISpellMechanicsFactory::get(this);
  404. adventureMechanics = IAdventureSpellMechanics::createMechanics(this);
  405. }
  406. std::unique_ptr<spells::Mechanics> CSpell::battleMechanics(const spells::IBattleCast * event) const
  407. {
  408. return mechanics->create(event);
  409. }
  410. void CSpell::registerIcons(const IconRegistar & cb) const
  411. {
  412. cb(getIndex(), 0, "SPELLS", iconBook);
  413. cb(getIndex()+1, 0, "SPELLINT", iconEffect);
  414. cb(getIndex(), 0, "SPELLBON", iconScenarioBonus);
  415. cb(getIndex(), 0, "SPELLSCR", iconScroll);
  416. }
  417. void CSpell::updateFrom(const JsonNode & data)
  418. {
  419. //todo:CSpell::updateFrom
  420. }
  421. void CSpell::serializeJson(JsonSerializeFormat & handler)
  422. {
  423. }
  424. ///CSpell::AnimationInfo
  425. CSpell::AnimationItem::AnimationItem() :
  426. verticalPosition(VerticalPosition::TOP),
  427. pause(0)
  428. {
  429. }
  430. ///CSpell::AnimationInfo
  431. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  432. {
  433. std::string res;
  434. double maximum = 0.0;
  435. for(const auto & info : projectile)
  436. {
  437. if(info.minimumAngle < angle && info.minimumAngle >= maximum)
  438. {
  439. maximum = info.minimumAngle;
  440. res = info.resourceName;
  441. }
  442. }
  443. return res;
  444. }
  445. ///CSpell::TargetInfo
  446. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, spells::Mode mode)
  447. : type(spell->getTargetType()),
  448. smart(false),
  449. massive(false),
  450. clearAffected(false),
  451. clearTarget(false)
  452. {
  453. const auto & levelInfo = spell->getLevelInfo(level);
  454. smart = levelInfo.smartTarget;
  455. massive = levelInfo.range == "X";
  456. clearAffected = levelInfo.clearAffected;
  457. clearTarget = levelInfo.clearTarget;
  458. }
  459. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  460. {
  461. int3 diff = pos - center;
  462. return diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8;
  463. }
  464. ///CSpellHandler
  465. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  466. {
  467. using namespace SpellConfig;
  468. std::vector<JsonNode> legacyData;
  469. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  470. auto readSchool = [&](JsonMap & schools, const std::string & name)
  471. {
  472. if (parser.readString() == "x")
  473. {
  474. schools[name].Bool() = true;
  475. }
  476. };
  477. auto read = [&](bool combat, bool ability)
  478. {
  479. do
  480. {
  481. JsonNode lineNode(JsonNode::JsonType::DATA_STRUCT);
  482. const auto id = legacyData.size();
  483. lineNode["index"].Integer() = id;
  484. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  485. lineNode["name"].String() = parser.readString();
  486. parser.readString(); //ignored unused abbreviated name
  487. lineNode["level"].Integer() = static_cast<si64>(parser.readNumber());
  488. auto& schools = lineNode["school"].Struct();
  489. readSchool(schools, "earth");
  490. readSchool(schools, "water");
  491. readSchool(schools, "fire");
  492. readSchool(schools, "air");
  493. auto& levels = lineNode["levels"].Struct();
  494. auto getLevel = [&](const size_t idx)->JsonMap&
  495. {
  496. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  497. return levels[LEVEL_NAMES[idx]].Struct();
  498. };
  499. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  500. lineNode["power"].Integer() = static_cast<si64>(parser.readNumber());
  501. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  502. auto & chances = lineNode["gainChance"].Struct();
  503. for(const auto & name : ETownType::names)
  504. chances[name].Integer() = static_cast<si64>(parser.readNumber());
  505. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  506. std::vector<std::string> descriptions;
  507. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  508. descriptions.push_back(parser.readString());
  509. parser.readString(); //ignore attributes. All data present in JSON
  510. //save parsed level specific data
  511. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  512. {
  513. auto& level = getLevel(i);
  514. level["description"].String() = descriptions[i];
  515. level["cost"].Integer() = costs[i];
  516. level["power"].Integer() = powers[i];
  517. level["aiValue"].Integer() = AIVals[i];
  518. }
  519. legacyData.push_back(lineNode);
  520. }
  521. while (parser.endLine() && !parser.isNextEntryEmpty());
  522. };
  523. auto skip = [&](int cnt)
  524. {
  525. for(int i=0; i<cnt; i++)
  526. parser.endLine();
  527. };
  528. skip(5);// header
  529. read(false,false); //read adventure map spells
  530. skip(3);
  531. read(true,false); //read battle spells
  532. skip(3);
  533. read(true,true);//read creature abilities
  534. //TODO: maybe move to config
  535. //clone Acid Breath attributes for Acid Breath damage effect
  536. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  537. temp["index"].Integer() = SpellID::ACID_BREATH_DAMAGE;
  538. legacyData.push_back(temp);
  539. objects.resize(legacyData.size());
  540. return legacyData;
  541. }
  542. const std::vector<std::string> & CSpellHandler::getTypeNames() const
  543. {
  544. static const std::vector<std::string> typeNames = { "spell" };
  545. return typeNames;
  546. }
  547. CSpell * CSpellHandler::loadFromJson(const std::string & scope, const JsonNode & json, const std::string & identifier, size_t index)
  548. {
  549. assert(identifier.find(':') == std::string::npos);
  550. assert(!scope.empty());
  551. using namespace SpellConfig;
  552. SpellID id(static_cast<si32>(index));
  553. auto * spell = new CSpell();
  554. spell->id = id;
  555. spell->identifier = identifier;
  556. spell->modScope = scope;
  557. const auto type = json["type"].String();
  558. if(type == "ability")
  559. {
  560. spell->creatureAbility = true;
  561. spell->combat = true;
  562. }
  563. else
  564. {
  565. spell->creatureAbility = false;
  566. spell->combat = type == "combat";
  567. }
  568. VLC->generaltexth->registerString(spell->getNameTextID(), json["name"].String());
  569. logMod->trace("%s: loading spell %s", __FUNCTION__, spell->getNameTranslated());
  570. const auto schoolNames = json["school"];
  571. for(const spells::SchoolInfo & info : SpellConfig::SCHOOL)
  572. {
  573. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  574. }
  575. spell->level = static_cast<si32>(json["level"].Integer());
  576. spell->power = static_cast<si32>(json["power"].Integer());
  577. spell->defaultProbability = static_cast<si32>(json["defaultGainChance"].Integer());
  578. for(const auto & node : json["gainChance"].Struct())
  579. {
  580. const int chance = static_cast<int>(node.second.Integer());
  581. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction", node.first, [=](si32 factionID)
  582. {
  583. spell->probabilities[factionID] = chance;
  584. });
  585. }
  586. auto targetType = json["targetType"].String();
  587. if(targetType == "NO_TARGET")
  588. spell->targetType = spells::AimType::NO_TARGET;
  589. else if(targetType == "CREATURE")
  590. spell->targetType = spells::AimType::CREATURE;
  591. else if(targetType == "OBSTACLE")
  592. spell->targetType = spells::AimType::OBSTACLE;
  593. else if(targetType == "LOCATION")
  594. spell->targetType = spells::AimType::LOCATION;
  595. else
  596. logMod->warn("Spell %s: target type %s - assumed NO_TARGET.", spell->getNameTranslated(), (targetType.empty() ? "empty" : "unknown ("+targetType+")"));
  597. for(const auto & counteredSpell: json["counters"].Struct())
  598. {
  599. if(counteredSpell.second.Bool())
  600. {
  601. VLC->modh->identifiers.requestIdentifier(counteredSpell.second.meta, counteredSpell.first, [=](si32 id)
  602. {
  603. spell->counteredSpells.emplace_back(id);
  604. });
  605. }
  606. }
  607. //TODO: more error checking - f.e. conflicting flags
  608. const auto flags = json["flags"];
  609. //by default all flags are set to false in constructor
  610. spell->damage = flags["damage"].Bool(); //do this before "offensive"
  611. if(flags["offensive"].Bool())
  612. {
  613. spell->setIsOffensive(true);
  614. }
  615. if(flags["rising"].Bool())
  616. {
  617. spell->setIsRising(true);
  618. }
  619. const bool implicitPositiveness = spell->offensive || spell->rising; //(!) "damage" does not mean NEGATIVE --AVS
  620. if(flags["indifferent"].Bool())
  621. {
  622. spell->positiveness = CSpell::NEUTRAL;
  623. }
  624. else if(flags["negative"].Bool())
  625. {
  626. spell->positiveness = CSpell::NEGATIVE;
  627. }
  628. else if(flags["positive"].Bool())
  629. {
  630. spell->positiveness = CSpell::POSITIVE;
  631. }
  632. else if(!implicitPositiveness)
  633. {
  634. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  635. logMod->error("Spell %s: no positiveness specified, assumed NEUTRAL.", spell->getNameTranslated());
  636. }
  637. spell->special = flags["special"].Bool();
  638. auto findBonus = [&](const std::string & name, std::vector<Bonus::BonusType> & vec)
  639. {
  640. auto it = bonusNameMap.find(name);
  641. if(it == bonusNameMap.end())
  642. {
  643. logMod->error("Spell %s: invalid bonus name %s", spell->getNameTranslated(), name);
  644. }
  645. else
  646. {
  647. vec.push_back(static_cast<Bonus::BonusType>(it->second));
  648. }
  649. };
  650. auto readBonusStruct = [&](const std::string & name, std::vector<Bonus::BonusType> & vec)
  651. {
  652. for(auto bonusData: json[name].Struct())
  653. {
  654. const std::string bonusId = bonusData.first;
  655. const bool flag = bonusData.second.Bool();
  656. if(flag)
  657. findBonus(bonusId, vec);
  658. }
  659. };
  660. if(json["targetCondition"].isNull())
  661. {
  662. CSpell::BTVector immunities;
  663. CSpell::BTVector absoluteImmunities;
  664. CSpell::BTVector limiters;
  665. CSpell::BTVector absoluteLimiters;
  666. readBonusStruct("immunity", immunities);
  667. readBonusStruct("absoluteImmunity", absoluteImmunities);
  668. readBonusStruct("limit", limiters);
  669. readBonusStruct("absoluteLimit", absoluteLimiters);
  670. if(!(immunities.empty() && absoluteImmunities.empty() && limiters.empty() && absoluteLimiters.empty()))
  671. {
  672. logMod->warn("Spell %s has old target condition format. Expected configuration: ", spell->getNameTranslated());
  673. spell->targetCondition = spell->convertTargetCondition(immunities, absoluteImmunities, limiters, absoluteLimiters);
  674. logMod->warn("\n\"targetCondition\" : %s", spell->targetCondition.toJson());
  675. }
  676. }
  677. else
  678. {
  679. spell->targetCondition = json["targetCondition"];
  680. //TODO: could this be safely merged instead of discarding?
  681. if(!json["immunity"].isNull())
  682. logMod->warn("Spell %s 'immunity' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  683. if(!json["absoluteImmunity"].isNull())
  684. logMod->warn("Spell %s 'absoluteImmunity' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  685. if(!json["limit"].isNull())
  686. logMod->warn("Spell %s 'limit' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  687. if(!json["absoluteLimit"].isNull())
  688. logMod->warn("Spell %s 'absoluteLimit' field mixed with 'targetCondition' discarded", spell->getNameTranslated());
  689. }
  690. const JsonNode & graphicsNode = json["graphics"];
  691. spell->iconImmune = graphicsNode["iconImmune"].String();
  692. spell->iconBook = graphicsNode["iconBook"].String();
  693. spell->iconEffect = graphicsNode["iconEffect"].String();
  694. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  695. spell->iconScroll = graphicsNode["iconScroll"].String();
  696. const JsonNode & animationNode = json["animation"];
  697. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  698. {
  699. auto queueNode = animationNode[jsonName].Vector();
  700. for(const JsonNode & item : queueNode)
  701. {
  702. CSpell::TAnimation newItem;
  703. if(item.getType() == JsonNode::JsonType::DATA_STRING)
  704. newItem.resourceName = item.String();
  705. else if(item.getType() == JsonNode::JsonType::DATA_STRUCT)
  706. {
  707. newItem.resourceName = item["defName"].String();
  708. newItem.effectName = item["effectName"].String();
  709. auto vPosStr = item["verticalPosition"].String();
  710. if("bottom" == vPosStr)
  711. newItem.verticalPosition = VerticalPosition::BOTTOM;
  712. }
  713. else if(item.isNumber())
  714. {
  715. newItem.pause = static_cast<int>(item.Float());
  716. }
  717. q.push_back(newItem);
  718. }
  719. };
  720. loadAnimationQueue("affect", spell->animationInfo.affect);
  721. loadAnimationQueue("cast", spell->animationInfo.cast);
  722. loadAnimationQueue("hit", spell->animationInfo.hit);
  723. const JsonVector & projectile = animationNode["projectile"].Vector();
  724. for(const JsonNode & item : projectile)
  725. {
  726. CSpell::ProjectileInfo info;
  727. info.resourceName = item["defName"].String();
  728. info.minimumAngle = item["minimumAngle"].Float();
  729. spell->animationInfo.projectile.push_back(info);
  730. }
  731. const JsonNode & soundsNode = json["sounds"];
  732. spell->castSound = soundsNode["cast"].String();
  733. //load level attributes
  734. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  735. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  736. {
  737. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  738. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  739. const si32 levelPower = levelObject.power = static_cast<si32>(levelNode["power"].Integer());
  740. if (!spell->isCreatureAbility())
  741. VLC->generaltexth->registerString(spell->getDescriptionTextID(levelIndex), levelNode["description"].String());
  742. levelObject.cost = static_cast<si32>(levelNode["cost"].Integer());
  743. levelObject.AIValue = static_cast<si32>(levelNode["aiValue"].Integer());
  744. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  745. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  746. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  747. levelObject.range = levelNode["range"].String();
  748. for(const auto & elem : levelNode["effects"].Struct())
  749. {
  750. const JsonNode & bonusNode = elem.second;
  751. auto b = JsonUtils::parseBonus(bonusNode);
  752. const bool usePowerAsValue = bonusNode["val"].isNull();
  753. b->sid = spell->id; //for all
  754. b->source = Bonus::SPELL_EFFECT;//for all
  755. if(usePowerAsValue)
  756. b->val = levelPower;
  757. levelObject.effects.push_back(b);
  758. }
  759. for(const auto & elem : levelNode["cumulativeEffects"].Struct())
  760. {
  761. const JsonNode & bonusNode = elem.second;
  762. auto b = JsonUtils::parseBonus(bonusNode);
  763. const bool usePowerAsValue = bonusNode["val"].isNull();
  764. b->sid = spell->id; //for all
  765. b->source = Bonus::SPELL_EFFECT;//for all
  766. if(usePowerAsValue)
  767. b->val = levelPower;
  768. levelObject.cumulativeEffects.push_back(b);
  769. }
  770. if(levelNode["battleEffects"].getType() == JsonNode::JsonType::DATA_STRUCT && !levelNode["battleEffects"].Struct().empty())
  771. {
  772. levelObject.battleEffects = levelNode["battleEffects"];
  773. if(!levelObject.cumulativeEffects.empty() || !levelObject.effects.empty() || spell->isOffensive())
  774. logGlobal->error("Mixing %s special effects with old format effects gives unpredictable result", spell->getNameTranslated());
  775. }
  776. }
  777. return spell;
  778. }
  779. void CSpellHandler::afterLoadFinalization()
  780. {
  781. for(auto spell : objects)
  782. {
  783. spell->setupMechanics();
  784. }
  785. }
  786. void CSpellHandler::beforeValidate(JsonNode & object)
  787. {
  788. //handle "base" level info
  789. JsonNode & levels = object["levels"];
  790. JsonNode & base = levels["base"];
  791. auto inheritNode = [&](const std::string & name)
  792. {
  793. JsonUtils::inherit(levels[name],base);
  794. };
  795. inheritNode("none");
  796. inheritNode("basic");
  797. inheritNode("advanced");
  798. inheritNode("expert");
  799. }
  800. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  801. {
  802. std::vector<bool> allowedSpells;
  803. allowedSpells.reserve(objects.size());
  804. for(const CSpell * s : objects)
  805. {
  806. allowedSpells.push_back( !(s->isSpecial() || s->isCreatureAbility()));
  807. }
  808. return allowedSpells;
  809. }
  810. VCMI_LIB_NAMESPACE_END