CGCreature.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  1. /*
  2. * CGCreature.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 "CGCreature.h"
  12. #include "CGHeroInstance.h"
  13. #include "../texts/CGeneralTextHandler.h"
  14. #include "../CConfigHandler.h"
  15. #include "../IGameSettings.h"
  16. #include "../bonuses/BonusParameters.h"
  17. #include "../callback/IGameInfoCallback.h"
  18. #include "../callback/IGameEventCallback.h"
  19. #include "../callback/IGameRandomizer.h"
  20. #include "../gameState/CGameState.h"
  21. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  22. #include "../networkPacks/PacksForClient.h"
  23. #include "../networkPacks/PacksForClientBattle.h"
  24. #include "../networkPacks/StackLocation.h"
  25. #include "../serializer/JsonSerializeFormat.h"
  26. #include "../entities/faction/CTownHandler.h"
  27. #include "../entities/ResourceTypeHandler.h"
  28. #include <vstd/RNG.h>
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. std::string CGCreature::getHoverText(PlayerColor player) const
  31. {
  32. if(stacks.empty())
  33. {
  34. //should not happen...
  35. logGlobal->error("Invalid stack at tile %s: subID=%d; id=%d", anchorPos().toString(), getCreature(), id.getNum());
  36. return "INVALID_STACK";
  37. }
  38. MetaString ms;
  39. CCreature::CreatureQuantityId monsterQuantityId = stacks.begin()->second->getQuantityID();
  40. int quantityTextIndex = 172 + 3 * (int)monsterQuantityId;
  41. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  42. ms.appendRawString(CCreature::getQuantityRangeStringForId(monsterQuantityId));
  43. else
  44. ms.appendLocalString(EMetaText::ARRAY_TXT, quantityTextIndex);
  45. ms.appendRawString(" ");
  46. ms.appendNamePlural(getCreatureID());
  47. return ms.toString();
  48. }
  49. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  50. {
  51. if(hero->hasVisions(this, BonusCustomSubtype::visionsMonsters))
  52. {
  53. MetaString ms;
  54. ms.appendNumber(stacks.begin()->second->getCount());
  55. ms.appendRawString(" ");
  56. ms.appendName(getCreatureID(), stacks.begin()->second->getCount());
  57. return ms.toString();
  58. }
  59. else
  60. {
  61. return getHoverText(hero->tempOwner);
  62. }
  63. }
  64. std::string CGCreature::getMonsterLevelText() const
  65. {
  66. std::string monsterLevel = LIBRARY->generaltexth->translate("vcmi.adventureMap.monsterLevel");
  67. bool isRanged = getCreature()->getBonusBearer()->hasBonusOfType(BonusType::SHOOTER);
  68. std::string attackTypeKey = isRanged ? "vcmi.adventureMap.monsterRangedType" : "vcmi.adventureMap.monsterMeleeType";
  69. std::string attackType = LIBRARY->generaltexth->translate(attackTypeKey);
  70. boost::replace_first(monsterLevel, "%TOWN", getCreature()->getFactionID().toEntity(LIBRARY)->getNameTranslated());
  71. boost::replace_first(monsterLevel, "%LEVEL", std::to_string(getCreature()->getLevel()));
  72. boost::replace_first(monsterLevel, "%ATTACK_TYPE", attackType);
  73. return monsterLevel;
  74. }
  75. std::string CGCreature::getPopupText(const CGHeroInstance * hero) const
  76. {
  77. std::string hoverName;
  78. if(hero->hasVisions(this, BonusCustomSubtype::visionsMonsters))
  79. {
  80. MetaString ms;
  81. ms.appendRawString(getHoverText(hero));
  82. ms.appendRawString("\n\n");
  83. int decision = takenAction(hero, true);
  84. switch (decision)
  85. {
  86. case FIGHT:
  87. ms.appendLocalString(EMetaText::GENERAL_TXT,246);
  88. break;
  89. case FLEE:
  90. ms.appendLocalString(EMetaText::GENERAL_TXT,245);
  91. break;
  92. case JOIN_FOR_FREE:
  93. ms.appendLocalString(EMetaText::GENERAL_TXT,243);
  94. break;
  95. default: //decision = cost in gold
  96. ms.appendLocalString(EMetaText::GENERAL_TXT,244);
  97. ms.replaceNumber(decision);
  98. break;
  99. }
  100. hoverName = ms.toString();
  101. }
  102. else
  103. {
  104. hoverName = getHoverText(hero->tempOwner);
  105. }
  106. if (settings["general"]["enableUiEnhancements"].Bool())
  107. {
  108. hoverName += getMonsterLevelText();
  109. hoverName += LIBRARY->generaltexth->translate("vcmi.adventureMap.monsterThreat.title");
  110. int choice;
  111. uint64_t armyStrength = getArmyStrength();
  112. uint64_t heroStrength = hero->getTotalStrength();
  113. double ratio = static_cast<double>(armyStrength) / heroStrength;
  114. if (ratio < 0.1) choice = 0;
  115. else if (ratio < 0.25) choice = 1;
  116. else if (ratio < 0.6) choice = 2;
  117. else if (ratio < 0.9) choice = 3;
  118. else if (ratio < 1.1) choice = 4;
  119. else if (ratio < 1.3) choice = 5;
  120. else if (ratio < 1.8) choice = 6;
  121. else if (ratio < 2.5) choice = 7;
  122. else if (ratio < 4) choice = 8;
  123. else if (ratio < 8) choice = 9;
  124. else if (ratio < 20) choice = 10;
  125. else choice = 11;
  126. hoverName += LIBRARY->generaltexth->translate("vcmi.adventureMap.monsterThreat.levels." + std::to_string(choice));
  127. }
  128. return hoverName;
  129. }
  130. std::string CGCreature::getPopupText(PlayerColor player) const
  131. {
  132. std::string hoverName = getHoverText(player);
  133. if (settings["general"]["enableUiEnhancements"].Bool())
  134. hoverName += getMonsterLevelText();
  135. return hoverName;
  136. }
  137. std::vector<Component> CGCreature::getPopupComponents(PlayerColor player) const
  138. {
  139. return {
  140. Component(ComponentType::CREATURE, getCreatureID())
  141. };
  142. }
  143. void CGCreature::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  144. {
  145. //show message
  146. if(!message.empty())
  147. {
  148. InfoWindow iw;
  149. iw.player = h->tempOwner;
  150. iw.text = message;
  151. iw.type = EInfoWindowMode::MODAL;
  152. gameEvents.showInfoDialog(&iw);
  153. }
  154. int action = takenAction(h);
  155. switch( action ) //decide what we do...
  156. {
  157. case FIGHT:
  158. fight(gameEvents, h);
  159. break;
  160. case FLEE:
  161. {
  162. flee(gameEvents, h);
  163. break;
  164. }
  165. case JOIN_FOR_FREE: //join for free
  166. {
  167. BlockingDialog ynd(true,false);
  168. ynd.player = h->tempOwner;
  169. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, 86);
  170. ynd.text.replaceName(getCreatureID(), getJoiningAmount());
  171. gameEvents.showBlockingDialog(this, &ynd);
  172. break;
  173. }
  174. default: //join for gold
  175. {
  176. assert(action > 0);
  177. //ask if player agrees to pay gold
  178. BlockingDialog ynd(true,false);
  179. ynd.player = h->tempOwner;
  180. ynd.components.emplace_back(ComponentType::RESOURCE, GameResID(GameResID::GOLD), action);
  181. std::string tmp = LIBRARY->generaltexth->advobtxt[90];
  182. boost::algorithm::replace_first(tmp, "%d", std::to_string(getJoiningAmount()));
  183. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  184. boost::algorithm::replace_first(tmp,"%s",getCreature()->getNamePluralTranslated());
  185. ynd.text.appendRawString(tmp);
  186. gameEvents.showBlockingDialog(this, &ynd);
  187. break;
  188. }
  189. }
  190. }
  191. CreatureID CGCreature::getCreatureID() const
  192. {
  193. return CreatureID(getObjTypeIndex().getNum());
  194. }
  195. const CCreature * CGCreature::getCreature() const
  196. {
  197. return getCreatureID().toCreature();
  198. }
  199. TQuantity CGCreature::getJoiningAmount() const
  200. {
  201. return std::max(static_cast<int64_t>(1), getStackCount(SlotID(0)) * cb->getSettings().getInteger(EGameSettings::CREATURES_JOINING_PERCENTAGE) / 100);
  202. }
  203. void CGCreature::pickRandomObject(IGameRandomizer & gameRandomizer)
  204. {
  205. switch(ID.toEnum())
  206. {
  207. case MapObjectID::RANDOM_MONSTER:
  208. subID = gameRandomizer.rollCreature();
  209. break;
  210. case MapObjectID::RANDOM_MONSTER_L1:
  211. subID = gameRandomizer.rollCreature(1);
  212. break;
  213. case MapObjectID::RANDOM_MONSTER_L2:
  214. subID = gameRandomizer.rollCreature(2);
  215. break;
  216. case MapObjectID::RANDOM_MONSTER_L3:
  217. subID = gameRandomizer.rollCreature(3);
  218. break;
  219. case MapObjectID::RANDOM_MONSTER_L4:
  220. subID = gameRandomizer.rollCreature(4);
  221. break;
  222. case MapObjectID::RANDOM_MONSTER_L5:
  223. subID = gameRandomizer.rollCreature(5);
  224. break;
  225. case MapObjectID::RANDOM_MONSTER_L6:
  226. subID = gameRandomizer.rollCreature(6);
  227. break;
  228. case MapObjectID::RANDOM_MONSTER_L7:
  229. subID = gameRandomizer.rollCreature(7);
  230. break;
  231. }
  232. try {
  233. // sanity check
  234. LIBRARY->objtypeh->getHandlerFor(MapObjectID::MONSTER, subID);
  235. }
  236. catch (const std::out_of_range & )
  237. {
  238. // Try to generate some debug information if sanity check failed
  239. CreatureID creatureID(subID.getNum());
  240. throw std::out_of_range("Failed to find handler for creature " + std::to_string(creatureID.getNum()) + ", identifier:" + creatureID.toEntity(LIBRARY)->getJsonKey());
  241. }
  242. ID = MapObjectID::MONSTER;
  243. setType(ID, subID);
  244. }
  245. void CGCreature::initObj(IGameRandomizer & gameRandomizer)
  246. {
  247. blockVisit = true;
  248. switch(initialCharacter)
  249. {
  250. case Character::COMPLIANT:
  251. agression = -4;
  252. break;
  253. case Character::FRIENDLY:
  254. agression = gameRandomizer.getDefault().nextInt(1, 7);
  255. break;
  256. case Character::AGGRESSIVE:
  257. agression = gameRandomizer.getDefault().nextInt(1, 10);
  258. break;
  259. case Character::HOSTILE:
  260. agression = gameRandomizer.getDefault().nextInt(4, 10);
  261. break;
  262. case Character::SAVAGE:
  263. agression = 10;
  264. break;
  265. }
  266. stacks[SlotID(0)]->setType(getCreature());
  267. const Creature * c = getCreature();
  268. if(stacks[SlotID(0)]->getCount() == 0)
  269. {
  270. stacks[SlotID(0)]->setCount(gameRandomizer.getDefault().nextInt(c->getAdvMapAmountMin(), c->getAdvMapAmountMax()));
  271. if(stacks[SlotID(0)]->getCount() == 0) //armies with 0 creatures are illegal
  272. {
  273. logGlobal->warn("Stack cannot have 0 creatures. Check properties of %s", c->getJsonKey());
  274. stacks[SlotID(0)]->setCount(1);
  275. }
  276. }
  277. temppower = stacks[SlotID(0)]->getCount() * static_cast<int64_t>(1000);
  278. refusedJoining = false;
  279. }
  280. void CGCreature::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  281. {//Works only for stacks of single type of size up to 2 millions
  282. if (!notGrowingTeam)
  283. {
  284. if (stacks.begin()->second->getCount() < cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP) && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  285. {
  286. ui32 power = static_cast<ui32>(temppower * (100 + cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  287. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  288. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  289. }
  290. }
  291. if (cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  292. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_EXP, cb->getSettings().getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  293. }
  294. void CGCreature::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  295. {
  296. switch (what)
  297. {
  298. case ObjProperty::MONSTER_COUNT:
  299. stacks[SlotID(0)]->setCount(identifier.getNum());
  300. break;
  301. case ObjProperty::MONSTER_POWER:
  302. temppower = identifier.getNum();
  303. break;
  304. case ObjProperty::MONSTER_EXP:
  305. giveAverageStackExperience(identifier.getNum());
  306. break;
  307. case ObjProperty::MONSTER_REFUSED_JOIN:
  308. refusedJoining = identifier.getNum();
  309. break;
  310. }
  311. }
  312. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  313. {
  314. //calculate relative strength of hero and creatures armies
  315. double relStrength = static_cast<double>(h->getValueForDiplomacy()) / getArmyStrength();
  316. int powerFactor;
  317. if(relStrength >= 7)
  318. powerFactor = 11;
  319. else if(relStrength >= 1)
  320. powerFactor = static_cast<int>(2 * (relStrength - 1));
  321. else if(relStrength >= 0.5)
  322. powerFactor = -1;
  323. else if(relStrength >= 0.333)
  324. powerFactor = -2;
  325. else
  326. powerFactor = -3;
  327. int count = 0; //how many creatures of similar kind has hero
  328. int totalCount = 0;
  329. for(const auto & elem : h->Slots())
  330. {
  331. bool isOurUpgrade = vstd::contains(getCreature()->upgrades, elem.second->getCreatureID());
  332. bool isOurDowngrade = vstd::contains(elem.second->getCreature()->upgrades, getCreatureID());
  333. if(isOurUpgrade || isOurDowngrade)
  334. count += elem.second->getCount();
  335. totalCount += elem.second->getCount();
  336. }
  337. int sympathy = 0; // 0 if hero have no similar creatures
  338. if(count)
  339. sympathy++; // 1 - if hero have at least 1 similar creature
  340. if(count*2 > totalCount)
  341. sympathy++; // 2 - hero have similar creatures more that 50%
  342. int diplomacy = h->valOfBonuses(BonusType::WANDERING_CREATURES_JOIN_BONUS);
  343. int charisma = powerFactor + diplomacy + sympathy;
  344. if(charisma < agression)
  345. return FIGHT;
  346. if (allowJoin && cb->getSettings().getInteger(EGameSettings::CREATURES_JOINING_PERCENTAGE) > 0)
  347. {
  348. if((cb->getSettings().getBoolean(EGameSettings::CREATURES_ALLOW_JOINING_FOR_FREE) || initialCharacter == Character::COMPLIANT) && diplomacy + sympathy + 1 >= agression && !joinOnlyForMoney)
  349. return JOIN_FOR_FREE;
  350. if(diplomacy * 2 + sympathy + 1 >= agression)
  351. {
  352. int32_t recruitCost = getCreature()->getRecruitCost(EGameResID::GOLD);
  353. int32_t stackCount = getStackCount(SlotID(0));
  354. return recruitCost * stackCount; //join for gold
  355. }
  356. }
  357. //we are still here - creatures have not joined hero, flee or fight
  358. if (charisma > agression && !neverFlees)
  359. return FLEE;
  360. else
  361. return FIGHT;
  362. }
  363. void CGCreature::fleeDecision(IGameEventCallback & gameEvents, const CGHeroInstance *h, ui32 pursue) const
  364. {
  365. if(refusedJoining)
  366. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  367. if(pursue)
  368. {
  369. fight(gameEvents, h);
  370. }
  371. else
  372. {
  373. gameEvents.removeObject(this, h->getOwner());
  374. }
  375. }
  376. void CGCreature::joinDecision(IGameEventCallback & gameEvents, const CGHeroInstance *h, int cost, ui32 accept) const
  377. {
  378. if(!accept)
  379. {
  380. if(takenAction(h,false) == FLEE)
  381. {
  382. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  383. flee(gameEvents, h);
  384. }
  385. else //they fight
  386. {
  387. h->showInfoDialog(gameEvents, 87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  388. fight(gameEvents, h);
  389. }
  390. }
  391. else //accepted
  392. {
  393. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  394. {
  395. InfoWindow iw;
  396. iw.player = h->tempOwner;
  397. iw.text.appendLocalString(EMetaText::GENERAL_TXT,29); //You don't have enough gold
  398. gameEvents.showInfoDialog(&iw);
  399. //act as if player refused
  400. joinDecision(gameEvents, h, cost, false);
  401. return;
  402. }
  403. //take gold
  404. if(cost)
  405. gameEvents.giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  406. giveReward(gameEvents, h);
  407. for(auto & stack : this->stacks)
  408. stack.second->setCount(getJoiningAmount());
  409. gameEvents.tryJoiningArmy(this, h, true, true);
  410. }
  411. }
  412. void CGCreature::fight(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  413. {
  414. //split stacks
  415. int stacksCount = getNumberOfStacks(h);
  416. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  417. int amount = getStackCount(SlotID(0));
  418. int m = amount / stacksCount;
  419. int b = stacksCount * (m + 1) - amount;
  420. int a = stacksCount - b;
  421. SlotID sourceSlot = stacks.begin()->first;
  422. for (int slotID = 1; slotID < a; ++slotID)
  423. {
  424. int stackSize = m + 1;
  425. gameEvents.moveStack(StackLocation(id, sourceSlot), StackLocation(id, SlotID(slotID)), stackSize);
  426. }
  427. for (int slotID = a; slotID < stacksCount; ++slotID)
  428. {
  429. int stackSize = m;
  430. if (slotID) //don't do this when a = 0 -> stack is single
  431. gameEvents.moveStack(StackLocation(id, sourceSlot), StackLocation(id, SlotID(slotID)), stackSize);
  432. }
  433. if (stacksCount > 1)
  434. {
  435. if (containsUpgradedStack()) //upgrade
  436. {
  437. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  438. const auto & upgrades = getStack(slotID).getCreature()->upgrades;
  439. if(!upgrades.empty())
  440. {
  441. auto it = RandomGeneratorUtil::nextItem(upgrades, gameEvents.getRandomGenerator());
  442. gameEvents.changeStackType(StackLocation(id, slotID), it->toCreature());
  443. }
  444. }
  445. }
  446. gameEvents.startBattle(h, this);
  447. }
  448. void CGCreature::flee(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  449. {
  450. BlockingDialog ynd(true,false);
  451. ynd.player = h->tempOwner;
  452. ynd.text.appendLocalString(EMetaText::ADVOB_TXT,91);
  453. ynd.text.replaceName(getCreatureID(), getStackCount(SlotID(0)));
  454. gameEvents.showBlockingDialog(this, &ynd);
  455. }
  456. void CGCreature::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance *hero, const BattleResult &result) const
  457. {
  458. if(result.winner == BattleSide::ATTACKER)
  459. {
  460. giveReward(gameEvents, hero);
  461. gameEvents.removeObject(this, hero->getOwner());
  462. }
  463. else if(result.winner == BattleSide::NONE) // draw
  464. {
  465. // guarded reward is lost forever on draw
  466. gameEvents.removeObject(this, result.attacker);
  467. }
  468. else
  469. {
  470. //merge stacks into one
  471. TSlots::const_iterator i;
  472. const CCreature * cre = getCreature();
  473. for(i = stacks.begin(); i != stacks.end(); i++)
  474. {
  475. if(cre->isMyDirectUpgrade(i->second->getCreature()))
  476. {
  477. gameEvents.changeStackType(StackLocation(id, i->first), cre); //un-upgrade creatures
  478. }
  479. }
  480. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  481. if(!hasStackAtSlot(SlotID(0)))
  482. gameEvents.moveStack(StackLocation(id, stacks.begin()->first), StackLocation(id, SlotID(0)), stacks.begin()->second->getCount());
  483. while(stacks.size() > 1) //hopefully that's enough
  484. {
  485. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  486. i = stacks.end();
  487. i--;
  488. SlotID slot = getSlotFor(i->second->getCreature());
  489. if(slot == i->first) //no reason to move stack to its own slot
  490. break;
  491. else
  492. gameEvents.moveStack(StackLocation(id, i->first), StackLocation(id, slot), i->second->getCount());
  493. }
  494. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->getCount() * 1000); //remember casualties
  495. }
  496. }
  497. void CGCreature::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  498. {
  499. auto action = takenAction(hero);
  500. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  501. joinDecision(gameEvents, hero, action, answer);
  502. else if(action != FIGHT)
  503. fleeDecision(gameEvents, hero, answer);
  504. else
  505. assert(0);
  506. }
  507. bool CGCreature::containsUpgradedStack() const
  508. {
  509. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  510. static constexpr float a = 2992.911117f;
  511. static constexpr float b = 14174.264968f;
  512. static constexpr float c = 5325.181015f;
  513. static constexpr float d = 32788.727920f;
  514. switch (upgradedStackPresence)
  515. {
  516. case UpgradedStackPresence::ALWAYS:
  517. return true;
  518. case UpgradedStackPresence::NEVER:
  519. return false;
  520. default:
  521. {
  522. int val = static_cast<int>(std::floor(a * visitablePos().x + b * visitablePos().y + c * visitablePos().z + d));
  523. return ((val % 32768) % 100) < 50;
  524. }
  525. }
  526. }
  527. int CGCreature::getNumberOfStacks(const CGHeroInstance * hero) const
  528. {
  529. if(stacksCount > 0)
  530. return stacksCount;
  531. int split = 0;
  532. if (hero->hasBonusOfType(BonusType::FORCE_NEUTRAL_ENCOUNTER_STACK_COUNT))
  533. split = getNumberOfStacksFromBonus(hero);
  534. if(split == 0)
  535. split = getDefaultNumberOfStacks(hero);
  536. vstd::amin(split, getStack(SlotID(0)).getCount()); //can't divide into more stacks than creatures total
  537. vstd::amin(split, 7);
  538. vstd::amax(split, 1);
  539. return split;
  540. }
  541. int CGCreature::getNumberOfStacksFromBonus(const CGHeroInstance * hero) const
  542. {
  543. auto bonus = hero->getBonus(Selector::type()(BonusType::FORCE_NEUTRAL_ENCOUNTER_STACK_COUNT));
  544. if(bonus->val > 0)
  545. return bonus->val;
  546. if (!bonus->parameters)
  547. return 0;
  548. auto addInfo = bonus->parameters->toVector();
  549. if(addInfo.empty())
  550. return 0;
  551. const size_t maxEntries = std::min<size_t>(addInfo.size(), 7);
  552. int total = 0;
  553. for(size_t i = 0; i < maxEntries; i++)
  554. total += std::max<int>(0, addInfo[i]);
  555. if(total <= 0)
  556. return 0;
  557. ui32 R2 = hashByPosition();
  558. int R4 = R2 % total + 1;
  559. int acc = 0;
  560. for(size_t i = 0; i < maxEntries; i++)
  561. {
  562. acc += std::max<int>(0, addInfo[i]);
  563. if(R4 <= acc)
  564. return static_cast<int>(i + 1);
  565. }
  566. return 0;
  567. }
  568. int CGCreature::getDefaultNumberOfStacks(const CGHeroInstance *hero) const
  569. {
  570. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  571. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  572. int split = 1;
  573. if (strengthRatio < 0.5f)
  574. split = 7;
  575. else if (strengthRatio < 0.67f)
  576. split = 6;
  577. else if (strengthRatio < 1)
  578. split = 5;
  579. else if (strengthRatio < 1.5f)
  580. split = 4;
  581. else if (strengthRatio < 2)
  582. split = 3;
  583. else
  584. split = 2;
  585. ui32 R2 = hashByPosition();
  586. int R4 = R2 % 100 + 1;
  587. if(stacksCount == -3)
  588. ;
  589. else if (stacksCount == -2 || R4 <= 20)
  590. split -= 1;
  591. else if(stacksCount == 0 || R4 >= 80)
  592. split += 1;
  593. vstd::amin(split, getStack(SlotID(0)).getCount()); //can't divide into more stacks than creatures total
  594. vstd::amin(split, 7); //can't have more than 7 stacks
  595. return split;
  596. }
  597. ui32 CGCreature::hashByPosition() const
  598. {
  599. ui32 a = 1550811371u;
  600. ui32 b = 3359066809u;
  601. ui32 c = 1943276003u;
  602. ui32 d = 3174620878u;
  603. ui32 R1 = a * static_cast<ui32>(visitablePos().x) + b * static_cast<ui32>(visitablePos().y) + c * static_cast<ui32>(visitablePos().z) + d;
  604. ui32 R2 = (R1 >> 16) & 0x7fff;
  605. return R2;
  606. }
  607. void CGCreature::giveReward(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  608. {
  609. InfoWindow iw;
  610. iw.player = h->tempOwner;
  611. if(!resources.empty())
  612. {
  613. gameEvents.giveResources(h->tempOwner, resources);
  614. for(const auto & res : LIBRARY->resourceTypeHandler->getAllObjects())
  615. {
  616. if(resources[res] > 0)
  617. iw.components.emplace_back(ComponentType::RESOURCE, res, resources[res]);
  618. }
  619. }
  620. if(gainedArtifact != ArtifactID::NONE)
  621. {
  622. gameEvents.giveHeroNewArtifact(h, gainedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  623. iw.components.emplace_back(ComponentType::ARTIFACT, gainedArtifact);
  624. }
  625. if(!iw.components.empty())
  626. {
  627. iw.type = EInfoWindowMode::AUTO;
  628. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 183); // % has found treasure
  629. iw.text.replaceRawString(h->getNameTranslated());
  630. gameEvents.showInfoDialog(&iw);
  631. }
  632. }
  633. static const std::vector<std::string> CHARACTER_JSON =
  634. {
  635. "compliant", "friendly", "aggressive", "hostile", "savage", "custom"
  636. };
  637. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  638. {
  639. handler.serializeEnum("character", initialCharacter, CHARACTER_JSON);
  640. if(handler.saving)
  641. {
  642. if(hasStackAtSlot(SlotID(0)))
  643. {
  644. si32 amount = getStack(SlotID(0)).getCount();
  645. handler.serializeInt("amount", amount, 0);
  646. }
  647. }
  648. else
  649. {
  650. si32 amount = 0;
  651. handler.serializeInt("amount", amount);
  652. auto hlp = std::make_unique<CStackInstance>(cb);
  653. hlp->setCount(amount);
  654. //type will be set during initialization
  655. putStack(SlotID(0), std::move(hlp));
  656. }
  657. resources.serializeJson(handler, "rewardResources");
  658. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  659. handler.serializeBool("noGrowing", notGrowingTeam);
  660. handler.serializeBool("neverFlees", neverFlees);
  661. handler.serializeStruct("rewardMessage", message);
  662. }
  663. VCMI_LIB_NAMESPACE_END