CCreatureHandler.cpp 32 KB

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