CCreatureHandler.cpp 33 KB

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