CCreatureHandler.cpp 40 KB

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