CCreatureHandler.cpp 31 KB

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