CGCreature.cpp 20 KB

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