2
0

MiscObjects.cpp 56 KB

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