CSpellHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. #include "StdInc.h"
  2. #include "CSpellHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/CResourceLoader.h"
  5. #include "VCMI_Lib.h"
  6. #include "JsonNode.h"
  7. #include <cctype>
  8. #include "BattleHex.h"
  9. #include "CModHandler.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. using namespace boost::assign;
  20. namespace SRSLPraserHelpers
  21. {
  22. static int XYToHex(int x, int y)
  23. {
  24. return x + 17 * y;
  25. }
  26. static int XYToHex(std::pair<int, int> xy)
  27. {
  28. return XYToHex(xy.first, xy.second);
  29. }
  30. static int hexToY(int battleFieldPosition)
  31. {
  32. return battleFieldPosition/17;
  33. }
  34. static int hexToX(int battleFieldPosition)
  35. {
  36. int pos = battleFieldPosition - hexToY(battleFieldPosition) * 17;
  37. return pos;
  38. }
  39. static std::pair<int, int> hexToPair(int battleFieldPosition)
  40. {
  41. return std::make_pair(hexToX(battleFieldPosition), hexToY(battleFieldPosition));
  42. }
  43. //moves hex by one hex in given direction
  44. //0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left
  45. static std::pair<int, int> gotoDir(int x, int y, int direction)
  46. {
  47. switch(direction)
  48. {
  49. case 0: //top left
  50. return std::make_pair((y%2) ? x-1 : x, y-1);
  51. case 1: //top right
  52. return std::make_pair((y%2) ? x : x+1, y-1);
  53. case 2: //right
  54. return std::make_pair(x+1, y);
  55. case 3: //right bottom
  56. return std::make_pair((y%2) ? x : x+1, y+1);
  57. case 4: //left bottom
  58. return std::make_pair((y%2) ? x-1 : x, y+1);
  59. case 5: //left
  60. return std::make_pair(x-1, y);
  61. default:
  62. throw std::runtime_error("Disaster: wrong direction in SRSLPraserHelpers::gotoDir!\n");
  63. }
  64. }
  65. static std::pair<int, int> gotoDir(std::pair<int, int> xy, int direction)
  66. {
  67. return gotoDir(xy.first, xy.second, direction);
  68. }
  69. static bool isGoodHex(std::pair<int, int> xy)
  70. {
  71. return xy.first >=0 && xy.first < 17 && xy.second >= 0 && xy.second < 11;
  72. }
  73. //helper function for std::set<ui16> CSpell::rangeInHexes(unsigned int centralHex, ui8 schoolLvl ) const
  74. static std::set<ui16> getInRange(unsigned int center, int low, int high)
  75. {
  76. std::set<ui16> ret;
  77. if(low == 0)
  78. {
  79. ret.insert(center);
  80. }
  81. std::pair<int, int> mainPointForLayer[6]; //A, B, C, D, E, F points
  82. for(int b=0; b<6; ++b)
  83. mainPointForLayer[b] = hexToPair(center);
  84. for(int it=1; it<=high; ++it) //it - distance to the center
  85. {
  86. for(int b=0; b<6; ++b)
  87. mainPointForLayer[b] = gotoDir(mainPointForLayer[b], b);
  88. if(it>=low)
  89. {
  90. std::pair<int, int> curHex;
  91. //adding lines (A-b, B-c, C-d, etc)
  92. for(int v=0; v<6; ++v)
  93. {
  94. curHex = mainPointForLayer[v];
  95. for(int h=0; h<it; ++h)
  96. {
  97. if(isGoodHex(curHex))
  98. ret.insert(XYToHex(curHex));
  99. curHex = gotoDir(curHex, (v+2)%6);
  100. }
  101. }
  102. } //if(it>=low)
  103. }
  104. return ret;
  105. }
  106. }
  107. using namespace SRSLPraserHelpers;
  108. CSpell::CSpell()
  109. {
  110. isDamage = false;
  111. isRising = false;
  112. isOffensive = false;
  113. }
  114. CSpell::~CSpell()
  115. {
  116. for (size_t i=0; i<effects.size(); i++)
  117. {
  118. for (size_t j=0; j<effects[i].size(); j++)
  119. delete effects[i][j];
  120. }
  121. }
  122. std::vector<BattleHex> CSpell::rangeInHexes(BattleHex centralHex, ui8 schoolLvl, ui8 side, bool *outDroppedHexes) const
  123. {
  124. std::vector<BattleHex> ret;
  125. if(id == SpellID::FIRE_WALL || id == SpellID::FORCE_FIELD)
  126. {
  127. //Special case - shape of obstacle depends on caster's side
  128. //TODO make it possible through spell_info config
  129. BattleHex::EDir firstStep, secondStep;
  130. if(side)
  131. {
  132. firstStep = BattleHex::TOP_LEFT;
  133. secondStep = BattleHex::TOP_RIGHT;
  134. }
  135. else
  136. {
  137. firstStep = BattleHex::TOP_RIGHT;
  138. secondStep = BattleHex::TOP_LEFT;
  139. }
  140. //Adds hex to the ret if it's valid. Otherwise sets output arg flag if given.
  141. auto addIfValid = [&](BattleHex hex)
  142. {
  143. if(hex.isValid())
  144. ret.push_back(hex);
  145. else if(outDroppedHexes)
  146. *outDroppedHexes = true;
  147. };
  148. ret.push_back(centralHex);
  149. addIfValid(centralHex.moveInDir(firstStep, false));
  150. if(schoolLvl >= 2) //advanced versions of fire wall / force field cotnains of 3 hexes
  151. addIfValid(centralHex.moveInDir(firstStep, false).moveInDir(secondStep, false));
  152. return ret;
  153. }
  154. std::string rng = range[schoolLvl] + ','; //copy + artificial comma for easier handling
  155. if(rng.size() >= 1 && rng[0] != 'X') //there is at lest one hex in range
  156. {
  157. std::string number1, number2;
  158. int beg, end;
  159. bool readingFirst = true;
  160. for(int it=0; it<rng.size(); ++it)
  161. {
  162. if( std::isdigit(rng[it]) ) //reading numer
  163. {
  164. if(readingFirst)
  165. number1 += rng[it];
  166. else
  167. number2 += rng[it];
  168. }
  169. else if(rng[it] == ',') //comma
  170. {
  171. //calculating variables
  172. if(readingFirst)
  173. {
  174. beg = atoi(number1.c_str());
  175. number1 = "";
  176. }
  177. else
  178. {
  179. end = atoi(number2.c_str());
  180. number2 = "";
  181. }
  182. //obtaining new hexes
  183. std::set<ui16> curLayer;
  184. if(readingFirst)
  185. {
  186. curLayer = getInRange(centralHex, beg, beg);
  187. }
  188. else
  189. {
  190. curLayer = getInRange(centralHex, beg, end);
  191. readingFirst = true;
  192. }
  193. //adding abtained hexes
  194. for(std::set<ui16>::iterator it = curLayer.begin(); it != curLayer.end(); ++it)
  195. {
  196. ret.push_back(*it);
  197. }
  198. }
  199. else if(rng[it] == '-') //dash
  200. {
  201. beg = atoi(number1.c_str());
  202. number1 = "";
  203. readingFirst = false;
  204. }
  205. }
  206. }
  207. //remove duplicates (TODO check if actually needed)
  208. range::unique(ret);
  209. return ret;
  210. }
  211. CSpell::ETargetType CSpell::getTargetType() const
  212. {
  213. return targetType;
  214. }
  215. void CSpell::getEffects(std::vector<Bonus>& lst, const int level) const
  216. {
  217. if (level < 0 || level >= GameConstants::SPELL_SCHOOL_LEVELS)
  218. {
  219. logGlobal->errorStream() << __FUNCTION__ << " invalid school level " << level;
  220. return;
  221. }
  222. if (effects.empty())
  223. {
  224. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") has no bonus effects! " << name;
  225. return;
  226. }
  227. if (effects.size() <= level)
  228. {
  229. logGlobal->errorStream() << __FUNCTION__ << " This spell (" + name + ") is missing entry for level " << level;
  230. return;
  231. }
  232. lst.reserve(lst.size() + effects[level].size());
  233. BOOST_FOREACH (Bonus *b, effects[level])
  234. {
  235. //TODO: value, add value
  236. lst.push_back(Bonus(*b));
  237. }
  238. }
  239. bool CSpell::isImmuneBy(const IBonusBearer* obj) const
  240. {
  241. //todo: use new bonus API
  242. BOOST_FOREACH(auto b, limiters)
  243. {
  244. if (!obj->hasBonusOfType(b))
  245. return true;
  246. }
  247. BOOST_FOREACH(auto b, immunities)
  248. {
  249. if (obj->hasBonusOfType(b))
  250. return true;
  251. }
  252. auto battleTestElementalImmunity = [&,this](Bonus::BonusType element) -> bool
  253. {
  254. if (isPositive())
  255. {
  256. if (obj->hasBonusOfType(element, 0)) //must be immune to all spells
  257. return true;
  258. }
  259. else //negative or indifferent
  260. {
  261. if ((isDamageSpell() && obj->hasBonusOfType(element, 2)) || obj->hasBonusOfType(element, 1))
  262. return true;
  263. }
  264. return false;
  265. };
  266. if (fire)
  267. {
  268. if (battleTestElementalImmunity(Bonus::FIRE_IMMUNITY))
  269. return true;
  270. }
  271. if (water)
  272. {
  273. if (battleTestElementalImmunity(Bonus::WATER_IMMUNITY))
  274. return true;
  275. }
  276. if (earth)
  277. {
  278. if (battleTestElementalImmunity(Bonus::EARTH_IMMUNITY))
  279. return true;
  280. }
  281. if (air)
  282. {
  283. if (battleTestElementalImmunity(Bonus::AIR_IMMUNITY))
  284. return true;
  285. }
  286. TBonusListPtr levelImmunities = obj->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  287. if(obj->hasBonusOfType(Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  288. {
  289. levelImmunities->remove_if([](const Bonus* b){ return b->source == Bonus::CREATURE_ABILITY; });
  290. }
  291. if(obj->hasBonusOfType(Bonus::SPELL_IMMUNITY, id)
  292. || ( levelImmunities->size() > 0 && levelImmunities->totalValue() >= level && level))
  293. {
  294. return true;
  295. }
  296. return false;
  297. }
  298. void CSpell::setAttributes(const std::string& newValue)
  299. {
  300. attributes = newValue;
  301. if(attributes.find("CREATURE_TARGET_1") != std::string::npos
  302. || attributes.find("CREATURE_TARGET_2") != std::string::npos)
  303. targetType = CREATURE_EXPERT_MASSIVE;
  304. else if(attributes.find("CREATURE_TARGET") != std::string::npos)
  305. targetType = CREATURE;
  306. else if(attributes.find("OBSTACLE_TARGET") != std::string::npos)
  307. targetType = OBSTACLE;
  308. else
  309. targetType = NO_TARGET;
  310. }
  311. bool DLL_LINKAGE isInScreenRange(const int3 &center, const int3 &pos)
  312. {
  313. int3 diff = pos - center;
  314. if(diff.x >= -9 && diff.x <= 9 && diff.y >= -8 && diff.y <= 8)
  315. return true;
  316. else
  317. return false;
  318. }
  319. CSpell * CSpellHandler::loadSpell(CLegacyConfigParser & parser, const SpellID id)
  320. {
  321. CSpell * spell = new CSpell; //new currently being read spell
  322. spell->id = id;
  323. spell->name = parser.readString();
  324. spell->abbName = parser.readString();
  325. spell->level = parser.readNumber();
  326. spell->earth = parser.readString() == "x";
  327. spell->water = parser.readString() == "x";
  328. spell->fire = parser.readString() == "x";
  329. spell->air = parser.readString() == "x";
  330. spell->costs = parser.readNumArray<si32>(4);
  331. spell->power = parser.readNumber();
  332. spell->powers = parser.readNumArray<si32>(4);
  333. for (int i = 0; i < 9 ; i++)
  334. spell->probabilities[i] = parser.readNumber();
  335. spell->AIVals = parser.readNumArray<si32>(4);
  336. for (int i = 0; i < 4 ; i++)
  337. spell->descriptions.push_back(parser.readString());
  338. std::string attributes = parser.readString();
  339. //spell fixes
  340. if (id == SpellID::FORGETFULNESS)
  341. {
  342. //forgetfulness needs to get targets automatically on expert level
  343. boost::replace_first(attributes, "CREATURE_TARGET", "CREATURE_TARGET_2");
  344. }
  345. if (id == SpellID::DISRUPTING_RAY)
  346. {
  347. // disrupting ray will now affect single creature
  348. boost::replace_first(attributes,"2", "");
  349. }
  350. spell->setAttributes(attributes);
  351. spell->mainEffectAnim = -1;
  352. return spell;
  353. }
  354. CSpellHandler::CSpellHandler()
  355. {
  356. CLegacyConfigParser parser("DATA/SPTRAITS.TXT");
  357. auto read = [&,this](bool combat, bool alility)
  358. {
  359. do
  360. {
  361. const SpellID id = SpellID(spells.size());
  362. CSpell * spell = loadSpell(parser,id);
  363. spell->combatSpell = combat;
  364. spell->creatureAbility = alility;
  365. spells.push_back(spell);
  366. }
  367. while (parser.endLine() && !parser.isNextEntryEmpty());
  368. };
  369. auto skip = [&](int cnt)
  370. {
  371. for(int i=0; i<cnt; i++)
  372. parser.endLine();
  373. };
  374. skip(5);// header
  375. read(false,false); //read adventure map spells
  376. skip(3);
  377. read(true,false); //read battle spells
  378. skip(3);
  379. read(true,true);//read creature abilities
  380. spells.push_back(spells[SpellID::ACID_BREATH_DEFENSE]); //clone Acid Breath attributes for Acid Breath damage effect
  381. //loading of additional spell traits
  382. JsonNode config(ResourceID("config/spell_info.json"));
  383. config.setMeta("core");
  384. BOOST_FOREACH(auto &spell, config["spells"].Struct())
  385. {
  386. //reading exact info
  387. int spellID = spell.second["id"].Float();
  388. CSpell *s = spells[spellID];
  389. s->positiveness = spell.second["effect"].Float();
  390. s->mainEffectAnim = spell.second["anim"].Float();
  391. s->range.resize(4);
  392. int idx = 0;
  393. BOOST_FOREACH(const JsonNode &range, spell.second["ranges"].Vector())
  394. s->range[idx++] = range.String();
  395. s->counteredSpells = spell.second["counters"].convertTo<std::vector<SpellID> >();
  396. s->identifier = spell.first;
  397. VLC->modh->identifiers.registerObject("core", "spell", spell.first, spellID);
  398. const JsonNode & flags_node = spell.second["flags"];
  399. if (!flags_node.isNull())
  400. {
  401. auto flags = flags_node.convertTo<std::vector<std::string> >();
  402. BOOST_FOREACH (const auto & flag, flags)
  403. {
  404. if (flag == "damage")
  405. {
  406. s->isDamage = true;
  407. }
  408. else if (flag == "rising")
  409. {
  410. s->isRising = true;
  411. }
  412. else if (flag == "offensive")
  413. {
  414. s->isOffensive = true;
  415. }
  416. }
  417. }
  418. const JsonNode & effects_node = spell.second["effects"];
  419. BOOST_FOREACH (const JsonNode & bonus_node, effects_node.Vector())
  420. {
  421. auto &v_node = bonus_node["values"];
  422. auto &a_node = bonus_node["ainfos"];
  423. auto v = v_node.convertTo<std::vector<int> >();
  424. auto a = a_node.convertTo<std::vector<int> >();
  425. if(v.size() && v.size() != GameConstants::SPELL_SCHOOL_LEVELS)
  426. logGlobal->errorStream() << s->name << " should either have no values or exactly " << GameConstants::SPELL_SCHOOL_LEVELS;
  427. if(a.size() && a.size() != GameConstants::SPELL_SCHOOL_LEVELS)
  428. logGlobal->errorStream() << s->name << " should either have no ainfos or exactly " << GameConstants::SPELL_SCHOOL_LEVELS;
  429. s->effects.resize(GameConstants::SPELL_SCHOOL_LEVELS);
  430. for (int i = 0; i < GameConstants::SPELL_SCHOOL_LEVELS; i++)
  431. {
  432. Bonus * b = JsonUtils::parseBonus(bonus_node);
  433. b->sid = s->id; //for all
  434. b->source = Bonus::SPELL_EFFECT;//for all
  435. b->val = s->powers[i];
  436. if (!v.empty())
  437. b->val = v[i];
  438. if (!a.empty())
  439. b->additionalInfo = a[i];
  440. s->effects[i].push_back(b);
  441. }
  442. }
  443. auto find_in_map = [](std::string name, std::vector<Bonus::BonusType> &vec)
  444. {
  445. auto it = bonusNameMap.find(name);
  446. if (it == bonusNameMap.end())
  447. {
  448. logGlobal->errorStream() << "Error: invalid bonus name" << name;
  449. }
  450. else
  451. {
  452. vec.push_back((Bonus::BonusType)it->second);
  453. }
  454. };
  455. auto read_node = [&](std::string name, std::vector<Bonus::BonusType> &vec)
  456. {
  457. const JsonNode & node = spell.second[name];
  458. if (!node.isNull())
  459. {
  460. auto names = node.convertTo<std::vector<std::string> >();
  461. BOOST_FOREACH(auto name, names)
  462. find_in_map(name, vec);
  463. }
  464. };
  465. read_node("immunity",s->immunities);
  466. read_node("limit",s->limiters);
  467. const JsonNode & graphicsNode = spell.second["graphics"];
  468. if (!graphicsNode.isNull())
  469. {
  470. s->iconImmune = graphicsNode["iconImmune"].String();
  471. }
  472. }
  473. }
  474. CSpellHandler::~CSpellHandler()
  475. {
  476. BOOST_FOREACH(auto & spell, spells)
  477. {
  478. spell.dellNull();
  479. }
  480. }
  481. std::vector<bool> CSpellHandler::getDefaultAllowed() const
  482. {
  483. std::vector<bool> allowedSpells;
  484. allowedSpells.resize(GameConstants::SPELLS_QUANTITY, true);
  485. return allowedSpells;
  486. }