CHeroHandler.cpp 17 KB

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