2
0

CCreatureHandler.cpp 40 KB

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