CCreatureHandler.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  1. #include "StdInc.h"
  2. #include "CCreatureHandler.h"
  3. #include "CGeneralTextHandler.h"
  4. #include "filesystem/Filesystem.h"
  5. #include "VCMI_Lib.h"
  6. #include "CGameState.h"
  7. #include "CTownHandler.h"
  8. #include "CModHandler.h"
  9. #include "StringConstants.h"
  10. using namespace boost::assign;
  11. /*
  12. * CCreatureHandler.cpp, part of VCMI engine
  13. *
  14. * Authors: listed in file AUTHORS in main folder
  15. *
  16. * License: GNU General Public License v2.0 or later
  17. * Full text of license available in license.txt file, in main folder
  18. *
  19. */
  20. int CCreature::getQuantityID(const int & quantity)
  21. {
  22. if (quantity<5)
  23. return 1;
  24. if (quantity<10)
  25. return 2;
  26. if (quantity<20)
  27. return 3;
  28. if (quantity<50)
  29. return 4;
  30. if (quantity<100)
  31. return 5;
  32. if (quantity<250)
  33. return 6;
  34. if (quantity<500)
  35. return 7;
  36. if (quantity<1000)
  37. return 8;
  38. return 9;
  39. }
  40. int CCreature::estimateCreatureCount(ui32 countID)
  41. {
  42. static const int creature_count[] = { 0, 3, 8, 15, 35, 75, 175, 375, 750, 2500 };
  43. if (countID > 9)
  44. assert("Wrong countID!");
  45. return creature_count[countID];
  46. }
  47. bool CCreature::isDoubleWide() const
  48. {
  49. return doubleWide;
  50. }
  51. bool CCreature::isFlying() const
  52. {
  53. return hasBonusOfType(Bonus::FLYING);
  54. }
  55. bool CCreature::isShooting() const
  56. {
  57. return hasBonusOfType(Bonus::SHOOTER);
  58. }
  59. bool CCreature::isUndead() const
  60. {
  61. return hasBonusOfType(Bonus::UNDEAD);
  62. }
  63. /**
  64. * Determines if the creature is of a good alignment.
  65. * @return true if the creture is good, false otherwise.
  66. */
  67. bool CCreature::isGood () const
  68. {
  69. return VLC->townh->factions[faction]->alignment == EAlignment::GOOD;
  70. }
  71. /**
  72. * Determines if the creature is of an evil alignment.
  73. * @return true if the creature is evil, false otherwise.
  74. */
  75. bool CCreature::isEvil () const
  76. {
  77. return VLC->townh->factions[faction]->alignment == EAlignment::EVIL;
  78. }
  79. si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
  80. {
  81. int ret = 2147483645;
  82. int resAmnt = std::min(res.size(),cost.size());
  83. for(int i=0;i<resAmnt;i++)
  84. if(cost[i])
  85. ret = std::min(ret,(int)(res[i]/cost[i]));
  86. return ret;
  87. }
  88. CCreature::CCreature()
  89. {
  90. doubleWide = false;
  91. setNodeType(CBonusSystemNode::CREATURE);
  92. }
  93. void CCreature::addBonus(int val, Bonus::BonusType type, int subtype /*= -1*/)
  94. {
  95. auto added = new Bonus(Bonus::PERMANENT, type, Bonus::CREATURE_ABILITY, val, idNumber, subtype, Bonus::BASE_NUMBER);
  96. addNewBonus(added);
  97. }
  98. bool CCreature::isMyUpgrade(const CCreature *anotherCre) const
  99. {
  100. //TODO upgrade of upgrade?
  101. return vstd::contains(upgrades, anotherCre->idNumber);
  102. }
  103. bool CCreature::valid() const
  104. {
  105. return this == VLC->creh->creatures[idNumber];
  106. }
  107. std::string CCreature::nodeName() const
  108. {
  109. return "\"" + namePl + "\"";
  110. }
  111. bool CCreature::isItNativeTerrain(int terrain) const
  112. {
  113. return VLC->townh->factions[faction]->nativeTerrain == terrain;
  114. }
  115. void CCreature::setId(CreatureID ID)
  116. {
  117. idNumber = ID;
  118. for(auto bonus : getExportedBonusList())
  119. {
  120. if(bonus->source == Bonus::CREATURE_ABILITY)
  121. bonus->sid = ID;
  122. }
  123. }
  124. static void AddAbility(CCreature *cre, const JsonVector &ability_vec)
  125. {
  126. auto nsf = new Bonus();
  127. std::string type = ability_vec[0].String();
  128. auto it = bonusNameMap.find(type);
  129. if (it == bonusNameMap.end()) {
  130. if (type == "DOUBLE_WIDE")
  131. cre->doubleWide = true;
  132. else if (type == "ENEMY_MORALE_DECREASING") {
  133. cre->addBonus(-1, Bonus::MORALE);
  134. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  135. }
  136. else if (type == "ENEMY_LUCK_DECREASING") {
  137. cre->addBonus(-1, Bonus::LUCK);
  138. cre->getBonusList().back()->effectRange = Bonus::ONLY_ENEMY_ARMY;
  139. } else
  140. logGlobal->errorStream() << "Error: invalid ability type " << type << " in creatures config";
  141. return;
  142. }
  143. nsf->type = it->second;
  144. JsonUtils::parseTypedBonusShort(ability_vec,nsf);
  145. nsf->source = Bonus::CREATURE_ABILITY;
  146. nsf->sid = cre->idNumber;
  147. cre->addNewBonus(nsf);
  148. }
  149. CCreatureHandler::CCreatureHandler()
  150. {
  151. VLC->creh = this;
  152. allCreatures.setDescription("All creatures");
  153. creaturesOfLevel[0].setDescription("Creatures of unnormalized tier");
  154. for(int i = 1; i < ARRAY_COUNT(creaturesOfLevel); i++)
  155. creaturesOfLevel[i].setDescription("Creatures of tier " + boost::lexical_cast<std::string>(i));
  156. loadCommanders();
  157. }
  158. void CCreatureHandler::loadCommanders()
  159. {
  160. JsonNode data(ResourceID("config/commanders.json"));
  161. data.setMeta("core"); // assume that commanders are in core mod (for proper bonuses resolution)
  162. const JsonNode & config = data; // switch to const data accessors
  163. for (auto bonus : config["bonusPerLevel"].Vector())
  164. {
  165. commanderLevelPremy.push_back(JsonUtils::parseBonus (bonus.Vector()));
  166. }
  167. int i = 0;
  168. for (auto skill : config["skillLevels"].Vector())
  169. {
  170. skillLevels.push_back (std::vector<ui8>());
  171. for (auto skillLevel : skill["levels"].Vector())
  172. {
  173. skillLevels[i].push_back (skillLevel.Float());
  174. }
  175. ++i;
  176. }
  177. for (auto ability : config["abilityRequirements"].Vector())
  178. {
  179. std::pair <Bonus*, std::pair <ui8, ui8> > a;
  180. a.first = JsonUtils::parseBonus (ability["ability"].Vector());
  181. a.second.first = ability["skills"].Vector()[0].Float();
  182. a.second.second = ability["skills"].Vector()[1].Float();
  183. skillRequirements.push_back (a);
  184. }
  185. }
  186. void CCreatureHandler::loadBonuses(JsonNode & creature, std::string bonuses)
  187. {
  188. auto makeBonusNode = [&](std::string type) -> JsonNode
  189. {
  190. JsonNode ret;
  191. ret["type"].String() = type;
  192. return ret;
  193. };
  194. static const std::map<std::string, JsonNode> abilityMap =
  195. boost::assign::map_list_of
  196. ("FLYING_ARMY", makeBonusNode("FLYING"))
  197. ("SHOOTING_ARMY", makeBonusNode("SHOOTER"))
  198. ("SIEGE_WEAPON", makeBonusNode("SIEGE_WEAPON"))
  199. ("const_free_attack", makeBonusNode("BLOCKS_RETALIATION"))
  200. ("IS_UNDEAD", makeBonusNode("UNDEAD"))
  201. ("const_no_melee_penalty", makeBonusNode("NO_MELEE_PENALTY"))
  202. ("const_jousting", makeBonusNode("JOUSTING"))
  203. ("KING_1", makeBonusNode("KING1"))
  204. ("KING_2", makeBonusNode("KING2"))
  205. ("KING_3", makeBonusNode("KING3"))
  206. ("const_no_wall_penalty", makeBonusNode("NO_WALL_PENALTY"))
  207. ("CATAPULT", makeBonusNode("CATAPULT"))
  208. ("MULTI_HEADED", makeBonusNode("ATTACKS_ALL_ADJACENT"))
  209. ("IMMUNE_TO_MIND_SPELLS", makeBonusNode("MIND_IMMUNITY"))
  210. ("HAS_EXTENDED_ATTACK", makeBonusNode("TWO_HEX_ATTACK_BREATH"));
  211. auto hasAbility = [&](const std::string name) -> bool
  212. {
  213. return boost::algorithm::find_first(bonuses, name);
  214. };
  215. for(auto a : abilityMap)
  216. {
  217. if(hasAbility(a.first))
  218. creature["abilities"][a.first] = a.second;
  219. }
  220. if(hasAbility("DOUBLE_WIDE"))
  221. creature["doubleWide"].Bool() = true;
  222. if(hasAbility("const_raises_morale"))
  223. {
  224. JsonNode node = makeBonusNode("MORALE");
  225. node["val"].Float() = 1;
  226. node["propagator"].String() = "HERO";
  227. creature["abilities"]["const_raises_morale"] = node;
  228. }
  229. if(hasAbility("const_lowers_morale"))
  230. {
  231. JsonNode node = makeBonusNode("MORALE");
  232. node["val"].Float() = -1;
  233. node["effectRange"].String() = "ONLY_ENEMY_ARMY";
  234. creature["abilities"]["const_lowers_morale"] = node;
  235. }
  236. }
  237. std::vector<JsonNode> CCreatureHandler::loadLegacyData(size_t dataSize)
  238. {
  239. creatures.resize(dataSize);
  240. std::vector<JsonNode> h3Data;
  241. h3Data.reserve(dataSize);
  242. CLegacyConfigParser parser("DATA/CRTRAITS.TXT");
  243. parser.endLine(); // header
  244. // this file is a bit different in some of Russian localisations:
  245. //ENG: Singular Plural Wood ...
  246. //RUS: Singular Plural Plural2 Wood ...
  247. // Try to detect which version this is by header
  248. // TODO: use 3rd name? Stand for "whose", e.g. pikemans'
  249. size_t namesCount;
  250. {
  251. if ( parser.readString() != "Singular" || parser.readString() != "Plural" )
  252. throw std::runtime_error("Incorrect format of CrTraits.txt");
  253. if (parser.readString() == "Plural2")
  254. namesCount = 3;
  255. else
  256. namesCount = 2;
  257. parser.endLine();
  258. }
  259. for (size_t i=0; i<dataSize; i++)
  260. {
  261. //loop till non-empty line
  262. while (parser.isNextEntryEmpty())
  263. parser.endLine();
  264. JsonNode data;
  265. data["name"]["singular"].String() = parser.readString();
  266. if (namesCount == 3)
  267. parser.readString();
  268. data["name"]["plural"].String() = parser.readString();
  269. for(int v=0; v<7; ++v)
  270. data["cost"][GameConstants::RESOURCE_NAMES[v]].Float() = parser.readNumber();
  271. data["fightValue"].Float() = parser.readNumber();
  272. data["aiValue"].Float() = parser.readNumber();
  273. data["growth"].Float() = parser.readNumber();
  274. data["horde"].Float() = parser.readNumber();
  275. data["hitPoints"].Float() = parser.readNumber();
  276. data["speed"].Float() = parser.readNumber();
  277. data["attack"].Float() = parser.readNumber();
  278. data["defense"].Float() = parser.readNumber();
  279. data["damage"]["min"].Float() = parser.readNumber();
  280. data["damage"]["max"].Float() = parser.readNumber();
  281. if (float shots = parser.readNumber())
  282. data["shots"].Float() = shots;
  283. if (float spells = parser.readNumber())
  284. data["spellPoints"].Float() = spells;
  285. data["advMapAmount"]["min"].Float() = parser.readNumber();
  286. data["advMapAmount"]["max"].Float() = parser.readNumber();
  287. data["abilityText"].String() = parser.readString();
  288. loadBonuses(data, parser.readString()); //Attributes
  289. h3Data.push_back(data);
  290. }
  291. loadAnimationInfo(h3Data);
  292. return h3Data;
  293. }
  294. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data)
  295. {
  296. auto object = loadFromJson(data);
  297. object->setId(CreatureID(creatures.size()));
  298. object->iconIndex = object->idNumber + 2;
  299. creatures.push_back(object);
  300. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  301. for(auto node : data["extraNames"].Vector())
  302. {
  303. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  304. }
  305. }
  306. void CCreatureHandler::loadObject(std::string scope, std::string name, const JsonNode & data, size_t index)
  307. {
  308. auto object = loadFromJson(data);
  309. object->setId(CreatureID(index));
  310. object->iconIndex = object->idNumber + 2;
  311. if(data["hasDoubleWeek"].Bool()) //
  312. {
  313. doubledCreatures.insert (object->idNumber); //we need to have id (or identifier) before it is inserted
  314. }
  315. assert(creatures[index] == nullptr); // ensure that this id was not loaded before
  316. creatures[index] = object;
  317. VLC->modh->identifiers.registerObject(scope, "creature", name, object->idNumber);
  318. for(auto & node : data["extraNames"].Vector())
  319. {
  320. VLC->modh->identifiers.registerObject(scope, "creature", node.String(), object->idNumber);
  321. }
  322. }
  323. std::vector<bool> CCreatureHandler::getDefaultAllowed() const
  324. {
  325. std::vector<bool> ret;
  326. for(const CCreature * crea : creatures)
  327. {
  328. ret.push_back(crea ? !crea->special : false);
  329. }
  330. return ret;
  331. }
  332. void CCreatureHandler::loadCrExpBon()
  333. {
  334. if (VLC->modh->modules.STACK_EXP) //reading default stack experience bonuses
  335. {
  336. CLegacyConfigParser parser("DATA/CREXPBON.TXT");
  337. Bonus b; //prototype with some default properties
  338. b.source = Bonus::STACK_EXPERIENCE;
  339. b.duration = Bonus::PERMANENT;
  340. b.valType = Bonus::ADDITIVE_VALUE;
  341. b.effectRange = Bonus::NO_LIMIT;
  342. b.additionalInfo = 0;
  343. b.turnsRemain = 0;
  344. BonusList bl;
  345. parser.endLine();
  346. parser.readString(); //ignore index
  347. loadStackExp(b, bl, parser);
  348. for(Bonus * b : bl)
  349. addBonusForAllCreatures(b); //health bonus is common for all
  350. parser.endLine();
  351. for (int i = 1; i < 7; ++i)
  352. {
  353. for (int j = 0; j < 4; ++j) //four modifiers common for tiers
  354. {
  355. parser.readString(); //ignore index
  356. bl.clear();
  357. loadStackExp(b, bl, parser);
  358. for(Bonus * b : bl)
  359. addBonusForTier(i, b);
  360. parser.endLine();
  361. }
  362. }
  363. for (int j = 0; j < 4; ++j) //tier 7
  364. {
  365. parser.readString(); //ignore index
  366. bl.clear();
  367. loadStackExp(b, bl, parser);
  368. for(Bonus * b : bl)
  369. {
  370. addBonusForTier(7, b);
  371. creaturesOfLevel[0].addNewBonus(b); //bonuses from level 7 are given to high-level creatures
  372. }
  373. parser.endLine();
  374. }
  375. do //parse everything that's left
  376. {
  377. b.sid = parser.readNumber(); //id = this particular creature ID
  378. loadStackExp(b, creatures[b.sid]->getBonusList(), parser); //add directly to CCreature Node
  379. }
  380. while (parser.endLine());
  381. //Calculate rank exp values, formula appears complicated bu no parsing needed
  382. expRanks.resize(8);
  383. int dif = 0;
  384. int it = 8000; //ignore name of this variable
  385. expRanks[0].push_back(it);
  386. for (int j = 1; j < 10; ++j) //used for tiers 8-10, and all other probably
  387. {
  388. expRanks[0].push_back(expRanks[0][j-1] + it + dif);
  389. dif += it/5;
  390. }
  391. for (int i = 1; i < 8; ++i)
  392. {
  393. dif = 0;
  394. it = 1000 * i;
  395. expRanks[i].push_back(it);
  396. for (int j = 1; j < 10; ++j)
  397. {
  398. expRanks[i].push_back(expRanks[i][j-1] + it + dif);
  399. dif += it/5;
  400. }
  401. }
  402. CLegacyConfigParser expBonParser("DATA/CREXPMOD.TXT");
  403. expBonParser.endLine(); //header
  404. maxExpPerBattle.resize(8);
  405. for (int i = 1; i < 8; ++i)
  406. {
  407. expBonParser.readString(); //index
  408. expBonParser.readString(); //float multiplier -> hardcoded
  409. expBonParser.readString(); //ignore upgrade mod? ->hardcoded
  410. expBonParser.readString(); //already calculated
  411. maxExpPerBattle[i] = expBonParser.readNumber();
  412. expRanks[i].push_back(expRanks[i].back() + expBonParser.readNumber());
  413. expBonParser.endLine();
  414. }
  415. //skeleton gets exp penalty
  416. creatures[56].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  417. creatures[57].get()->addBonus(-50, Bonus::EXP_MULTIPLIER, -1);
  418. //exp for tier >7, rank 11
  419. expRanks[0].push_back(147000);
  420. expAfterUpgrade = 75; //percent
  421. maxExpPerBattle[0] = maxExpPerBattle[7];
  422. }//end of Stack Experience
  423. }
  424. void CCreatureHandler::loadAnimationInfo(std::vector<JsonNode> &h3Data)
  425. {
  426. CLegacyConfigParser parser("DATA/CRANIM.TXT");
  427. parser.endLine(); // header
  428. parser.endLine();
  429. for(int dd=0; dd<VLC->modh->settings.data["textData"]["creature"].Float(); ++dd)
  430. {
  431. while (parser.isNextEntryEmpty() && parser.endLine()) // skip empty lines
  432. ;
  433. loadUnitAnimInfo(h3Data[dd]["graphics"], parser);
  434. parser.endLine();
  435. }
  436. }
  437. void CCreatureHandler::loadUnitAnimInfo(JsonNode & graphics, CLegacyConfigParser & parser)
  438. {
  439. graphics["timeBetweenFidgets"].Float() = parser.readNumber();
  440. JsonNode & animationTime = graphics["animationTime"];
  441. animationTime["walk"].Float() = parser.readNumber();
  442. animationTime["attack"].Float() = parser.readNumber();
  443. animationTime["flight"].Float() = parser.readNumber();
  444. animationTime["idle"].Float() = 10.0;
  445. JsonNode & missile = graphics["missile"];
  446. JsonNode & offsets = missile["offset"];
  447. offsets["upperX"].Float() = parser.readNumber();
  448. offsets["upperY"].Float() = parser.readNumber();
  449. offsets["middleX"].Float() = parser.readNumber();
  450. offsets["middleY"].Float() = parser.readNumber();
  451. offsets["lowerX"].Float() = parser.readNumber();
  452. offsets["lowerY"].Float() = parser.readNumber();
  453. for(int i=0; i<12; i++)
  454. {
  455. JsonNode entry;
  456. entry.Float() = parser.readNumber();
  457. missile["frameAngles"].Vector().push_back(entry);
  458. }
  459. graphics["troopCountLocationOffset"].Float() = parser.readNumber();
  460. missile["attackClimaxFrame"].Float() = parser.readNumber();
  461. // assume that creature is not a shooter and should not have whole missile field
  462. if (missile["frameAngles"].Vector()[0].Float() == 0 &&
  463. missile["attackClimaxFrame"].Float() == 0)
  464. graphics.Struct().erase("missile");
  465. }
  466. CCreature * CCreatureHandler::loadFromJson(const JsonNode & node)
  467. {
  468. auto cre = new CCreature();
  469. const JsonNode & name = node["name"];
  470. cre->nameSing = name["singular"].String();
  471. cre->namePl = name["plural"].String();
  472. cre->cost = Res::ResourceSet(node["cost"]);
  473. cre->fightValue = node["fightValue"].Float();
  474. cre->AIValue = node["aiValue"].Float();
  475. cre->growth = node["growth"].Float();
  476. cre->hordeGrowth = node["horde"].Float(); // Needed at least until configurable buildings
  477. cre->addBonus(node["hitPoints"].Float(), Bonus::STACK_HEALTH);
  478. cre->addBonus(node["speed"].Float(), Bonus::STACKS_SPEED);
  479. cre->addBonus(node["attack"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK);
  480. cre->addBonus(node["defense"].Float(), Bonus::PRIMARY_SKILL, PrimarySkill::DEFENSE);
  481. cre->addBonus(node["damage"]["min"].Float(), Bonus::CREATURE_DAMAGE, 1);
  482. cre->addBonus(node["damage"]["max"].Float(), Bonus::CREATURE_DAMAGE, 2);
  483. assert(node["damage"]["min"].Float() <= node["damage"]["max"].Float());
  484. cre->ammMin = node["advMapAmount"]["min"].Float();
  485. cre->ammMax = node["advMapAmount"]["max"].Float();
  486. assert(cre->ammMin <= cre->ammMax);
  487. if (!node["shots"].isNull())
  488. cre->addBonus(node["shots"].Float(), Bonus::SHOTS);
  489. if (node["spellPoints"].isNull())
  490. cre->addBonus(node["spellPoints"].Float(), Bonus::CASTS);
  491. cre->doubleWide = node["doubleWide"].Bool();
  492. loadStackExperience(cre, node["stackExperience"]);
  493. loadJsonAnimation(cre, node["graphics"]);
  494. loadCreatureJson(cre, node);
  495. return cre;
  496. }
  497. void CCreatureHandler::loadJsonAnimation(CCreature * cre, const JsonNode & graphics)
  498. {
  499. cre->animation.timeBetweenFidgets = graphics["timeBetweenFidgets"].Float();
  500. cre->animation.troopCountLocationOffset = graphics["troopCountLocationOffset"].Float();
  501. const JsonNode & animationTime = graphics["animationTime"];
  502. cre->animation.walkAnimationTime = animationTime["walk"].Float();
  503. cre->animation.idleAnimationTime = animationTime["idle"].Float();
  504. cre->animation.attackAnimationTime = animationTime["attack"].Float();
  505. cre->animation.flightAnimationDistance = animationTime["flight"].Float(); //?
  506. const JsonNode & missile = graphics["missile"];
  507. const JsonNode & offsets = missile["offset"];
  508. cre->animation.upperRightMissleOffsetX = offsets["upperX"].Float();
  509. cre->animation.upperRightMissleOffsetY = offsets["upperY"].Float();
  510. cre->animation.rightMissleOffsetX = offsets["middleX"].Float();
  511. cre->animation.rightMissleOffsetY = offsets["middleY"].Float();
  512. cre->animation.lowerRightMissleOffsetX = offsets["lowerX"].Float();
  513. cre->animation.lowerRightMissleOffsetY = offsets["lowerY"].Float();
  514. cre->animation.attackClimaxFrame = missile["attackClimaxFrame"].Float();
  515. cre->animation.missleFrameAngles = missile["frameAngles"].convertTo<std::vector<double> >();
  516. cre->advMapDef = graphics["map"].String();
  517. cre->smallIconName = graphics["iconSmall"].String();
  518. cre->largeIconName = graphics["iconLarge"].String();
  519. }
  520. void CCreatureHandler::loadCreatureJson(CCreature * creature, const JsonNode & config)
  521. {
  522. creature->level = config["level"].Float();
  523. creature->animDefName = config["graphics"]["animation"].String();
  524. //FIXME: MOD COMPATIBILITY
  525. if (config["abilities"].getType() == JsonNode::DATA_STRUCT)
  526. {
  527. for(auto &ability : config["abilities"].Struct())
  528. {
  529. if (!ability.second.isNull())
  530. {
  531. auto b = JsonUtils::parseBonus(ability.second);
  532. b->source = Bonus::CREATURE_ABILITY;
  533. b->duration = Bonus::PERMANENT;
  534. creature->addNewBonus(b);
  535. }
  536. }
  537. }
  538. else
  539. {
  540. for(const JsonNode &ability : config["abilities"].Vector())
  541. {
  542. if (ability.getType() == JsonNode::DATA_VECTOR)
  543. {
  544. assert(0); // should be unused now
  545. AddAbility(creature, ability.Vector()); // used only for H3 creatures
  546. }
  547. else
  548. {
  549. auto b = JsonUtils::parseBonus(ability);
  550. b->source = Bonus::CREATURE_ABILITY;
  551. b->duration = Bonus::PERMANENT;
  552. creature->addNewBonus(b);
  553. }
  554. }
  555. }
  556. VLC->modh->identifiers.requestIdentifier("faction", config["faction"], [=](si32 faction)
  557. {
  558. creature->faction = faction;
  559. });
  560. for(const JsonNode &value : config["upgrades"].Vector())
  561. {
  562. VLC->modh->identifiers.requestIdentifier("creature", value, [=](si32 identifier)
  563. {
  564. creature->upgrades.insert(CreatureID(identifier));
  565. });
  566. }
  567. creature->animation.projectileImageName = config["graphics"]["missile"]["projectile"].String();
  568. creature->special = config["special"].Bool() || config["disabled"].Bool();
  569. const JsonNode & sounds = config["sound"];
  570. #define GET_SOUND_VALUE(value_name) creature->sounds.value_name = sounds[#value_name].String()
  571. GET_SOUND_VALUE(attack);
  572. GET_SOUND_VALUE(defend);
  573. GET_SOUND_VALUE(killed);
  574. GET_SOUND_VALUE(move);
  575. GET_SOUND_VALUE(shoot);
  576. GET_SOUND_VALUE(wince);
  577. GET_SOUND_VALUE(startMoving);
  578. GET_SOUND_VALUE(endMoving);
  579. #undef GET_SOUND_VALUE
  580. }
  581. void CCreatureHandler::loadStackExperience(CCreature * creature, const JsonNode & input)
  582. {
  583. for (const JsonNode &exp : input.Vector())
  584. {
  585. auto bonus = JsonUtils::parseBonus (exp["bonus"]);
  586. bonus->source = Bonus::STACK_EXPERIENCE;
  587. bonus->duration = Bonus::PERMANENT;
  588. const JsonVector &values = exp["values"].Vector();
  589. int lowerLimit = 1;//, upperLimit = 255;
  590. if (values[0].getType() == JsonNode::JsonType::DATA_BOOL)
  591. {
  592. for (const JsonNode &val : values)
  593. {
  594. if (val.Bool() == true)
  595. {
  596. bonus->limiter = make_shared<RankRangeLimiter>(RankRangeLimiter(lowerLimit));
  597. creature->addNewBonus (new Bonus(*bonus)); //bonuses must be unique objects
  598. break; //TODO: allow bonuses to turn off?
  599. }
  600. ++lowerLimit;
  601. }
  602. }
  603. else
  604. {
  605. int lastVal = 0;
  606. for (const JsonNode &val : values)
  607. {
  608. if (val.Float() != lastVal)
  609. {
  610. bonus->val = val.Float() - lastVal;
  611. bonus->limiter.reset (new RankRangeLimiter(lowerLimit));
  612. creature->addNewBonus (new Bonus(*bonus));
  613. }
  614. lastVal = val.Float();
  615. ++lowerLimit;
  616. }
  617. }
  618. delete bonus;
  619. }
  620. }
  621. void CCreatureHandler::loadStackExp(Bonus & b, BonusList & bl, CLegacyConfigParser & parser) //help function for parsing CREXPBON.txt
  622. {
  623. bool enable = false; //some bonuses are activated with values 2 or 1
  624. std::string buf = parser.readString();
  625. std::string mod = parser.readString();
  626. switch (buf[0])
  627. {
  628. case 'H':
  629. b.type = Bonus::STACK_HEALTH;
  630. b.valType = Bonus::PERCENT_TO_BASE;
  631. break;
  632. case 'A':
  633. b.type = Bonus::PRIMARY_SKILL;
  634. b.subtype = PrimarySkill::ATTACK;
  635. break;
  636. case 'D':
  637. b.type = Bonus::PRIMARY_SKILL;
  638. b.subtype = PrimarySkill::DEFENSE;
  639. break;
  640. case 'M': //Max damage
  641. b.type = Bonus::CREATURE_DAMAGE;
  642. b.subtype = 2;
  643. break;
  644. case 'm': //Min damage
  645. b.type = Bonus::CREATURE_DAMAGE;
  646. b.subtype = 1;
  647. break;
  648. case 'S':
  649. b.type = Bonus::STACKS_SPEED; break;
  650. case 'O':
  651. b.type = Bonus::SHOTS; break;
  652. case 'b':
  653. b.type = Bonus::ENEMY_DEFENCE_REDUCTION; break;
  654. case 'C':
  655. b.type = Bonus::CHANGES_SPELL_COST_FOR_ALLY; break;
  656. case 'd':
  657. b.type = Bonus::DEFENSIVE_STANCE; break;
  658. case 'e':
  659. b.type = Bonus::DOUBLE_DAMAGE_CHANCE;
  660. b.subtype = 0;
  661. break;
  662. case 'E':
  663. b.type = Bonus::DEATH_STARE;
  664. b.subtype = 0; //Gorgon
  665. break;
  666. case 'F':
  667. b.type = Bonus::FEAR; break;
  668. case 'g':
  669. b.type = Bonus::SPELL_DAMAGE_REDUCTION;
  670. b.subtype = -1; //all magic schools
  671. break;
  672. case 'P':
  673. b.type = Bonus::CASTS; break;
  674. case 'R':
  675. b.type = Bonus::ADDITIONAL_RETALIATION; break;
  676. case 'W':
  677. b.type = Bonus::MAGIC_RESISTANCE;
  678. b.subtype = 0; //otherwise creature window goes crazy
  679. break;
  680. case 'f': //on-off skill
  681. enable = true; //sometimes format is: 2 -> 0, 1 -> 1
  682. switch (mod[0])
  683. {
  684. case 'A':
  685. b.type = Bonus::ATTACKS_ALL_ADJACENT; break;
  686. case 'b':
  687. b.type = Bonus::RETURN_AFTER_STRIKE; break;
  688. case 'B':
  689. b.type = Bonus::TWO_HEX_ATTACK_BREATH; break;
  690. case 'c':
  691. b.type = Bonus::JOUSTING; break;
  692. case 'D':
  693. b.type = Bonus::ADDITIONAL_ATTACK; break;
  694. case 'f':
  695. b.type = Bonus::FEARLESS; break;
  696. case 'F':
  697. b.type = Bonus::FLYING; break;
  698. case 'm':
  699. b.type = Bonus::SELF_MORALE; break;
  700. case 'M':
  701. b.type = Bonus::NO_MORALE; break;
  702. case 'p': //Mind spells
  703. case 'P':
  704. b.type = Bonus::MIND_IMMUNITY; break;
  705. case 'r':
  706. b.type = Bonus::REBIRTH; //on/off? makes sense?
  707. b.subtype = 0;
  708. b.val = 20; //arbitrary value
  709. break;
  710. case 'R':
  711. b.type = Bonus::BLOCKS_RETALIATION; break;
  712. case 's':
  713. b.type = Bonus::FREE_SHOOTING; break;
  714. case 'u':
  715. b.type = Bonus::SPELL_RESISTANCE_AURA; break;
  716. case 'U':
  717. b.type = Bonus::UNDEAD; break;
  718. default:
  719. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  720. return;
  721. break;
  722. }
  723. break;
  724. case 'w': //specific spell immunities, enabled/disabled
  725. enable = true;
  726. switch (mod[0])
  727. {
  728. case 'B': //Blind
  729. b.type = Bonus::SPELL_IMMUNITY;
  730. b.subtype = SpellID::BLIND;
  731. break;
  732. case 'H': //Hypnotize
  733. b.type = Bonus::SPELL_IMMUNITY;
  734. b.subtype = SpellID::HYPNOTIZE;
  735. break;
  736. case 'I': //Implosion
  737. b.type = Bonus::SPELL_IMMUNITY;
  738. b.subtype = SpellID::IMPLOSION;
  739. break;
  740. case 'K': //Berserk
  741. b.type = Bonus::SPELL_IMMUNITY;
  742. b.subtype = SpellID::BERSERK;
  743. break;
  744. case 'M': //Meteor Shower
  745. b.type = Bonus::SPELL_IMMUNITY;
  746. b.subtype = SpellID::METEOR_SHOWER;
  747. break;
  748. case 'N': //dispell beneficial spells
  749. b.type = Bonus::SPELL_IMMUNITY;
  750. b.subtype = SpellID::DISPEL_HELPFUL_SPELLS;
  751. break;
  752. case 'R': //Armageddon
  753. b.type = Bonus::SPELL_IMMUNITY;
  754. b.subtype = SpellID::ARMAGEDDON;
  755. break;
  756. case 'S': //Slow
  757. b.type = Bonus::SPELL_IMMUNITY;
  758. b.subtype = SpellID::SLOW;
  759. break;
  760. case '6':
  761. case '7':
  762. case '8':
  763. case '9':
  764. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  765. b.val = std::atoi(mod.c_str()) - 5;
  766. break;
  767. case ':':
  768. b.type = Bonus::LEVEL_SPELL_IMMUNITY;
  769. b.val = GameConstants::SPELL_LEVELS; //in case someone adds higher level spells?
  770. break;
  771. case 'F':
  772. b.type = Bonus::FIRE_IMMUNITY;
  773. b.subtype = 1; //not positive
  774. break;
  775. case 'O':
  776. b.type = Bonus::FIRE_IMMUNITY;
  777. b.subtype = 2; //only direct damage
  778. break;
  779. case 'f':
  780. b.type = Bonus::FIRE_IMMUNITY;
  781. b.subtype = 0; //all
  782. break;
  783. case 'C':
  784. b.type = Bonus::WATER_IMMUNITY;
  785. b.subtype = 1; //not positive
  786. break;
  787. case 'W':
  788. b.type = Bonus::WATER_IMMUNITY;
  789. b.subtype = 2; //only direct damage
  790. break;
  791. case 'w':
  792. b.type = Bonus::WATER_IMMUNITY;
  793. b.subtype = 0; //all
  794. break;
  795. case 'E':
  796. b.type = Bonus::EARTH_IMMUNITY;
  797. b.subtype = 2; //only direct damage
  798. break;
  799. case 'e':
  800. b.type = Bonus::EARTH_IMMUNITY;
  801. b.subtype = 0; //all
  802. break;
  803. case 'A':
  804. b.type = Bonus::AIR_IMMUNITY;
  805. b.subtype = 2; //only direct damage
  806. break;
  807. case 'a':
  808. b.type = Bonus::AIR_IMMUNITY;
  809. b.subtype = 0; //all
  810. break;
  811. case 'D':
  812. b.type = Bonus::DIRECT_DAMAGE_IMMUNITY;
  813. break;
  814. case '0':
  815. b.type = Bonus::RECEPTIVE;
  816. break;
  817. case 'm':
  818. b.type = Bonus::MIND_IMMUNITY;
  819. break;
  820. default:
  821. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  822. return;
  823. }
  824. break;
  825. case 'i':
  826. enable = true;
  827. b.type = Bonus::NO_DISTANCE_PENALTY;
  828. break;
  829. case 'o':
  830. enable = true;
  831. b.type = Bonus::NO_WALL_PENALTY;
  832. break;
  833. case 'a':
  834. case 'c':
  835. case 'K':
  836. case 'k':
  837. b.type = Bonus::SPELL_AFTER_ATTACK;
  838. b.subtype = stringToNumber(mod);
  839. break;
  840. case 'h':
  841. b.type= Bonus::HATE;
  842. b.subtype = stringToNumber(mod);
  843. break;
  844. case 'p':
  845. case 'J':
  846. b.type = Bonus::SPELL_BEFORE_ATTACK;
  847. b.subtype = stringToNumber(mod);
  848. b.additionalInfo = 3; //always expert?
  849. break;
  850. case 'r':
  851. b.type = Bonus::HP_REGENERATION;
  852. b.val = stringToNumber(mod);
  853. break;
  854. case 's':
  855. b.type = Bonus::ENCHANTED;
  856. b.subtype = stringToNumber(mod);
  857. b.valType = Bonus::INDEPENDENT_MAX;
  858. break;
  859. default:
  860. logGlobal->traceStream() << "Not parsed bonus " << buf << mod;
  861. return;
  862. break;
  863. }
  864. switch (mod[0])
  865. {
  866. case '+':
  867. case '=': //should we allow percent values to stack or pick highest?
  868. b.valType = Bonus::ADDITIVE_VALUE;
  869. break;
  870. }
  871. //limiters, range
  872. si32 lastVal, curVal, lastLev = 0;
  873. if (enable) //0 and 2 means non-active, 1 - active
  874. {
  875. if (b.type != Bonus::REBIRTH)
  876. b.val = 0; //on-off ability, no value specified
  877. curVal = parser.readNumber();// 0 level is never active
  878. for (int i = 1; i < 11; ++i)
  879. {
  880. curVal = parser.readNumber();
  881. if (curVal == 1)
  882. {
  883. b.limiter.reset (new RankRangeLimiter(i));
  884. bl.push_back(new Bonus(b));
  885. break; //never turned off it seems
  886. }
  887. }
  888. }
  889. else
  890. {
  891. lastVal = parser.readNumber();
  892. if (b.type == Bonus::HATE)
  893. lastVal *= 10; //odd fix
  894. //FIXME: value for zero level should be stored in our config files (independent of stack exp)
  895. for (int i = 1; i < 11; ++i)
  896. {
  897. curVal = parser.readNumber();
  898. if (b.type == Bonus::HATE)
  899. curVal *= 10; //odd fix
  900. if (curVal > lastVal) //threshold, add new bonus
  901. {
  902. b.val = curVal - lastVal;
  903. lastVal = curVal;
  904. b.limiter.reset (new RankRangeLimiter(i));
  905. bl.push_back(new Bonus(b));
  906. lastLev = i; //start new range from here, i = previous rank
  907. }
  908. else if (curVal < lastVal)
  909. {
  910. b.val = lastVal;
  911. b.limiter.reset (new RankRangeLimiter(lastLev, i));
  912. }
  913. }
  914. }
  915. }
  916. int CCreatureHandler::stringToNumber(std::string & s)
  917. {
  918. boost::algorithm::replace_first(s,"#",""); //drop hash character
  919. return std::atoi(s.c_str());
  920. }
  921. CCreatureHandler::~CCreatureHandler()
  922. {
  923. for(auto & creature : creatures)
  924. creature.dellNull();
  925. }
  926. CreatureID CCreatureHandler::pickRandomMonster(const std::function<int()> &randGen, int tier) const
  927. {
  928. int r = 0;
  929. if(tier == -1) //pick any allowed creature
  930. {
  931. do
  932. {
  933. r = vstd::pickRandomElementOf(creatures, randGen)->idNumber;
  934. } while (VLC->creh->creatures[r] && VLC->creh->creatures[r]->special); // find first "not special" creature
  935. }
  936. else
  937. {
  938. assert(vstd::iswithin(tier, 1, 7));
  939. std::vector<CreatureID> allowed;
  940. for(const CBonusSystemNode *b : creaturesOfLevel[tier].getChildrenNodes())
  941. {
  942. assert(b->getNodeType() == CBonusSystemNode::CREATURE);
  943. const CCreature * crea = dynamic_cast<const CCreature*>(b);
  944. if(crea && !crea->special)
  945. allowed.push_back(crea->idNumber);
  946. }
  947. if(!allowed.size())
  948. {
  949. logGlobal->warnStream() << "Cannot pick a random creature of tier " << tier << "!";
  950. return CreatureID::NONE;
  951. }
  952. return vstd::pickRandomElementOf(allowed, randGen);
  953. }
  954. assert (r >= 0); //should always be, but it crashed
  955. return CreatureID(r);
  956. }
  957. void CCreatureHandler::addBonusForTier(int tier, Bonus *b)
  958. {
  959. assert(vstd::iswithin(tier, 1, 7));
  960. creaturesOfLevel[tier].addNewBonus(b);
  961. }
  962. void CCreatureHandler::addBonusForAllCreatures(Bonus *b)
  963. {
  964. allCreatures.addNewBonus(b);
  965. }
  966. void CCreatureHandler::buildBonusTreeForTiers()
  967. {
  968. for(CCreature *c : creatures)
  969. {
  970. if(vstd::isbetween(c->level, 0, ARRAY_COUNT(creaturesOfLevel)))
  971. c->attachTo(&creaturesOfLevel[c->level]);
  972. else
  973. c->attachTo(&creaturesOfLevel[0]);
  974. }
  975. for(CBonusSystemNode &b : creaturesOfLevel)
  976. b.attachTo(&allCreatures);
  977. }
  978. void CCreatureHandler::deserializationFix()
  979. {
  980. buildBonusTreeForTiers();
  981. }