CSpellHandler.cpp 27 KB

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