CSpellHandler.cpp 25 KB

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