CGCreature.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 "../NetPacks.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../CConfigHandler.h"
  15. #include "../GameSettings.h"
  16. #include "../IGameCallback.h"
  17. #include "../serializer/JsonSerializeFormat.h"
  18. VCMI_LIB_NAMESPACE_BEGIN
  19. std::string CGCreature::getHoverText(PlayerColor player) const
  20. {
  21. if(stacks.empty())
  22. {
  23. //should not happen...
  24. logGlobal->error("Invalid stack at tile %s: subID=%d; id=%d", pos.toString(), subID, id.getNum());
  25. return "INVALID_STACK";
  26. }
  27. std::string hoverName;
  28. MetaString ms;
  29. CCreature::CreatureQuantityId monsterQuantityId = stacks.begin()->second->getQuantityID();
  30. int quantityTextIndex = 172 + 3 * (int)monsterQuantityId;
  31. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  32. ms.appendRawString(CCreature::getQuantityRangeStringForId(monsterQuantityId));
  33. else
  34. ms.appendLocalString(EMetaText::ARRAY_TXT, quantityTextIndex);
  35. ms.appendRawString(" ");
  36. ms.appendLocalString(EMetaText::CRE_PL_NAMES,subID);
  37. hoverName = ms.toString();
  38. return hoverName;
  39. }
  40. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  41. {
  42. std::string hoverName;
  43. if(hero->hasVisions(this, 0))
  44. {
  45. MetaString ms;
  46. ms.appendNumber(stacks.begin()->second->count);
  47. ms.appendRawString(" ");
  48. ms.appendLocalString(EMetaText::CRE_PL_NAMES,subID);
  49. ms.appendRawString("\n\n");
  50. int decision = takenAction(hero, true);
  51. switch (decision)
  52. {
  53. case FIGHT:
  54. ms.appendLocalString(EMetaText::GENERAL_TXT,246);
  55. break;
  56. case FLEE:
  57. ms.appendLocalString(EMetaText::GENERAL_TXT,245);
  58. break;
  59. case JOIN_FOR_FREE:
  60. ms.appendLocalString(EMetaText::GENERAL_TXT,243);
  61. break;
  62. default: //decision = cost in gold
  63. ms.appendRawString(boost::str(boost::format(VLC->generaltexth->allTexts[244]) % decision));
  64. break;
  65. }
  66. hoverName = ms.toString();
  67. }
  68. else
  69. {
  70. hoverName = getHoverText(hero->tempOwner);
  71. }
  72. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.title");
  73. int choice;
  74. double ratio = (static_cast<double>(getArmyStrength()) / hero->getTotalStrength());
  75. if (ratio < 0.1) choice = 0;
  76. else if (ratio < 0.25) choice = 1;
  77. else if (ratio < 0.6) choice = 2;
  78. else if (ratio < 0.9) choice = 3;
  79. else if (ratio < 1.1) choice = 4;
  80. else if (ratio < 1.3) choice = 5;
  81. else if (ratio < 1.8) choice = 6;
  82. else if (ratio < 2.5) choice = 7;
  83. else if (ratio < 4) choice = 8;
  84. else if (ratio < 8) choice = 9;
  85. else if (ratio < 20) choice = 10;
  86. else choice = 11;
  87. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.levels." + std::to_string(choice));
  88. return hoverName;
  89. }
  90. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  91. {
  92. int action = takenAction(h);
  93. switch( action ) //decide what we do...
  94. {
  95. case FIGHT:
  96. fight(h);
  97. break;
  98. case FLEE:
  99. {
  100. flee(h);
  101. break;
  102. }
  103. case JOIN_FOR_FREE: //join for free
  104. {
  105. BlockingDialog ynd(true,false);
  106. ynd.player = h->tempOwner;
  107. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, 86);
  108. ynd.text.replaceLocalString(EMetaText::CRE_PL_NAMES, subID);
  109. cb->showBlockingDialog(&ynd);
  110. break;
  111. }
  112. default: //join for gold
  113. {
  114. assert(action > 0);
  115. //ask if player agrees to pay gold
  116. BlockingDialog ynd(true,false);
  117. ynd.player = h->tempOwner;
  118. std::string tmp = VLC->generaltexth->advobtxt[90];
  119. boost::algorithm::replace_first(tmp, "%d", std::to_string(getStackCount(SlotID(0))));
  120. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  121. boost::algorithm::replace_first(tmp,"%s",VLC->creh->objects[subID]->getNamePluralTranslated());
  122. ynd.text.appendRawString(tmp);
  123. cb->showBlockingDialog(&ynd);
  124. break;
  125. }
  126. }
  127. }
  128. void CGCreature::initObj(CRandomGenerator & rand)
  129. {
  130. blockVisit = true;
  131. switch(character)
  132. {
  133. case 0:
  134. character = -4;
  135. break;
  136. case 1:
  137. character = rand.nextInt(1, 7);
  138. break;
  139. case 2:
  140. character = rand.nextInt(1, 10);
  141. break;
  142. case 3:
  143. character = rand.nextInt(4, 10);
  144. break;
  145. case 4:
  146. character = 10;
  147. break;
  148. }
  149. stacks[SlotID(0)]->setType(CreatureID(subID));
  150. TQuantity &amount = stacks[SlotID(0)]->count;
  151. CCreature &c = *VLC->creh->objects[subID];
  152. if(amount == 0)
  153. {
  154. amount = rand.nextInt(c.ammMin, c.ammMax);
  155. if(amount == 0) //armies with 0 creatures are illegal
  156. {
  157. logGlobal->warn("Stack %s cannot have 0 creatures. Check properties of %s", nodeName(), c.nodeName());
  158. amount = 1;
  159. }
  160. }
  161. temppower = stacks[SlotID(0)]->count * static_cast<ui64>(1000);
  162. refusedJoining = false;
  163. }
  164. void CGCreature::newTurn(CRandomGenerator & rand) const
  165. {//Works only for stacks of single type of size up to 2 millions
  166. if (!notGrowingTeam)
  167. {
  168. if (stacks.begin()->second->count < VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP) && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  169. {
  170. ui32 power = static_cast<ui32>(temppower * (100 + VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  171. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  172. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  173. }
  174. }
  175. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  176. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->settings()->getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  177. }
  178. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  179. {
  180. switch (what)
  181. {
  182. case ObjProperty::MONSTER_COUNT:
  183. stacks[SlotID(0)]->count = val;
  184. break;
  185. case ObjProperty::MONSTER_POWER:
  186. temppower = val;
  187. break;
  188. case ObjProperty::MONSTER_EXP:
  189. giveStackExp(val);
  190. break;
  191. case ObjProperty::MONSTER_RESTORE_TYPE:
  192. formation.basicType = val;
  193. break;
  194. case ObjProperty::MONSTER_REFUSED_JOIN:
  195. refusedJoining = val;
  196. break;
  197. }
  198. }
  199. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  200. {
  201. //calculate relative strength of hero and creatures armies
  202. double relStrength = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  203. int powerFactor;
  204. if(relStrength >= 7)
  205. powerFactor = 11;
  206. else if(relStrength >= 1)
  207. powerFactor = static_cast<int>(2 * (relStrength - 1));
  208. else if(relStrength >= 0.5)
  209. powerFactor = -1;
  210. else if(relStrength >= 0.333)
  211. powerFactor = -2;
  212. else
  213. powerFactor = -3;
  214. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  215. const CCreature * myCreature = VLC->creh->objects[subID];
  216. myKindCres.insert(myCreature->getId()); //we
  217. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  218. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->objects)
  219. {
  220. if(vstd::contains(crea->upgrades, myCreature->getId())) //it's our base creatures
  221. myKindCres.insert(crea->getId());
  222. }
  223. int count = 0; //how many creatures of similar kind has hero
  224. int totalCount = 0;
  225. for(const auto & elem : h->Slots())
  226. {
  227. if(vstd::contains(myKindCres,elem.second->type->getId()))
  228. count += elem.second->count;
  229. totalCount += elem.second->count;
  230. }
  231. int sympathy = 0; // 0 if hero have no similar creatures
  232. if(count)
  233. sympathy++; // 1 - if hero have at least 1 similar creature
  234. if(count*2 > totalCount)
  235. sympathy++; // 2 - hero have similar creatures more that 50%
  236. int diplomacy = h->valOfBonuses(BonusType::WANDERING_CREATURES_JOIN_BONUS);
  237. int charisma = powerFactor + diplomacy + sympathy;
  238. if(charisma < character)
  239. return FIGHT;
  240. if (allowJoin)
  241. {
  242. if(diplomacy + sympathy + 1 >= character)
  243. return JOIN_FOR_FREE;
  244. else if(diplomacy * 2 + sympathy + 1 >= character)
  245. return VLC->creatures()->getByIndex(subID)->getRecruitCost(EGameResID::GOLD) * getStackCount(SlotID(0)); //join for gold
  246. }
  247. //we are still here - creatures have not joined hero, flee or fight
  248. if (charisma > character && !neverFlees)
  249. return FLEE;
  250. else
  251. return FIGHT;
  252. }
  253. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  254. {
  255. if(refusedJoining)
  256. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  257. if(pursue)
  258. {
  259. fight(h);
  260. }
  261. else
  262. {
  263. cb->removeObject(this);
  264. }
  265. }
  266. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  267. {
  268. if(!accept)
  269. {
  270. if(takenAction(h,false) == FLEE)
  271. {
  272. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  273. flee(h);
  274. }
  275. else //they fight
  276. {
  277. h->showInfoDialog(87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  278. fight(h);
  279. }
  280. }
  281. else //accepted
  282. {
  283. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  284. {
  285. InfoWindow iw;
  286. iw.player = h->tempOwner;
  287. iw.text.appendLocalString(EMetaText::GENERAL_TXT,29); //You don't have enough gold
  288. cb->showInfoDialog(&iw);
  289. //act as if player refused
  290. joinDecision(h,cost,false);
  291. return;
  292. }
  293. //take gold
  294. if(cost)
  295. cb->giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  296. giveReward(h);
  297. cb->tryJoiningArmy(this, h, true, true);
  298. }
  299. }
  300. void CGCreature::fight( const CGHeroInstance *h ) const
  301. {
  302. //split stacks
  303. //TODO: multiple creature types in a stack?
  304. int basicType = stacks.begin()->second->type->getId();
  305. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  306. int stacksCount = getNumberOfStacks(h);
  307. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  308. int amount = getStackCount(SlotID(0));
  309. int m = amount / stacksCount;
  310. int b = stacksCount * (m + 1) - amount;
  311. int a = stacksCount - b;
  312. SlotID sourceSlot = stacks.begin()->first;
  313. for (int slotID = 1; slotID < a; ++slotID)
  314. {
  315. int stackSize = m + 1;
  316. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  317. }
  318. for (int slotID = a; slotID < stacksCount; ++slotID)
  319. {
  320. int stackSize = m;
  321. if (slotID) //don't do this when a = 0 -> stack is single
  322. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  323. }
  324. if (stacksCount > 1)
  325. {
  326. if (containsUpgradedStack()) //upgrade
  327. {
  328. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  329. const auto & upgrades = getStack(slotID).type->upgrades;
  330. if(!upgrades.empty())
  331. {
  332. auto it = RandomGeneratorUtil::nextItem(upgrades, CRandomGenerator::getDefault());
  333. cb->changeStackType(StackLocation(this, slotID), VLC->creh->objects[*it]);
  334. }
  335. }
  336. }
  337. cb->startBattleI(h, this);
  338. }
  339. void CGCreature::flee( const CGHeroInstance * h ) const
  340. {
  341. BlockingDialog ynd(true,false);
  342. ynd.player = h->tempOwner;
  343. ynd.text.appendLocalString(EMetaText::ADVOB_TXT,91);
  344. ynd.text.replaceLocalString(EMetaText::CRE_PL_NAMES, subID);
  345. cb->showBlockingDialog(&ynd);
  346. }
  347. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  348. {
  349. if(result.winner == 0)
  350. {
  351. giveReward(hero);
  352. cb->removeObject(this);
  353. }
  354. else if(result.winner > 1) // draw
  355. {
  356. // guarded reward is lost forever on draw
  357. cb->removeObject(this);
  358. }
  359. else
  360. {
  361. //merge stacks into one
  362. TSlots::const_iterator i;
  363. CCreature * cre = VLC->creh->objects[formation.basicType];
  364. for(i = stacks.begin(); i != stacks.end(); i++)
  365. {
  366. if(cre->isMyUpgrade(i->second->type))
  367. {
  368. cb->changeStackType(StackLocation(this, i->first), cre); //un-upgrade creatures
  369. }
  370. }
  371. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  372. if(!hasStackAtSlot(SlotID(0)))
  373. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  374. while(stacks.size() > 1) //hopefully that's enough
  375. {
  376. // 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)
  377. i = stacks.end();
  378. i--;
  379. SlotID slot = getSlotFor(i->second->type);
  380. if(slot == i->first) //no reason to move stack to its own slot
  381. break;
  382. else
  383. cb->moveStack(StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  384. }
  385. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  386. }
  387. }
  388. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  389. {
  390. auto action = takenAction(hero);
  391. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  392. joinDecision(hero, action, answer);
  393. else if(action != FIGHT)
  394. fleeDecision(hero, answer);
  395. else
  396. assert(0);
  397. }
  398. bool CGCreature::containsUpgradedStack() const
  399. {
  400. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  401. float a = 2992.911117f;
  402. float b = 14174.264968f;
  403. float c = 5325.181015f;
  404. float d = 32788.727920f;
  405. int val = static_cast<int>(std::floor(a * pos.x + b * pos.y + c * pos.z + d));
  406. return ((val % 32768) % 100) < 50;
  407. }
  408. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  409. {
  410. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  411. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  412. int split = 1;
  413. if (strengthRatio < 0.5f)
  414. split = 7;
  415. else if (strengthRatio < 0.67f)
  416. split = 6;
  417. else if (strengthRatio < 1)
  418. split = 5;
  419. else if (strengthRatio < 1.5f)
  420. split = 4;
  421. else if (strengthRatio < 2)
  422. split = 3;
  423. else
  424. split = 2;
  425. ui32 a = 1550811371u;
  426. ui32 b = 3359066809u;
  427. ui32 c = 1943276003u;
  428. ui32 d = 3174620878u;
  429. ui32 R1 = a * static_cast<ui32>(pos.x) + b * static_cast<ui32>(pos.y) + c * static_cast<ui32>(pos.z) + d;
  430. ui32 R2 = (R1 >> 16) & 0x7fff;
  431. int R4 = R2 % 100 + 1;
  432. if (R4 <= 20)
  433. split -= 1;
  434. else if (R4 >= 80)
  435. split += 1;
  436. vstd::amin(split, getStack(SlotID(0)).count); //can't divide into more stacks than creatures total
  437. vstd::amin(split, 7); //can't have more than 7 stacks
  438. return split;
  439. }
  440. void CGCreature::giveReward(const CGHeroInstance * h) const
  441. {
  442. InfoWindow iw;
  443. iw.player = h->tempOwner;
  444. if(!resources.empty())
  445. {
  446. cb->giveResources(h->tempOwner, resources);
  447. for(int i = 0; i < resources.size(); i++)
  448. {
  449. if(resources[i] > 0)
  450. iw.components.emplace_back(Component::EComponentType::RESOURCE, i, resources[i], 0);
  451. }
  452. }
  453. if(gainedArtifact != ArtifactID::NONE)
  454. {
  455. cb->giveHeroNewArtifact(h, VLC->arth->objects[gainedArtifact], ArtifactPosition::FIRST_AVAILABLE);
  456. iw.components.emplace_back(Component::EComponentType::ARTIFACT, gainedArtifact, 0, 0);
  457. }
  458. if(!iw.components.empty())
  459. {
  460. iw.type = EInfoWindowMode::AUTO;
  461. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 183); // % has found treasure
  462. iw.text.replaceRawString(h->getNameTranslated());
  463. cb->showInfoDialog(&iw);
  464. }
  465. }
  466. static const std::vector<std::string> CHARACTER_JSON =
  467. {
  468. "compliant", "friendly", "aggressive", "hostile", "savage"
  469. };
  470. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  471. {
  472. handler.serializeEnum("character", character, CHARACTER_JSON);
  473. if(handler.saving)
  474. {
  475. if(hasStackAtSlot(SlotID(0)))
  476. {
  477. si32 amount = getStack(SlotID(0)).count;
  478. handler.serializeInt("amount", amount, 0);
  479. }
  480. }
  481. else
  482. {
  483. si32 amount = 0;
  484. handler.serializeInt("amount", amount);
  485. auto * hlp = new CStackInstance();
  486. hlp->count = amount;
  487. //type will be set during initialization
  488. putStack(SlotID(0), hlp);
  489. }
  490. resources.serializeJson(handler, "rewardResources");
  491. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  492. handler.serializeBool("noGrowing", notGrowingTeam);
  493. handler.serializeBool("neverFlees", neverFlees);
  494. handler.serializeString("rewardMessage", message);
  495. }
  496. VCMI_LIB_NAMESPACE_END