MiscObjects.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198
  1. /*
  2. * MiscObjects.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 "MiscObjects.h"
  12. #include "../StringConstants.h"
  13. #include "../NetPacks.h"
  14. #include "../CGeneralTextHandler.h"
  15. #include "../CSoundBase.h"
  16. #include "../CConfigHandler.h"
  17. #include "../CModHandler.h"
  18. #include "../CHeroHandler.h"
  19. #include "../CSkillHandler.h"
  20. #include "../spells/CSpellHandler.h"
  21. #include "../IGameCallback.h"
  22. #include "../CGameState.h"
  23. #include "../mapping/CMap.h"
  24. #include "../CPlayerState.h"
  25. #include "../GameSettings.h"
  26. #include "../serializer/JsonSerializeFormat.h"
  27. #include "../mapObjectConstructors/AObjectTypeHandler.h"
  28. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  29. VCMI_LIB_NAMESPACE_BEGIN
  30. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  31. ui8 CGObelisk::obeliskCount = 0; //how many obelisks are on map
  32. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  33. ///helpers
  34. static std::string visitedTxt(const bool visited)
  35. {
  36. int id = visited ? 352 : 353;
  37. return VLC->generaltexth->allTexts[id];
  38. }
  39. void CTeamVisited::setPropertyDer(ui8 what, ui32 val)
  40. {
  41. if(what == CTeamVisited::OBJPROP_VISITED)
  42. players.insert(PlayerColor(val));
  43. }
  44. bool CTeamVisited::wasVisited(PlayerColor player) const
  45. {
  46. return wasVisited(cb->getPlayerState(player)->team);
  47. }
  48. bool CTeamVisited::wasVisited(const CGHeroInstance * h) const
  49. {
  50. return wasVisited(h->tempOwner);
  51. }
  52. bool CTeamVisited::wasVisited(const TeamID & team) const
  53. {
  54. for(const auto & i : players)
  55. {
  56. if(cb->getPlayerState(i)->team == team)
  57. return true;
  58. }
  59. return false;
  60. }
  61. std::string CGCreature::getHoverText(PlayerColor player) const
  62. {
  63. if(stacks.empty())
  64. {
  65. //should not happen...
  66. logGlobal->error("Invalid stack at tile %s: subID=%d; id=%d", pos.toString(), subID, id.getNum());
  67. return "INVALID_STACK";
  68. }
  69. std::string hoverName;
  70. MetaString ms;
  71. CCreature::CreatureQuantityId monsterQuantityId = stacks.begin()->second->getQuantityID();
  72. int quantityTextIndex = 172 + 3 * (int)monsterQuantityId;
  73. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  74. ms << CCreature::getQuantityRangeStringForId(monsterQuantityId);
  75. else
  76. ms.addTxt(MetaString::ARRAY_TXT, quantityTextIndex);
  77. ms << " " ;
  78. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  79. ms.toString(hoverName);
  80. return hoverName;
  81. }
  82. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  83. {
  84. std::string hoverName;
  85. if(hero->hasVisions(this, 0))
  86. {
  87. MetaString ms;
  88. ms << stacks.begin()->second->count;
  89. ms << " " ;
  90. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  91. ms << "\n";
  92. int decision = takenAction(hero, true);
  93. switch (decision)
  94. {
  95. case FIGHT:
  96. ms.addTxt(MetaString::GENERAL_TXT,246);
  97. break;
  98. case FLEE:
  99. ms.addTxt(MetaString::GENERAL_TXT,245);
  100. break;
  101. case JOIN_FOR_FREE:
  102. ms.addTxt(MetaString::GENERAL_TXT,243);
  103. break;
  104. default: //decision = cost in gold
  105. ms << boost::to_string(boost::format(VLC->generaltexth->allTexts[244]) % decision);
  106. break;
  107. }
  108. ms.toString(hoverName);
  109. }
  110. else
  111. {
  112. hoverName = getHoverText(hero->tempOwner);
  113. }
  114. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.title");
  115. int choice;
  116. double ratio = (static_cast<double>(getArmyStrength()) / hero->getTotalStrength());
  117. if (ratio < 0.1) choice = 0;
  118. else if (ratio < 0.25) choice = 1;
  119. else if (ratio < 0.6) choice = 2;
  120. else if (ratio < 0.9) choice = 3;
  121. else if (ratio < 1.1) choice = 4;
  122. else if (ratio < 1.3) choice = 5;
  123. else if (ratio < 1.8) choice = 6;
  124. else if (ratio < 2.5) choice = 7;
  125. else if (ratio < 4) choice = 8;
  126. else if (ratio < 8) choice = 9;
  127. else if (ratio < 20) choice = 10;
  128. else choice = 11;
  129. hoverName += VLC->generaltexth->translate("vcmi.adventureMap.monsterThreat.levels." + std::to_string(choice));
  130. return hoverName;
  131. }
  132. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  133. {
  134. int action = takenAction(h);
  135. switch( action ) //decide what we do...
  136. {
  137. case FIGHT:
  138. fight(h);
  139. break;
  140. case FLEE:
  141. {
  142. flee(h);
  143. break;
  144. }
  145. case JOIN_FOR_FREE: //join for free
  146. {
  147. BlockingDialog ynd(true,false);
  148. ynd.player = h->tempOwner;
  149. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  150. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  151. cb->showBlockingDialog(&ynd);
  152. break;
  153. }
  154. default: //join for gold
  155. {
  156. assert(action > 0);
  157. //ask if player agrees to pay gold
  158. BlockingDialog ynd(true,false);
  159. ynd.player = h->tempOwner;
  160. std::string tmp = VLC->generaltexth->advobtxt[90];
  161. boost::algorithm::replace_first(tmp, "%d", std::to_string(getStackCount(SlotID(0))));
  162. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  163. boost::algorithm::replace_first(tmp,"%s",VLC->creh->objects[subID]->getNamePluralTranslated());
  164. ynd.text << tmp;
  165. cb->showBlockingDialog(&ynd);
  166. break;
  167. }
  168. }
  169. }
  170. void CGCreature::initObj(CRandomGenerator & rand)
  171. {
  172. blockVisit = true;
  173. switch(character)
  174. {
  175. case 0:
  176. character = -4;
  177. break;
  178. case 1:
  179. character = rand.nextInt(1, 7);
  180. break;
  181. case 2:
  182. character = rand.nextInt(1, 10);
  183. break;
  184. case 3:
  185. character = rand.nextInt(4, 10);
  186. break;
  187. case 4:
  188. character = 10;
  189. break;
  190. }
  191. stacks[SlotID(0)]->setType(CreatureID(subID));
  192. TQuantity &amount = stacks[SlotID(0)]->count;
  193. CCreature &c = *VLC->creh->objects[subID];
  194. if(amount == 0)
  195. {
  196. amount = rand.nextInt(c.ammMin, c.ammMax);
  197. if(amount == 0) //armies with 0 creatures are illegal
  198. {
  199. logGlobal->warn("Stack %s cannot have 0 creatures. Check properties of %s", nodeName(), c.nodeName());
  200. amount = 1;
  201. }
  202. }
  203. temppower = stacks[SlotID(0)]->count * static_cast<ui64>(1000);
  204. refusedJoining = false;
  205. }
  206. void CGCreature::newTurn(CRandomGenerator & rand) const
  207. {//Works only for stacks of single type of size up to 2 millions
  208. if (!notGrowingTeam)
  209. {
  210. 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)
  211. {
  212. ui32 power = static_cast<ui32>(temppower * (100 + VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  213. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, VLC->settings()->getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  214. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  215. }
  216. }
  217. if (VLC->settings()->getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  218. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->settings()->getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  219. }
  220. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  221. {
  222. switch (what)
  223. {
  224. case ObjProperty::MONSTER_COUNT:
  225. stacks[SlotID(0)]->count = val;
  226. break;
  227. case ObjProperty::MONSTER_POWER:
  228. temppower = val;
  229. break;
  230. case ObjProperty::MONSTER_EXP:
  231. giveStackExp(val);
  232. break;
  233. case ObjProperty::MONSTER_RESTORE_TYPE:
  234. formation.basicType = val;
  235. break;
  236. case ObjProperty::MONSTER_REFUSED_JOIN:
  237. refusedJoining = val;
  238. break;
  239. }
  240. }
  241. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  242. {
  243. //calculate relative strength of hero and creatures armies
  244. double relStrength = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  245. int powerFactor;
  246. if(relStrength >= 7)
  247. powerFactor = 11;
  248. else if(relStrength >= 1)
  249. powerFactor = static_cast<int>(2 * (relStrength - 1));
  250. else if(relStrength >= 0.5)
  251. powerFactor = -1;
  252. else if(relStrength >= 0.333)
  253. powerFactor = -2;
  254. else
  255. powerFactor = -3;
  256. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  257. const CCreature * myCreature = VLC->creh->objects[subID];
  258. myKindCres.insert(myCreature->getId()); //we
  259. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  260. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->objects)
  261. {
  262. if(vstd::contains(crea->upgrades, myCreature->getId())) //it's our base creatures
  263. myKindCres.insert(crea->getId());
  264. }
  265. int count = 0; //how many creatures of similar kind has hero
  266. int totalCount = 0;
  267. for(const auto & elem : h->Slots())
  268. {
  269. if(vstd::contains(myKindCres,elem.second->type->getId()))
  270. count += elem.second->count;
  271. totalCount += elem.second->count;
  272. }
  273. int sympathy = 0; // 0 if hero have no similar creatures
  274. if(count)
  275. sympathy++; // 1 - if hero have at least 1 similar creature
  276. if(count*2 > totalCount)
  277. sympathy++; // 2 - hero have similar creatures more that 50%
  278. int diplomacy = h->valOfBonuses(BonusType::WANDERING_CREATURES_JOIN_BONUS);
  279. int charisma = powerFactor + diplomacy + sympathy;
  280. if(charisma < character)
  281. return FIGHT;
  282. if (allowJoin)
  283. {
  284. if(diplomacy + sympathy + 1 >= character)
  285. return JOIN_FOR_FREE;
  286. else if(diplomacy * 2 + sympathy + 1 >= character)
  287. return VLC->creatures()->getByIndex(subID)->getRecruitCost(EGameResID::GOLD) * getStackCount(SlotID(0)); //join for gold
  288. }
  289. //we are still here - creatures have not joined hero, flee or fight
  290. if (charisma > character && !neverFlees)
  291. return FLEE;
  292. else
  293. return FIGHT;
  294. }
  295. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  296. {
  297. if(refusedJoining)
  298. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  299. if(pursue)
  300. {
  301. fight(h);
  302. }
  303. else
  304. {
  305. cb->removeObject(this);
  306. }
  307. }
  308. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  309. {
  310. if(!accept)
  311. {
  312. if(takenAction(h,false) == FLEE)
  313. {
  314. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  315. flee(h);
  316. }
  317. else //they fight
  318. {
  319. h->showInfoDialog(87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  320. fight(h);
  321. }
  322. }
  323. else //accepted
  324. {
  325. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  326. {
  327. InfoWindow iw;
  328. iw.player = h->tempOwner;
  329. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  330. cb->showInfoDialog(&iw);
  331. //act as if player refused
  332. joinDecision(h,cost,false);
  333. return;
  334. }
  335. //take gold
  336. if(cost)
  337. cb->giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  338. giveReward(h);
  339. cb->tryJoiningArmy(this, h, true, true);
  340. }
  341. }
  342. void CGCreature::fight( const CGHeroInstance *h ) const
  343. {
  344. //split stacks
  345. //TODO: multiple creature types in a stack?
  346. int basicType = stacks.begin()->second->type->getId();
  347. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  348. int stacksCount = getNumberOfStacks(h);
  349. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  350. int amount = getStackCount(SlotID(0));
  351. int m = amount / stacksCount;
  352. int b = stacksCount * (m + 1) - amount;
  353. int a = stacksCount - b;
  354. SlotID sourceSlot = stacks.begin()->first;
  355. for (int slotID = 1; slotID < a; ++slotID)
  356. {
  357. int stackSize = m + 1;
  358. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  359. }
  360. for (int slotID = a; slotID < stacksCount; ++slotID)
  361. {
  362. int stackSize = m;
  363. if (slotID) //don't do this when a = 0 -> stack is single
  364. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, SlotID(slotID)), stackSize);
  365. }
  366. if (stacksCount > 1)
  367. {
  368. if (containsUpgradedStack()) //upgrade
  369. {
  370. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  371. const auto & upgrades = getStack(slotID).type->upgrades;
  372. if(!upgrades.empty())
  373. {
  374. auto it = RandomGeneratorUtil::nextItem(upgrades, CRandomGenerator::getDefault());
  375. cb->changeStackType(StackLocation(this, slotID), VLC->creh->objects[*it]);
  376. }
  377. }
  378. }
  379. cb->startBattleI(h, this);
  380. }
  381. void CGCreature::flee( const CGHeroInstance * h ) const
  382. {
  383. BlockingDialog ynd(true,false);
  384. ynd.player = h->tempOwner;
  385. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  386. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  387. cb->showBlockingDialog(&ynd);
  388. }
  389. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  390. {
  391. if(result.winner == 0)
  392. {
  393. giveReward(hero);
  394. cb->removeObject(this);
  395. }
  396. else if(result.winner > 1) // draw
  397. {
  398. // guarded reward is lost forever on draw
  399. cb->removeObject(this);
  400. }
  401. else
  402. {
  403. //merge stacks into one
  404. TSlots::const_iterator i;
  405. CCreature * cre = VLC->creh->objects[formation.basicType];
  406. for(i = stacks.begin(); i != stacks.end(); i++)
  407. {
  408. if(cre->isMyUpgrade(i->second->type))
  409. {
  410. cb->changeStackType(StackLocation(this, i->first), cre); //un-upgrade creatures
  411. }
  412. }
  413. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  414. if(!hasStackAtSlot(SlotID(0)))
  415. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  416. while(stacks.size() > 1) //hopefully that's enough
  417. {
  418. // 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)
  419. i = stacks.end();
  420. i--;
  421. SlotID slot = getSlotFor(i->second->type);
  422. if(slot == i->first) //no reason to move stack to its own slot
  423. break;
  424. else
  425. cb->moveStack(StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  426. }
  427. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  428. }
  429. }
  430. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  431. {
  432. auto action = takenAction(hero);
  433. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  434. joinDecision(hero, action, answer);
  435. else if(action != FIGHT)
  436. fleeDecision(hero, answer);
  437. else
  438. assert(0);
  439. }
  440. bool CGCreature::containsUpgradedStack() const
  441. {
  442. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  443. float a = 2992.911117f;
  444. float b = 14174.264968f;
  445. float c = 5325.181015f;
  446. float d = 32788.727920f;
  447. int val = static_cast<int>(std::floor(a * pos.x + b * pos.y + c * pos.z + d));
  448. return ((val % 32768) % 100) < 50;
  449. }
  450. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  451. {
  452. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  453. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  454. int split = 1;
  455. if (strengthRatio < 0.5f)
  456. split = 7;
  457. else if (strengthRatio < 0.67f)
  458. split = 6;
  459. else if (strengthRatio < 1)
  460. split = 5;
  461. else if (strengthRatio < 1.5f)
  462. split = 4;
  463. else if (strengthRatio < 2)
  464. split = 3;
  465. else
  466. split = 2;
  467. ui32 a = 1550811371u;
  468. ui32 b = 3359066809u;
  469. ui32 c = 1943276003u;
  470. ui32 d = 3174620878u;
  471. ui32 R1 = a * static_cast<ui32>(pos.x) + b * static_cast<ui32>(pos.y) + c * static_cast<ui32>(pos.z) + d;
  472. ui32 R2 = (R1 >> 16) & 0x7fff;
  473. int R4 = R2 % 100 + 1;
  474. if (R4 <= 20)
  475. split -= 1;
  476. else if (R4 >= 80)
  477. split += 1;
  478. vstd::amin(split, getStack(SlotID(0)).count); //can't divide into more stacks than creatures total
  479. vstd::amin(split, 7); //can't have more than 7 stacks
  480. return split;
  481. }
  482. void CGCreature::giveReward(const CGHeroInstance * h) const
  483. {
  484. InfoWindow iw;
  485. iw.player = h->tempOwner;
  486. if(!resources.empty())
  487. {
  488. cb->giveResources(h->tempOwner, resources);
  489. for(int i = 0; i < resources.size(); i++)
  490. {
  491. if(resources[i] > 0)
  492. iw.components.emplace_back(Component::EComponentType::RESOURCE, i, resources[i], 0);
  493. }
  494. }
  495. if(gainedArtifact != ArtifactID::NONE)
  496. {
  497. cb->giveHeroNewArtifact(h, VLC->arth->objects[gainedArtifact], ArtifactPosition::FIRST_AVAILABLE);
  498. iw.components.emplace_back(Component::EComponentType::ARTIFACT, gainedArtifact, 0, 0);
  499. }
  500. if(!iw.components.empty())
  501. {
  502. iw.type = EInfoWindowMode::AUTO;
  503. iw.text.addTxt(MetaString::ADVOB_TXT, 183); // % has found treasure
  504. iw.text.addReplacement(h->getNameTranslated());
  505. cb->showInfoDialog(&iw);
  506. }
  507. }
  508. static const std::vector<std::string> CHARACTER_JSON =
  509. {
  510. "compliant", "friendly", "aggressive", "hostile", "savage"
  511. };
  512. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  513. {
  514. handler.serializeEnum("character", character, CHARACTER_JSON);
  515. if(handler.saving)
  516. {
  517. if(hasStackAtSlot(SlotID(0)))
  518. {
  519. si32 amount = getStack(SlotID(0)).count;
  520. handler.serializeInt("amount", amount, 0);
  521. }
  522. }
  523. else
  524. {
  525. si32 amount = 0;
  526. handler.serializeInt("amount", amount);
  527. auto * hlp = new CStackInstance();
  528. hlp->count = amount;
  529. //type will be set during initialization
  530. putStack(SlotID(0), hlp);
  531. }
  532. resources.serializeJson(handler, "rewardResources");
  533. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  534. handler.serializeBool("noGrowing", notGrowingTeam);
  535. handler.serializeBool("neverFlees", neverFlees);
  536. handler.serializeString("rewardMessage", message);
  537. }
  538. //CGMine
  539. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  540. {
  541. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  542. if(relations == 2) //we're visiting our mine
  543. {
  544. cb->showGarrisonDialog(id,h->id,true);
  545. return;
  546. }
  547. else if (relations == 1)//ally
  548. return;
  549. if(stacksCount()) //Mine is guarded
  550. {
  551. BlockingDialog ynd(true,false);
  552. ynd.player = h->tempOwner;
  553. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  554. cb->showBlockingDialog(&ynd);
  555. return;
  556. }
  557. flagMine(h->tempOwner);
  558. }
  559. void CGMine::newTurn(CRandomGenerator & rand) const
  560. {
  561. if(cb->getDate() == 1)
  562. return;
  563. if (tempOwner == PlayerColor::NEUTRAL)
  564. return;
  565. cb->giveResource(tempOwner, producedResource, producedQuantity);
  566. }
  567. void CGMine::initObj(CRandomGenerator & rand)
  568. {
  569. if(isAbandoned())
  570. {
  571. //set guardians
  572. int howManyTroglodytes = rand.nextInt(100, 199);
  573. auto * troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  574. putStack(SlotID(0), troglodytes);
  575. assert(!abandonedMineResources.empty());
  576. producedResource = *RandomGeneratorUtil::nextItem(abandonedMineResources, rand);
  577. }
  578. else
  579. {
  580. producedResource = GameResID(subID);
  581. }
  582. producedQuantity = defaultResProduction();
  583. }
  584. bool CGMine::isAbandoned() const
  585. {
  586. return (subID >= 7);
  587. }
  588. std::string CGMine::getObjectName() const
  589. {
  590. return VLC->generaltexth->translate("core.minename", subID);
  591. }
  592. std::string CGMine::getHoverText(PlayerColor player) const
  593. {
  594. std::string hoverName = CArmedInstance::getHoverText(player);
  595. if (tempOwner != PlayerColor::NEUTRAL)
  596. hoverName += "\n(" + VLC->generaltexth->restypes[producedResource] + ")";
  597. if(stacksCount())
  598. {
  599. hoverName += "\n";
  600. hoverName += VLC->generaltexth->allTexts[202]; //Guarded by
  601. hoverName += " ";
  602. hoverName += getArmyDescription();
  603. }
  604. return hoverName;
  605. }
  606. void CGMine::flagMine(const PlayerColor & player) const
  607. {
  608. assert(tempOwner != player);
  609. cb->setOwner(this, player); //not ours? flag it!
  610. InfoWindow iw;
  611. iw.type = EInfoWindowMode::AUTO;
  612. iw.soundID = soundBase::FLAGMINE;
  613. iw.text.addTxt(MetaString::MINE_EVNTS, producedResource); //not use subID, abandoned mines uses default mine texts
  614. iw.player = player;
  615. iw.components.emplace_back(Component::EComponentType::RESOURCE, producedResource, producedQuantity, -1);
  616. cb->showInfoDialog(&iw);
  617. }
  618. ui32 CGMine::defaultResProduction() const
  619. {
  620. switch(producedResource.toEnum())
  621. {
  622. case EGameResID::WOOD:
  623. case EGameResID::ORE:
  624. return 2;
  625. case EGameResID::GOLD:
  626. return 1000;
  627. default:
  628. return 1;
  629. }
  630. }
  631. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  632. {
  633. if(result.winner == 0) //attacker won
  634. {
  635. if(isAbandoned())
  636. {
  637. hero->showInfoDialog(85);
  638. }
  639. flagMine(hero->tempOwner);
  640. }
  641. }
  642. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  643. {
  644. if(answer)
  645. cb->startBattleI(hero, this);
  646. }
  647. void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
  648. {
  649. CCreatureSet::serializeJson(handler, "army", 7);
  650. if(isAbandoned())
  651. {
  652. if(handler.saving)
  653. {
  654. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  655. for(auto const & resID : abandonedMineResources)
  656. {
  657. JsonNode one(JsonNode::JsonType::DATA_STRING);
  658. one.String() = GameConstants::RESOURCE_NAMES[resID];
  659. node.Vector().push_back(one);
  660. }
  661. handler.serializeRaw("possibleResources", node, std::nullopt);
  662. }
  663. else
  664. {
  665. auto guard = handler.enterArray("possibleResources");
  666. const JsonNode & node = handler.getCurrent();
  667. auto names = node.convertTo<std::vector<std::string>>();
  668. for(const std::string & s : names)
  669. {
  670. int raw_res = vstd::find_pos(GameConstants::RESOURCE_NAMES, s);
  671. if(raw_res < 0)
  672. logGlobal->error("Invalid resource name: %s", s);
  673. else
  674. abandonedMineResources.emplace(raw_res);
  675. }
  676. }
  677. }
  678. else
  679. {
  680. serializeJsonOwner(handler);
  681. }
  682. }
  683. std::string CGResource::getHoverText(PlayerColor player) const
  684. {
  685. return VLC->generaltexth->restypes[subID];
  686. }
  687. void CGResource::initObj(CRandomGenerator & rand)
  688. {
  689. blockVisit = true;
  690. if(amount == CGResource::RANDOM_AMOUNT)
  691. {
  692. switch(static_cast<EGameResID>(subID))
  693. {
  694. case EGameResID::GOLD:
  695. amount = rand.nextInt(5, 10) * 100;
  696. break;
  697. case EGameResID::WOOD: case EGameResID::ORE:
  698. amount = rand.nextInt(6, 10);
  699. break;
  700. default:
  701. amount = rand.nextInt(3, 5);
  702. break;
  703. }
  704. }
  705. }
  706. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  707. {
  708. if(stacksCount())
  709. {
  710. if(!message.empty())
  711. {
  712. BlockingDialog ynd(true,false);
  713. ynd.player = h->getOwner();
  714. ynd.text << message;
  715. cb->showBlockingDialog(&ynd);
  716. }
  717. else
  718. {
  719. blockingDialogAnswered(h, true); //behave as if player accepted battle
  720. }
  721. }
  722. else
  723. collectRes(h->getOwner());
  724. }
  725. void CGResource::collectRes(const PlayerColor & player) const
  726. {
  727. cb->giveResource(player, static_cast<EGameResID>(subID), amount);
  728. InfoWindow sii;
  729. sii.player = player;
  730. if(!message.empty())
  731. {
  732. sii.type = EInfoWindowMode::AUTO;
  733. sii.text << message;
  734. }
  735. else
  736. {
  737. sii.type = EInfoWindowMode::INFO;
  738. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  739. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  740. }
  741. sii.components.emplace_back(Component::EComponentType::RESOURCE,subID,amount,0);
  742. sii.soundID = soundBase::pickup01 + CRandomGenerator::getDefault().nextInt(6);
  743. cb->showInfoDialog(&sii);
  744. cb->removeObject(this);
  745. }
  746. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  747. {
  748. if(result.winner == 0) //attacker won
  749. collectRes(hero->getOwner());
  750. }
  751. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  752. {
  753. if(answer)
  754. cb->startBattleI(hero, this);
  755. }
  756. void CGResource::serializeJsonOptions(JsonSerializeFormat & handler)
  757. {
  758. CCreatureSet::serializeJson(handler, "guards", 7);
  759. handler.serializeInt("amount", amount, 0);
  760. handler.serializeString("guardMessage", message);
  761. }
  762. bool CGTeleport::isEntrance() const
  763. {
  764. return type == BOTH || type == ENTRANCE;
  765. }
  766. bool CGTeleport::isExit() const
  767. {
  768. return type == BOTH || type == EXIT;
  769. }
  770. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  771. {
  772. return vstd::contains(getAllEntrances(), id);
  773. }
  774. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  775. {
  776. return vstd::contains(getAllExits(), id);
  777. }
  778. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  779. {
  780. auto ret = cb->getTeleportChannelEntraces(channel);
  781. if(excludeCurrent)
  782. vstd::erase_if_present(ret, id);
  783. return ret;
  784. }
  785. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  786. {
  787. auto ret = cb->getTeleportChannelExits(channel);
  788. if(excludeCurrent)
  789. vstd::erase_if_present(ret, id);
  790. return ret;
  791. }
  792. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  793. {
  794. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  795. if(!passableExits.empty())
  796. return *RandomGeneratorUtil::nextItem(passableExits, CRandomGenerator::getDefault());
  797. return ObjectInstanceID();
  798. }
  799. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  800. {
  801. return ((dynamic_cast<const CGTeleport *>(obj)));
  802. }
  803. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  804. {
  805. return src && dst && src->isChannelExit(dst->id);
  806. }
  807. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  808. {
  809. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  810. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  811. return isConnected(srcObj, dstObj);
  812. }
  813. bool CGTeleport::isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  814. {
  815. auto * objTopVisObj = gs->map->getTile(obj->visitablePos()).topVisitableObj();
  816. if(objTopVisObj->ID == Obj::HERO)
  817. {
  818. if(h->id == objTopVisObj->id) // Just to be sure it's won't happen.
  819. return false;
  820. // Check if it's friendly hero or not
  821. if(gs->getPlayerRelations(h->tempOwner, objTopVisObj->tempOwner) != PlayerRelations::ENEMIES)
  822. {
  823. // Exchange between heroes only possible via subterranean gates
  824. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  825. return false;
  826. }
  827. }
  828. return true;
  829. }
  830. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  831. {
  832. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  833. {
  834. return !isExitPassable(gs, h, gs->getObj(exit));
  835. });
  836. return exits;
  837. }
  838. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  839. {
  840. std::shared_ptr<TeleportChannel> tc;
  841. if(channelsList.find(obj->channel) == channelsList.end())
  842. {
  843. tc = std::make_shared<TeleportChannel>();
  844. channelsList.insert(std::make_pair(obj->channel, tc));
  845. }
  846. else
  847. tc = channelsList[obj->channel];
  848. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  849. tc->entrances.push_back(obj->id);
  850. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  851. tc->exits.push_back(obj->id);
  852. if(!tc->entrances.empty() && !tc->exits.empty()
  853. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  854. {
  855. tc->passability = TeleportChannel::PASSABLE;
  856. }
  857. }
  858. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, int SubID) const
  859. {
  860. for(auto obj : cb->gameState()->map->objects)
  861. {
  862. if(!obj)
  863. continue;
  864. const auto * teleportObj = dynamic_cast<const CGTeleport *>(cb->getObj(obj->id));
  865. if(teleportObj && vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  866. return teleportObj->channel;
  867. }
  868. return TeleportChannelID();
  869. }
  870. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  871. {
  872. TeleportDialog td(h->tempOwner, channel);
  873. if(isEntrance())
  874. {
  875. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  876. {
  877. auto exits = cb->getTeleportChannelExits(channel);
  878. for(const auto & exit : exits)
  879. {
  880. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  881. }
  882. }
  883. if(cb->isTeleportChannelImpassable(channel))
  884. {
  885. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), pos.toString());
  886. td.impassable = true;
  887. }
  888. else if(getRandomExit(h) == ObjectInstanceID())
  889. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), pos.toString());
  890. }
  891. else
  892. h->showInfoDialog(70);
  893. cb->showTeleportDialog(&td);
  894. }
  895. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  896. {
  897. int3 dPos;
  898. auto randomExit = getRandomExit(hero);
  899. auto realExits = getAllExits(true);
  900. if(!isEntrance() // Do nothing if hero visited exit only object
  901. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  902. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  903. {
  904. return;
  905. }
  906. else if(vstd::isValidIndex(exits, answer))
  907. dPos = exits[answer].second;
  908. else
  909. dPos = hero->convertFromVisitablePos(cb->getObj(randomExit)->visitablePos());
  910. cb->moveHero(hero->id, dPos, true);
  911. }
  912. void CGMonolith::initObj(CRandomGenerator & rand)
  913. {
  914. std::vector<Obj> IDs;
  915. IDs.push_back(ID);
  916. switch(ID)
  917. {
  918. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  919. type = ENTRANCE;
  920. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  921. break;
  922. case Obj::MONOLITH_ONE_WAY_EXIT:
  923. type = EXIT;
  924. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  925. break;
  926. case Obj::MONOLITH_TWO_WAY:
  927. default:
  928. type = BOTH;
  929. break;
  930. }
  931. channel = findMeChannel(IDs, subID);
  932. if(channel == TeleportChannelID())
  933. channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  934. addToChannel(cb->gameState()->map->teleportChannels, this);
  935. }
  936. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  937. {
  938. TeleportDialog td(h->tempOwner, channel);
  939. if(cb->isTeleportChannelImpassable(channel))
  940. {
  941. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  942. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), pos.toString());
  943. td.impassable = true;
  944. }
  945. else
  946. {
  947. auto exit = getRandomExit(h);
  948. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  949. }
  950. cb->showTeleportDialog(&td);
  951. }
  952. void CGSubterraneanGate::initObj(CRandomGenerator & rand)
  953. {
  954. type = BOTH;
  955. }
  956. void CGSubterraneanGate::postInit() //matches subterranean gates into pairs
  957. {
  958. //split on underground and surface gates
  959. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  960. for(auto & obj : cb->gameState()->map->objects)
  961. {
  962. if(!obj) // FIXME: Find out why there are nullptr objects right after initialization
  963. continue;
  964. auto * hlp = dynamic_cast<CGSubterraneanGate *>(cb->gameState()->getObjInstance(obj->id));
  965. if(hlp)
  966. gatesSplit[hlp->pos.z].push_back(hlp);
  967. }
  968. //sort by position
  969. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  970. {
  971. return a->pos < b->pos;
  972. });
  973. auto assignToChannel = [&](CGSubterraneanGate * obj)
  974. {
  975. if(obj->channel == TeleportChannelID())
  976. { // if object not linked to channel then create new channel
  977. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  978. addToChannel(cb->gameState()->map->teleportChannels, obj);
  979. }
  980. };
  981. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  982. {
  983. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  984. //find nearest underground exit
  985. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  986. for(int j = 0; j < gatesSplit[1].size(); j++)
  987. {
  988. CGSubterraneanGate *checked = gatesSplit[1][j];
  989. if(checked->channel != TeleportChannelID())
  990. continue;
  991. si32 hlp = checked->pos.dist2dSQ(objCurrent->pos);
  992. if(hlp < best.second)
  993. {
  994. best.first = j;
  995. best.second = hlp;
  996. }
  997. }
  998. assignToChannel(objCurrent);
  999. if(best.first >= 0) //found pair
  1000. {
  1001. gatesSplit[1][best.first]->channel = objCurrent->channel;
  1002. addToChannel(cb->gameState()->map->teleportChannels, gatesSplit[1][best.first]);
  1003. }
  1004. }
  1005. // we should assign empty channels to underground gates if they don't have matching overground gates
  1006. for(auto & i : gatesSplit[1])
  1007. assignToChannel(i);
  1008. }
  1009. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  1010. {
  1011. TeleportDialog td(h->tempOwner, channel);
  1012. if(cb->isTeleportChannelImpassable(channel))
  1013. {
  1014. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), pos.toString());
  1015. td.impassable = true;
  1016. }
  1017. else if(getRandomExit(h) == ObjectInstanceID())
  1018. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), pos.toString());
  1019. if(!isProtected(h))
  1020. {
  1021. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  1022. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  1023. {
  1024. if(h->getPower(targetstack) > h->getPower(i->first))
  1025. targetstack = (i->first);
  1026. }
  1027. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  1028. vstd::amax(countToTake, 1);
  1029. InfoWindow iw;
  1030. iw.type = EInfoWindowMode::AUTO;
  1031. iw.player = h->tempOwner;
  1032. iw.text.addTxt(MetaString::ADVOB_TXT, 168);
  1033. iw.components.emplace_back(CStackBasicDescriptor(h->getCreature(targetstack), -countToTake));
  1034. cb->showInfoDialog(&iw);
  1035. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  1036. }
  1037. else
  1038. {
  1039. auto exits = getAllExits();
  1040. for(const auto & exit : exits)
  1041. {
  1042. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  1043. for(const auto & bPos : blockedPosList)
  1044. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(bPos)));
  1045. }
  1046. }
  1047. cb->showTeleportDialog(&td);
  1048. }
  1049. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  1050. {
  1051. int3 dPos;
  1052. auto realExits = getAllExits();
  1053. if(exits.empty() && realExits.empty())
  1054. return;
  1055. else if(vstd::isValidIndex(exits, answer))
  1056. dPos = exits[answer].second;
  1057. else
  1058. {
  1059. auto exit = getRandomExit(hero);
  1060. if(exit == ObjectInstanceID())
  1061. return;
  1062. const auto * obj = cb->getObj(exit);
  1063. std::set<int3> tiles = obj->getBlockedPos();
  1064. dPos = hero->convertFromVisitablePos(*RandomGeneratorUtil::nextItem(tiles, CRandomGenerator::getDefault()));
  1065. }
  1066. cb->moveHero(hero->id, dPos, true);
  1067. }
  1068. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  1069. {
  1070. return h->hasBonusOfType(BonusType::WHIRLPOOL_PROTECTION)
  1071. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1);
  1072. }
  1073. void CGArtifact::initObj(CRandomGenerator & rand)
  1074. {
  1075. blockVisit = true;
  1076. if(ID == Obj::ARTIFACT)
  1077. {
  1078. if (!storedArtifact)
  1079. {
  1080. auto * a = new CArtifactInstance();
  1081. cb->gameState()->map->addNewArtifactInstance(a);
  1082. storedArtifact = a;
  1083. }
  1084. if(!storedArtifact->artType)
  1085. storedArtifact->setType(VLC->arth->objects[subID]);
  1086. }
  1087. if(ID == Obj::SPELL_SCROLL)
  1088. subID = 1;
  1089. assert(storedArtifact->artType);
  1090. assert(storedArtifact->getParentNodes().size());
  1091. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  1092. }
  1093. std::string CGArtifact::getObjectName() const
  1094. {
  1095. return VLC->artifacts()->getByIndex(subID)->getNameTranslated();
  1096. }
  1097. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  1098. {
  1099. if(!stacksCount())
  1100. {
  1101. InfoWindow iw;
  1102. iw.type = EInfoWindowMode::AUTO;
  1103. iw.player = h->tempOwner;
  1104. if(storedArtifact->artType->canBePutAt(h))
  1105. {
  1106. switch (ID)
  1107. {
  1108. case Obj::ARTIFACT:
  1109. {
  1110. iw.components.emplace_back(Component::EComponentType::ARTIFACT, subID, 0, 0);
  1111. if(message.length())
  1112. iw.text << message;
  1113. else
  1114. iw.text.addTxt(MetaString::ART_EVNTS, subID);
  1115. }
  1116. break;
  1117. case Obj::SPELL_SCROLL:
  1118. {
  1119. int spellID = storedArtifact->getScrollSpellID();
  1120. iw.components.emplace_back(Component::EComponentType::SPELL, spellID, 0, 0);
  1121. if(message.length())
  1122. iw.text << message;
  1123. else
  1124. {
  1125. iw.text.addTxt(MetaString::ADVOB_TXT,135);
  1126. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  1127. }
  1128. }
  1129. break;
  1130. }
  1131. }
  1132. else
  1133. {
  1134. iw.text.addTxt(MetaString::ADVOB_TXT, 2);
  1135. }
  1136. cb->showInfoDialog(&iw);
  1137. pick(h);
  1138. }
  1139. else
  1140. {
  1141. switch(ID)
  1142. {
  1143. case Obj::ARTIFACT:
  1144. {
  1145. BlockingDialog ynd(true,false);
  1146. ynd.player = h->getOwner();
  1147. if(message.length())
  1148. ynd.text << message;
  1149. else
  1150. {
  1151. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  1152. ynd.text.addTxt(MetaString::GENERAL_TXT, 420);
  1153. ynd.text.addReplacement("");
  1154. ynd.text.addReplacement(getArmyDescription());
  1155. ynd.text.addReplacement(MetaString::GENERAL_TXT, 43); // creatures
  1156. }
  1157. cb->showBlockingDialog(&ynd);
  1158. }
  1159. break;
  1160. case Obj::SPELL_SCROLL:
  1161. {
  1162. if(message.length())
  1163. {
  1164. BlockingDialog ynd(true,false);
  1165. ynd.player = h->getOwner();
  1166. ynd.text << message;
  1167. cb->showBlockingDialog(&ynd);
  1168. }
  1169. else
  1170. blockingDialogAnswered(h, true);
  1171. }
  1172. break;
  1173. }
  1174. }
  1175. }
  1176. void CGArtifact::pick(const CGHeroInstance * h) const
  1177. {
  1178. if(cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE))
  1179. cb->removeObject(this);
  1180. }
  1181. BattleField CGArtifact::getBattlefield() const
  1182. {
  1183. return BattleField::NONE;
  1184. }
  1185. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1186. {
  1187. if(result.winner == 0) //attacker won
  1188. pick(hero);
  1189. }
  1190. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1191. {
  1192. if(answer)
  1193. cb->startBattleI(hero, this);
  1194. }
  1195. void CGArtifact::afterAddToMap(CMap * map)
  1196. {
  1197. //Artifacts from map objects are never removed
  1198. //FIXME: This should be revertible in map editor
  1199. if(ID == Obj::SPELL_SCROLL && storedArtifact && storedArtifact->id.getNum() < 0)
  1200. map->addNewArtifactInstance(storedArtifact);
  1201. }
  1202. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  1203. {
  1204. handler.serializeString("guardMessage", message);
  1205. CCreatureSet::serializeJson(handler, "guards" ,7);
  1206. if(handler.saving && ID == Obj::SPELL_SCROLL)
  1207. {
  1208. const std::shared_ptr<Bonus> b = storedArtifact->getBonusLocalFirst(Selector::type()(BonusType::SPELL));
  1209. SpellID spellId(b->subtype);
  1210. handler.serializeId("spell", spellId, SpellID::NONE);
  1211. }
  1212. }
  1213. void CGWitchHut::initObj(CRandomGenerator & rand)
  1214. {
  1215. if (allowedAbilities.empty()) //this can happen for RMG and RoE maps.
  1216. {
  1217. auto defaultAllowed = VLC->skillh->getDefaultAllowed();
  1218. // Necromancy and Leadership can't be learned by default
  1219. defaultAllowed[SecondarySkill::NECROMANCY] = false;
  1220. defaultAllowed[SecondarySkill::LEADERSHIP] = false;
  1221. for(int i = 0; i < defaultAllowed.size(); i++)
  1222. if (defaultAllowed[i] && cb->isAllowed(2, i))
  1223. allowedAbilities.insert(SecondarySkill(i));
  1224. }
  1225. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, rand);
  1226. }
  1227. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  1228. {
  1229. InfoWindow iw;
  1230. iw.type = EInfoWindowMode::AUTO;
  1231. iw.player = h->getOwner();
  1232. if(!wasVisited(h->tempOwner))
  1233. cb->setObjProperty(id, CGWitchHut::OBJPROP_VISITED, h->tempOwner.getNum());
  1234. ui32 txt_id;
  1235. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  1236. {
  1237. txt_id =172;
  1238. }
  1239. else if(!h->canLearnSkill()) //already all skills slots used
  1240. {
  1241. txt_id = 173;
  1242. }
  1243. else //give sec skill
  1244. {
  1245. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, ability, 1, 0);
  1246. txt_id = 171;
  1247. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  1248. }
  1249. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  1250. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  1251. cb->showInfoDialog(&iw);
  1252. }
  1253. std::string CGWitchHut::getHoverText(PlayerColor player) const
  1254. {
  1255. std::string hoverName = getObjectName();
  1256. if(wasVisited(player))
  1257. {
  1258. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  1259. boost::algorithm::replace_first(hoverName, "%s", VLC->skillh->getByIndex(ability)->getNameTranslated());
  1260. }
  1261. return hoverName;
  1262. }
  1263. std::string CGWitchHut::getHoverText(const CGHeroInstance * hero) const
  1264. {
  1265. std::string hoverName = getHoverText(hero->tempOwner);
  1266. if(wasVisited(hero->tempOwner) && hero->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  1267. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  1268. return hoverName;
  1269. }
  1270. void CGWitchHut::serializeJsonOptions(JsonSerializeFormat & handler)
  1271. {
  1272. //TODO: unify allowed abilities with others - make them std::vector<bool>
  1273. std::vector<bool> temp;
  1274. size_t skillCount = VLC->skillh->size();
  1275. temp.resize(skillCount, false);
  1276. auto standard = VLC->skillh->getDefaultAllowed(); //todo: for WitchHut default is all except Leadership and Necromancy
  1277. if(handler.saving)
  1278. {
  1279. for(si32 i = 0; i < skillCount; ++i)
  1280. if(vstd::contains(allowedAbilities, i))
  1281. temp[i] = true;
  1282. }
  1283. handler.serializeLIC("allowedSkills", &CSkillHandler::decodeSkill, &CSkillHandler::encodeSkill, standard, temp);
  1284. if(!handler.saving)
  1285. {
  1286. allowedAbilities.clear();
  1287. for(si32 i = 0; i < skillCount; ++i)
  1288. if(temp[i])
  1289. allowedAbilities.insert(SecondarySkill(i));
  1290. }
  1291. }
  1292. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  1293. {
  1294. InfoWindow iw;
  1295. iw.type = EInfoWindowMode::AUTO;
  1296. iw.player = h->tempOwner;
  1297. switch (ID)
  1298. {
  1299. case Obj::REDWOOD_OBSERVATORY:
  1300. case Obj::PILLAR_OF_FIRE:
  1301. {
  1302. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  1303. FoWChange fw;
  1304. fw.player = h->tempOwner;
  1305. fw.mode = 1;
  1306. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  1307. cb->sendAndApply (&fw);
  1308. break;
  1309. }
  1310. case Obj::COVER_OF_DARKNESS:
  1311. {
  1312. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  1313. for (auto & player : cb->gameState()->players)
  1314. {
  1315. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1316. cb->getPlayerRelations(player.first, h->tempOwner) == PlayerRelations::ENEMIES)
  1317. cb->changeFogOfWar(visitablePos(), 20, player.first, true);
  1318. }
  1319. break;
  1320. }
  1321. }
  1322. cb->showInfoDialog(&iw);
  1323. }
  1324. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  1325. {
  1326. if(spell == SpellID::NONE)
  1327. {
  1328. logGlobal->error("Not initialized shrine visited!");
  1329. return;
  1330. }
  1331. if(!wasVisited(h->tempOwner))
  1332. cb->setObjProperty(id, CGShrine::OBJPROP_VISITED, h->tempOwner.getNum());
  1333. InfoWindow iw;
  1334. iw.type = EInfoWindowMode::AUTO;
  1335. iw.player = h->getOwner();
  1336. iw.text = visitText;
  1337. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  1338. iw.text << ".";
  1339. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  1340. {
  1341. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  1342. }
  1343. else if(h->spellbookContainsSpell(spell))//hero already knows the spell
  1344. {
  1345. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  1346. }
  1347. else if(spell.toSpell()->getLevel() > h->maxSpellLevel()) //it's third level spell and hero doesn't have wisdom
  1348. {
  1349. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  1350. }
  1351. else //give spell
  1352. {
  1353. std::set<SpellID> spells;
  1354. spells.insert(spell);
  1355. cb->changeSpells(h, true, spells);
  1356. iw.components.emplace_back(Component::EComponentType::SPELL, spell, 0, 0);
  1357. }
  1358. cb->showInfoDialog(&iw);
  1359. }
  1360. void CGShrine::initObj(CRandomGenerator & rand)
  1361. {
  1362. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  1363. }
  1364. std::string CGShrine::getHoverText(PlayerColor player) const
  1365. {
  1366. std::string hoverName = getObjectName();
  1367. if(wasVisited(player))
  1368. {
  1369. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  1370. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->getNameTranslated());
  1371. }
  1372. return hoverName;
  1373. }
  1374. std::string CGShrine::getHoverText(const CGHeroInstance * hero) const
  1375. {
  1376. std::string hoverName = getHoverText(hero->tempOwner);
  1377. if(wasVisited(hero->tempOwner) && hero->spellbookContainsSpell(spell)) //know what spell there is and hero knows that spell
  1378. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  1379. return hoverName;
  1380. }
  1381. void CGShrine::serializeJsonOptions(JsonSerializeFormat & handler)
  1382. {
  1383. handler.serializeId("spell", spell, SpellID::NONE);
  1384. }
  1385. void CGSignBottle::initObj(CRandomGenerator & rand)
  1386. {
  1387. //if no text is set than we pick random from the predefined ones
  1388. if(message.empty())
  1389. {
  1390. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  1391. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  1392. message = VLC->generaltexth->translate(messageIdentifier);
  1393. }
  1394. if(ID == Obj::OCEAN_BOTTLE)
  1395. {
  1396. blockVisit = true;
  1397. }
  1398. }
  1399. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  1400. {
  1401. InfoWindow iw;
  1402. iw.player = h->getOwner();
  1403. iw.text << message;
  1404. cb->showInfoDialog(&iw);
  1405. if(ID == Obj::OCEAN_BOTTLE)
  1406. cb->removeObject(this);
  1407. }
  1408. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  1409. {
  1410. handler.serializeString("text", message);
  1411. }
  1412. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  1413. {
  1414. EBonusType type = bonusType;
  1415. int bid = bonusID;
  1416. //check if the bonus if applicable, if not - give primary skill (always possible)
  1417. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  1418. if((type == SECONDARY_SKILL && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  1419. || (type == SPELL && !h->canLearnSpell(SpellID(bid).toSpell())))
  1420. {
  1421. type = PRIM_SKILL;
  1422. bid = CRandomGenerator::getDefault().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1423. }
  1424. InfoWindow iw;
  1425. iw.type = EInfoWindowMode::AUTO;
  1426. iw.player = h->getOwner();
  1427. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  1428. switch (type)
  1429. {
  1430. case PRIM_SKILL:
  1431. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  1432. iw.components.emplace_back(Component::EComponentType::PRIM_SKILL, bid, +1, 0);
  1433. break;
  1434. case SECONDARY_SKILL:
  1435. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  1436. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, bid, ssl + 1, 0);
  1437. break;
  1438. case SPELL:
  1439. {
  1440. std::set<SpellID> hlp;
  1441. hlp.insert(SpellID(bid));
  1442. cb->changeSpells(h,true,hlp);
  1443. iw.components.emplace_back(Component::EComponentType::SPELL, bid, 0, 0);
  1444. }
  1445. break;
  1446. default:
  1447. logGlobal->error("Error: wrong bonus type (%d) for Scholar!\n", static_cast<int>(type));
  1448. return;
  1449. }
  1450. cb->showInfoDialog(&iw);
  1451. cb->removeObject(this);
  1452. }
  1453. void CGScholar::initObj(CRandomGenerator & rand)
  1454. {
  1455. blockVisit = true;
  1456. if(bonusType == RANDOM)
  1457. {
  1458. bonusType = static_cast<EBonusType>(rand.nextInt(2));
  1459. switch(bonusType)
  1460. {
  1461. case PRIM_SKILL:
  1462. bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1);
  1463. break;
  1464. case SECONDARY_SKILL:
  1465. bonusID = rand.nextInt(static_cast<int>(VLC->skillh->size()) - 1);
  1466. break;
  1467. case SPELL:
  1468. std::vector<SpellID> possibilities;
  1469. cb->getAllowedSpells (possibilities);
  1470. bonusID = *RandomGeneratorUtil::nextItem(possibilities, rand);
  1471. break;
  1472. }
  1473. }
  1474. }
  1475. void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
  1476. {
  1477. if(handler.saving)
  1478. {
  1479. std::string value;
  1480. switch(bonusType)
  1481. {
  1482. case PRIM_SKILL:
  1483. value = PrimarySkill::names[bonusID];
  1484. handler.serializeString("rewardPrimSkill", value);
  1485. break;
  1486. case SECONDARY_SKILL:
  1487. value = CSkillHandler::encodeSkill(bonusID);
  1488. handler.serializeString("rewardSkill", value);
  1489. break;
  1490. case SPELL:
  1491. value = SpellID::encode(bonusID);
  1492. handler.serializeString("rewardSpell", value);
  1493. break;
  1494. case RANDOM:
  1495. break;
  1496. }
  1497. }
  1498. else
  1499. {
  1500. //TODO: unify
  1501. const JsonNode & json = handler.getCurrent();
  1502. bonusType = RANDOM;
  1503. if(!json["rewardPrimSkill"].String().empty())
  1504. {
  1505. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "primSkill", json["rewardPrimSkill"].String());
  1506. if(raw)
  1507. {
  1508. bonusType = PRIM_SKILL;
  1509. bonusID = raw.value();
  1510. }
  1511. }
  1512. else if(!json["rewardSkill"].String().empty())
  1513. {
  1514. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "skill", json["rewardSkill"].String());
  1515. if(raw)
  1516. {
  1517. bonusType = SECONDARY_SKILL;
  1518. bonusID = raw.value();
  1519. }
  1520. }
  1521. else if(!json["rewardSpell"].String().empty())
  1522. {
  1523. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "spell", json["rewardSpell"].String());
  1524. if(raw)
  1525. {
  1526. bonusType = SPELL;
  1527. bonusID = raw.value();
  1528. }
  1529. }
  1530. }
  1531. }
  1532. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1533. {
  1534. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1535. if (!ally && stacksCount() > 0) {
  1536. //TODO: Find a way to apply magic garrison effects in battle.
  1537. cb->startBattleI(h, this);
  1538. return;
  1539. }
  1540. //New owner.
  1541. if (!ally)
  1542. cb->setOwner(this, h->tempOwner);
  1543. cb->showGarrisonDialog(id, h->id, removableUnits);
  1544. }
  1545. bool CGGarrison::passableFor(PlayerColor player) const
  1546. {
  1547. //FIXME: identical to same method in CGTownInstance
  1548. if ( !stacksCount() )//empty - anyone can visit
  1549. return true;
  1550. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1551. return false;
  1552. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1553. return true;
  1554. return false;
  1555. }
  1556. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1557. {
  1558. if (result.winner == 0)
  1559. onHeroVisit(hero);
  1560. }
  1561. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  1562. {
  1563. handler.serializeBool("removableUnits", removableUnits);
  1564. serializeJsonOwner(handler);
  1565. CCreatureSet::serializeJson(handler, "army", 7);
  1566. }
  1567. void CGMagi::reset()
  1568. {
  1569. eyelist.clear();
  1570. }
  1571. void CGMagi::initObj(CRandomGenerator & rand)
  1572. {
  1573. if (ID == Obj::EYE_OF_MAGI)
  1574. {
  1575. blockVisit = true;
  1576. eyelist[subID].push_back(id);
  1577. }
  1578. }
  1579. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1580. {
  1581. if (ID == Obj::HUT_OF_MAGI)
  1582. {
  1583. h->showInfoDialog(61);
  1584. if (!eyelist[subID].empty())
  1585. {
  1586. CenterView cv;
  1587. cv.player = h->tempOwner;
  1588. cv.focusTime = 2000;
  1589. FoWChange fw;
  1590. fw.player = h->tempOwner;
  1591. fw.mode = 1;
  1592. fw.waitForDialogs = true;
  1593. for(const auto & it : eyelist[subID])
  1594. {
  1595. const CGObjectInstance *eye = cb->getObj(it);
  1596. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1597. cb->sendAndApply(&fw);
  1598. cv.pos = eye->pos;
  1599. cb->sendAndApply(&cv);
  1600. }
  1601. cv.pos = h->visitablePos();
  1602. cv.focusTime = 0;
  1603. cb->sendAndApply(&cv);
  1604. }
  1605. }
  1606. else if (ID == Obj::EYE_OF_MAGI)
  1607. {
  1608. h->showInfoDialog(48);
  1609. }
  1610. }
  1611. void CGBoat::initObj(CRandomGenerator & rand)
  1612. {
  1613. hero = nullptr;
  1614. }
  1615. int3 CGBoat::translatePos(const int3& pos, bool reverse /* = false */)
  1616. {
  1617. //pos - offset we want to place the boat at the map
  1618. //returned value - actual position as seen by game mechanics
  1619. //If reverse = true, then it's the opposite.
  1620. if (!reverse)
  1621. {
  1622. return pos + int3(1, 0, 0);
  1623. }
  1624. else
  1625. {
  1626. return pos - int3(1, 0, 0);
  1627. }
  1628. }
  1629. void CGSirens::initObj(CRandomGenerator & rand)
  1630. {
  1631. blockVisit = true;
  1632. }
  1633. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1634. {
  1635. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(BonusSource::OBJECT,ID));
  1636. }
  1637. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1638. {
  1639. InfoWindow iw;
  1640. iw.player = h->tempOwner;
  1641. if(h->hasBonusFrom(BonusSource::OBJECT,ID)) //has already visited Sirens
  1642. {
  1643. iw.type = EInfoWindowMode::AUTO;
  1644. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  1645. }
  1646. else
  1647. {
  1648. giveDummyBonus(h->id, BonusDuration::ONE_BATTLE);
  1649. TExpType xp = 0;
  1650. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1651. {
  1652. // 1-sized stacks are not affected by sirens
  1653. if (i->second->count == 1)
  1654. continue;
  1655. // tested H3 behavior: 30% (rounded up) of stack drowns
  1656. TQuantity drown = std::ceil(i->second->count * 0.3);
  1657. if(drown)
  1658. {
  1659. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1660. xp += drown * i->second->type->getMaxHealth();
  1661. }
  1662. }
  1663. if(xp)
  1664. {
  1665. xp = h->calculateXp(static_cast<int>(xp));
  1666. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  1667. iw.text.addReplacement(static_cast<int>(xp));
  1668. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1669. }
  1670. else
  1671. {
  1672. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  1673. }
  1674. }
  1675. cb->showInfoDialog(&iw);
  1676. }
  1677. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1678. {
  1679. // H J L K I
  1680. // A x S x B
  1681. // C E G F D
  1682. offsets = {
  1683. int3(-3,0,0), int3(1,0,0), //AB
  1684. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1685. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0) //HIJKL
  1686. };
  1687. }
  1688. const IObjectInterface * CGShipyard::getObject() const
  1689. {
  1690. return this;
  1691. }
  1692. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1693. {
  1694. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1695. cb->setOwner(this, h->tempOwner);
  1696. auto s = shipyardStatus();
  1697. if(s != IBoatGenerator::GOOD)
  1698. {
  1699. InfoWindow iw;
  1700. iw.type = EInfoWindowMode::AUTO;
  1701. iw.player = tempOwner;
  1702. getProblemText(iw.text, h);
  1703. cb->showInfoDialog(&iw);
  1704. }
  1705. else
  1706. {
  1707. openWindow(EOpenWindowMode::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1708. }
  1709. }
  1710. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1711. {
  1712. serializeJsonOwner(handler);
  1713. }
  1714. BoatId CGShipyard::getBoatType() const
  1715. {
  1716. return EBoatId::BOAT_GOOD;
  1717. }
  1718. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1719. {
  1720. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1721. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1722. {
  1723. if (cb->getResource(h->tempOwner, EGameResID::GOLD) >= 1000) //if he can afford a map
  1724. {
  1725. //ask if he wants to buy one
  1726. int text=0;
  1727. switch (subID)
  1728. {
  1729. case 0:
  1730. text = 25;
  1731. break;
  1732. case 1:
  1733. text = 26;
  1734. break;
  1735. case 2:
  1736. text = 27;
  1737. break;
  1738. default:
  1739. logGlobal->warn("Unrecognized subtype of cartographer");
  1740. }
  1741. assert(text);
  1742. BlockingDialog bd (true, false);
  1743. bd.player = h->getOwner();
  1744. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  1745. cb->showBlockingDialog (&bd);
  1746. }
  1747. else //if he cannot afford
  1748. {
  1749. h->showInfoDialog(28);
  1750. }
  1751. }
  1752. else //if he already visited carographer
  1753. {
  1754. h->showInfoDialog(24);
  1755. }
  1756. }
  1757. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1758. {
  1759. if(answer) //if hero wants to buy map
  1760. {
  1761. cb->giveResource(hero->tempOwner, EGameResID::GOLD, -1000);
  1762. FoWChange fw;
  1763. fw.mode = 1;
  1764. fw.player = hero->tempOwner;
  1765. //subIDs of different types of cartographers:
  1766. //water = 0; land = 1; underground = 2;
  1767. IGameCallback::MapTerrainFilterMode tileFilterMode = IGameCallback::MapTerrainFilterMode::NONE;
  1768. switch(subID)
  1769. {
  1770. case 0:
  1771. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::WATER;
  1772. break;
  1773. case 1:
  1774. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::LAND_CARTOGRAPHER;
  1775. break;
  1776. case 2:
  1777. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::UNDERGROUND_CARTOGRAPHER;
  1778. break;
  1779. }
  1780. cb->getAllTiles(fw.tiles, hero->tempOwner, -1, tileFilterMode); //reveal appropriate tiles
  1781. cb->sendAndApply(&fw);
  1782. cb->setObjProperty(id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1783. }
  1784. }
  1785. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1786. {
  1787. cb->showThievesGuildWindow(h->tempOwner, id);
  1788. }
  1789. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1790. {
  1791. InfoWindow iw;
  1792. iw.type = EInfoWindowMode::AUTO;
  1793. iw.player = h->tempOwner;
  1794. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1795. assert(ts);
  1796. TeamID team = ts->id;
  1797. if(!wasVisited(team))
  1798. {
  1799. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  1800. cb->sendAndApply(&iw);
  1801. // increment general visited obelisks counter
  1802. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1803. openWindow(EOpenWindowMode::PUZZLE_MAP, h->tempOwner.getNum());
  1804. // mark that particular obelisk as visited for all players in the team
  1805. for(const auto & color : ts->players)
  1806. {
  1807. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1808. }
  1809. }
  1810. else
  1811. {
  1812. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  1813. cb->sendAndApply(&iw);
  1814. }
  1815. }
  1816. void CGObelisk::initObj(CRandomGenerator & rand)
  1817. {
  1818. obeliskCount++;
  1819. }
  1820. void CGObelisk::reset()
  1821. {
  1822. obeliskCount = 0;
  1823. visited.clear();
  1824. }
  1825. std::string CGObelisk::getHoverText(PlayerColor player) const
  1826. {
  1827. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1828. }
  1829. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1830. {
  1831. switch(what)
  1832. {
  1833. case CGObelisk::OBJPROP_INC:
  1834. {
  1835. auto progress = ++visited[TeamID(val)];
  1836. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1837. if(progress > obeliskCount)
  1838. {
  1839. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1840. throw std::runtime_error("internal error");
  1841. }
  1842. break;
  1843. }
  1844. default:
  1845. CTeamVisited::setPropertyDer(what, val);
  1846. break;
  1847. }
  1848. }
  1849. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1850. {
  1851. if(h->tempOwner != tempOwner)
  1852. {
  1853. PlayerColor oldOwner = tempOwner;
  1854. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1855. h->showInfoDialog(69);
  1856. giveBonusTo(h->tempOwner);
  1857. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1858. {
  1859. RemoveBonus rb(GiveBonus::ETarget::PLAYER);
  1860. rb.whoID = oldOwner.getNum();
  1861. rb.source = vstd::to_underlying(BonusSource::OBJECT);
  1862. rb.id = id.getNum();
  1863. cb->sendAndApply(&rb);
  1864. }
  1865. }
  1866. }
  1867. void CGLighthouse::initObj(CRandomGenerator & rand)
  1868. {
  1869. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1870. {
  1871. // FIXME: This is dirty hack
  1872. giveBonusTo(tempOwner, true);
  1873. }
  1874. }
  1875. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1876. {
  1877. GiveBonus gb(GiveBonus::ETarget::PLAYER);
  1878. gb.bonus.type = BonusType::MOVEMENT;
  1879. gb.bonus.val = 500;
  1880. gb.id = player.getNum();
  1881. gb.bonus.duration = BonusDuration::PERMANENT;
  1882. gb.bonus.source = BonusSource::OBJECT;
  1883. gb.bonus.sid = id.getNum();
  1884. gb.bonus.subtype = 0;
  1885. // FIXME: This is really dirty hack
  1886. // Proper fix would be to make CGLighthouse into bonus system node
  1887. // Unfortunately this will cause saves breakage
  1888. if(onInit)
  1889. gb.applyGs(cb->gameState());
  1890. else
  1891. cb->sendAndApply(&gb);
  1892. }
  1893. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1894. {
  1895. serializeJsonOwner(handler);
  1896. }
  1897. void HillFort::onHeroVisit(const CGHeroInstance * h) const
  1898. {
  1899. openWindow(EOpenWindowMode::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  1900. }
  1901. void HillFort::initObj(CRandomGenerator & rand)
  1902. {
  1903. VLC->objtypeh->getHandlerFor(ID, subID)->configureObject(this, rand);
  1904. }
  1905. void HillFort::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
  1906. {
  1907. int32_t level = stack.type->getLevel();
  1908. int32_t index = std::clamp<int32_t>(level - 1, 0, upgradeCostPercentage.size() - 1);
  1909. int costModifier = upgradeCostPercentage[index];
  1910. if (costModifier < 0)
  1911. return; // upgrade not allowed
  1912. for(const auto & nid : stack.type->upgrades)
  1913. {
  1914. info.newID.push_back(nid);
  1915. info.cost.push_back((nid.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost()) * costModifier / 100);
  1916. }
  1917. }
  1918. VCMI_LIB_NAMESPACE_END