CSpellHandler.cpp 25 KB

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