CHeroHandler.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. #include "StdInc.h"
  2. #include "CHeroHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "VCMI_Lib.h"
  6. #include "JsonNode.h"
  7. #include "StringConstants.h"
  8. #include "BattleHex.h"
  9. #include "CCreatureHandler.h"
  10. #include "CModHandler.h"
  11. #include "CTownHandler.h"
  12. #include "mapObjects/CObjectHandler.h" //for hero specialty
  13. #include <math.h>
  14. #include "mapObjects/CObjectClassesHandler.h"
  15. /*
  16. * CHeroHandler.cpp, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  24. SecondarySkill CHeroClass::chooseSecSkill(const std::set<SecondarySkill> & possibles, CRandomGenerator & rand) const //picks secondary skill out from given possibilities
  25. {
  26. int totalProb = 0;
  27. for(auto & possible : possibles)
  28. {
  29. totalProb += secSkillProbability[possible];
  30. }
  31. if (totalProb != 0) // may trigger if set contains only banned skills (0 probability)
  32. {
  33. auto ran = rand.nextInt(totalProb - 1);
  34. for(auto & possible : possibles)
  35. {
  36. ran -= secSkillProbability[possible];
  37. if(ran < 0)
  38. {
  39. return possible;
  40. }
  41. }
  42. }
  43. // FIXME: select randomly? How H3 handles such rare situation?
  44. return *possibles.begin();
  45. }
  46. bool CHeroClass::isMagicHero() const
  47. {
  48. return affinity == MAGIC;
  49. }
  50. EAlignment::EAlignment CHeroClass::getAlignment() const
  51. {
  52. return EAlignment::EAlignment(VLC->townh->factions[faction]->alignment);
  53. }
  54. CHeroClass::CHeroClass()
  55. : commander(nullptr)
  56. {
  57. }
  58. std::vector<BattleHex> CObstacleInfo::getBlocked(BattleHex hex) const
  59. {
  60. std::vector<BattleHex> ret;
  61. if(isAbsoluteObstacle)
  62. {
  63. assert(!hex.isValid());
  64. range::copy(blockedTiles, std::back_inserter(ret));
  65. return ret;
  66. }
  67. for(int offset : blockedTiles)
  68. {
  69. BattleHex toBlock = hex + offset;
  70. if((hex.getY() & 1) && !(toBlock.getY() & 1))
  71. toBlock += BattleHex::LEFT;
  72. if(!toBlock.isValid())
  73. logGlobal->errorStream() << "Misplaced obstacle!";
  74. else
  75. ret.push_back(toBlock);
  76. }
  77. return ret;
  78. }
  79. bool CObstacleInfo::isAppropriate(ETerrainType terrainType, int specialBattlefield /*= -1*/) const
  80. {
  81. if(specialBattlefield != -1)
  82. return vstd::contains(allowedSpecialBfields, specialBattlefield);
  83. return vstd::contains(allowedTerrains, terrainType);
  84. }
  85. CHeroClass *CHeroClassHandler::loadFromJson(const JsonNode & node)
  86. {
  87. std::string affinityStr[2] = { "might", "magic" };
  88. auto heroClass = new CHeroClass();
  89. heroClass->imageBattleFemale = node["animation"]["battle"]["female"].String();
  90. heroClass->imageBattleMale = node["animation"]["battle"]["male"].String();
  91. //MODS COMPATIBILITY FOR 0.96
  92. heroClass->imageMapFemale = node["animation"]["map"]["female"].String();
  93. heroClass->imageMapMale = node["animation"]["map"]["male"].String();
  94. heroClass->name = node["name"].String();
  95. heroClass->affinity = vstd::find_pos(affinityStr, node["affinity"].String());
  96. for(const std::string & pSkill : PrimarySkill::names)
  97. {
  98. heroClass->primarySkillInitial.push_back(node["primarySkills"][pSkill].Float());
  99. heroClass->primarySkillLowLevel.push_back(node["lowLevelChance"][pSkill].Float());
  100. heroClass->primarySkillHighLevel.push_back(node["highLevelChance"][pSkill].Float());
  101. }
  102. for(const std::string & secSkill : NSecondarySkill::names)
  103. {
  104. heroClass->secSkillProbability.push_back(node["secondarySkills"][secSkill].Float());
  105. }
  106. VLC->modh->identifiers.requestIdentifier ("creature", node["commander"],
  107. [=](si32 commanderID)
  108. {
  109. heroClass->commander = VLC->creh->creatures[commanderID];
  110. });
  111. heroClass->defaultTavernChance = node["defaultTavern"].Float();
  112. for(auto & tavern : node["tavern"].Struct())
  113. {
  114. int value = tavern.second.Float();
  115. VLC->modh->identifiers.requestIdentifier(tavern.second.meta, "faction", tavern.first,
  116. [=](si32 factionID)
  117. {
  118. heroClass->selectionProbability[factionID] = value;
  119. });
  120. }
  121. VLC->modh->identifiers.requestIdentifier("faction", node["faction"],
  122. [=](si32 factionID)
  123. {
  124. heroClass->faction = factionID;
  125. });
  126. return heroClass;
  127. }
  128. std::vector<JsonNode> CHeroClassHandler::loadLegacyData(size_t dataSize)
  129. {
  130. heroClasses.resize(dataSize);
  131. std::vector<JsonNode> h3Data;
  132. h3Data.reserve(dataSize);
  133. CLegacyConfigParser parser("DATA/HCTRAITS.TXT");
  134. parser.endLine(); // header
  135. parser.endLine();
  136. for (size_t i=0; i<dataSize; i++)
  137. {
  138. JsonNode entry;
  139. entry["name"].String() = parser.readString();
  140. parser.readNumber(); // unused aggression
  141. for (auto & name : PrimarySkill::names)
  142. entry["primarySkills"][name].Float() = parser.readNumber();
  143. for (auto & name : PrimarySkill::names)
  144. entry["lowLevelChance"][name].Float() = parser.readNumber();
  145. for (auto & name : PrimarySkill::names)
  146. entry["highLevelChance"][name].Float() = parser.readNumber();
  147. for (auto & name : NSecondarySkill::names)
  148. entry["secondarySkills"][name].Float() = parser.readNumber();
  149. for(auto & name : ETownType::names)
  150. entry["tavern"][name].Float() = parser.readNumber();
  151. parser.endLine();
  152. h3Data.push_back(entry);
  153. }
  154. return h3Data;
  155. }
  156. void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  157. {
  158. auto object = loadFromJson(data);
  159. object->id = heroClasses.size();
  160. heroClasses.push_back(object);
  161. VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
  162. {
  163. JsonNode classConf = data["mapObject"];
  164. classConf["heroClass"].String() = name;
  165. classConf.setMeta(scope);
  166. VLC->objtypeh->loadSubObject(name, classConf, index, object->id);
  167. });
  168. VLC->modh->identifiers.registerObject(scope, "heroClass", name, object->id);
  169. }
  170. void CHeroClassHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  171. {
  172. auto object = loadFromJson(data);
  173. object->id = index;
  174. assert(heroClasses[index] == nullptr); // ensure that this id was not loaded before
  175. heroClasses[index] = object;
  176. VLC->modh->identifiers.requestIdentifier(scope, "object", "hero", [=](si32 index)
  177. {
  178. JsonNode classConf = data["mapObject"];
  179. classConf["heroClass"].String() = name;
  180. classConf.setMeta(scope);
  181. VLC->objtypeh->loadSubObject(name, classConf, index, object->id);
  182. });
  183. VLC->modh->identifiers.registerObject(scope, "heroClass", name, object->id);
  184. }
  185. void CHeroClassHandler::afterLoadFinalization()
  186. {
  187. // for each pair <class, town> set selection probability if it was not set before in tavern entries
  188. for (CHeroClass * heroClass : heroClasses)
  189. {
  190. for (CFaction * faction : VLC->townh->factions)
  191. {
  192. if (!faction->town)
  193. continue;
  194. if (heroClass->selectionProbability.count(faction->index))
  195. continue;
  196. float chance = heroClass->defaultTavernChance * faction->town->defaultTavernChance;
  197. heroClass->selectionProbability[faction->index] = static_cast<int>(sqrt(chance) + 0.5); //FIXME: replace with std::round once MVS supports it
  198. }
  199. }
  200. for (CHeroClass * hc : heroClasses)
  201. {
  202. if (!hc->imageMapMale.empty())
  203. {
  204. JsonNode templ;
  205. templ["animation"].String() = hc->imageMapMale;
  206. VLC->objtypeh->getHandlerFor(Obj::HERO, hc->id)->addTemplate(templ);
  207. }
  208. }
  209. }
  210. std::vector<bool> CHeroClassHandler::getDefaultAllowed() const
  211. {
  212. return std::vector<bool>(heroClasses.size(), true);
  213. }
  214. CHeroClassHandler::~CHeroClassHandler()
  215. {
  216. for(auto heroClass : heroClasses)
  217. {
  218. delete heroClass.get();
  219. }
  220. }
  221. CHeroHandler::~CHeroHandler()
  222. {
  223. for(auto hero : heroes)
  224. delete hero.get();
  225. }
  226. CHeroHandler::CHeroHandler()
  227. {
  228. VLC->heroh = this;
  229. for (int i = 0; i < GameConstants::SKILL_QUANTITY; ++i)
  230. {
  231. VLC->modh->identifiers.registerObject("core", "skill", NSecondarySkill::names[i], i);
  232. }
  233. loadObstacles();
  234. loadTerrains();
  235. for (int i = 0; i < GameConstants::TERRAIN_TYPES; ++i)
  236. {
  237. VLC->modh->identifiers.registerObject("core", "terrain", GameConstants::TERRAIN_NAMES[i], i);
  238. }
  239. loadBallistics();
  240. loadExperience();
  241. }
  242. CHero * CHeroHandler::loadFromJson(const JsonNode & node)
  243. {
  244. auto hero = new CHero;
  245. hero->sex = node["female"].Bool();
  246. hero->special = node["special"].Bool();
  247. hero->name = node["texts"]["name"].String();
  248. hero->biography = node["texts"]["biography"].String();
  249. hero->specName = node["texts"]["specialty"]["name"].String();
  250. hero->specTooltip = node["texts"]["specialty"]["tooltip"].String();
  251. hero->specDescr = node["texts"]["specialty"]["description"].String();
  252. hero->iconSpecSmall = node["images"]["specialtySmall"].String();
  253. hero->iconSpecLarge = node["images"]["specialtyLarge"].String();
  254. hero->portraitSmall = node["images"]["small"].String();
  255. hero->portraitLarge = node["images"]["large"].String();
  256. loadHeroArmy(hero, node);
  257. loadHeroSkills(hero, node);
  258. loadHeroSpecialty(hero, node);
  259. VLC->modh->identifiers.requestIdentifier("heroClass", node["class"],
  260. [=](si32 classID)
  261. {
  262. hero->heroClass = classes.heroClasses[classID];
  263. });
  264. return hero;
  265. }
  266. void CHeroHandler::loadHeroArmy(CHero * hero, const JsonNode & node)
  267. {
  268. assert(node["army"].Vector().size() <= 3); // anything bigger is useless - army initialization uses up to 3 slots
  269. hero->initialArmy.resize(node["army"].Vector().size());
  270. for (size_t i=0; i< hero->initialArmy.size(); i++)
  271. {
  272. const JsonNode & source = node["army"].Vector()[i];
  273. hero->initialArmy[i].minAmount = source["min"].Float();
  274. hero->initialArmy[i].maxAmount = source["max"].Float();
  275. assert(hero->initialArmy[i].minAmount <= hero->initialArmy[i].maxAmount);
  276. VLC->modh->identifiers.requestIdentifier("creature", source["creature"], [=](si32 creature)
  277. {
  278. hero->initialArmy[i].creature = CreatureID(creature);
  279. });
  280. }
  281. }
  282. void CHeroHandler::loadHeroSkills(CHero * hero, const JsonNode & node)
  283. {
  284. for(const JsonNode &set : node["skills"].Vector())
  285. {
  286. int skillLevel = boost::range::find(NSecondarySkill::levels, set["level"].String()) - std::begin(NSecondarySkill::levels);
  287. if (skillLevel < SecSkillLevel::LEVELS_SIZE)
  288. {
  289. size_t currentIndex = hero->secSkillsInit.size();
  290. hero->secSkillsInit.push_back(std::make_pair(SecondarySkill(-1), skillLevel));
  291. VLC->modh->identifiers.requestIdentifier("skill", set["skill"], [=](si32 id)
  292. {
  293. hero->secSkillsInit[currentIndex].first = SecondarySkill(id);
  294. });
  295. }
  296. else
  297. {
  298. logGlobal->errorStream() << "Unknown skill level: " <<set["level"].String();
  299. }
  300. }
  301. // spellbook is considered present if hero have "spellbook" entry even when this is an empty set (0 spells)
  302. hero->haveSpellBook = !node["spellbook"].isNull();
  303. for(const JsonNode & spell : node["spellbook"].Vector())
  304. {
  305. VLC->modh->identifiers.requestIdentifier("spell", spell,
  306. [=](si32 spellID)
  307. {
  308. hero->spells.insert(SpellID(spellID));
  309. });
  310. }
  311. }
  312. void CHeroHandler::loadHeroSpecialty(CHero * hero, const JsonNode & node)
  313. {
  314. //deprecated, used only for original spciealties
  315. for(const JsonNode &specialty : node["specialties"].Vector())
  316. {
  317. SSpecialtyInfo spec;
  318. spec.type = specialty["type"].Float();
  319. spec.val = specialty["val"].Float();
  320. spec.subtype = specialty["subtype"].Float();
  321. spec.additionalinfo = specialty["info"].Float();
  322. hero->spec.push_back(spec); //put a copy of dummy
  323. }
  324. //new format, using bonus system
  325. for(const JsonNode &specialty : node["specialty"].Vector())
  326. {
  327. SSpecialtyBonus hs;
  328. hs.growsWithLevel = specialty["growsWithLevel"].Bool();
  329. for (const JsonNode & bonus : specialty["bonuses"].Vector())
  330. {
  331. auto b = JsonUtils::parseBonus(bonus);
  332. hs.bonuses.push_back (b);
  333. }
  334. hero->specialty.push_back (hs); //now, how to get CGHeroInstance from it?
  335. }
  336. }
  337. void CHeroHandler::loadExperience()
  338. {
  339. expPerLevel.push_back(0);
  340. expPerLevel.push_back(1000);
  341. expPerLevel.push_back(2000);
  342. expPerLevel.push_back(3200);
  343. expPerLevel.push_back(4600);
  344. expPerLevel.push_back(6200);
  345. expPerLevel.push_back(8000);
  346. expPerLevel.push_back(10000);
  347. expPerLevel.push_back(12200);
  348. expPerLevel.push_back(14700);
  349. expPerLevel.push_back(17500);
  350. expPerLevel.push_back(20600);
  351. expPerLevel.push_back(24320);
  352. expPerLevel.push_back(28784);
  353. expPerLevel.push_back(34140);
  354. while (expPerLevel[expPerLevel.size() - 1] > expPerLevel[expPerLevel.size() - 2])
  355. {
  356. int i = expPerLevel.size() - 1;
  357. expPerLevel.push_back (expPerLevel[i] + (expPerLevel[i] - expPerLevel[i-1]) * 1.2);
  358. }
  359. expPerLevel.pop_back();//last value is broken
  360. }
  361. void CHeroHandler::loadObstacles()
  362. {
  363. auto loadObstacles = [](const JsonNode &node, bool absolute, std::map<int, CObstacleInfo> &out)
  364. {
  365. for(const JsonNode &obs : node.Vector())
  366. {
  367. int ID = obs["id"].Float();
  368. CObstacleInfo & obi = out[ID];
  369. obi.ID = ID;
  370. obi.defName = obs["defname"].String();
  371. obi.width = obs["width"].Float();
  372. obi.height = obs["height"].Float();
  373. obi.allowedTerrains = obs["allowedTerrain"].convertTo<std::vector<ETerrainType> >();
  374. obi.allowedSpecialBfields = obs["specialBattlefields"].convertTo<std::vector<BFieldType> >();
  375. obi.blockedTiles = obs["blockedTiles"].convertTo<std::vector<si16> >();
  376. obi.isAbsoluteObstacle = absolute;
  377. }
  378. };
  379. const JsonNode config(ResourceID("config/obstacles.json"));
  380. loadObstacles(config["obstacles"], false, obstacles);
  381. loadObstacles(config["absoluteObstacles"], true, absoluteObstacles);
  382. //loadObstacles(config["moats"], true, moats);
  383. }
  384. /// convert h3-style ID (e.g. Gobin Wolf Rider) to vcmi (e.g. goblinWolfRider)
  385. static std::string genRefName(std::string input)
  386. {
  387. boost::algorithm::replace_all(input, " ", ""); //remove spaces
  388. input[0] = std::tolower(input[0]); // to camelCase
  389. return input;
  390. }
  391. void CHeroHandler::loadBallistics()
  392. {
  393. CLegacyConfigParser ballParser("DATA/BALLIST.TXT");
  394. ballParser.endLine(); //header
  395. ballParser.endLine();
  396. do
  397. {
  398. ballParser.readString();
  399. ballParser.readString();
  400. CHeroHandler::SBallisticsLevelInfo bli;
  401. bli.keep = ballParser.readNumber();
  402. bli.tower = ballParser.readNumber();
  403. bli.gate = ballParser.readNumber();
  404. bli.wall = ballParser.readNumber();
  405. bli.shots = ballParser.readNumber();
  406. bli.noDmg = ballParser.readNumber();
  407. bli.oneDmg = ballParser.readNumber();
  408. bli.twoDmg = ballParser.readNumber();
  409. bli.sum = ballParser.readNumber();
  410. ballistics.push_back(bli);
  411. assert(bli.noDmg + bli.oneDmg + bli.twoDmg == 100 && bli.sum == 100);
  412. }
  413. while (ballParser.endLine());
  414. }
  415. std::vector<JsonNode> CHeroHandler::loadLegacyData(size_t dataSize)
  416. {
  417. heroes.resize(dataSize);
  418. std::vector<JsonNode> h3Data;
  419. h3Data.reserve(dataSize);
  420. CLegacyConfigParser specParser("DATA/HEROSPEC.TXT");
  421. CLegacyConfigParser bioParser("DATA/HEROBIOS.TXT");
  422. CLegacyConfigParser parser("DATA/HOTRAITS.TXT");
  423. parser.endLine(); //ignore header
  424. parser.endLine();
  425. specParser.endLine(); //ignore header
  426. specParser.endLine();
  427. for (int i=0; i<GameConstants::HEROES_QUANTITY; i++)
  428. {
  429. JsonNode heroData;
  430. heroData["texts"]["name"].String() = parser.readString();
  431. heroData["texts"]["biography"].String() = bioParser.readString();
  432. heroData["texts"]["specialty"]["name"].String() = specParser.readString();
  433. heroData["texts"]["specialty"]["tooltip"].String() = specParser.readString();
  434. heroData["texts"]["specialty"]["description"].String() = specParser.readString();
  435. for(int x=0;x<3;x++)
  436. {
  437. JsonNode armySlot;
  438. armySlot["min"].Float() = parser.readNumber();
  439. armySlot["max"].Float() = parser.readNumber();
  440. armySlot["creature"].String() = genRefName(parser.readString());
  441. heroData["army"].Vector().push_back(armySlot);
  442. }
  443. parser.endLine();
  444. specParser.endLine();
  445. bioParser.endLine();
  446. h3Data.push_back(heroData);
  447. }
  448. return h3Data;
  449. }
  450. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  451. {
  452. auto object = loadFromJson(data);
  453. object->ID = HeroTypeID(heroes.size());
  454. object->imageIndex = heroes.size() + 30; // 2 special frames + some extra portraits
  455. heroes.push_back(object);
  456. VLC->modh->identifiers.registerObject(scope, "hero", name, object->ID.getNum());
  457. }
  458. void CHeroHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  459. {
  460. auto object = loadFromJson(data);
  461. object->ID = HeroTypeID(index);
  462. object->imageIndex = index;
  463. assert(heroes[index] == nullptr); // ensure that this id was not loaded before
  464. heroes[index] = object;
  465. VLC->modh->identifiers.registerObject(scope, "hero", name, object->ID.getNum());
  466. }
  467. ui32 CHeroHandler::level (ui64 experience) const
  468. {
  469. return boost::range::upper_bound(expPerLevel, experience) - std::begin(expPerLevel);
  470. }
  471. ui64 CHeroHandler::reqExp (ui32 level) const
  472. {
  473. if(!level)
  474. return 0;
  475. if (level <= expPerLevel.size())
  476. {
  477. return expPerLevel[level-1];
  478. }
  479. else
  480. {
  481. logGlobal->warnStream() << "A hero has reached unsupported amount of experience";
  482. return expPerLevel[expPerLevel.size()-1];
  483. }
  484. }
  485. void CHeroHandler::loadTerrains()
  486. {
  487. const JsonNode config(ResourceID("config/terrains.json"));
  488. terrCosts.reserve(GameConstants::TERRAIN_TYPES);
  489. for(const std::string & name : GameConstants::TERRAIN_NAMES)
  490. terrCosts.push_back(config[name]["moveCost"].Float());
  491. }
  492. std::vector<bool> CHeroHandler::getDefaultAllowed() const
  493. {
  494. // Look Data/HOTRAITS.txt for reference
  495. std::vector<bool> allowedHeroes;
  496. allowedHeroes.reserve(heroes.size());
  497. for(const CHero * hero : heroes)
  498. {
  499. allowedHeroes.push_back(!hero->special);
  500. }
  501. return allowedHeroes;
  502. }
  503. std::vector<bool> CHeroHandler::getDefaultAllowedAbilities() const
  504. {
  505. std::vector<bool> allowedAbilities;
  506. allowedAbilities.resize(GameConstants::SKILL_QUANTITY, true);
  507. return allowedAbilities;
  508. }