CGCreature.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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(getCreature());
  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->count);
  51. ms.appendRawString(" ");
  52. ms.appendName(getCreature(), stacks.begin()->second->count);
  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 = VLC->generaltexth->translate("vcmi.adventureMap.monsterLevel");
  63. bool isRanged = VLC->creatures()->getById(getCreature())->getBonusBearer()->hasBonusOfType(BonusType::SHOOTER);
  64. std::string attackTypeKey = isRanged ? "vcmi.adventureMap.monsterRangedType" : "vcmi.adventureMap.monsterMeleeType";
  65. std::string attackType = VLC->generaltexth->translate(attackTypeKey);
  66. boost::replace_first(monsterLevel, "%TOWN", (*VLC->townh)[VLC->creatures()->getById(getCreature())->getFaction()]->getNameTranslated());
  67. boost::replace_first(monsterLevel, "%LEVEL", std::to_string(VLC->creatures()->getById(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 += VLC->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 += VLC->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, getCreature())
  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(getCreature(), getStackCount(SlotID(0)));
  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 = VLC->generaltexth->advobtxt[90];
  178. boost::algorithm::replace_first(tmp, "%d", std::to_string(getStackCount(SlotID(0))));
  179. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  180. boost::algorithm::replace_first(tmp,"%s",VLC->creatures()->getById(getCreature())->getNamePluralTranslated());
  181. ynd.text.appendRawString(tmp);
  182. cb->showBlockingDialog(this, &ynd);
  183. break;
  184. }
  185. }
  186. }
  187. CreatureID CGCreature::getCreature() const
  188. {
  189. return CreatureID(getObjTypeIndex().getNum());
  190. }
  191. void CGCreature::pickRandomObject(vstd::RNG & rand)
  192. {
  193. switch(ID.toEnum())
  194. {
  195. case MapObjectID::RANDOM_MONSTER:
  196. subID = VLC->creh->pickRandomMonster(rand);
  197. break;
  198. case MapObjectID::RANDOM_MONSTER_L1:
  199. subID = VLC->creh->pickRandomMonster(rand, 1);
  200. break;
  201. case MapObjectID::RANDOM_MONSTER_L2:
  202. subID = VLC->creh->pickRandomMonster(rand, 2);
  203. break;
  204. case MapObjectID::RANDOM_MONSTER_L3:
  205. subID = VLC->creh->pickRandomMonster(rand, 3);
  206. break;
  207. case MapObjectID::RANDOM_MONSTER_L4:
  208. subID = VLC->creh->pickRandomMonster(rand, 4);
  209. break;
  210. case MapObjectID::RANDOM_MONSTER_L5:
  211. subID = VLC->creh->pickRandomMonster(rand, 5);
  212. break;
  213. case MapObjectID::RANDOM_MONSTER_L6:
  214. subID = VLC->creh->pickRandomMonster(rand, 6);
  215. break;
  216. case MapObjectID::RANDOM_MONSTER_L7:
  217. subID = VLC->creh->pickRandomMonster(rand, 7);
  218. break;
  219. }
  220. try {
  221. // sanity check
  222. VLC->objtypeh->getHandlerFor(MapObjectID::MONSTER, subID);
  223. }
  224. catch (const std::out_of_range & )
  225. {
  226. // Try to generate some debug information if sanity check failed
  227. CreatureID creatureID(subID.getNum());
  228. throw std::out_of_range("Failed to find handler for creature " + std::to_string(creatureID.getNum()) + ", identifier:" + creatureID.toEntity(VLC)->getJsonKey());
  229. }
  230. ID = MapObjectID::MONSTER;
  231. setType(ID, subID);
  232. }
  233. void CGCreature::initObj(vstd::RNG & rand)
  234. {
  235. blockVisit = true;
  236. switch(character)
  237. {
  238. case 0:
  239. character = -4;
  240. break;
  241. case 1:
  242. character = rand.nextInt(1, 7);
  243. break;
  244. case 2:
  245. character = rand.nextInt(1, 10);
  246. break;
  247. case 3:
  248. character = rand.nextInt(4, 10);
  249. break;
  250. case 4:
  251. character = 10;
  252. break;
  253. }
  254. stacks[SlotID(0)]->setType(getCreature());
  255. TQuantity &amount = stacks[SlotID(0)]->count;
  256. const Creature * c = VLC->creatures()->getById(getCreature());
  257. if(amount == 0)
  258. {
  259. amount = rand.nextInt(c->getAdvMapAmountMin(), c->getAdvMapAmountMax());
  260. if(amount == 0) //armies with 0 creatures are illegal
  261. {
  262. logGlobal->warn("Stack cannot have 0 creatures. Check properties of %s", c->getJsonKey());
  263. amount = 1;
  264. }
  265. }
  266. temppower = stacks[SlotID(0)]->count * static_cast<int64_t>(1000);
  267. refusedJoining = false;
  268. }
  269. void CGCreature::newTurn(vstd::RNG & rand) const
  270. {//Works only for stacks of single type of size up to 2 millions
  271. if (!notGrowingTeam)
  272. {
  273. if (stacks.begin()->second->count < cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP) && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  274. {
  275. ui32 power = static_cast<ui32>(temppower * (100 + cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  276. cb->setObjPropertyValue(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  277. cb->setObjPropertyValue(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  278. }
  279. }
  280. if (cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  281. cb->setObjPropertyValue(id, ObjProperty::MONSTER_EXP, cb->getSettings().getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  282. }
  283. void CGCreature::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  284. {
  285. switch (what)
  286. {
  287. case ObjProperty::MONSTER_COUNT:
  288. stacks[SlotID(0)]->count = identifier.getNum();
  289. break;
  290. case ObjProperty::MONSTER_POWER:
  291. temppower = identifier.getNum();
  292. break;
  293. case ObjProperty::MONSTER_EXP:
  294. giveStackExp(identifier.getNum());
  295. break;
  296. case ObjProperty::MONSTER_REFUSED_JOIN:
  297. refusedJoining = identifier.getNum();
  298. break;
  299. }
  300. }
  301. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  302. {
  303. //calculate relative strength of hero and creatures armies
  304. double relStrength = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  305. int powerFactor;
  306. if(relStrength >= 7)
  307. powerFactor = 11;
  308. else if(relStrength >= 1)
  309. powerFactor = static_cast<int>(2 * (relStrength - 1));
  310. else if(relStrength >= 0.5)
  311. powerFactor = -1;
  312. else if(relStrength >= 0.333)
  313. powerFactor = -2;
  314. else
  315. powerFactor = -3;
  316. int count = 0; //how many creatures of similar kind has hero
  317. int totalCount = 0;
  318. for(const auto & elem : h->Slots())
  319. {
  320. bool isOurUpgrade = vstd::contains(getCreature().toCreature()->upgrades, elem.second->getCreatureID());
  321. bool isOurDowngrade = vstd::contains(elem.second->type->upgrades, getCreature());
  322. if(isOurUpgrade || isOurDowngrade)
  323. count += elem.second->count;
  324. totalCount += elem.second->count;
  325. }
  326. int sympathy = 0; // 0 if hero have no similar creatures
  327. if(count)
  328. sympathy++; // 1 - if hero have at least 1 similar creature
  329. if(count*2 > totalCount)
  330. sympathy++; // 2 - hero have similar creatures more that 50%
  331. int diplomacy = h->valOfBonuses(BonusType::WANDERING_CREATURES_JOIN_BONUS);
  332. int charisma = powerFactor + diplomacy + sympathy;
  333. if(charisma < character)
  334. return FIGHT;
  335. if (allowJoin)
  336. {
  337. if(diplomacy + sympathy + 1 >= character)
  338. return JOIN_FOR_FREE;
  339. if(diplomacy * 2 + sympathy + 1 >= character)
  340. {
  341. int32_t recruitCost = VLC->creatures()->getById(getCreature())->getRecruitCost(EGameResID::GOLD);
  342. int32_t stackCount = getStackCount(SlotID(0));
  343. return recruitCost * stackCount; //join for gold
  344. }
  345. }
  346. //we are still here - creatures have not joined hero, flee or fight
  347. if (charisma > character && !neverFlees)
  348. return FLEE;
  349. else
  350. return FIGHT;
  351. }
  352. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  353. {
  354. if(refusedJoining)
  355. cb->setObjPropertyValue(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  356. if(pursue)
  357. {
  358. fight(h);
  359. }
  360. else
  361. {
  362. cb->removeObject(this, h->getOwner());
  363. }
  364. }
  365. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  366. {
  367. if(!accept)
  368. {
  369. if(takenAction(h,false) == FLEE)
  370. {
  371. cb->setObjPropertyValue(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  372. flee(h);
  373. }
  374. else //they fight
  375. {
  376. h->showInfoDialog(87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  377. fight(h);
  378. }
  379. }
  380. else //accepted
  381. {
  382. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  383. {
  384. InfoWindow iw;
  385. iw.player = h->tempOwner;
  386. iw.text.appendLocalString(EMetaText::GENERAL_TXT,29); //You don't have enough gold
  387. cb->showInfoDialog(&iw);
  388. //act as if player refused
  389. joinDecision(h,cost,false);
  390. return;
  391. }
  392. //take gold
  393. if(cost)
  394. cb->giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  395. giveReward(h);
  396. cb->tryJoiningArmy(this, h, true, true);
  397. }
  398. }
  399. void CGCreature::fight( const CGHeroInstance *h ) const
  400. {
  401. //split stacks
  402. int stacksCount = getNumberOfStacks(h);
  403. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  404. int amount = getStackCount(SlotID(0));
  405. int m = amount / stacksCount;
  406. int b = stacksCount * (m + 1) - amount;
  407. int a = stacksCount - b;
  408. SlotID sourceSlot = stacks.begin()->first;
  409. for (int slotID = 1; slotID < a; ++slotID)
  410. {
  411. int stackSize = m + 1;
  412. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  413. }
  414. for (int slotID = a; slotID < stacksCount; ++slotID)
  415. {
  416. int stackSize = m;
  417. if (slotID) //don't do this when a = 0 -> stack is single
  418. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  419. }
  420. if (stacksCount > 1)
  421. {
  422. if (containsUpgradedStack()) //upgrade
  423. {
  424. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  425. const auto & upgrades = getStack(slotID).type->upgrades;
  426. if(!upgrades.empty())
  427. {
  428. auto it = RandomGeneratorUtil::nextItem(upgrades, cb->gameState()->getRandomGenerator());
  429. cb->changeStackType(StackLocation(this, slotID), it->toCreature());
  430. }
  431. }
  432. }
  433. cb->startBattle(h, this);
  434. }
  435. void CGCreature::flee( const CGHeroInstance * h ) const
  436. {
  437. BlockingDialog ynd(true,false);
  438. ynd.player = h->tempOwner;
  439. ynd.text.appendLocalString(EMetaText::ADVOB_TXT,91);
  440. ynd.text.replaceName(getCreature(), getStackCount(SlotID(0)));
  441. cb->showBlockingDialog(this, &ynd);
  442. }
  443. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  444. {
  445. if(result.winner == BattleSide::ATTACKER)
  446. {
  447. giveReward(hero);
  448. cb->removeObject(this, hero->getOwner());
  449. }
  450. else if(result.winner == BattleSide::NONE) // draw
  451. {
  452. // guarded reward is lost forever on draw
  453. cb->removeObject(this, hero->getOwner());
  454. }
  455. else
  456. {
  457. //merge stacks into one
  458. TSlots::const_iterator i;
  459. const CCreature * cre = getCreature().toCreature();
  460. for(i = stacks.begin(); i != stacks.end(); i++)
  461. {
  462. if(cre->isMyUpgrade(i->second->type))
  463. {
  464. cb->changeStackType(StackLocation(this, i->first), cre); //un-upgrade creatures
  465. }
  466. }
  467. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  468. if(!hasStackAtSlot(SlotID(0)))
  469. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  470. while(stacks.size() > 1) //hopefully that's enough
  471. {
  472. // 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)
  473. i = stacks.end();
  474. i--;
  475. SlotID slot = getSlotFor(i->second->type);
  476. if(slot == i->first) //no reason to move stack to its own slot
  477. break;
  478. else
  479. cb->moveStack(StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  480. }
  481. cb->setObjPropertyValue(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  482. }
  483. }
  484. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, int32_t answer) const
  485. {
  486. auto action = takenAction(hero);
  487. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  488. joinDecision(hero, action, answer);
  489. else if(action != FIGHT)
  490. fleeDecision(hero, answer);
  491. else
  492. assert(0);
  493. }
  494. bool CGCreature::containsUpgradedStack() const
  495. {
  496. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  497. float a = 2992.911117f;
  498. float b = 14174.264968f;
  499. float c = 5325.181015f;
  500. float d = 32788.727920f;
  501. int val = static_cast<int>(std::floor(a * visitablePos().x + b * visitablePos().y + c * visitablePos().z + d));
  502. return ((val % 32768) % 100) < 50;
  503. }
  504. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  505. {
  506. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  507. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  508. int split = 1;
  509. if (strengthRatio < 0.5f)
  510. split = 7;
  511. else if (strengthRatio < 0.67f)
  512. split = 6;
  513. else if (strengthRatio < 1)
  514. split = 5;
  515. else if (strengthRatio < 1.5f)
  516. split = 4;
  517. else if (strengthRatio < 2)
  518. split = 3;
  519. else
  520. split = 2;
  521. ui32 a = 1550811371u;
  522. ui32 b = 3359066809u;
  523. ui32 c = 1943276003u;
  524. ui32 d = 3174620878u;
  525. ui32 R1 = a * static_cast<ui32>(visitablePos().x) + b * static_cast<ui32>(visitablePos().y) + c * static_cast<ui32>(visitablePos().z) + d;
  526. ui32 R2 = (R1 >> 16) & 0x7fff;
  527. int R4 = R2 % 100 + 1;
  528. if (R4 <= 20)
  529. split -= 1;
  530. else if (R4 >= 80)
  531. split += 1;
  532. vstd::amin(split, getStack(SlotID(0)).count); //can't divide into more stacks than creatures total
  533. vstd::amin(split, 7); //can't have more than 7 stacks
  534. return split;
  535. }
  536. void CGCreature::giveReward(const CGHeroInstance * h) const
  537. {
  538. InfoWindow iw;
  539. iw.player = h->tempOwner;
  540. if(!resources.empty())
  541. {
  542. cb->giveResources(h->tempOwner, resources);
  543. for(const auto & res : GameResID::ALL_RESOURCES())
  544. {
  545. if(resources[res] > 0)
  546. iw.components.emplace_back(ComponentType::RESOURCE, res, resources[res]);
  547. }
  548. }
  549. if(gainedArtifact != ArtifactID::NONE)
  550. {
  551. cb->giveHeroNewArtifact(h, gainedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  552. iw.components.emplace_back(ComponentType::ARTIFACT, gainedArtifact);
  553. }
  554. if(!iw.components.empty())
  555. {
  556. iw.type = EInfoWindowMode::AUTO;
  557. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 183); // % has found treasure
  558. iw.text.replaceRawString(h->getNameTranslated());
  559. cb->showInfoDialog(&iw);
  560. }
  561. }
  562. static const std::vector<std::string> CHARACTER_JSON =
  563. {
  564. "compliant", "friendly", "aggressive", "hostile", "savage"
  565. };
  566. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  567. {
  568. handler.serializeEnum("character", character, CHARACTER_JSON);
  569. if(handler.saving)
  570. {
  571. if(hasStackAtSlot(SlotID(0)))
  572. {
  573. si32 amount = getStack(SlotID(0)).count;
  574. handler.serializeInt("amount", amount, 0);
  575. }
  576. }
  577. else
  578. {
  579. si32 amount = 0;
  580. handler.serializeInt("amount", amount);
  581. auto * hlp = new CStackInstance();
  582. hlp->count = amount;
  583. //type will be set during initialization
  584. putStack(SlotID(0), hlp);
  585. }
  586. resources.serializeJson(handler, "rewardResources");
  587. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  588. handler.serializeBool("noGrowing", notGrowingTeam);
  589. handler.serializeBool("neverFlees", neverFlees);
  590. handler.serializeStruct("rewardMessage", message);
  591. }
  592. VCMI_LIB_NAMESPACE_END