2
0

MiscObjects.cpp 55 KB

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