CCreatureHandler.cpp 32 KB

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