CCreatureHandler.cpp 40 KB

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