CCreatureHandler.cpp 39 KB

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