2
0

CSpellHandler.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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 "../CGeneralTextHandler.h"
  14. #include "../filesystem/Filesystem.h"
  15. #include "../JsonNode.h"
  16. #include "../BattleHex.h"
  17. #include "../CModHandler.h"
  18. #include "../StringConstants.h"
  19. #include "../mapObjects/CGHeroInstance.h"
  20. #include "../BattleState.h"
  21. #include "../CBattleCallback.h"
  22. #include "../CGameState.h" //todo: remove
  23. #include "../NetPacks.h" //todo: remove
  24. #include "ISpellMechanics.h"
  25. namespace SpellConfig
  26. {
  27. static const std::string LEVEL_NAMES[] = {"none", "basic", "advanced", "expert"};
  28. static const SpellSchoolInfo SCHOOL[4] =
  29. {
  30. {
  31. ESpellSchool::AIR,
  32. Bonus::AIR_SPELL_DMG_PREMY,
  33. Bonus::AIR_IMMUNITY,
  34. "air",
  35. SecondarySkill::AIR_MAGIC,
  36. Bonus::AIR_SPELLS
  37. },
  38. {
  39. ESpellSchool::FIRE,
  40. Bonus::FIRE_SPELL_DMG_PREMY,
  41. Bonus::FIRE_IMMUNITY,
  42. "fire",
  43. SecondarySkill::FIRE_MAGIC,
  44. Bonus::FIRE_SPELLS
  45. },
  46. {
  47. ESpellSchool::WATER,
  48. Bonus::WATER_SPELL_DMG_PREMY,
  49. Bonus::WATER_IMMUNITY,
  50. "water",
  51. SecondarySkill::WATER_MAGIC,
  52. Bonus::WATER_SPELLS
  53. },
  54. {
  55. ESpellSchool::EARTH,
  56. Bonus::EARTH_SPELL_DMG_PREMY,
  57. Bonus::EARTH_IMMUNITY,
  58. "earth",
  59. SecondarySkill::EARTH_MAGIC,
  60. Bonus::EARTH_SPELLS
  61. }
  62. };
  63. }
  64. ///CSpell::LevelInfo
  65. CSpell::LevelInfo::LevelInfo()
  66. :description(""),cost(0),power(0),AIValue(0),smartTarget(true), clearTarget(false), clearAffected(false), range("0")
  67. {
  68. }
  69. CSpell::LevelInfo::~LevelInfo()
  70. {
  71. }
  72. ///CSpell
  73. CSpell::CSpell():
  74. id(SpellID::NONE), level(0),
  75. combatSpell(false), creatureAbility(false),
  76. positiveness(ESpellPositiveness::NEUTRAL),
  77. defaultProbability(0),
  78. isRising(false), isDamage(false), isOffensive(false),
  79. targetType(ETargetType::NO_TARGET),
  80. mechanics(nullptr)
  81. {
  82. levels.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  83. }
  84. CSpell::~CSpell()
  85. {
  86. delete mechanics;
  87. }
  88. void CSpell::applyBattle(BattleInfo * battle, const BattleSpellCast * packet) const
  89. {
  90. mechanics->applyBattle(battle, packet);
  91. }
  92. bool CSpell::adventureCast(const SpellCastEnvironment * env, AdventureSpellCastParameters & parameters) const
  93. {
  94. assert(env);
  95. return mechanics->adventureCast(env, parameters);
  96. }
  97. void CSpell::battleCast(const SpellCastEnvironment * env, BattleSpellCastParameters & parameters) const
  98. {
  99. assert(env);
  100. mechanics->battleCast(env, parameters);
  101. }
  102. const CSpell::LevelInfo & CSpell::getLevelInfo(const int level) const
  103. {
  104. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  105. {
  106. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  107. throw new std::runtime_error("Invalid school level");
  108. }
  109. return levels.at(level);
  110. }
  111. ui32 CSpell::calculateDamage(const ISpellCaster * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const
  112. {
  113. //check if spell really does damage - if not, return 0
  114. if(!isDamageSpell())
  115. return 0;
  116. return adjustRawDamage(caster, affectedCreature, calculateRawEffectValue(spellSchoolLevel, usedSpellPower));
  117. }
  118. ESpellCastProblem::ESpellCastProblem CSpell::canBeCast(const CBattleInfoCallback * cb, PlayerColor player) const
  119. {
  120. return mechanics->canBeCast(cb, player);
  121. }
  122. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  123. {
  124. return mechanics->rangeInHexes(centralHex,schoolLvl,side,outDroppedHexes);
  125. }
  126. std::set<const CStack *> CSpell::getAffectedStacks(const CBattleInfoCallback * cb, ECastingMode::ECastingMode mode, PlayerColor casterColor, int spellLvl, BattleHex destination, const ISpellCaster * caster) const
  127. {
  128. ISpellMechanics::SpellTargetingContext ctx(this, cb,mode,casterColor,spellLvl,destination);
  129. std::set<const CStack* > attackedCres = mechanics->getAffectedStacks(ctx);
  130. //now handle immunities
  131. auto predicate = [&, this](const CStack * s)->bool
  132. {
  133. bool hitDirectly = ctx.ti.alwaysHitDirectly && s->coversPos(destination);
  134. bool notImmune = (ESpellCastProblem::OK == isImmuneByStack(caster, s));
  135. return !(hitDirectly || notImmune);
  136. };
  137. vstd::erase_if(attackedCres, predicate);
  138. return attackedCres;
  139. }
  140. CSpell::ETargetType CSpell::getTargetType() const
  141. {
  142. return targetType;
  143. }
  144. void CSpell::forEachSchool(const std::function<void(const SpellSchoolInfo &, bool &)>& cb) const
  145. {
  146. bool stop = false;
  147. for(const SpellSchoolInfo & cnf : SpellConfig::SCHOOL)
  148. {
  149. if(school.at(cnf.id))
  150. {
  151. cb(cnf, stop);
  152. if(stop)
  153. break;
  154. }
  155. }
  156. }
  157. bool CSpell::isCombatSpell() const
  158. {
  159. return combatSpell;
  160. }
  161. bool CSpell::isAdventureSpell() const
  162. {
  163. return !combatSpell;
  164. }
  165. bool CSpell::isCreatureAbility() const
  166. {
  167. return creatureAbility;
  168. }
  169. bool CSpell::isPositive() const
  170. {
  171. return positiveness == POSITIVE;
  172. }
  173. bool CSpell::isNegative() const
  174. {
  175. return positiveness == NEGATIVE;
  176. }
  177. bool CSpell::isNeutral() const
  178. {
  179. return positiveness == NEUTRAL;
  180. }
  181. bool CSpell::isHealingSpell() const
  182. {
  183. return isRisingSpell() || (id == SpellID::CURE);
  184. }
  185. bool CSpell::isRisingSpell() const
  186. {
  187. return isRising;
  188. }
  189. bool CSpell::isDamageSpell() const
  190. {
  191. return isDamage;
  192. }
  193. bool CSpell::isOffensiveSpell() const
  194. {
  195. return isOffensive;
  196. }
  197. bool CSpell::isSpecialSpell() const
  198. {
  199. return isSpecial;
  200. }
  201. bool CSpell::hasEffects() const
  202. {
  203. return !levels[0].effects.empty();
  204. }
  205. const std::string & CSpell::getIconImmune() const
  206. {
  207. return iconImmune;
  208. }
  209. const std::string & CSpell::getCastSound() const
  210. {
  211. return castSound;
  212. }
  213. si32 CSpell::getCost(const int skillLevel) const
  214. {
  215. return getLevelInfo(skillLevel).cost;
  216. }
  217. si32 CSpell::getPower(const int skillLevel) const
  218. {
  219. return getLevelInfo(skillLevel).power;
  220. }
  221. si32 CSpell::getProbability(const TFaction factionId) const
  222. {
  223. if(!vstd::contains(probabilities,factionId))
  224. {
  225. return defaultProbability;
  226. }
  227. return probabilities.at(factionId);
  228. }
  229. void CSpell::getEffects(std::vector<Bonus> & lst, const int level) const
  230. {
  231. if(level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  232. {
  233. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  234. return;
  235. }
  236. const std::vector<Bonus> & effects = levels[level].effects;
  237. if(effects.empty())
  238. {
  239. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  240. return;
  241. }
  242. lst.reserve(lst.size() + effects.size());
  243. for(const Bonus & b : effects)
  244. {
  245. lst.push_back(Bonus(b));
  246. }
  247. }
  248. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneAt(const CBattleInfoCallback * cb, const CGHeroInstance * caster, ECastingMode::ECastingMode mode, BattleHex destination) const
  249. {
  250. // Get all stacks at destination hex. only alive if not rising spell
  251. TStacks stacks = cb->battleGetStacksIf([=](const CStack * s){
  252. return s->coversPos(destination) && (isRisingSpell() || s->alive());
  253. });
  254. if(!stacks.empty())
  255. {
  256. bool allImmune = true;
  257. ESpellCastProblem::ESpellCastProblem problem = ESpellCastProblem::INVALID;
  258. for(auto s : stacks)
  259. {
  260. ESpellCastProblem::ESpellCastProblem res = isImmuneByStack(caster,s);
  261. if(res == ESpellCastProblem::OK)
  262. {
  263. allImmune = false;
  264. }
  265. else
  266. {
  267. problem = res;
  268. }
  269. }
  270. if(allImmune)
  271. return problem;
  272. }
  273. else //no target stack on this tile
  274. {
  275. if(getTargetType() == CSpell::CREATURE)
  276. {
  277. if(caster && mode == ECastingMode::HERO_CASTING) //TODO why???
  278. {
  279. const CSpell::TargetInfo ti(this, caster->getSpellSchoolLevel(this), mode);
  280. if(!ti.massive)
  281. return ESpellCastProblem::WRONG_SPELL_TARGET;
  282. }
  283. else
  284. {
  285. return ESpellCastProblem::WRONG_SPELL_TARGET;
  286. }
  287. }
  288. }
  289. return ESpellCastProblem::OK;
  290. }
  291. int CSpell::adjustRawDamage(const ISpellCaster * caster, const CStack * affectedCreature, int rawDamage) const
  292. {
  293. int ret = rawDamage;
  294. //affected creature-specific part
  295. if(nullptr != affectedCreature)
  296. {
  297. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  298. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  299. {
  300. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id))
  301. {
  302. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, (ui8)cnf.id);
  303. ret /= 100;
  304. stop = true;//only bonus from one school is used
  305. }
  306. });
  307. //general spell dmg reduction
  308. if(affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
  309. {
  310. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  311. ret /= 100;
  312. }
  313. //dmg increasing
  314. if(affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, id))
  315. {
  316. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, id.toEnum());
  317. ret /= 100;
  318. }
  319. }
  320. ret = caster->getSpellBonus(this, ret, affectedCreature);
  321. return ret;
  322. }
  323. int CSpell::calculateRawEffectValue(int effectLevel, int effectPower) const
  324. {
  325. return effectPower * power + getPower(effectLevel);
  326. }
  327. ESpellCastProblem::ESpellCastProblem CSpell::internalIsImmune(const ISpellCaster * caster, const CStack *obj) const
  328. {
  329. //todo: use new bonus API
  330. //1. Check absolute limiters
  331. for(auto b : absoluteLimiters)
  332. {
  333. if (!obj->hasBonusOfType(b))
  334. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  335. }
  336. //2. Check absolute immunities
  337. for(auto b : absoluteImmunities)
  338. {
  339. if (obj->hasBonusOfType(b))
  340. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  341. }
  342. {
  343. //spell-based spell immunity (only ANTIMAGIC in OH3) is treated as absolute
  344. std::stringstream cachingStr;
  345. cachingStr << "type_" << Bonus::LEVEL_SPELL_IMMUNITY << "source_" << Bonus::SPELL_EFFECT;
  346. TBonusListPtr levelImmunitiesFromSpell = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY).And(Selector::sourceType(Bonus::SPELL_EFFECT)), cachingStr.str());
  347. if(levelImmunitiesFromSpell->size() > 0 && levelImmunitiesFromSpell->totalValue() >= level && level)
  348. {
  349. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  350. }
  351. }
  352. {
  353. //SPELL_IMMUNITY absolute case
  354. std::stringstream cachingStr;
  355. cachingStr << "type_" << Bonus::SPELL_IMMUNITY << "subtype_" << id.toEnum() << "addInfo_1";
  356. if(obj->hasBonus(Selector::typeSubtypeInfo(Bonus::SPELL_IMMUNITY, id.toEnum(), 1), cachingStr.str()))
  357. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  358. }
  359. //check receptivity
  360. if (isPositive() && obj->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
  361. return ESpellCastProblem::OK;
  362. //3. Check negation
  363. //Orb of vulnerability
  364. //FIXME: Orb of vulnerability mechanics is not such trivial (issue 1791)
  365. const bool battleWideNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 0);
  366. const bool heroNegation = obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES, 1);
  367. //anyone can cast on artifact holder`s stacks
  368. if(heroNegation)
  369. return ESpellCastProblem::NOT_DECIDED;
  370. //this stack is from other player
  371. //todo: check that caster is always present (not trivial is this case)
  372. //todo: NEGATE_ALL_NATURAL_IMMUNITIES special cases: dispell, chain lightning
  373. else if(battleWideNegation && caster)
  374. {
  375. if(obj->owner != caster->getOwner())
  376. return ESpellCastProblem::NOT_DECIDED;
  377. }
  378. //4. Check negatable limit
  379. for(auto b : limiters)
  380. {
  381. if (!obj->hasBonusOfType(b))
  382. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  383. }
  384. //5. Check negatable immunities
  385. for(auto b : immunities)
  386. {
  387. if (obj->hasBonusOfType(b))
  388. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  389. }
  390. //6. Check elemental immunities
  391. ESpellCastProblem::ESpellCastProblem tmp = ESpellCastProblem::NOT_DECIDED;
  392. forEachSchool([&](const SpellSchoolInfo & cnf, bool & stop)
  393. {
  394. auto element = cnf.immunityBonus;
  395. if(obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  396. {
  397. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  398. stop = true;
  399. }
  400. else if(!isPositive()) //negative or indifferent
  401. {
  402. if((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  403. {
  404. tmp = ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  405. stop = true;
  406. }
  407. }
  408. });
  409. if(tmp != ESpellCastProblem::NOT_DECIDED)
  410. return tmp;
  411. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  412. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  413. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  414. {
  415. return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
  416. }
  417. return ESpellCastProblem::NOT_DECIDED;
  418. }
  419. ESpellCastProblem::ESpellCastProblem CSpell::isImmuneByStack(const ISpellCaster * caster, const CStack * obj) const
  420. {
  421. const auto immuneResult = mechanics->isImmuneByStack(caster,obj);
  422. if (ESpellCastProblem::NOT_DECIDED != immuneResult)
  423. return immuneResult;
  424. return ESpellCastProblem::OK;
  425. }
  426. void CSpell::prepareBattleLog(const CBattleInfoCallback * cb, const BattleSpellCast * packet, std::vector<std::string> & logLines) const
  427. {
  428. bool displayDamage = true;
  429. std::string casterName("Something"); //todo: localize
  430. if(packet->castByHero)
  431. casterName = cb->battleGetHeroInfo(packet->side).name;
  432. {
  433. const auto casterStackID = packet->casterStack;
  434. if(casterStackID > 0)
  435. {
  436. const CStack * casterStack = cb->battleGetStackByID(casterStackID);
  437. if(casterStack != nullptr)
  438. casterName = casterStack->type->namePl;
  439. }
  440. }
  441. if(packet->affectedCres.size() == 1)
  442. {
  443. const CStack * attackedStack = cb->battleGetStackByID(*packet->affectedCres.begin(), false);
  444. const std::string attackedNamePl = attackedStack->getCreature()->namePl;
  445. if(packet->castByHero)
  446. {
  447. const std::string fmt = VLC->generaltexth->allTexts[195];
  448. logLines.push_back(boost::to_string(boost::format(fmt) % casterName % this->name % attackedNamePl));
  449. }
  450. else
  451. {
  452. mechanics->battleLogSingleTarget(logLines, packet, casterName, attackedStack, displayDamage);
  453. }
  454. }
  455. else
  456. {
  457. boost::format text(VLC->generaltexth->allTexts[196]);
  458. text % casterName % this->name;
  459. logLines.push_back(text.str());
  460. }
  461. if(packet->dmgToDisplay > 0 && displayDamage)
  462. {
  463. boost::format dmgInfo(VLC->generaltexth->allTexts[376]);
  464. dmgInfo % this->name % packet->dmgToDisplay;
  465. logLines.push_back(dmgInfo.str());
  466. }
  467. }
  468. void CSpell::setIsOffensive(const bool val)
  469. {
  470. isOffensive = val;
  471. if(val)
  472. {
  473. positiveness = CSpell::NEGATIVE;
  474. isDamage = true;
  475. }
  476. }
  477. void CSpell::setIsRising(const bool val)
  478. {
  479. isRising = val;
  480. if(val)
  481. {
  482. positiveness = CSpell::POSITIVE;
  483. }
  484. }
  485. void CSpell::setup()
  486. {
  487. setupMechanics();
  488. }
  489. void CSpell::setupMechanics()
  490. {
  491. if(nullptr != mechanics)
  492. {
  493. logGlobal->errorStream() << "Spell " << this->name << ": mechanics already set";
  494. delete mechanics;
  495. }
  496. mechanics = ISpellMechanics::createMechanics(this);
  497. }
  498. ///CSpell::AnimationInfo
  499. CSpell::AnimationItem::AnimationItem()
  500. :resourceName(""),verticalPosition(VerticalPosition::TOP),pause(0)
  501. {
  502. }
  503. ///CSpell::AnimationInfo
  504. CSpell::AnimationInfo::AnimationInfo()
  505. {
  506. }
  507. CSpell::AnimationInfo::~AnimationInfo()
  508. {
  509. }
  510. std::string CSpell::AnimationInfo::selectProjectile(const double angle) const
  511. {
  512. std::string res;
  513. double maximum = 0.0;
  514. for(const auto & info : projectile)
  515. {
  516. if(info.minimumAngle < angle && info.minimumAngle > maximum)
  517. {
  518. maximum = info.minimumAngle;
  519. res = info.resourceName;
  520. }
  521. }
  522. return std::move(res);
  523. }
  524. ///CSpell::TargetInfo
  525. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level)
  526. {
  527. init(spell, level);
  528. }
  529. CSpell::TargetInfo::TargetInfo(const CSpell * spell, const int level, ECastingMode::ECastingMode mode)
  530. {
  531. init(spell, level);
  532. if(mode == ECastingMode::ENCHANTER_CASTING)
  533. {
  534. smart = true; //FIXME: not sure about that, this makes all spells smart in this mode
  535. massive = true;
  536. }
  537. else if(mode == ECastingMode::SPELL_LIKE_ATTACK)
  538. {
  539. alwaysHitDirectly = true;
  540. }
  541. }
  542. void CSpell::TargetInfo::init(const CSpell * spell, const int level)
  543. {
  544. auto & levelInfo = spell->getLevelInfo(level);
  545. type = spell->getTargetType();
  546. smart = levelInfo.smartTarget;
  547. massive = levelInfo.range == "X";
  548. onlyAlive = !spell->isRisingSpell();
  549. alwaysHitDirectly = false;
  550. clearAffected = levelInfo.clearAffected;
  551. clearTarget = levelInfo.clearTarget;
  552. }
  553. bool DLL_LINKAGE isInScreenRange(const int3 & center, const int3 & pos)
  554. {
  555. int3 diff = pos - center;
  556. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  557. return true;
  558. else
  559. return false;
  560. }
  561. ///CSpellHandler
  562. CSpellHandler::CSpellHandler()
  563. {
  564. }
  565. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  566. {
  567. using namespace SpellConfig;
  568. std::vector<JsonNode> legacyData;
  569. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  570. auto readSchool = [&](JsonMap & schools, const std::string & name)
  571. {
  572. if (parser.readString() == "x")
  573. {
  574. schools[name].Bool() = true;
  575. }
  576. };
  577. auto read = [&,this](bool combat, bool ability)
  578. {
  579. do
  580. {
  581. JsonNode lineNode(JsonNode::DATA_STRUCT);
  582. const si32 id = legacyData.size();
  583. lineNode["index"].Float() = id;
  584. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  585. lineNode["name"].String() = parser.readString();
  586. parser.readString(); //ignored unused abbreviated name
  587. lineNode["level"].Float() = parser.readNumber();
  588. auto& schools = lineNode["school"].Struct();
  589. readSchool(schools, "earth");
  590. readSchool(schools, "water");
  591. readSchool(schools, "fire");
  592. readSchool(schools, "air");
  593. auto& levels = lineNode["levels"].Struct();
  594. auto getLevel = [&](const size_t idx)->JsonMap&
  595. {
  596. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  597. return levels[LEVEL_NAMES[idx]].Struct();
  598. };
  599. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  600. lineNode["power"].Float() = parser.readNumber();
  601. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  602. auto& chances = lineNode["gainChance"].Struct();
  603. for(size_t i = 0; i < GameConstants::F_NUMBER; i++){
  604. chances[ETownType::names[i]].Float() = parser.readNumber();
  605. }
  606. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  607. std::vector<std::string> descriptions;
  608. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  609. descriptions.push_back(parser.readString());
  610. parser.readString(); //ignore attributes. All data present in JSON
  611. //save parsed level specific data
  612. for(size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  613. {
  614. auto& level = getLevel(i);
  615. level["description"].String() = descriptions[i];
  616. level["cost"].Float() = costs[i];
  617. level["power"].Float() = powers[i];
  618. level["aiValue"].Float() = AIVals[i];
  619. }
  620. legacyData.push_back(lineNode);
  621. }
  622. while (parser.endLine() && !parser.isNextEntryEmpty());
  623. };
  624. auto skip = [&](int cnt)
  625. {
  626. for(int i=0; i<cnt; i++)
  627. parser.endLine();
  628. };
  629. skip(5);// header
  630. read(false,false); //read adventure map spells
  631. skip(3);
  632. read(true,false); //read battle spells
  633. skip(3);
  634. read(true,true);//read creature abilities
  635. //TODO: maybe move to config
  636. //clone Acid Breath attributes for Acid Breath damage effect
  637. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  638. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  639. legacyData.push_back(temp);
  640. objects.resize(legacyData.size());
  641. return legacyData;
  642. }
  643. const std::string CSpellHandler::getTypeName() const
  644. {
  645. return "spell";
  646. }
  647. CSpell * CSpellHandler::loadFromJson(const JsonNode & json)
  648. {
  649. using namespace SpellConfig;
  650. CSpell * spell = new CSpell();
  651. const auto type = json["type"].String();
  652. if(type == "ability")
  653. {
  654. spell->creatureAbility = true;
  655. spell->combatSpell = true;
  656. }
  657. else
  658. {
  659. spell->creatureAbility = false;
  660. spell->combatSpell = type == "combat";
  661. }
  662. spell->name = json["name"].String();
  663. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  664. const auto schoolNames = json["school"];
  665. for(const SpellSchoolInfo & info : SpellConfig::SCHOOL)
  666. {
  667. spell->school[info.id] = schoolNames[info.jsonName].Bool();
  668. }
  669. spell->level = json["level"].Float();
  670. spell->power = json["power"].Float();
  671. spell->defaultProbability = json["defaultGainChance"].Float();
  672. for(const auto & node : json["gainChance"].Struct())
  673. {
  674. const int chance = node.second.Float();
  675. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  676. {
  677. spell->probabilities[factionID] = chance;
  678. });
  679. }
  680. auto targetType = json["targetType"].String();
  681. if(targetType == "NO_TARGET")
  682. spell->targetType = CSpell::NO_TARGET;
  683. else if(targetType == "CREATURE")
  684. spell->targetType = CSpell::CREATURE;
  685. else if(targetType == "OBSTACLE")
  686. spell->targetType = CSpell::OBSTACLE;
  687. else if(targetType == "LOCATION")
  688. spell->targetType = CSpell::LOCATION;
  689. else
  690. logGlobal->warnStream() << "Spell " << spell->name << ": target type " << (targetType.empty() ? "empty" : "unknown ("+targetType+")") << ", assumed NO_TARGET.";
  691. for(const auto & counteredSpell: json["counters"].Struct())
  692. if (counteredSpell.second.Bool())
  693. {
  694. VLC->modh->identifiers.requestIdentifier(json.meta, counteredSpell.first, [=](si32 id)
  695. {
  696. spell->counteredSpells.push_back(SpellID(id));
  697. });
  698. }
  699. //TODO: more error checking - f.e. conflicting flags
  700. const auto flags = json["flags"];
  701. //by default all flags are set to false in constructor
  702. spell->isDamage = flags["damage"].Bool(); //do this before "offensive"
  703. if(flags["offensive"].Bool())
  704. {
  705. spell->setIsOffensive(true);
  706. }
  707. if(flags["rising"].Bool())
  708. {
  709. spell->setIsRising(true);
  710. }
  711. const bool implicitPositiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  712. if(flags["indifferent"].Bool())
  713. {
  714. spell->positiveness = CSpell::NEUTRAL;
  715. }
  716. else if(flags["negative"].Bool())
  717. {
  718. spell->positiveness = CSpell::NEGATIVE;
  719. }
  720. else if(flags["positive"].Bool())
  721. {
  722. spell->positiveness = CSpell::POSITIVE;
  723. }
  724. else if(!implicitPositiveness)
  725. {
  726. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  727. logGlobal->errorStream() << "Spell " << spell->name << ": no positiveness specified, assumed NEUTRAL.";
  728. }
  729. spell->isSpecial = flags["special"].Bool();
  730. auto findBonus = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  731. {
  732. auto it = bonusNameMap.find(name);
  733. if(it == bonusNameMap.end())
  734. {
  735. logGlobal->errorStream() << "Spell " << spell->name << ": invalid bonus name " << name;
  736. }
  737. else
  738. {
  739. vec.push_back((Bonus::BonusType)it->second);
  740. }
  741. };
  742. auto readBonusStruct = [&](std::string name, std::vector<Bonus::BonusType> & vec)
  743. {
  744. for(auto bonusData: json[name].Struct())
  745. {
  746. const std::string bonusId = bonusData.first;
  747. const bool flag = bonusData.second.Bool();
  748. if(flag)
  749. findBonus(bonusId, vec);
  750. }
  751. };
  752. readBonusStruct("immunity", spell->immunities);
  753. readBonusStruct("absoluteImmunity", spell->absoluteImmunities);
  754. readBonusStruct("limit", spell->limiters);
  755. readBonusStruct("absoluteLimit", spell->absoluteLimiters);
  756. const JsonNode & graphicsNode = json["graphics"];
  757. spell->iconImmune = graphicsNode["iconImmune"].String();
  758. spell->iconBook = graphicsNode["iconBook"].String();
  759. spell->iconEffect = graphicsNode["iconEffect"].String();
  760. spell->iconScenarioBonus = graphicsNode["iconScenarioBonus"].String();
  761. spell->iconScroll = graphicsNode["iconScroll"].String();
  762. const JsonNode & animationNode = json["animation"];
  763. auto loadAnimationQueue = [&](const std::string & jsonName, CSpell::TAnimationQueue & q)
  764. {
  765. auto queueNode = animationNode[jsonName].Vector();
  766. for(const JsonNode & item : queueNode)
  767. {
  768. CSpell::TAnimation newItem;
  769. if(item.getType() == JsonNode::DATA_STRING)
  770. newItem.resourceName = item.String();
  771. else if(item.getType() == JsonNode::DATA_STRUCT)
  772. {
  773. newItem.resourceName = item["defName"].String();
  774. auto vPosStr = item["verticalPosition"].String();
  775. if("bottom" == vPosStr)
  776. newItem.verticalPosition = VerticalPosition::BOTTOM;
  777. }
  778. else if(item.getType() == JsonNode::DATA_FLOAT)
  779. {
  780. newItem.pause = item.Float();
  781. }
  782. q.push_back(newItem);
  783. }
  784. };
  785. loadAnimationQueue("affect", spell->animationInfo.affect);
  786. loadAnimationQueue("cast", spell->animationInfo.cast);
  787. loadAnimationQueue("hit", spell->animationInfo.hit);
  788. const JsonVector & projectile = animationNode["projectile"].Vector();
  789. for(const JsonNode & item : projectile)
  790. {
  791. CSpell::ProjectileInfo info;
  792. info.resourceName = item["defName"].String();
  793. info.minimumAngle = item["minimumAngle"].Float();
  794. spell->animationInfo.projectile.push_back(info);
  795. }
  796. const JsonNode & soundsNode = json["sounds"];
  797. spell->castSound = soundsNode["cast"].String();
  798. //load level attributes
  799. const int levelsCount = GameConstants::SPELL_SCHOOL_LEVELS;
  800. for(int levelIndex = 0; levelIndex < levelsCount; levelIndex++)
  801. {
  802. const JsonNode & levelNode = json["levels"][LEVEL_NAMES[levelIndex]];
  803. CSpell::LevelInfo & levelObject = spell->levels[levelIndex];
  804. const si32 levelPower = levelObject.power = levelNode["power"].Float();
  805. levelObject.description = levelNode["description"].String();
  806. levelObject.cost = levelNode["cost"].Float();
  807. levelObject.AIValue = levelNode["aiValue"].Float();
  808. levelObject.smartTarget = levelNode["targetModifier"]["smart"].Bool();
  809. levelObject.clearTarget = levelNode["targetModifier"]["clearTarget"].Bool();
  810. levelObject.clearAffected = levelNode["targetModifier"]["clearAffected"].Bool();
  811. levelObject.range = levelNode["range"].String();
  812. for(const auto & elem : levelNode["effects"].Struct())
  813. {
  814. const JsonNode & bonusNode = elem.second;
  815. Bonus * b = JsonUtils::parseBonus(bonusNode);
  816. const bool usePowerAsValue = bonusNode["val"].isNull();
  817. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  818. //b->sid = spell->id; //for all
  819. b->source = Bonus::SPELL_EFFECT;//for all
  820. if(usePowerAsValue)
  821. b->val = levelPower;
  822. levelObject.effectsTmp.push_back(b);
  823. }
  824. }
  825. return spell;
  826. }
  827. void CSpellHandler::afterLoadFinalization()
  828. {
  829. //FIXME: it is a bad place for this code, should refactor loadFromJson to know object id during loading
  830. for(auto spell: objects)
  831. {
  832. for(auto & level: spell->levels)
  833. {
  834. for(Bonus * bonus : level.effectsTmp)
  835. {
  836. level.effects.push_back(*bonus);
  837. delete bonus;
  838. }
  839. level.effectsTmp.clear();
  840. for(auto & bonus: level.effects)
  841. bonus.sid = spell->id;
  842. }
  843. spell->setup();
  844. }
  845. }
  846. void CSpellHandler::beforeValidate(JsonNode & object)
  847. {
  848. //handle "base" level info
  849. JsonNode & levels = object["levels"];
  850. JsonNode & base = levels["base"];
  851. auto inheritNode = [&](const std::string & name){
  852. JsonUtils::inherit(levels[name],base);
  853. };
  854. inheritNode("none");
  855. inheritNode("basic");
  856. inheritNode("advanced");
  857. inheritNode("expert");
  858. }
  859. CSpellHandler::~CSpellHandler()
  860. {
  861. }
  862. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  863. {
  864. std::vector<bool> allowedSpells;
  865. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  866. return allowedSpells;
  867. }