CCreatureHandler.cpp 38 KB

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