CCreatureHandler.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383
  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 "StringConstants.h"
  19. #include "serializer/JsonDeserializer.h"
  20. #include "serializer/JsonUpdater.h"
  21. #include "mapObjects/CObjectClassesHandler.h"
  22. VCMI_LIB_NAMESPACE_BEGIN
  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(), 0, "CPRSMALL", smallIconName);
  42. cb(getIconIndex(), 0, "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(TerrainId terrain) const
  244. {
  245. auto native = getNativeTerrain();
  246. return native == terrain || native == ETerrainId::ANY_TERRAIN;
  247. }
  248. TerrainId CCreature::getNativeTerrain() const
  249. {
  250. const std::string cachingStringNoTerrainPenalty = "type_NO_TERRAIN_PENALTY";
  251. static const auto selectorNoTerrainPenalty = 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(selectorNoTerrainPenalty, selectorNoTerrainPenalty)
  255. ? TerrainId(ETerrainId::ANY_TERRAIN)
  256. : (*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(CModHandler::scopeBuiltin()); // 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. loadStackExperience(cre, node["stackExperience"]);
  503. loadJsonAnimation(cre, node["graphics"]);
  504. loadCreatureJson(cre, node);
  505. for(auto & extraName : node["extraNames"].Vector())
  506. {
  507. for(auto type_name : getTypeNames())
  508. registerObject(scope, type_name, extraName.String(), cre->getIndex());
  509. }
  510. VLC->modh->identifiers.requestIdentifier(scope, "object", "monster", [=](si32 index)
  511. {
  512. JsonNode conf;
  513. conf.setMeta(scope);
  514. VLC->objtypeh->loadSubObject(cre->identifier, conf, Obj::MONSTER, cre->idNumber.num);
  515. if (!cre->advMapDef.empty())
  516. {
  517. JsonNode templ;
  518. templ["animation"].String() = cre->advMapDef;
  519. templ.setMeta(scope);
  520. VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->idNumber.num)->addTemplate(templ);
  521. }
  522. // object does not have any templates - this is not usable object (e.g. pseudo-creature like Arrow Tower)
  523. if (VLC->objtypeh->getHandlerFor(Obj::MONSTER, cre->idNumber.num)->getTemplates().empty())
  524. VLC->objtypeh->removeSubObject(Obj::MONSTER, cre->idNumber.num);
  525. });
  526. return cre;
  527. }
  528. const std::vector<std::string> & CCreatureHandler::getTypeNames() const
  529. {
  530. static const std::vector<std::string> typeNames = { "creature" };
  531. return typeNames;
  532. }
  533. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  534. {
  535. std::vector<bool> ret;
  536. for(const CCreature * crea : objects)
  537. {
  538. ret.push_back(crea ? !crea->special : false);
  539. }
  540. return ret;
  541. }
  542. void CCreatureHandler::loadCrExpBon()
  543. {
  544. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  545. {
  546. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  547. Bonus b; //prototype with some default properties
  548. b.source = Bonus::STACK_EXPERIENCE;
  549. b.duration = Bonus::PERMANENT;
  550. b.valType = Bonus::ADDITIVE_VALUE;
  551. b.effectRange = Bonus::NO_LIMIT;
  552. b.additionalInfo = 0;
  553. b.turnsRemain = 0;
  554. BonusList bl;
  555. parser.endLine();
  556. parser.readString(); //ignore index
  557. loadStackExp(b, bl, parser);
  558. for(auto b : bl)
  559. addBonusForAllCreatures(b); //health bonus is common for all
  560. parser.endLine();
  561. for (int i = 1; i < 7; ++i)
  562. {
  563. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  564. {
  565. parser.readString(); //ignore index
  566. bl.clear();
  567. loadStackExp(b, bl, parser);
  568. for(auto b : bl)
  569. addBonusForTier(i, b);
  570. parser.endLine();
  571. }
  572. }
  573. for (int j = 0; j < 4; ++j) //tier 7
  574. {
  575. parser.readString(); //ignore index
  576. bl.clear();
  577. loadStackExp(b, bl, parser);
  578. for(auto b : bl)
  579. {
  580. addBonusForTier(7, b);
  581. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  582. }
  583. parser.endLine();
  584. }
  585. do //parse everything that's left
  586. {
  587. auto sid = static_cast<ui32>(parser.readNumber()); //id = this particular creature ID
  588. b.sid = sid;
  589. bl.clear();
  590. loadStackExp(b, bl, parser);
  591. for(auto b : bl)
  592. {
  593. objects[sid]->addNewBonus(b); //add directly to CCreature Node
  594. }
  595. }
  596. while (parser.endLine());
  597. //Calculate rank exp values, formula appears complicated bu no parsing needed
  598. expRanks.resize(8);
  599. int dif = 0;
  600. int it = 8000; //ignore name of this variable
  601. expRanks[0].push_back(it);
  602. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  603. {
  604. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  605. dif += it/5;
  606. }
  607. for (int i = 1; i < 8; ++i)
  608. {
  609. dif = 0;
  610. it = 1000 * i;
  611. expRanks[i].push_back(it);
  612. for (int j = 1; j < 10; ++j)
  613. {
  614. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  615. dif += it/5;
  616. }
  617. }
  618. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  619. expBonParser.endLine(); //header
  620. maxExpPerBattle.resize(8);
  621. for (int i = 1; i < 8; ++i)
  622. {
  623. expBonParser.readString(); //index
  624. expBonParser.readString(); //float multiplier -> hardcoded
  625. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  626. expBonParser.readString(); //already calculated
  627. maxExpPerBattle[i] = static_cast<ui32>(expBonParser.readNumber());
  628. expRanks[i].push_back(expRanks[i].back() + (ui32)expBonParser.readNumber());
  629. expBonParser.endLine();
  630. }
  631. //skeleton gets exp penalty
  632. objects[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  633. objects[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  634. //exp for tier >7, rank 11
  635. expRanks[0].push_back(147000);
  636. expAfterUpgrade = 75; //percent
  637. maxExpPerBattle[0] = maxExpPerBattle[7];
  638. }//end of Stack Experience
  639. }
  640. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  641. {
  642. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  643. parser.endLine(); // header
  644. parser.endLine();
  645. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++dd)
  646. {
  647. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  648. ;
  649. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  650. parser.endLine();
  651. }
  652. }
  653. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  654. {
  655. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  656. JsonNode & animationTime = graphics["animationTime"];
  657. animationTime["walk"].Float() = parser.readNumber();
  658. animationTime["attack"].Float() = parser.readNumber();
  659. animationTime["flight"].Float() = parser.readNumber();
  660. animationTime["idle"].Float() = 10.0;
  661. JsonNode & missile = graphics["missile"];
  662. JsonNode & offsets = missile["offset"];
  663. offsets["upperX"].Float() = parser.readNumber();
  664. offsets["upperY"].Float() = parser.readNumber();
  665. offsets["middleX"].Float() = parser.readNumber();
  666. offsets["middleY"].Float() = parser.readNumber();
  667. offsets["lowerX"].Float() = parser.readNumber();
  668. offsets["lowerY"].Float() = parser.readNumber();
  669. for(int i=0; i<12; i++)
  670. {
  671. JsonNode entry;
  672. entry.Float() = parser.readNumber();
  673. missile["frameAngles"].Vector().push_back(entry);
  674. }
  675. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  676. missile["attackClimaxFrame"].Float() = parser.readNumber();
  677. // assume that creature is not a shooter and should not have whole missile field
  678. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  679. missile["attackClimaxFrame"].Float() == 0)
  680. graphics.Struct().erase("missile");
  681. }
  682. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  683. {
  684. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  685. cre->animation.troopCountLocationOffset = static_cast<int>(graphics["troopCountLocationOffset"].Float());
  686. const JsonNode & animationTime = graphics["animationTime"];
  687. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  688. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  689. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  690. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  691. const JsonNode & missile = graphics["missile"];
  692. const JsonNode & offsets = missile["offset"];
  693. cre->animation.upperRightMissleOffsetX = static_cast<int>(offsets["upperX"].Float());
  694. cre->animation.upperRightMissleOffsetY = static_cast<int>(offsets["upperY"].Float());
  695. cre->animation.rightMissleOffsetX = static_cast<int>(offsets["middleX"].Float());
  696. cre->animation.rightMissleOffsetY = static_cast<int>(offsets["middleY"].Float());
  697. cre->animation.lowerRightMissleOffsetX = static_cast<int>(offsets["lowerX"].Float());
  698. cre->animation.lowerRightMissleOffsetY = static_cast<int>(offsets["lowerY"].Float());
  699. cre->animation.attackClimaxFrame = static_cast<int>(missile["attackClimaxFrame"].Float());
  700. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  701. cre->advMapDef = graphics["map"].String();
  702. cre->smallIconName = graphics["iconSmall"].String();
  703. cre->largeIconName = graphics["iconLarge"].String();
  704. }
  705. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  706. {
  707. creature->animDefName = config["graphics"]["animation"].String();
  708. //FIXME: MOD COMPATIBILITY
  709. if (config["abilities"].getType() == JsonNode::JsonType::DATA_STRUCT)
  710. {
  711. for(auto &ability : config["abilities"].Struct())
  712. {
  713. if (!ability.second.isNull())
  714. {
  715. auto b = JsonUtils::parseBonus(ability.second);
  716. b->source = Bonus::CREATURE_ABILITY;
  717. b->sid = creature->getIndex();
  718. b->duration = Bonus::PERMANENT;
  719. creature->addNewBonus(b);
  720. }
  721. }
  722. }
  723. else
  724. {
  725. for(const JsonNode &ability : config["abilities"].Vector())
  726. {
  727. if(ability.getType() == JsonNode::JsonType::DATA_VECTOR)
  728. {
  729. logMod->error("Ignored outdated creature ability format in %s", creature->getJsonKey());
  730. }
  731. else
  732. {
  733. auto b = JsonUtils::parseBonus(ability);
  734. b->source = Bonus::CREATURE_ABILITY;
  735. b->sid = creature->getIndex();
  736. b->duration = Bonus::PERMANENT;
  737. creature->addNewBonus(b);
  738. }
  739. }
  740. }
  741. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  742. {
  743. creature->faction = faction;
  744. });
  745. for(const JsonNode &value : config["upgrades"].Vector())
  746. {
  747. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  748. {
  749. creature->upgrades.insert(CreatureID(identifier));
  750. });
  751. }
  752. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  753. for(const JsonNode & value : config["graphics"]["missile"]["ray"].Vector())
  754. {
  755. CCreature::CreatureAnimation::RayColor color;
  756. color.r1 = value["start"].Vector()[0].Integer();
  757. color.g1 = value["start"].Vector()[1].Integer();
  758. color.b1 = value["start"].Vector()[2].Integer();
  759. color.a1 = value["start"].Vector()[3].Integer();
  760. color.r2 = value["end"].Vector()[0].Integer();
  761. color.g2 = value["end"].Vector()[1].Integer();
  762. color.b2 = value["end"].Vector()[2].Integer();
  763. color.a2 = value["end"].Vector()[3].Integer();
  764. creature->animation.projectileRay.push_back(color);
  765. }
  766. creature->special = config["special"].Bool() || config["disabled"].Bool();
  767. const JsonNode & sounds = config["sound"];
  768. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  769. GET_SOUND_VALUE(attack);
  770. GET_SOUND_VALUE(defend);
  771. GET_SOUND_VALUE(killed);
  772. GET_SOUND_VALUE(move);
  773. GET_SOUND_VALUE(shoot);
  774. GET_SOUND_VALUE(wince);
  775. GET_SOUND_VALUE(startMoving);
  776. GET_SOUND_VALUE(endMoving);
  777. #undef GET_SOUND_VALUE
  778. }
  779. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  780. {
  781. for (const JsonNode &exp : input.Vector())
  782. {
  783. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  784. bonus->source = Bonus::STACK_EXPERIENCE;
  785. bonus->duration = Bonus::PERMANENT;
  786. const JsonVector &values = exp["values"].Vector();
  787. int lowerLimit = 1;//, upperLimit = 255;
  788. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  789. {
  790. for (const JsonNode &val : values)
  791. {
  792. if (val.Bool() == true)
  793. {
  794. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  795. creature->addNewBonus (std::make_shared<Bonus>(*bonus)); //bonuses must be unique objects
  796. break; //TODO: allow bonuses to turn off?
  797. }
  798. ++lowerLimit;
  799. }
  800. }
  801. else
  802. {
  803. int lastVal = 0;
  804. for (const JsonNode &val : values)
  805. {
  806. if (val.Float() != lastVal)
  807. {
  808. bonus->val = (int)val.Float() - lastVal;
  809. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  810. creature->addNewBonus (std::make_shared<Bonus>(*bonus));
  811. }
  812. lastVal = static_cast<int>(val.Float());
  813. ++lowerLimit;
  814. }
  815. }
  816. }
  817. }
  818. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  819. {
  820. bool enable = false; //some bonuses are activated with values 2 or 1
  821. std::string buf = parser.readString();
  822. std::string mod = parser.readString();
  823. switch (buf[0])
  824. {
  825. case 'H':
  826. b.type = Bonus::STACK_HEALTH;
  827. b.valType = Bonus::PERCENT_TO_BASE;
  828. break;
  829. case 'A':
  830. b.type = Bonus::PRIMARY_SKILL;
  831. b.subtype = PrimarySkill::ATTACK;
  832. break;
  833. case 'D':
  834. b.type = Bonus::PRIMARY_SKILL;
  835. b.subtype = PrimarySkill::DEFENSE;
  836. break;
  837. case 'M': //Max damage
  838. b.type = Bonus::CREATURE_DAMAGE;
  839. b.subtype = 2;
  840. break;
  841. case 'm': //Min damage
  842. b.type = Bonus::CREATURE_DAMAGE;
  843. b.subtype = 1;
  844. break;
  845. case 'S':
  846. b.type = Bonus::STACKS_SPEED; break;
  847. case 'O':
  848. b.type = Bonus::SHOTS; break;
  849. case 'b':
  850. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  851. case 'C':
  852. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  853. case 'd':
  854. b.type = Bonus::DEFENSIVE_STANCE; break;
  855. case 'e':
  856. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  857. b.subtype = 0;
  858. break;
  859. case 'E':
  860. b.type = Bonus::DEATH_STARE;
  861. b.subtype = 0; //Gorgon
  862. break;
  863. case 'F':
  864. b.type = Bonus::FEAR; break;
  865. case 'g':
  866. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  867. b.subtype = -1; //all magic schools
  868. break;
  869. case 'P':
  870. b.type = Bonus::CASTS; break;
  871. case 'R':
  872. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  873. case 'W':
  874. b.type = Bonus::MAGIC_RESISTANCE;
  875. b.subtype = 0; //otherwise creature window goes crazy
  876. break;
  877. case 'f': //on-off skill
  878. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  879. switch (mod[0])
  880. {
  881. case 'A':
  882. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  883. case 'b':
  884. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  885. case 'B':
  886. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  887. case 'c':
  888. b.type = Bonus::JOUSTING; break;
  889. case 'D':
  890. b.type = Bonus::ADDITIONAL_ATTACK; break;
  891. case 'f':
  892. b.type = Bonus::FEARLESS; break;
  893. case 'F':
  894. b.type = Bonus::FLYING; break;
  895. case 'm':
  896. b.type = Bonus::SELF_MORALE; break;
  897. case 'M':
  898. b.type = Bonus::NO_MORALE; break;
  899. case 'p': //Mind spells
  900. case 'P':
  901. b.type = Bonus::MIND_IMMUNITY; break;
  902. case 'r':
  903. b.type = Bonus::REBIRTH; //on/off? makes sense?
  904. b.subtype = 0;
  905. b.val = 20; //arbitrary value
  906. break;
  907. case 'R':
  908. b.type = Bonus::BLOCKS_RETALIATION; break;
  909. case 's':
  910. b.type = Bonus::FREE_SHOOTING; break;
  911. case 'u':
  912. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  913. case 'U':
  914. b.type = Bonus::UNDEAD; break;
  915. default:
  916. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  917. return;
  918. break;
  919. }
  920. break;
  921. case 'w': //specific spell immunities, enabled/disabled
  922. enable = true;
  923. switch (mod[0])
  924. {
  925. case 'B': //Blind
  926. b.type = Bonus::SPELL_IMMUNITY;
  927. b.subtype = SpellID::BLIND;
  928. b.additionalInfo = 0;//normal immunity
  929. break;
  930. case 'H': //Hypnotize
  931. b.type = Bonus::SPELL_IMMUNITY;
  932. b.subtype = SpellID::HYPNOTIZE;
  933. b.additionalInfo = 0;//normal immunity
  934. break;
  935. case 'I': //Implosion
  936. b.type = Bonus::SPELL_IMMUNITY;
  937. b.subtype = SpellID::IMPLOSION;
  938. b.additionalInfo = 0;//normal immunity
  939. break;
  940. case 'K': //Berserk
  941. b.type = Bonus::SPELL_IMMUNITY;
  942. b.subtype = SpellID::BERSERK;
  943. b.additionalInfo = 0;//normal immunity
  944. break;
  945. case 'M': //Meteor Shower
  946. b.type = Bonus::SPELL_IMMUNITY;
  947. b.subtype = SpellID::METEOR_SHOWER;
  948. b.additionalInfo = 0;//normal immunity
  949. break;
  950. case 'N': //dispell beneficial spells
  951. b.type = Bonus::SPELL_IMMUNITY;
  952. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  953. b.additionalInfo = 0;//normal immunity
  954. break;
  955. case 'R': //Armageddon
  956. b.type = Bonus::SPELL_IMMUNITY;
  957. b.subtype = SpellID::ARMAGEDDON;
  958. b.additionalInfo = 0;//normal immunity
  959. break;
  960. case 'S': //Slow
  961. b.type = Bonus::SPELL_IMMUNITY;
  962. b.subtype = SpellID::SLOW;
  963. b.additionalInfo = 0;//normal immunity
  964. break;
  965. case '6':
  966. case '7':
  967. case '8':
  968. case '9':
  969. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  970. b.val = std::atoi(mod.c_str()) - 5;
  971. break;
  972. case ':':
  973. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  974. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  975. break;
  976. case 'F':
  977. b.type = Bonus::FIRE_IMMUNITY;
  978. b.subtype = 1; //not positive
  979. break;
  980. case 'O':
  981. b.type = Bonus::FIRE_IMMUNITY;
  982. b.subtype = 2; //only direct damage
  983. break;
  984. case 'f':
  985. b.type = Bonus::FIRE_IMMUNITY;
  986. b.subtype = 0; //all
  987. break;
  988. case 'C':
  989. b.type = Bonus::WATER_IMMUNITY;
  990. b.subtype = 1; //not positive
  991. break;
  992. case 'W':
  993. b.type = Bonus::WATER_IMMUNITY;
  994. b.subtype = 2; //only direct damage
  995. break;
  996. case 'w':
  997. b.type = Bonus::WATER_IMMUNITY;
  998. b.subtype = 0; //all
  999. break;
  1000. case 'E':
  1001. b.type = Bonus::EARTH_IMMUNITY;
  1002. b.subtype = 2; //only direct damage
  1003. break;
  1004. case 'e':
  1005. b.type = Bonus::EARTH_IMMUNITY;
  1006. b.subtype = 0; //all
  1007. break;
  1008. case 'A':
  1009. b.type = Bonus::AIR_IMMUNITY;
  1010. b.subtype = 2; //only direct damage
  1011. break;
  1012. case 'a':
  1013. b.type = Bonus::AIR_IMMUNITY;
  1014. b.subtype = 0; //all
  1015. break;
  1016. case 'D':
  1017. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  1018. break;
  1019. case '0':
  1020. b.type = Bonus::RECEPTIVE;
  1021. break;
  1022. case 'm':
  1023. b.type = Bonus::MIND_IMMUNITY;
  1024. break;
  1025. default:
  1026. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1027. return;
  1028. }
  1029. break;
  1030. case 'i':
  1031. enable = true;
  1032. b.type = Bonus::NO_DISTANCE_PENALTY;
  1033. break;
  1034. case 'o':
  1035. enable = true;
  1036. b.type = Bonus::NO_WALL_PENALTY;
  1037. break;
  1038. case 'a':
  1039. case 'c':
  1040. case 'K':
  1041. case 'k':
  1042. b.type = Bonus::SPELL_AFTER_ATTACK;
  1043. b.subtype = stringToNumber(mod);
  1044. break;
  1045. case 'h':
  1046. b.type= Bonus::HATE;
  1047. b.subtype = stringToNumber(mod);
  1048. break;
  1049. case 'p':
  1050. case 'J':
  1051. b.type = Bonus::SPELL_BEFORE_ATTACK;
  1052. b.subtype = stringToNumber(mod);
  1053. b.additionalInfo = 3; //always expert?
  1054. break;
  1055. case 'r':
  1056. b.type = Bonus::HP_REGENERATION;
  1057. b.val = stringToNumber(mod);
  1058. break;
  1059. case 's':
  1060. b.type = Bonus::ENCHANTED;
  1061. b.subtype = stringToNumber(mod);
  1062. b.valType = Bonus::INDEPENDENT_MAX;
  1063. break;
  1064. default:
  1065. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1066. return;
  1067. break;
  1068. }
  1069. switch (mod[0])
  1070. {
  1071. case '+':
  1072. case '=': //should we allow percent values to stack or pick highest?
  1073. b.valType = Bonus::ADDITIVE_VALUE;
  1074. break;
  1075. }
  1076. //limiters, range
  1077. si32 lastVal, curVal, lastLev = 0;
  1078. if (enable) //0 and 2 means non-active, 1 - active
  1079. {
  1080. if (b.type != Bonus::REBIRTH)
  1081. b.val = 0; //on-off ability, no value specified
  1082. parser.readNumber(); // 0 level is never active
  1083. for (int i = 1; i < 11; ++i)
  1084. {
  1085. curVal = static_cast<si32>(parser.readNumber());
  1086. if (curVal == 1)
  1087. {
  1088. b.limiter.reset (new RankRangeLimiter(i));
  1089. bl.push_back(std::make_shared<Bonus>(b));
  1090. break; //never turned off it seems
  1091. }
  1092. }
  1093. }
  1094. else
  1095. {
  1096. lastVal = static_cast<si32>(parser.readNumber());
  1097. if (b.type == Bonus::HATE)
  1098. lastVal *= 10; //odd fix
  1099. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1100. for (int i = 1; i < 11; ++i)
  1101. {
  1102. curVal = static_cast<si32>(parser.readNumber());
  1103. if (b.type == Bonus::HATE)
  1104. curVal *= 10; //odd fix
  1105. if (curVal > lastVal) //threshold, add new bonus
  1106. {
  1107. b.val = curVal - lastVal;
  1108. lastVal = curVal;
  1109. b.limiter.reset (new RankRangeLimiter(i));
  1110. bl.push_back(std::make_shared<Bonus>(b));
  1111. lastLev = i; //start new range from here, i = previous rank
  1112. }
  1113. else if (curVal < lastVal)
  1114. {
  1115. b.val = lastVal;
  1116. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1117. }
  1118. }
  1119. }
  1120. }
  1121. int CCreatureHandler::stringToNumber(std::string & s)
  1122. {
  1123. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1124. return std::atoi(s.c_str());
  1125. }
  1126. CCreatureHandler::~CCreatureHandler()
  1127. {
  1128. for(auto & p : skillRequirements)
  1129. p.first = nullptr;
  1130. }
  1131. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1132. {
  1133. int r = 0;
  1134. if(tier == -1) //pick any allowed creature
  1135. {
  1136. do
  1137. {
  1138. r = (*RandomGeneratorUtil::nextItem(objects, rand))->idNumber;
  1139. } while (objects[r] && objects[r]->special); // find first "not special" creature
  1140. }
  1141. else
  1142. {
  1143. assert(vstd::iswithin(tier, 1, 7));
  1144. std::vector<CreatureID> allowed;
  1145. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  1146. {
  1147. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  1148. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  1149. if(crea && !crea->special)
  1150. allowed.push_back(crea->idNumber);
  1151. }
  1152. if(!allowed.size())
  1153. {
  1154. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1155. return CreatureID::NONE;
  1156. }
  1157. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1158. }
  1159. assert (r >= 0); //should always be, but it crashed
  1160. return CreatureID(r);
  1161. }
  1162. void CCreatureHandler::addBonusForTier(int tier, const std::shared_ptr<Bonus> & b)
  1163. {
  1164. assert(vstd::iswithin(tier, 1, 7));
  1165. creaturesOfLevel[tier].addNewBonus(b);
  1166. }
  1167. void CCreatureHandler::addBonusForAllCreatures(const std::shared_ptr<Bonus> & b)
  1168. {
  1169. const auto & exportedBonuses = allCreatures.getExportedBonusList();
  1170. for(const auto & bonus : exportedBonuses)
  1171. {
  1172. if(bonus->type == b->type && bonus->subtype == b->subtype)
  1173. return;
  1174. }
  1175. allCreatures.addNewBonus(b);
  1176. }
  1177. void CCreatureHandler::removeBonusesFromAllCreatures()
  1178. {
  1179. allCreatures.removeBonuses(Selector::all);
  1180. }
  1181. void CCreatureHandler::buildBonusTreeForTiers()
  1182. {
  1183. for(CCreature * c : objects)
  1184. {
  1185. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  1186. c->attachTo(creaturesOfLevel[c->level]);
  1187. else
  1188. c->attachTo(creaturesOfLevel[0]);
  1189. }
  1190. for(CBonusSystemNode &b : creaturesOfLevel)
  1191. b.attachTo(allCreatures);
  1192. }
  1193. void CCreatureHandler::afterLoadFinalization()
  1194. {
  1195. }
  1196. void CCreatureHandler::deserializationFix()
  1197. {
  1198. buildBonusTreeForTiers();
  1199. }
  1200. VCMI_LIB_NAMESPACE_END