CHeroHandler.cpp 17 KB

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