CCreatureHandler.cpp 41 KB

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