CGCreature.cpp 20 KB

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