CCreatureHandler.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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. if(b->effectRange == Bonus::ONLY_ENEMY_ARMY) //Opposite Side bonuses should not be exported from CREATURE node.
  715. b->propagator.reset();
  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. creature->special = config["special"].Bool() || config["disabled"].Bool();
  754. const JsonNode & sounds = config["sound"];
  755. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  756. GET_SOUND_VALUE(attack);
  757. GET_SOUND_VALUE(defend);
  758. GET_SOUND_VALUE(killed);
  759. GET_SOUND_VALUE(move);
  760. GET_SOUND_VALUE(shoot);
  761. GET_SOUND_VALUE(wince);
  762. GET_SOUND_VALUE(startMoving);
  763. GET_SOUND_VALUE(endMoving);
  764. #undef GET_SOUND_VALUE
  765. }
  766. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  767. {
  768. for (const JsonNode &exp : input.Vector())
  769. {
  770. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  771. bonus->source = Bonus::STACK_EXPERIENCE;
  772. bonus->duration = Bonus::PERMANENT;
  773. const JsonVector &values = exp["values"].Vector();
  774. int lowerLimit = 1;//, upperLimit = 255;
  775. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  776. {
  777. for (const JsonNode &val : values)
  778. {
  779. if (val.Bool() == true)
  780. {
  781. bonus->limiter = std::make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  782. creature->addNewBonus (std::make_shared<Bonus>(*bonus)); //bonuses must be unique objects
  783. break; //TODO: allow bonuses to turn off?
  784. }
  785. ++lowerLimit;
  786. }
  787. }
  788. else
  789. {
  790. int lastVal = 0;
  791. for (const JsonNode &val : values)
  792. {
  793. if (val.Float() != lastVal)
  794. {
  795. bonus->val = (int)val.Float() - lastVal;
  796. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  797. creature->addNewBonus (std::make_shared<Bonus>(*bonus));
  798. }
  799. lastVal = static_cast<int>(val.Float());
  800. ++lowerLimit;
  801. }
  802. }
  803. }
  804. }
  805. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  806. {
  807. bool enable = false; //some bonuses are activated with values 2 or 1
  808. std::string buf = parser.readString();
  809. std::string mod = parser.readString();
  810. switch (buf[0])
  811. {
  812. case 'H':
  813. b.type = Bonus::STACK_HEALTH;
  814. b.valType = Bonus::PERCENT_TO_BASE;
  815. break;
  816. case 'A':
  817. b.type = Bonus::PRIMARY_SKILL;
  818. b.subtype = PrimarySkill::ATTACK;
  819. break;
  820. case 'D':
  821. b.type = Bonus::PRIMARY_SKILL;
  822. b.subtype = PrimarySkill::DEFENSE;
  823. break;
  824. case 'M': //Max damage
  825. b.type = Bonus::CREATURE_DAMAGE;
  826. b.subtype = 2;
  827. break;
  828. case 'm': //Min damage
  829. b.type = Bonus::CREATURE_DAMAGE;
  830. b.subtype = 1;
  831. break;
  832. case 'S':
  833. b.type = Bonus::STACKS_SPEED; break;
  834. case 'O':
  835. b.type = Bonus::SHOTS; break;
  836. case 'b':
  837. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  838. case 'C':
  839. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  840. case 'd':
  841. b.type = Bonus::DEFENSIVE_STANCE; break;
  842. case 'e':
  843. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  844. b.subtype = 0;
  845. break;
  846. case 'E':
  847. b.type = Bonus::DEATH_STARE;
  848. b.subtype = 0; //Gorgon
  849. break;
  850. case 'F':
  851. b.type = Bonus::FEAR; break;
  852. case 'g':
  853. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  854. b.subtype = -1; //all magic schools
  855. break;
  856. case 'P':
  857. b.type = Bonus::CASTS; break;
  858. case 'R':
  859. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  860. case 'W':
  861. b.type = Bonus::MAGIC_RESISTANCE;
  862. b.subtype = 0; //otherwise creature window goes crazy
  863. break;
  864. case 'f': //on-off skill
  865. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  866. switch (mod[0])
  867. {
  868. case 'A':
  869. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  870. case 'b':
  871. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  872. case 'B':
  873. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  874. case 'c':
  875. b.type = Bonus::JOUSTING; break;
  876. case 'D':
  877. b.type = Bonus::ADDITIONAL_ATTACK; break;
  878. case 'f':
  879. b.type = Bonus::FEARLESS; break;
  880. case 'F':
  881. b.type = Bonus::FLYING; break;
  882. case 'm':
  883. b.type = Bonus::SELF_MORALE; break;
  884. case 'M':
  885. b.type = Bonus::NO_MORALE; break;
  886. case 'p': //Mind spells
  887. case 'P':
  888. b.type = Bonus::MIND_IMMUNITY; break;
  889. case 'r':
  890. b.type = Bonus::REBIRTH; //on/off? makes sense?
  891. b.subtype = 0;
  892. b.val = 20; //arbitrary value
  893. break;
  894. case 'R':
  895. b.type = Bonus::BLOCKS_RETALIATION; break;
  896. case 's':
  897. b.type = Bonus::FREE_SHOOTING; break;
  898. case 'u':
  899. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  900. case 'U':
  901. b.type = Bonus::UNDEAD; break;
  902. default:
  903. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  904. return;
  905. break;
  906. }
  907. break;
  908. case 'w': //specific spell immunities, enabled/disabled
  909. enable = true;
  910. switch (mod[0])
  911. {
  912. case 'B': //Blind
  913. b.type = Bonus::SPELL_IMMUNITY;
  914. b.subtype = SpellID::BLIND;
  915. b.additionalInfo = 0;//normal immunity
  916. break;
  917. case 'H': //Hypnotize
  918. b.type = Bonus::SPELL_IMMUNITY;
  919. b.subtype = SpellID::HYPNOTIZE;
  920. b.additionalInfo = 0;//normal immunity
  921. break;
  922. case 'I': //Implosion
  923. b.type = Bonus::SPELL_IMMUNITY;
  924. b.subtype = SpellID::IMPLOSION;
  925. b.additionalInfo = 0;//normal immunity
  926. break;
  927. case 'K': //Berserk
  928. b.type = Bonus::SPELL_IMMUNITY;
  929. b.subtype = SpellID::BERSERK;
  930. b.additionalInfo = 0;//normal immunity
  931. break;
  932. case 'M': //Meteor Shower
  933. b.type = Bonus::SPELL_IMMUNITY;
  934. b.subtype = SpellID::METEOR_SHOWER;
  935. b.additionalInfo = 0;//normal immunity
  936. break;
  937. case 'N': //dispell beneficial spells
  938. b.type = Bonus::SPELL_IMMUNITY;
  939. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  940. b.additionalInfo = 0;//normal immunity
  941. break;
  942. case 'R': //Armageddon
  943. b.type = Bonus::SPELL_IMMUNITY;
  944. b.subtype = SpellID::ARMAGEDDON;
  945. b.additionalInfo = 0;//normal immunity
  946. break;
  947. case 'S': //Slow
  948. b.type = Bonus::SPELL_IMMUNITY;
  949. b.subtype = SpellID::SLOW;
  950. b.additionalInfo = 0;//normal immunity
  951. break;
  952. case '6':
  953. case '7':
  954. case '8':
  955. case '9':
  956. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  957. b.val = std::atoi(mod.c_str()) - 5;
  958. break;
  959. case ':':
  960. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  961. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  962. break;
  963. case 'F':
  964. b.type = Bonus::FIRE_IMMUNITY;
  965. b.subtype = 1; //not positive
  966. break;
  967. case 'O':
  968. b.type = Bonus::FIRE_IMMUNITY;
  969. b.subtype = 2; //only direct damage
  970. break;
  971. case 'f':
  972. b.type = Bonus::FIRE_IMMUNITY;
  973. b.subtype = 0; //all
  974. break;
  975. case 'C':
  976. b.type = Bonus::WATER_IMMUNITY;
  977. b.subtype = 1; //not positive
  978. break;
  979. case 'W':
  980. b.type = Bonus::WATER_IMMUNITY;
  981. b.subtype = 2; //only direct damage
  982. break;
  983. case 'w':
  984. b.type = Bonus::WATER_IMMUNITY;
  985. b.subtype = 0; //all
  986. break;
  987. case 'E':
  988. b.type = Bonus::EARTH_IMMUNITY;
  989. b.subtype = 2; //only direct damage
  990. break;
  991. case 'e':
  992. b.type = Bonus::EARTH_IMMUNITY;
  993. b.subtype = 0; //all
  994. break;
  995. case 'A':
  996. b.type = Bonus::AIR_IMMUNITY;
  997. b.subtype = 2; //only direct damage
  998. break;
  999. case 'a':
  1000. b.type = Bonus::AIR_IMMUNITY;
  1001. b.subtype = 0; //all
  1002. break;
  1003. case 'D':
  1004. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  1005. break;
  1006. case '0':
  1007. b.type = Bonus::RECEPTIVE;
  1008. break;
  1009. case 'm':
  1010. b.type = Bonus::MIND_IMMUNITY;
  1011. break;
  1012. default:
  1013. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1014. return;
  1015. }
  1016. break;
  1017. case 'i':
  1018. enable = true;
  1019. b.type = Bonus::NO_DISTANCE_PENALTY;
  1020. break;
  1021. case 'o':
  1022. enable = true;
  1023. b.type = Bonus::NO_WALL_PENALTY;
  1024. break;
  1025. case 'a':
  1026. case 'c':
  1027. case 'K':
  1028. case 'k':
  1029. b.type = Bonus::SPELL_AFTER_ATTACK;
  1030. b.subtype = stringToNumber(mod);
  1031. break;
  1032. case 'h':
  1033. b.type= Bonus::HATE;
  1034. b.subtype = stringToNumber(mod);
  1035. break;
  1036. case 'p':
  1037. case 'J':
  1038. b.type = Bonus::SPELL_BEFORE_ATTACK;
  1039. b.subtype = stringToNumber(mod);
  1040. b.additionalInfo = 3; //always expert?
  1041. break;
  1042. case 'r':
  1043. b.type = Bonus::HP_REGENERATION;
  1044. b.val = stringToNumber(mod);
  1045. break;
  1046. case 's':
  1047. b.type = Bonus::ENCHANTED;
  1048. b.subtype = stringToNumber(mod);
  1049. b.valType = Bonus::INDEPENDENT_MAX;
  1050. break;
  1051. default:
  1052. logGlobal->trace("Not parsed bonus %s %s", buf, mod);
  1053. return;
  1054. break;
  1055. }
  1056. switch (mod[0])
  1057. {
  1058. case '+':
  1059. case '=': //should we allow percent values to stack or pick highest?
  1060. b.valType = Bonus::ADDITIVE_VALUE;
  1061. break;
  1062. }
  1063. //limiters, range
  1064. si32 lastVal, curVal, lastLev = 0;
  1065. if (enable) //0 and 2 means non-active, 1 - active
  1066. {
  1067. if (b.type != Bonus::REBIRTH)
  1068. b.val = 0; //on-off ability, no value specified
  1069. curVal = static_cast<si32>(parser.readNumber());// 0 level is never active
  1070. for (int i = 1; i < 11; ++i)
  1071. {
  1072. curVal = static_cast<si32>(parser.readNumber());
  1073. if (curVal == 1)
  1074. {
  1075. b.limiter.reset (new RankRangeLimiter(i));
  1076. bl.push_back(std::make_shared<Bonus>(b));
  1077. break; //never turned off it seems
  1078. }
  1079. }
  1080. }
  1081. else
  1082. {
  1083. lastVal = static_cast<si32>(parser.readNumber());
  1084. if (b.type == Bonus::HATE)
  1085. lastVal *= 10; //odd fix
  1086. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  1087. for (int i = 1; i < 11; ++i)
  1088. {
  1089. curVal = static_cast<si32>(parser.readNumber());
  1090. if (b.type == Bonus::HATE)
  1091. curVal *= 10; //odd fix
  1092. if (curVal > lastVal) //threshold, add new bonus
  1093. {
  1094. b.val = curVal - lastVal;
  1095. lastVal = curVal;
  1096. b.limiter.reset (new RankRangeLimiter(i));
  1097. bl.push_back(std::make_shared<Bonus>(b));
  1098. lastLev = i; //start new range from here, i = previous rank
  1099. }
  1100. else if (curVal < lastVal)
  1101. {
  1102. b.val = lastVal;
  1103. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  1104. }
  1105. }
  1106. }
  1107. }
  1108. int CCreatureHandler::stringToNumber(std::string & s)
  1109. {
  1110. boost::algorithm::replace_first(s,"#",""); //drop hash character
  1111. return std::atoi(s.c_str());
  1112. }
  1113. CCreatureHandler::~CCreatureHandler()
  1114. {
  1115. for(auto & p : skillRequirements)
  1116. p.first = nullptr;
  1117. }
  1118. CreatureID CCreatureHandler::pickRandomMonster(CRandomGenerator & rand, int tier) const
  1119. {
  1120. int r = 0;
  1121. if(tier == -1) //pick any allowed creature
  1122. {
  1123. do
  1124. {
  1125. r = (*RandomGeneratorUtil::nextItem(objects, rand))->idNumber;
  1126. } while (objects[r] && objects[r]->special); // find first "not special" creature
  1127. }
  1128. else
  1129. {
  1130. assert(vstd::iswithin(tier, 1, 7));
  1131. std::vector<CreatureID> allowed;
  1132. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  1133. {
  1134. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  1135. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  1136. if(crea && !crea->special)
  1137. allowed.push_back(crea->idNumber);
  1138. }
  1139. if(!allowed.size())
  1140. {
  1141. logGlobal->warn("Cannot pick a random creature of tier %d!", tier);
  1142. return CreatureID::NONE;
  1143. }
  1144. return *RandomGeneratorUtil::nextItem(allowed, rand);
  1145. }
  1146. assert (r >= 0); //should always be, but it crashed
  1147. return CreatureID(r);
  1148. }
  1149. void CCreatureHandler::addBonusForTier(int tier, const std::shared_ptr<Bonus> & b)
  1150. {
  1151. assert(vstd::iswithin(tier, 1, 7));
  1152. creaturesOfLevel[tier].addNewBonus(b);
  1153. }
  1154. void CCreatureHandler::addBonusForAllCreatures(const std::shared_ptr<Bonus> & b)
  1155. {
  1156. const auto & exportedBonuses = allCreatures.getExportedBonusList();
  1157. for(const auto & bonus : exportedBonuses)
  1158. {
  1159. if(bonus->type == b->type && bonus->subtype == b->subtype)
  1160. return;
  1161. }
  1162. allCreatures.addNewBonus(b);
  1163. }
  1164. void CCreatureHandler::removeBonusesFromAllCreatures()
  1165. {
  1166. allCreatures.removeBonuses(Selector::all);
  1167. }
  1168. void CCreatureHandler::restoreAllCreaturesNodeType794()
  1169. {
  1170. allCreatures.setNodeType(CBonusSystemNode::ENodeTypes::ALL_CREATURES);
  1171. }
  1172. void CCreatureHandler::buildBonusTreeForTiers()
  1173. {
  1174. for(CCreature * c : objects)
  1175. {
  1176. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  1177. c->attachTo(&creaturesOfLevel[c->level]);
  1178. else
  1179. c->attachTo(&creaturesOfLevel[0]);
  1180. }
  1181. for(CBonusSystemNode &b : creaturesOfLevel)
  1182. b.attachTo(&allCreatures);
  1183. }
  1184. void CCreatureHandler::afterLoadFinalization()
  1185. {
  1186. }
  1187. void CCreatureHandler::deserializationFix()
  1188. {
  1189. buildBonusTreeForTiers();
  1190. }