2
0

MiscObjects.cpp 56 KB

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