CSpellHandler.cpp 26 KB

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