CSpellHandler.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. /*
  11. * CSpellHandler.cpp, part of VCMI engine
  12. *
  13. * Authors: listed in file AUTHORS in main folder
  14. *
  15. * License: GNU General Public License v2.0 or later
  16. * Full text of license available in license.txt file, in main folder
  17. *
  18. */
  19. namespace SpellConfigJson
  20. {
  21. static const std::string level_names[] = {"none","basic","advanced","expert"};
  22. }
  23. using namespace boost::assign;
  24. namespace SRSLPraserHelpers
  25. {
  26. static int XYToHex(int x, int y)
  27. {
  28. return x + 17 * y;
  29. }
  30. static int XYToHex(std::pair<int, int> xy)
  31. {
  32. return XYToHex(xy.first, xy.second);
  33. }
  34. static int hexToY(int battleFieldPosition)
  35. {
  36. return battleFieldPosition/17;
  37. }
  38. static int hexToX(int battleFieldPosition)
  39. {
  40. int pos = battleFieldPosition - hexToY(battleFieldPosition) * 17;
  41. return pos;
  42. }
  43. static std::pair<int, int> hexToPair(int battleFieldPosition)
  44. {
  45. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  46. }
  47. //moves hex by one hex in given direction
  48. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  49. static std::pair<int, int> gotoDir(int x, int y, int direction)
  50. {
  51. switch(direction)
  52. {
  53. case 0: //top left
  54. return std::make_pair((y%2) ? x-1 : x, y-1);
  55. case 1: //top right
  56. return std::make_pair((y%2) ? x : x+1, y-1);
  57. case 2: //right
  58. return std::make_pair(x+1, y);
  59. case 3: //right bottom
  60. return std::make_pair((y%2) ? x : x+1, y+1);
  61. case 4: //left bottom
  62. return std::make_pair((y%2) ? x-1 : x, y+1);
  63. case 5: //left
  64. return std::make_pair(x-1, y);
  65. default:
  66. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  67. }
  68. }
  69. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  70. {
  71. return gotoDir(xy.first, xy.second, direction);
  72. }
  73. static bool isGoodHex(std::pair<int, int> xy)
  74. {
  75. return xy.first >=0 && xy.first < 17 && xy.second >= 0 && xy.second < 11;
  76. }
  77. //helper function for std::set<ui16> CSpell::rangeInHexes(unsigned int centralHex, ui8 schoolLvl ) const
  78. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  79. {
  80. std::set<ui16> ret;
  81. if(low == 0)
  82. {
  83. ret.insert(center);
  84. }
  85. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  86. for(auto & elem : mainPointForLayer)
  87. elem = hexToPair(center);
  88. for(int it=1; it<=high; ++it) //it - distance to the center
  89. {
  90. for(int b=0; b<6; ++b)
  91. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  92. if(it>=low)
  93. {
  94. std::pair<int, int> curHex;
  95. //adding lines (A-b, B-c, C-d, etc)
  96. for(int v=0; v<6; ++v)
  97. {
  98. curHex = mainPointForLayer[v];
  99. for(int h=0; h<it; ++h)
  100. {
  101. if(isGoodHex(curHex))
  102. ret.insert(XYToHex(curHex));
  103. curHex = gotoDir(curHex, (v+2)%6);
  104. }
  105. }
  106. } //if(it>=low)
  107. }
  108. return ret;
  109. }
  110. }
  111. using namespace SRSLPraserHelpers;
  112. CSpell::CSpell():
  113. id(SpellID::NONE), level(0),
  114. earth(false),water(false),fire(false),air(false),
  115. power(0),
  116. combatSpell(false),creatureAbility(false),
  117. positiveness(ESpellPositiveness::NEUTRAL),
  118. mainEffectAnim(-1),
  119. defaultProbability(0),
  120. isRising(false),isDamage(false),isOffensive(false),targetType(ETargetType::NO_TARGET)
  121. {
  122. }
  123. CSpell::~CSpell()
  124. {
  125. for (auto & elem : effects)
  126. {
  127. for (size_t j=0; j<elem.size(); j++)
  128. delete elem[j];
  129. }
  130. }
  131. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  132. {
  133. std::vector<BattleHex> ret;
  134. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  135. {
  136. //Special case - shape of obstacle depends on caster's side
  137. //TODO make it possible through spell_info config
  138. BattleHex::EDir firstStep, secondStep;
  139. if(side)
  140. {
  141. firstStep = BattleHex::TOP_LEFT;
  142. secondStep = BattleHex::TOP_RIGHT;
  143. }
  144. else
  145. {
  146. firstStep = BattleHex::TOP_RIGHT;
  147. secondStep = BattleHex::TOP_LEFT;
  148. }
  149. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  150. auto addIfValid = [&](BattleHex hex)
  151. {
  152. if(hex.isValid())
  153. ret.push_back(hex);
  154. else if(outDroppedHexes)
  155. *outDroppedHexes = true;
  156. };
  157. ret.push_back(centralHex);
  158. addIfValid(centralHex.moveInDir(firstStep, false));
  159. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  160. addIfValid(centralHex.moveInDir(secondStep, false)); //moveInDir function modifies subject hex
  161. return ret;
  162. }
  163. std::string rng = range[schoolLvl] + ','; //copy + artificial comma for easier handling
  164. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  165. {
  166. std::string number1, number2;
  167. int beg, end;
  168. bool readingFirst = true;
  169. for(auto & elem : rng)
  170. {
  171. if( std::isdigit(elem) ) //reading numer
  172. {
  173. if(readingFirst)
  174. number1 += elem;
  175. else
  176. number2 += elem;
  177. }
  178. else if(elem == ',') //comma
  179. {
  180. //calculating variables
  181. if(readingFirst)
  182. {
  183. beg = atoi(number1.c_str());
  184. number1 = "";
  185. }
  186. else
  187. {
  188. end = atoi(number2.c_str());
  189. number2 = "";
  190. }
  191. //obtaining new hexes
  192. std::set<ui16> curLayer;
  193. if(readingFirst)
  194. {
  195. curLayer = getInRange(centralHex, beg, beg);
  196. }
  197. else
  198. {
  199. curLayer = getInRange(centralHex, beg, end);
  200. readingFirst = true;
  201. }
  202. //adding abtained hexes
  203. for(auto & curLayer_it : curLayer)
  204. {
  205. ret.push_back(curLayer_it);
  206. }
  207. }
  208. else if(elem == '-') //dash
  209. {
  210. beg = atoi(number1.c_str());
  211. number1 = "";
  212. readingFirst = false;
  213. }
  214. }
  215. }
  216. //remove duplicates (TODO check if actually needed)
  217. range::unique(ret);
  218. return ret;
  219. }
  220. CSpell::ETargetType CSpell::getTargetType() const
  221. {
  222. return targetType;
  223. }
  224. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  225. {
  226. if (level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  227. {
  228. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  229. return;
  230. }
  231. if (effects.empty())
  232. {
  233. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no bonus effects! " << name;
  234. return;
  235. }
  236. if (effects.size() <= level)
  237. {
  238. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") is missing entry for level " << level;
  239. return;
  240. }
  241. if (effects[level].empty())
  242. {
  243. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no effects for level " << level;
  244. return;
  245. }
  246. lst.reserve(lst.size() + effects[level].size());
  247. for (Bonus *b : effects[level])
  248. {
  249. lst.push_back(Bonus(*b));
  250. }
  251. }
  252. bool CSpell::isImmuneBy(const IBonusBearer* obj) const
  253. {
  254. //todo: use new bonus API
  255. //1. Check limiters
  256. for(auto b : limiters)
  257. {
  258. if (!obj->hasBonusOfType(b))
  259. return true;
  260. }
  261. //2. Check absolute immunities
  262. //todo: check config: some creatures are unaffected always, for example undead to resurrection.
  263. for(auto b : absoluteImmunities)
  264. {
  265. if (obj->hasBonusOfType(b))
  266. return true;
  267. }
  268. //3. Check negation
  269. if (obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES)) //Orb of vulnerability
  270. return false;
  271. //4. Check negatable immunities
  272. for(auto b : immunities)
  273. {
  274. if (obj->hasBonusOfType(b))
  275. return true;
  276. }
  277. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  278. {
  279. if (obj->hasBonusOfType(element, 0)) //always resist if immune to all spells altogether
  280. return true;
  281. else if (!isPositive()) //negative or indifferent
  282. {
  283. if ((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  284. return true;
  285. }
  286. return false;
  287. };
  288. //4. Check elemental immunities
  289. if (fire)
  290. {
  291. if (battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  292. return true;
  293. }
  294. if (water)
  295. {
  296. if (battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  297. return true;
  298. }
  299. if (earth)
  300. {
  301. if (battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  302. return true;
  303. }
  304. if (air)
  305. {
  306. if (battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  307. return true;
  308. }
  309. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  310. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  311. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  312. {
  313. return true;
  314. }
  315. return false;
  316. }
  317. void CSpell::setAttributes(const std::string& newValue)
  318. {
  319. attributes = newValue;
  320. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  321. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  322. targetType = CREATURE_EXPERT_MASSIVE;
  323. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  324. targetType = CREATURE;
  325. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  326. targetType = OBSTACLE;
  327. else
  328. targetType = NO_TARGET;
  329. }
  330. void CSpell::setIsOffensive(const bool val)
  331. {
  332. isOffensive = val;
  333. if (val)
  334. {
  335. positiveness = CSpell::NEGATIVE;
  336. isDamage = true;
  337. }
  338. }
  339. void CSpell::setIsRising(const bool val)
  340. {
  341. isRising = val;
  342. if (val)
  343. {
  344. positiveness = CSpell::POSITIVE;
  345. }
  346. }
  347. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  348. {
  349. int3 diff = pos - center;
  350. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  351. return true;
  352. else
  353. return false;
  354. }
  355. CSpellHandler::CSpellHandler()
  356. {
  357. }
  358. std::vector<JsonNode> CSpellHandler::loadLegacyData(size_t dataSize)
  359. {
  360. using namespace SpellConfigJson;
  361. std::vector<JsonNode> legacyData;
  362. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  363. auto readSchool = [&](JsonMap& schools, const std::string& name)
  364. {
  365. if (parser.readString() == "x")
  366. {
  367. schools[name].Bool() = true;
  368. }
  369. };
  370. auto read = [&,this](bool combat, bool ability)
  371. {
  372. do
  373. {
  374. JsonNode lineNode(JsonNode::DATA_STRUCT);
  375. const si32 id = legacyData.size();
  376. lineNode["index"].Float() = id;
  377. lineNode["type"].String() = ability ? "ability" : (combat ? "combat" : "adventure");
  378. lineNode["name"].String() = parser.readString();
  379. parser.readString(); //ignored unused abbreviated name
  380. lineNode["level"].Float() = parser.readNumber();
  381. auto& schools = lineNode["school"].Struct();
  382. readSchool(schools, "earth");
  383. readSchool(schools, "water");
  384. readSchool(schools, "fire");
  385. readSchool(schools, "air");
  386. auto& levels = lineNode["levels"].Struct();
  387. auto getLevel = [&](const size_t idx)->JsonMap&
  388. {
  389. assert(idx < GameConstants::SPELL_SCHOOL_LEVELS);
  390. return levels[level_names[idx]].Struct();
  391. };
  392. auto costs = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  393. lineNode["power"].Float() = parser.readNumber();
  394. auto powers = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  395. auto& chances = lineNode["gainChance"].Struct();
  396. for (size_t i = 0; i < GameConstants::F_NUMBER ; i++){
  397. chances[ETownType::names[i]].Float() = parser.readNumber();
  398. }
  399. auto AIVals = parser.readNumArray<si32>(GameConstants::SPELL_SCHOOL_LEVELS);
  400. std::vector<std::string> descriptions;
  401. for (size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS ; i++)
  402. descriptions.push_back(parser.readString());
  403. std::string attributes = parser.readString();
  404. std::string targetType = "NO_TARGET";
  405. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  406. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  407. targetType = "CREATURE_EXPERT_MASSIVE";
  408. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  409. targetType = "CREATURE";
  410. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  411. targetType = "OBSTACLE";
  412. lineNode["targetType"].String() = targetType;
  413. //save parsed level specific data
  414. for (size_t i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  415. {
  416. auto& level = getLevel(i);
  417. level["description"].String() = descriptions[i];
  418. level["cost"].Float() = costs[i];
  419. level["power"].Float() = powers[i];
  420. level["aiValue"].Float() = AIVals[i];
  421. }
  422. // logGlobal->errorStream() << lineNode;
  423. legacyData.push_back(lineNode);
  424. }
  425. while (parser.endLine() && !parser.isNextEntryEmpty());
  426. };
  427. auto skip = [&](int cnt)
  428. {
  429. for(int i=0; i<cnt; i++)
  430. parser.endLine();
  431. };
  432. skip(5);// header
  433. read(false,false); //read adventure map spells
  434. skip(3);
  435. read(true,false); //read battle spells
  436. skip(3);
  437. read(true,true);//read creature abilities
  438. //TODO: maybe move to config
  439. //clone Acid Breath attributes for Acid Breath damage effect
  440. JsonNode temp = legacyData[SpellID::ACID_BREATH_DEFENSE];
  441. temp["index"].Float() = SpellID::ACID_BREATH_DAMAGE;
  442. legacyData.push_back(temp);
  443. objects.resize(legacyData.size());
  444. return legacyData;
  445. }
  446. const std::string CSpellHandler::getTypeName() const
  447. {
  448. return "spell";
  449. }
  450. static void fatalConfigurationError()
  451. {
  452. throw std::runtime_error("SpellHandler: Fatal configuration error, See log for details");
  453. }
  454. CSpell * CSpellHandler::loadFromJson(const JsonNode& json)
  455. {
  456. using namespace SpellConfigJson;
  457. CSpell * spell = new CSpell();
  458. const auto type_str = json["type"].String();
  459. if (type_str == "ability")
  460. {
  461. spell->creatureAbility = true;
  462. spell->combatSpell = true;
  463. }
  464. else
  465. {
  466. spell->creatureAbility = false;
  467. spell->combatSpell = type_str == "combat";
  468. }
  469. spell->name = json["name"].String();
  470. logGlobal->traceStream() << __FUNCTION__ << ": loading spell " << spell->name;
  471. auto readFlag = [](const JsonNode& flagsNode, const std::string& name)
  472. {
  473. if (flagsNode.getType() != JsonNode::DATA_STRUCT)
  474. {
  475. logGlobal->errorStream() << "Flags node shall be object";
  476. return false;
  477. }
  478. const JsonNode& flag = flagsNode[name];
  479. if (flag.isNull())
  480. {
  481. return false;
  482. }
  483. else if (flag.getType() == JsonNode::DATA_BOOL)
  484. {
  485. return flag.Bool();
  486. }
  487. else
  488. {
  489. logGlobal->errorStream() << "Flag shall be boolean: "<<name;
  490. return false;
  491. }
  492. };
  493. const auto school_names = json["school"];
  494. spell->air = readFlag(school_names, "air");
  495. spell->earth = readFlag(school_names, "earth");
  496. spell->fire = readFlag(school_names, "fire");
  497. spell->water = readFlag(school_names, "water");
  498. spell->level = json["level"].Float();
  499. spell->power = json["power"].Float();
  500. //TODO: default chance
  501. spell->defaultProbability = json["defaultGainChance"].Float();
  502. auto chances = json["gainChance"].Struct();
  503. for(auto &node : chances)
  504. {
  505. int chance = node.second.Float();
  506. VLC->modh->identifiers.requestIdentifier(node.second.meta, "faction",node.first, [=](si32 factionID)
  507. {
  508. spell->probabilities[factionID] = chance;
  509. });
  510. }
  511. auto target_type_str = json["targetType"].String();
  512. if (target_type_str == "NO_TARGET")
  513. spell->targetType = CSpell::NO_TARGET;
  514. else if (target_type_str == "CREATURE")
  515. spell->targetType = CSpell::CREATURE;
  516. else if (target_type_str == "OBSTACLE")
  517. spell->targetType = CSpell::OBSTACLE;
  518. else if (target_type_str == "CREATURE_EXPERT_MASSIVE")
  519. spell->targetType = CSpell::CREATURE_EXPERT_MASSIVE;
  520. else
  521. {
  522. logGlobal->errorStream() << spell->name << ": invalid target type '" <<target_type_str<<"'";
  523. fatalConfigurationError();
  524. }
  525. spell->mainEffectAnim = json["anim"].Float();
  526. for(const auto& k_v: json["counters"].Struct())
  527. {
  528. if (k_v.second.Bool())
  529. {
  530. JsonNode tmp(JsonNode::DATA_STRING);
  531. tmp.meta = json.meta;
  532. tmp.String() = k_v.first;
  533. VLC->modh->identifiers.requestIdentifier(tmp,[=](si32 id){
  534. spell->counteredSpells.push_back(SpellID(id));
  535. });
  536. }
  537. }
  538. //TODO: more error checking - f.e. conflicting flags
  539. const auto flags = json["flags"];
  540. //by default all flags are set to false in constructor
  541. if (readFlag(flags,"summoning"))
  542. {
  543. logGlobal->warnStream() << spell->name << ": summoning flag in unimplemented";
  544. }
  545. spell->isDamage = readFlag(flags,"damage"); //do this before "offensive"
  546. if (readFlag(flags,"offensive"))
  547. {
  548. spell->setIsOffensive(true);
  549. }
  550. if (readFlag(flags,"rising"))
  551. {
  552. spell->setIsRising(true);
  553. }
  554. const bool implicit_positiveness = spell->isOffensive || spell->isRising; //(!) "damage" does not mean NEGATIVE --AVS
  555. if (readFlag(flags,"indifferent"))
  556. {
  557. spell->positiveness = CSpell::NEUTRAL;
  558. }
  559. else if (readFlag(flags,"negative"))
  560. {
  561. spell->positiveness = CSpell::NEGATIVE;
  562. }
  563. else if (readFlag(flags,"positive"))
  564. {
  565. spell->positiveness = CSpell::POSITIVE;
  566. }
  567. else if(!implicit_positiveness)
  568. {
  569. spell->positiveness = CSpell::NEUTRAL; //duplicates constructor but, just in case
  570. logGlobal->errorStream() << "No positiveness specified, assumed NEUTRAL";
  571. }
  572. spell->isSpecial = readFlag(flags,"special");
  573. auto find_in_map = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  574. {
  575. auto it = bonusNameMap.find(name);
  576. if (it == bonusNameMap.end())
  577. {
  578. logGlobal->errorStream() << spell->name << ": invalid bonus name" << name;
  579. }
  580. else
  581. {
  582. vec.push_back((Bonus::BonusType)it->second);
  583. }
  584. };
  585. auto read_node = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  586. {
  587. const JsonNode & node = json[name];
  588. if (!node.isNull())
  589. {
  590. for (auto key_value: node.Struct())
  591. {
  592. const std::string bonus_id = key_value.first;
  593. const bool flag = key_value.second.Bool();
  594. if (flag)
  595. {
  596. find_in_map(bonus_id, vec);
  597. }
  598. }
  599. }
  600. };
  601. read_node("immunity",spell->immunities);
  602. read_node("absoluteImmunity", spell->absoluteImmunities);
  603. read_node("limit",spell->limiters);
  604. const JsonNode & graphicsNode = json["graphics"];
  605. if (!graphicsNode.isNull())
  606. {
  607. spell->iconImmune = graphicsNode["iconImmune"].String();
  608. }
  609. //load level attributes
  610. const int level_count = GameConstants::SPELL_SCHOOL_LEVELS;
  611. spell->AIVals.resize(level_count);
  612. spell->costs.resize(level_count);
  613. spell->descriptions.resize(level_count);
  614. spell->powers.resize(level_count);
  615. spell->range.resize(level_count);
  616. const JsonNode & levels_node = json["levels"];
  617. if (levels_node.isNull())
  618. {
  619. logGlobal->errorStream() << spell->name << ": no level specific data";
  620. fatalConfigurationError();
  621. }
  622. if (levels_node.getType()!=JsonNode::DATA_STRUCT)
  623. {
  624. logGlobal->errorStream() << spell->name << ": level specific data shall be JSON object";
  625. fatalConfigurationError();
  626. }
  627. const JsonMap & levels = json["levels"].Struct();
  628. for(int level_idx = 0; level_idx < level_count; level_idx++)
  629. {
  630. const auto& level_node = levels.at(level_names[level_idx]);
  631. if (level_node.getType()!=JsonNode::DATA_STRUCT)
  632. {
  633. logGlobal->errorStream() << spell->name << ": level specific data shall be JSON object";
  634. fatalConfigurationError();
  635. }
  636. auto ensure_field = [&](const std::string json_name,JsonNode::JsonType type)->JsonNode
  637. {
  638. const auto& node = level_node[json_name];
  639. if (node.isNull())
  640. {
  641. logGlobal->errorStream() << spell->name << ": mandatory field "<<json_name<<" missing";
  642. fatalConfigurationError();
  643. }
  644. if (node.getType()!=type)
  645. {
  646. logGlobal->errorStream() << spell->name << ": field "<<json_name<<" - type mismatch";
  647. fatalConfigurationError();
  648. }
  649. return node;
  650. };
  651. auto get_string_mandatory = [&](const std::string json_name, std::vector<std::string>& target)
  652. {
  653. const auto& node = ensure_field(json_name, JsonNode::DATA_STRING);
  654. target[level_idx] = node.String();
  655. };
  656. auto get_string = [&](const std::string json_name, std::vector<std::string>& target)
  657. {
  658. const auto& node = level_node[json_name];
  659. if (node.getType() == JsonNode::DATA_STRING)
  660. {
  661. target[level_idx] = node.String();
  662. }
  663. };
  664. auto get_nomber = [&](const std::string json_name, std::vector<si32>& target)
  665. {
  666. const auto& node = level_node[json_name];
  667. if (node.getType() == JsonNode::DATA_FLOAT)
  668. {
  669. target[level_idx] = node.Float();
  670. }
  671. };
  672. auto get_nomber_mandatory = [&](const std::string json_name, std::vector<si32>& target)
  673. {
  674. const auto& node = ensure_field(json_name, JsonNode::DATA_FLOAT);
  675. target[level_idx] = node.Float();
  676. };
  677. if (spell->isCreatureAbility())
  678. {
  679. get_string("description", spell->descriptions);
  680. get_nomber("cost", spell->costs);
  681. get_nomber("power", spell->powers);
  682. get_nomber("aiValue", spell->AIVals);
  683. }
  684. else
  685. {
  686. get_string_mandatory("description", spell->descriptions);
  687. get_nomber_mandatory("cost", spell->costs);
  688. get_nomber_mandatory("power", spell->powers);
  689. get_nomber_mandatory("aiValue", spell->AIVals);
  690. }
  691. const JsonNode& effects_node = level_node["effects"];
  692. if (!effects_node.isNull())
  693. {
  694. if (spell->effects.empty())
  695. spell->effects.resize(level_count);
  696. for (const auto& elem : effects_node.Struct())
  697. {
  698. const JsonNode& bonus_node = elem.second;
  699. Bonus * b = JsonUtils::parseBonus(bonus_node);
  700. const bool usePowerAsValue = bonus_node["val"].isNull();
  701. //TODO: make this work. see CSpellHandler::afterLoadFinalization()
  702. //b->sid = spell->id; //for all
  703. b->source = Bonus::SPELL_EFFECT;//for all
  704. if (usePowerAsValue)
  705. {
  706. b->val = spell->powers[level_idx];
  707. }
  708. spell->effects[level_idx].push_back(b);
  709. }
  710. }
  711. }
  712. return spell;
  713. }
  714. void CSpellHandler::afterLoadFinalization()
  715. {
  716. //FIXME: this a bad place for this code, should refactor loadFromJson to know object id during load
  717. for (auto spell: objects)
  718. for (auto & level: spell->effects)
  719. for (auto * bonus: level)
  720. bonus->sid = spell->id;
  721. }
  722. CSpellHandler::~CSpellHandler()
  723. {
  724. }
  725. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  726. {
  727. std::vector<bool> allowedSpells;
  728. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  729. return allowedSpells;
  730. }