CCreatureHandler.cpp 40 KB

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