CCreatureHandler.cpp 38 KB

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