CCreatureHandler.cpp 34 KB

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