MiscObjects.cpp 55 KB

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