CCreatureHandler.cpp 39 KB

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