CCreatureHandler.cpp 39 KB

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