CSpellHandler.cpp 27 KB

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