CCreatureHandler.cpp 40 KB

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