CCreatureHandler.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  1. #include "StdInc.h"
  2. #include "CCreatureHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "VCMI_Lib.h"
  6. #include "CGameState.h"
  7. #include "CTownHandler.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. using namespace boost::assign;
  11. /*
  12. * CCreatureHandler.cpp, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. int CCreature::getQuantityID(const int & quantity)
  21. {
  22. if (quantity<5)
  23. return 1;
  24. if (quantity<10)
  25. return 2;
  26. if (quantity<20)
  27. return 3;
  28. if (quantity<50)
  29. return 4;
  30. if (quantity<100)
  31. return 5;
  32. if (quantity<250)
  33. return 6;
  34. if (quantity<500)
  35. return 7;
  36. if (quantity<1000)
  37. return 8;
  38. return 9;
  39. }
  40. int CCreature::estimateCreatureCount(ui32 countID)
  41. {
  42. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  43. if (countID > 9)
  44. assert("Wrong countID!");
  45. return creature_count[countID];
  46. }
  47. bool CCreature::isDoubleWide() const
  48. {
  49. return doubleWide;
  50. }
  51. bool CCreature::isFlying() const
  52. {
  53. return hasBonusOfType(Bonus::FLYING);
  54. }
  55. bool CCreature::isShooting() const
  56. {
  57. return hasBonusOfType(Bonus::SHOOTER);
  58. }
  59. bool CCreature::isUndead() const
  60. {
  61. return hasBonusOfType(Bonus::UNDEAD);
  62. }
  63. /**
  64. * Determines if the creature is of a good alignment.
  65. * @return true if the creture is good, false otherwise.
  66. */
  67. bool CCreature::isGood () const
  68. {
  69. return VLC->townh->factions[faction]->alignment == EAlignment::GOOD;
  70. }
  71. /**
  72. * Determines if the creature is of an evil alignment.
  73. * @return true if the creature is evil, false otherwise.
  74. */
  75. bool CCreature::isEvil () const
  76. {
  77. return VLC->townh->factions[faction]->alignment == EAlignment::EVIL;
  78. }
  79. si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
  80. {
  81. int ret = 2147483645;
  82. int resAmnt = std::min(res.size(),cost.size());
  83. for(int i=0;i<resAmnt;i++)
  84. if(cost[i])
  85. ret = std::min(ret,(int)(res[i]/cost[i]));
  86. return ret;
  87. }
  88. CCreature::CCreature()
  89. {
  90. doubleWide = false;
  91. setNodeType(CBonusSystemNode::CREATURE);
  92. }
  93. void CCreature::addBonus(int val, Bonus::BonusType type, int subtype /*= -1*/)
  94. {
  95. auto added = new Bonus(Bonus::PERMANENT, type, Bonus::CREATURE_ABILITY, val, idNumber, subtype, Bonus::BASE_NUMBER);
  96. addNewBonus(added);
  97. }
  98. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  99. {
  100. //TODO upgrade of upgrade?
  101. return vstd::contains(upgrades, anotherCre->idNumber);
  102. }
  103. bool CCreature::valid() const
  104. {
  105. return this == VLC->creh->creatures[idNumber];
  106. }
  107. std::string CCreature::nodeName() const
  108. {
  109. return "\"" + namePl + "\"";
  110. }
  111. bool CCreature::isItNativeTerrain(int terrain) const
  112. {
  113. return VLC->townh->factions[faction]->nativeTerrain == terrain;
  114. }
  115. void CCreature::setId(CreatureID ID)
  116. {
  117. idNumber = ID;
  118. for(auto bonus : getExportedBonusList())
  119. {
  120. if(bonus->source == Bonus::CREATURE_ABILITY)
  121. bonus->sid = ID;
  122. }
  123. }
  124. static void AddAbility(CCreature *cre, const JsonVector &ability_vec)
  125. {
  126. auto nsf = new Bonus();
  127. std::string type = ability_vec[0].String();
  128. auto it = bonusNameMap.find(type);
  129. if (it == bonusNameMap.end()) {
  130. if (type == "DOUBLE_WIDE")
  131. cre->doubleWide = true;
  132. else if (type == "ENEMY_MORALE_DECREASING") {
  133. cre->addBonus(-1, Bonus::MORALE);
  134. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  135. }
  136. else if (type == "ENEMY_LUCK_DECREASING") {
  137. cre->addBonus(-1, Bonus::LUCK);
  138. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  139. } else
  140. logGlobal->errorStream() << "Error: invalid ability type " << type << " in creatures config";
  141. return;
  142. }
  143. nsf->type = it->second;
  144. JsonUtils::parseTypedBonusShort(ability_vec,nsf);
  145. nsf->source = Bonus::CREATURE_ABILITY;
  146. nsf->sid = cre->idNumber;
  147. cre->addNewBonus(nsf);
  148. }
  149. CCreatureHandler::CCreatureHandler()
  150. {
  151. VLC->creh = this;
  152. allCreatures.setDescription("All creatures");
  153. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  154. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  155. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  156. loadCommanders();
  157. }
  158. void CCreatureHandler::loadCommanders()
  159. {
  160. JsonNode data(ResourceID("config/commanders.json"));
  161. data.setMeta("core"); // assume that commanders are in core mod (for proper bonuses resolution)
  162. const JsonNode & config = data; // switch to const data accessors
  163. for (auto bonus : config["bonusPerLevel"].Vector())
  164. {
  165. commanderLevelPremy.push_back(JsonUtils::parseBonus (bonus.Vector()));
  166. }
  167. int i = 0;
  168. for (auto skill : config["skillLevels"].Vector())
  169. {
  170. skillLevels.push_back (std::vector<ui8>());
  171. for (auto skillLevel : skill["levels"].Vector())
  172. {
  173. skillLevels[i].push_back (skillLevel.Float());
  174. }
  175. ++i;
  176. }
  177. for (auto ability : config["abilityRequirements"].Vector())
  178. {
  179. std::pair <Bonus*, std::pair <ui8, ui8> > a;
  180. a.first = JsonUtils::parseBonus (ability["ability"].Vector());
  181. a.second.first = ability["skills"].Vector()[0].Float();
  182. a.second.second = ability["skills"].Vector()[1].Float();
  183. skillRequirements.push_back (a);
  184. }
  185. }
  186. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses)
  187. {
  188. auto makeBonusNode = [&](std::string type) -> JsonNode
  189. {
  190. JsonNode ret;
  191. ret["type"].String() = type;
  192. return ret;
  193. };
  194. static const std::map<std::string, JsonNode> abilityMap =
  195. boost::assign::map_list_of
  196. ("FLYING_ARMY", makeBonusNode("FLYING"))
  197. ("SHOOTING_ARMY", makeBonusNode("SHOOTER"))
  198. ("SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON"))
  199. ("const_free_attack", makeBonusNode("BLOCKS_RETALIATION"))
  200. ("IS_UNDEAD", makeBonusNode("UNDEAD"))
  201. ("const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY"))
  202. ("const_jousting", makeBonusNode("JOUSTING"))
  203. ("KING_1", makeBonusNode("KING1"))
  204. ("KING_2", makeBonusNode("KING2"))
  205. ("KING_3", makeBonusNode("KING3"))
  206. ("const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY"))
  207. ("CATAPULT", makeBonusNode("CATAPULT"))
  208. ("MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT"))
  209. ("IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY"))
  210. ("HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH"));
  211. auto hasAbility = [&](const std::string name) -> bool
  212. {
  213. return boost::algorithm::find_first(bonuses, name);
  214. };
  215. for(auto a : abilityMap)
  216. {
  217. if(hasAbility(a.first))
  218. creature["abilities"][a.first] = a.second;
  219. }
  220. if(hasAbility("DOUBLE_WIDE"))
  221. creature["doubleWide"].Bool() = true;
  222. if(hasAbility("const_raises_morale"))
  223. {
  224. JsonNode node = makeBonusNode("MORALE");
  225. node["val"].Float() = 1;
  226. node["propagator"].String() = "HERO";
  227. creature["abilities"]["const_raises_morale"] = node;
  228. }
  229. if(hasAbility("const_lowers_morale"))
  230. {
  231. JsonNode node = makeBonusNode("MORALE");
  232. node["val"].Float() = -1;
  233. node["effectRange"].String() = "ONLY_ENEMY_ARMY";
  234. creature["abilities"]["const_lowers_morale"] = node;
  235. }
  236. }
  237. std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
  238. {
  239. creatures.resize(dataSize);
  240. std::vector<JsonNode> h3Data;
  241. h3Data.reserve(dataSize);
  242. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  243. parser.endLine(); // header
  244. // this file is a bit different in some of Russian localisations:
  245. //ENG: Singular Plural Wood ...
  246. //RUS: Singular Plural Plural2 Wood ...
  247. // Try to detect which version this is by header
  248. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  249. size_t namesCount;
  250. {
  251. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  252. throw std::runtime_error("Incorrect format of CrTraits.txt");
  253. if (parser.readString() == "Plural2")
  254. namesCount = 3;
  255. else
  256. namesCount = 2;
  257. parser.endLine();
  258. }
  259. for (size_t i=0; i<dataSize; i++)
  260. {
  261. //loop till non-empty line
  262. while (parser.isNextEntryEmpty())
  263. parser.endLine();
  264. JsonNode data;
  265. data["name"]["singular"].String() = parser.readString();
  266. if (namesCount == 3)
  267. parser.readString();
  268. data["name"]["plural"].String() = parser.readString();
  269. for(int v=0; v<7; ++v)
  270. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  271. data["fightValue"].Float() = parser.readNumber();
  272. data["aiValue"].Float() = parser.readNumber();
  273. data["growth"].Float() = parser.readNumber();
  274. data["horde"].Float() = parser.readNumber();
  275. data["hitPoints"].Float() = parser.readNumber();
  276. data["speed"].Float() = parser.readNumber();
  277. data["attack"].Float() = parser.readNumber();
  278. data["defense"].Float() = parser.readNumber();
  279. data["damage"]["min"].Float() = parser.readNumber();
  280. data["damage"]["max"].Float() = parser.readNumber();
  281. if (float shots = parser.readNumber())
  282. data["shots"].Float() = shots;
  283. if (float spells = parser.readNumber())
  284. data["spellPoints"].Float() = spells;
  285. data["advMapAmount"]["min"].Float() = parser.readNumber();
  286. data["advMapAmount"]["max"].Float() = parser.readNumber();
  287. data["abilityText"].String() = parser.readString();
  288. loadBonuses(data, parser.readString()); //Attributes
  289. h3Data.push_back(data);
  290. }
  291. loadAnimationInfo(h3Data);
  292. return h3Data;
  293. }
  294. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  295. {
  296. auto object = loadFromJson(data);
  297. object->setId(CreatureID(creatures.size()));
  298. object->iconIndex = object->idNumber + 2;
  299. creatures.push_back(object);
  300. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  301. for(auto node : data["extraNames"].Vector())
  302. {
  303. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  304. }
  305. }
  306. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  307. {
  308. auto object = loadFromJson(data);
  309. object->setId(CreatureID(index));
  310. object->iconIndex = object->idNumber + 2;
  311. if(data["hasDoubleWeek"].Bool()) //
  312. {
  313. doubledCreatures.insert (object->idNumber); //we need to have id (or identifier) before it is inserted
  314. }
  315. assert(creatures[index] == nullptr); // ensure that this id was not loaded before
  316. creatures[index] = object;
  317. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  318. for(auto node : data["extraNames"].Vector())
  319. {
  320. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  321. }
  322. }
  323. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  324. {
  325. std::vector<bool> ret;
  326. for(const CCreature * crea : creatures)
  327. {
  328. ret.push_back(crea ? !crea->special : false);
  329. }
  330. return ret;
  331. }
  332. void CCreatureHandler::loadCrExpBon()
  333. {
  334. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  335. {
  336. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  337. Bonus b; //prototype with some default properties
  338. b.source = Bonus::STACK_EXPERIENCE;
  339. b.duration = Bonus::PERMANENT;
  340. b.valType = Bonus::ADDITIVE_VALUE;
  341. b.effectRange = Bonus::NO_LIMIT;
  342. b.additionalInfo = 0;
  343. b.turnsRemain = 0;
  344. BonusList bl;
  345. parser.endLine();
  346. parser.readString(); //ignore index
  347. loadStackExp(b, bl, parser);
  348. for(Bonus * b : bl)
  349. addBonusForAllCreatures(b); //health bonus is common for all
  350. parser.endLine();
  351. for (int i = 1; i < 7; ++i)
  352. {
  353. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  354. {
  355. parser.readString(); //ignore index
  356. bl.clear();
  357. loadStackExp(b, bl, parser);
  358. for(Bonus * b : bl)
  359. addBonusForTier(i, b);
  360. parser.endLine();
  361. }
  362. }
  363. for (int j = 0; j < 4; ++j) //tier 7
  364. {
  365. parser.readString(); //ignore index
  366. bl.clear();
  367. loadStackExp(b, bl, parser);
  368. for(Bonus * b : bl)
  369. {
  370. addBonusForTier(7, b);
  371. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  372. }
  373. parser.endLine();
  374. }
  375. do //parse everything that's left
  376. {
  377. b.sid = parser.readNumber(); //id = this particular creature ID
  378. loadStackExp(b, creatures[b.sid]->getBonusList(), parser); //add directly to CCreature Node
  379. }
  380. while (parser.endLine());
  381. //Calculate rank exp values, formula appears complicated bu no parsing needed
  382. expRanks.resize(8);
  383. int dif = 0;
  384. int it = 8000; //ignore name of this variable
  385. expRanks[0].push_back(it);
  386. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  387. {
  388. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  389. dif += it/5;
  390. }
  391. for (int i = 1; i < 8; ++i)
  392. {
  393. dif = 0;
  394. it = 1000 * i;
  395. expRanks[i].push_back(it);
  396. for (int j = 1; j < 10; ++j)
  397. {
  398. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  399. dif += it/5;
  400. }
  401. }
  402. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  403. expBonParser.endLine(); //header
  404. maxExpPerBattle.resize(8);
  405. for (int i = 1; i < 8; ++i)
  406. {
  407. expBonParser.readString(); //index
  408. expBonParser.readString(); //float multiplier -> hardcoded
  409. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  410. expBonParser.readString(); //already calculated
  411. maxExpPerBattle[i] = expBonParser.readNumber();
  412. expRanks[i].push_back(expRanks[i].back() + expBonParser.readNumber());
  413. expBonParser.endLine();
  414. }
  415. //skeleton gets exp penalty
  416. creatures[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  417. creatures[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  418. //exp for tier >7, rank 11
  419. expRanks[0].push_back(147000);
  420. expAfterUpgrade = 75; //percent
  421. maxExpPerBattle[0] = maxExpPerBattle[7];
  422. }//end of Stack Experience
  423. }
  424. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  425. {
  426. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  427. parser.endLine(); // header
  428. parser.endLine();
  429. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++dd)
  430. {
  431. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  432. ;
  433. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  434. parser.endLine();
  435. }
  436. }
  437. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  438. {
  439. graphics["map"].String(); //create empty string. Real value will be loaded from H3 txt's
  440. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  441. JsonNode & animationTime = graphics["animationTime"];
  442. animationTime["walk"].Float() = parser.readNumber();
  443. animationTime["attack"].Float() = parser.readNumber();
  444. animationTime["flight"].Float() = parser.readNumber();
  445. JsonNode & missile = graphics["missile"];
  446. JsonNode & offsets = missile["offset"];
  447. offsets["upperX"].Float() = parser.readNumber();
  448. offsets["upperY"].Float() = parser.readNumber();
  449. offsets["middleX"].Float() = parser.readNumber();
  450. offsets["middleY"].Float() = parser.readNumber();
  451. offsets["lowerX"].Float() = parser.readNumber();
  452. offsets["lowerY"].Float() = parser.readNumber();
  453. for(int i=0; i<12; i++)
  454. {
  455. JsonNode entry;
  456. entry.Float() = parser.readNumber();
  457. missile["frameAngles"].Vector().push_back(entry);
  458. }
  459. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  460. missile["attackClimaxFrame"].Float() = parser.readNumber();
  461. // assume that creature is not a shooter and should not have whole missile field
  462. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  463. missile["attackClimaxFrame"].Float() == 0)
  464. graphics.Struct().erase("missile");
  465. }
  466. CCreature * CCreatureHandler::loadFromJson(const JsonNode & node)
  467. {
  468. auto cre = new CCreature();
  469. const JsonNode & name = node["name"];
  470. cre->nameSing = name["singular"].String();
  471. cre->namePl = name["plural"].String();
  472. cre->cost = Res::ResourceSet(node["cost"]);
  473. cre->fightValue = node["fightValue"].Float();
  474. cre->AIValue = node["aiValue"].Float();
  475. cre->growth = node["growth"].Float();
  476. cre->hordeGrowth = node["horde"].Float(); // Needed at least until configurable buildings
  477. cre->addBonus(node["hitPoints"].Float(), Bonus::STACK_HEALTH);
  478. cre->addBonus(node["speed"].Float(), Bonus::STACKS_SPEED);
  479. cre->addBonus(node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  480. cre->addBonus(node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  481. cre->addBonus(node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
  482. cre->addBonus(node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
  483. assert(node["damage"]["min"].Float() <= node["damage"]["max"].Float());
  484. cre->ammMin = node["advMapAmount"]["min"].Float();
  485. cre->ammMax = node["advMapAmount"]["max"].Float();
  486. assert(cre->ammMin <= cre->ammMax);
  487. if (!node["shots"].isNull())
  488. cre->addBonus(node["shots"].Float(), Bonus::SHOTS);
  489. if (node["spellPoints"].isNull())
  490. cre->addBonus(node["spellPoints"].Float(), Bonus::CASTS);
  491. cre->doubleWide = node["doubleWide"].Bool();
  492. loadStackExperience(cre, node["stackExperience"]);
  493. loadJsonAnimation(cre, node["graphics"]);
  494. loadCreatureJson(cre, node);
  495. return cre;
  496. }
  497. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  498. {
  499. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  500. cre->animation.troopCountLocationOffset = graphics["troopCountLocationOffset"].Float();
  501. const JsonNode & animationTime = graphics["animationTime"];
  502. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  503. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  504. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  505. const JsonNode & missile = graphics["missile"];
  506. const JsonNode & offsets = missile["offset"];
  507. cre->animation.upperRightMissleOffsetX = offsets["upperX"].Float();
  508. cre->animation.upperRightMissleOffsetY = offsets["upperY"].Float();
  509. cre->animation.rightMissleOffsetX = offsets["middleX"].Float();
  510. cre->animation.rightMissleOffsetY = offsets["middleY"].Float();
  511. cre->animation.lowerRightMissleOffsetX = offsets["lowerX"].Float();
  512. cre->animation.lowerRightMissleOffsetY = offsets["lowerY"].Float();
  513. cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float();
  514. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  515. cre->advMapDef = graphics["map"].String();
  516. cre->smallIconName = graphics["iconSmall"].String();
  517. cre->largeIconName = graphics["iconLarge"].String();
  518. }
  519. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  520. {
  521. creature->level = config["level"].Float();
  522. creature->animDefName = config["graphics"]["animation"].String();
  523. //FIXME: MOD COMPATIBILITY
  524. if (config["abilities"].getType() == JsonNode::DATA_STRUCT)
  525. {
  526. for(auto &ability : config["abilities"].Struct())
  527. {
  528. if (!ability.second.isNull())
  529. {
  530. auto b = JsonUtils::parseBonus(ability.second);
  531. b->source = Bonus::CREATURE_ABILITY;
  532. b->duration = Bonus::PERMANENT;
  533. creature->addNewBonus(b);
  534. }
  535. }
  536. }
  537. else
  538. {
  539. for(const JsonNode &ability : config["abilities"].Vector())
  540. {
  541. if (ability.getType() == JsonNode::DATA_VECTOR)
  542. {
  543. assert(0); // should be unused now
  544. AddAbility(creature, ability.Vector()); // used only for H3 creatures
  545. }
  546. else
  547. {
  548. auto b = JsonUtils::parseBonus(ability);
  549. b->source = Bonus::CREATURE_ABILITY;
  550. b->duration = Bonus::PERMANENT;
  551. creature->addNewBonus(b);
  552. }
  553. }
  554. }
  555. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  556. {
  557. creature->faction = faction;
  558. });
  559. for(const JsonNode &value : config["upgrades"].Vector())
  560. {
  561. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  562. {
  563. creature->upgrades.insert(CreatureID(identifier));
  564. });
  565. }
  566. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  567. creature->special = config["special"].Bool() || config["disabled"].Bool();
  568. const JsonNode & sounds = config["sound"];
  569. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  570. GET_SOUND_VALUE(attack);
  571. GET_SOUND_VALUE(defend);
  572. GET_SOUND_VALUE(killed);
  573. GET_SOUND_VALUE(move);
  574. GET_SOUND_VALUE(shoot);
  575. GET_SOUND_VALUE(wince);
  576. GET_SOUND_VALUE(startMoving);
  577. GET_SOUND_VALUE(endMoving);
  578. #undef GET_SOUND_VALUE
  579. }
  580. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  581. {
  582. for (const JsonNode &exp : input.Vector())
  583. {
  584. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  585. bonus->source = Bonus::STACK_EXPERIENCE;
  586. bonus->duration = Bonus::PERMANENT;
  587. const JsonVector &values = exp["values"].Vector();
  588. int lowerLimit = 1;//, upperLimit = 255;
  589. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  590. {
  591. for (const JsonNode &val : values)
  592. {
  593. if (val.Bool() == true)
  594. {
  595. bonus->limiter = make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  596. creature->addNewBonus (new Bonus(*bonus)); //bonuses must be unique objects
  597. break; //TODO: allow bonuses to turn off?
  598. }
  599. ++lowerLimit;
  600. }
  601. }
  602. else
  603. {
  604. int lastVal = 0;
  605. for (const JsonNode &val : values)
  606. {
  607. if (val.Float() != lastVal)
  608. {
  609. bonus->val = val.Float() - lastVal;
  610. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  611. creature->addNewBonus (new Bonus(*bonus));
  612. }
  613. lastVal = val.Float();
  614. ++lowerLimit;
  615. }
  616. }
  617. delete bonus;
  618. }
  619. }
  620. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  621. {
  622. bool enable = false; //some bonuses are activated with values 2 or 1
  623. std::string buf = parser.readString();
  624. std::string mod = parser.readString();
  625. switch (buf[0])
  626. {
  627. case 'H':
  628. b.type = Bonus::STACK_HEALTH;
  629. b.valType = Bonus::PERCENT_TO_BASE;
  630. break;
  631. case 'A':
  632. b.type = Bonus::PRIMARY_SKILL;
  633. b.subtype = PrimarySkill::ATTACK;
  634. break;
  635. case 'D':
  636. b.type = Bonus::PRIMARY_SKILL;
  637. b.subtype = PrimarySkill::DEFENSE;
  638. break;
  639. case 'M': //Max damage
  640. b.type = Bonus::CREATURE_DAMAGE;
  641. b.subtype = 2;
  642. break;
  643. case 'm': //Min damage
  644. b.type = Bonus::CREATURE_DAMAGE;
  645. b.subtype = 1;
  646. break;
  647. case 'S':
  648. b.type = Bonus::STACKS_SPEED; break;
  649. case 'O':
  650. b.type = Bonus::SHOTS; break;
  651. case 'b':
  652. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  653. case 'C':
  654. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  655. case 'd':
  656. b.type = Bonus::DEFENSIVE_STANCE; break;
  657. case 'e':
  658. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  659. b.subtype = 0;
  660. break;
  661. case 'E':
  662. b.type = Bonus::DEATH_STARE;
  663. b.subtype = 0; //Gorgon
  664. break;
  665. case 'F':
  666. b.type = Bonus::FEAR; break;
  667. case 'g':
  668. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  669. b.subtype = -1; //all magic schools
  670. break;
  671. case 'P':
  672. b.type = Bonus::CASTS; break;
  673. case 'R':
  674. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  675. case 'W':
  676. b.type = Bonus::MAGIC_RESISTANCE;
  677. b.subtype = 0; //otherwise creature window goes crazy
  678. break;
  679. case 'f': //on-off skill
  680. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  681. switch (mod[0])
  682. {
  683. case 'A':
  684. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  685. case 'b':
  686. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  687. case 'B':
  688. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  689. case 'c':
  690. b.type = Bonus::JOUSTING; break;
  691. case 'D':
  692. b.type = Bonus::ADDITIONAL_ATTACK; break;
  693. case 'f':
  694. b.type = Bonus::FEARLESS; break;
  695. case 'F':
  696. b.type = Bonus::FLYING; break;
  697. case 'm':
  698. b.type = Bonus::SELF_MORALE; break;
  699. case 'M':
  700. b.type = Bonus::NO_MORALE; break;
  701. case 'p': //Mind spells
  702. case 'P':
  703. b.type = Bonus::MIND_IMMUNITY; break;
  704. case 'r':
  705. b.type = Bonus::REBIRTH; //on/off? makes sense?
  706. b.subtype = 0;
  707. b.val = 20; //arbitrary value
  708. break;
  709. case 'R':
  710. b.type = Bonus::BLOCKS_RETALIATION; break;
  711. case 's':
  712. b.type = Bonus::FREE_SHOOTING; break;
  713. case 'u':
  714. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  715. case 'U':
  716. b.type = Bonus::UNDEAD; break;
  717. default:
  718. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  719. return;
  720. break;
  721. }
  722. break;
  723. case 'w': //specific spell immunities, enabled/disabled
  724. enable = true;
  725. switch (mod[0])
  726. {
  727. case 'B': //Blind
  728. b.type = Bonus::SPELL_IMMUNITY;
  729. b.subtype = SpellID::BLIND;
  730. break;
  731. case 'H': //Hypnotize
  732. b.type = Bonus::SPELL_IMMUNITY;
  733. b.subtype = SpellID::HYPNOTIZE;
  734. break;
  735. case 'I': //Implosion
  736. b.type = Bonus::SPELL_IMMUNITY;
  737. b.subtype = SpellID::IMPLOSION;
  738. break;
  739. case 'K': //Berserk
  740. b.type = Bonus::SPELL_IMMUNITY;
  741. b.subtype = SpellID::BERSERK;
  742. break;
  743. case 'M': //Meteor Shower
  744. b.type = Bonus::SPELL_IMMUNITY;
  745. b.subtype = SpellID::METEOR_SHOWER;
  746. break;
  747. case 'N': //dispell beneficial spells
  748. b.type = Bonus::SPELL_IMMUNITY;
  749. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  750. break;
  751. case 'R': //Armageddon
  752. b.type = Bonus::SPELL_IMMUNITY;
  753. b.subtype = SpellID::ARMAGEDDON;
  754. break;
  755. case 'S': //Slow
  756. b.type = Bonus::SPELL_IMMUNITY;
  757. b.subtype = SpellID::SLOW;
  758. break;
  759. case '6':
  760. case '7':
  761. case '8':
  762. case '9':
  763. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  764. b.val = std::atoi(mod.c_str()) - 5;
  765. break;
  766. case ':':
  767. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  768. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  769. break;
  770. case 'F':
  771. b.type = Bonus::FIRE_IMMUNITY;
  772. b.subtype = 1; //not positive
  773. break;
  774. case 'O':
  775. b.type = Bonus::FIRE_IMMUNITY;
  776. b.subtype = 2; //only direct damage
  777. break;
  778. case 'f':
  779. b.type = Bonus::FIRE_IMMUNITY;
  780. b.subtype = 0; //all
  781. break;
  782. case 'C':
  783. b.type = Bonus::WATER_IMMUNITY;
  784. b.subtype = 1; //not positive
  785. break;
  786. case 'W':
  787. b.type = Bonus::WATER_IMMUNITY;
  788. b.subtype = 2; //only direct damage
  789. break;
  790. case 'w':
  791. b.type = Bonus::WATER_IMMUNITY;
  792. b.subtype = 0; //all
  793. break;
  794. case 'E':
  795. b.type = Bonus::EARTH_IMMUNITY;
  796. b.subtype = 2; //only direct damage
  797. break;
  798. case 'e':
  799. b.type = Bonus::EARTH_IMMUNITY;
  800. b.subtype = 0; //all
  801. break;
  802. case 'A':
  803. b.type = Bonus::AIR_IMMUNITY;
  804. b.subtype = 2; //only direct damage
  805. break;
  806. case 'a':
  807. b.type = Bonus::AIR_IMMUNITY;
  808. b.subtype = 0; //all
  809. break;
  810. case 'D':
  811. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  812. break;
  813. case '0':
  814. b.type = Bonus::RECEPTIVE;
  815. break;
  816. case 'm':
  817. b.type = Bonus::MIND_IMMUNITY;
  818. break;
  819. default:
  820. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  821. return;
  822. }
  823. break;
  824. case 'i':
  825. enable = true;
  826. b.type = Bonus::NO_DISTANCE_PENALTY;
  827. break;
  828. case 'o':
  829. enable = true;
  830. b.type = Bonus::NO_WALL_PENALTY;
  831. break;
  832. case 'a':
  833. case 'c':
  834. case 'K':
  835. case 'k':
  836. b.type = Bonus::SPELL_AFTER_ATTACK;
  837. b.subtype = stringToNumber(mod);
  838. break;
  839. case 'h':
  840. b.type= Bonus::HATE;
  841. b.subtype = stringToNumber(mod);
  842. break;
  843. case 'p':
  844. case 'J':
  845. b.type = Bonus::SPELL_BEFORE_ATTACK;
  846. b.subtype = stringToNumber(mod);
  847. b.additionalInfo = 3; //always expert?
  848. break;
  849. case 'r':
  850. b.type = Bonus::HP_REGENERATION;
  851. b.val = stringToNumber(mod);
  852. break;
  853. case 's':
  854. b.type = Bonus::ENCHANTED;
  855. b.subtype = stringToNumber(mod);
  856. b.valType = Bonus::INDEPENDENT_MAX;
  857. break;
  858. default:
  859. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  860. return;
  861. break;
  862. }
  863. switch (mod[0])
  864. {
  865. case '+':
  866. case '=': //should we allow percent values to stack or pick highest?
  867. b.valType = Bonus::ADDITIVE_VALUE;
  868. break;
  869. }
  870. //limiters, range
  871. si32 lastVal, curVal, lastLev = 0;
  872. if (enable) //0 and 2 means non-active, 1 - active
  873. {
  874. if (b.type != Bonus::REBIRTH)
  875. b.val = 0; //on-off ability, no value specified
  876. curVal = parser.readNumber();// 0 level is never active
  877. for (int i = 1; i < 11; ++i)
  878. {
  879. curVal = parser.readNumber();
  880. if (curVal == 1)
  881. {
  882. b.limiter.reset (new RankRangeLimiter(i));
  883. bl.push_back(new Bonus(b));
  884. break; //never turned off it seems
  885. }
  886. }
  887. }
  888. else
  889. {
  890. lastVal = parser.readNumber(); //basic value, not particularly useful but existent
  891. for (int i = 1; i < 11; ++i)
  892. {
  893. curVal = parser.readNumber();
  894. if (b.type == Bonus::HATE)
  895. curVal *= 10; //odd fix
  896. if (curVal > lastVal) //threshold, add new bonus
  897. {
  898. b.val = curVal - lastVal;
  899. lastVal = curVal;
  900. b.limiter.reset (new RankRangeLimiter(i));
  901. bl.push_back(new Bonus(b));
  902. lastLev = i; //start new range from here, i = previous rank
  903. }
  904. else if (curVal < lastVal)
  905. {
  906. b.val = lastVal;
  907. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  908. }
  909. }
  910. }
  911. }
  912. int CCreatureHandler::stringToNumber(std::string & s)
  913. {
  914. boost::algorithm::replace_first(s,"#",""); //drop hash character
  915. return std::atoi(s.c_str());
  916. }
  917. CCreatureHandler::~CCreatureHandler()
  918. {
  919. for(auto & creature : creatures)
  920. creature.dellNull();
  921. }
  922. CreatureID CCreatureHandler::pickRandomMonster(const std::function<int()> &randGen, int tier) const
  923. {
  924. int r = 0;
  925. if(tier == -1) //pick any allowed creature
  926. {
  927. do
  928. {
  929. r = vstd::pickRandomElementOf(creatures, randGen)->idNumber;
  930. } while (VLC->creh->creatures[r] && VLC->creh->creatures[r]->special); // find first "not special" creature
  931. }
  932. else
  933. {
  934. assert(vstd::iswithin(tier, 1, 7));
  935. std::vector<CreatureID> allowed;
  936. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  937. {
  938. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  939. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  940. if(crea && !crea->special)
  941. allowed.push_back(crea->idNumber);
  942. }
  943. if(!allowed.size())
  944. {
  945. logGlobal->warnStream() << "Cannot pick a random creature of tier " << tier << "!";
  946. return CreatureID::NONE;
  947. }
  948. return vstd::pickRandomElementOf(allowed, randGen);
  949. }
  950. assert (r >= 0); //should always be, but it crashed
  951. return CreatureID(r);
  952. }
  953. void CCreatureHandler::addBonusForTier(int tier, Bonus *b)
  954. {
  955. assert(vstd::iswithin(tier, 1, 7));
  956. creaturesOfLevel[tier].addNewBonus(b);
  957. }
  958. void CCreatureHandler::addBonusForAllCreatures(Bonus *b)
  959. {
  960. allCreatures.addNewBonus(b);
  961. }
  962. void CCreatureHandler::buildBonusTreeForTiers()
  963. {
  964. for(CCreature *c : creatures)
  965. {
  966. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  967. c->attachTo(&creaturesOfLevel[c->level]);
  968. else
  969. c->attachTo(&creaturesOfLevel[0]);
  970. }
  971. for(CBonusSystemNode &b : creaturesOfLevel)
  972. b.attachTo(&allCreatures);
  973. }
  974. void CCreatureHandler::deserializationFix()
  975. {
  976. buildBonusTreeForTiers();
  977. }