CCreatureHandler.cpp 34 KB

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