CSpellHandler.cpp 26 KB

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