MiscObjects.cpp 53 KB

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