MiscObjects.cpp 55 KB

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