MiscObjects.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178
  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 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->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  209. {
  210. ui32 power = static_cast<ui32>(temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH) / 100);
  211. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min(power / 1000, static_cast<ui32>(VLC->modh->settings.CREEP_SIZE))); //set new amount
  212. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  213. }
  214. }
  215. if (VLC->modh->modules.STACK_EXP)
  216. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //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->idNumber); //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->idNumber)) //it's our base creatures
  261. myKindCres.insert(crea->idNumber);
  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->idNumber))
  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(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::DIPLOMACY);
  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->creh->objects[subID]->cost[6] * 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, Res::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,Res::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->idNumber;
  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::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::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. //after map reading tempOwner placeholds bitmask for allowed resources
  574. std::vector<Res::ERes> possibleResources;
  575. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  576. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  577. possibleResources.push_back(static_cast<Res::ERes>(i));
  578. assert(!possibleResources.empty());
  579. producedResource = *RandomGeneratorUtil::nextItem(possibleResources, rand);
  580. tempOwner = PlayerColor::NEUTRAL;
  581. }
  582. else
  583. {
  584. producedResource = static_cast<Res::ERes>(subID);
  585. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  586. tempOwner = PlayerColor::NEUTRAL;
  587. }
  588. producedQuantity = defaultResProduction();
  589. }
  590. bool CGMine::isAbandoned() const
  591. {
  592. return (subID >= 7);
  593. }
  594. std::string CGMine::getObjectName() const
  595. {
  596. return VLC->generaltexth->translate("core.minename", subID);
  597. }
  598. std::string CGMine::getHoverText(PlayerColor player) const
  599. {
  600. std::string hoverName = CArmedInstance::getHoverText(player);
  601. if (tempOwner != PlayerColor::NEUTRAL)
  602. hoverName += "\n(" + VLC->generaltexth->restypes[producedResource] + ")";
  603. if(stacksCount())
  604. {
  605. hoverName += "\n";
  606. hoverName += VLC->generaltexth->allTexts[202]; //Guarded by
  607. hoverName += " ";
  608. hoverName += getArmyDescription();
  609. }
  610. return hoverName;
  611. }
  612. void CGMine::flagMine(const PlayerColor & player) const
  613. {
  614. assert(tempOwner != player);
  615. cb->setOwner(this, player); //not ours? flag it!
  616. InfoWindow iw;
  617. iw.type = EInfoWindowMode::AUTO;
  618. iw.soundID = soundBase::FLAGMINE;
  619. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  620. iw.player = player;
  621. iw.components.emplace_back(Component::RESOURCE, producedResource, producedQuantity, -1);
  622. cb->showInfoDialog(&iw);
  623. }
  624. ui32 CGMine::defaultResProduction() const
  625. {
  626. switch(producedResource)
  627. {
  628. case Res::WOOD:
  629. case Res::ORE:
  630. return 2;
  631. case Res::GOLD:
  632. return 1000;
  633. default:
  634. return 1;
  635. }
  636. }
  637. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  638. {
  639. if(result.winner == 0) //attacker won
  640. {
  641. if(isAbandoned())
  642. {
  643. hero->showInfoDialog(85);
  644. }
  645. flagMine(hero->tempOwner);
  646. }
  647. }
  648. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  649. {
  650. if(answer)
  651. cb->startBattleI(hero, this);
  652. }
  653. void CGMine::serializeJsonOptions(JsonSerializeFormat & handler)
  654. {
  655. CCreatureSet::serializeJson(handler, "army", 7);
  656. if(isAbandoned())
  657. {
  658. if(handler.saving)
  659. {
  660. JsonNode node(JsonNode::JsonType::DATA_VECTOR);
  661. for(int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  662. {
  663. if(tempOwner.getNum() & 1<<i)
  664. {
  665. JsonNode one(JsonNode::JsonType::DATA_STRING);
  666. one.String() = GameConstants::RESOURCE_NAMES[i];
  667. node.Vector().push_back(one);
  668. }
  669. }
  670. handler.serializeRaw("possibleResources", node, boost::none);
  671. }
  672. else
  673. {
  674. auto guard = handler.enterArray("possibleResources");
  675. const JsonNode & node = handler.getCurrent();
  676. std::set<int> possibleResources;
  677. if(node.getType() != JsonNode::JsonType::DATA_VECTOR || node.Vector().empty())
  678. {
  679. //assume all allowed
  680. for(int i = static_cast<int>(Res::WOOD); i < static_cast<int>(Res::GOLD); i++)
  681. possibleResources.insert(i);
  682. }
  683. else
  684. {
  685. auto names = node.convertTo<std::vector<std::string>>();
  686. for(const std::string & s : names)
  687. {
  688. int raw_res = vstd::find_pos(GameConstants::RESOURCE_NAMES, s);
  689. if(raw_res < 0)
  690. logGlobal->error("Invalid resource name: %s", s);
  691. else
  692. possibleResources.insert(raw_res);
  693. }
  694. int tmp = 0;
  695. for(int r : possibleResources)
  696. tmp |= (1<<r);
  697. tempOwner = PlayerColor(tmp);
  698. }
  699. }
  700. }
  701. else
  702. {
  703. serializeJsonOwner(handler);
  704. }
  705. }
  706. std::string CGResource::getHoverText(PlayerColor player) const
  707. {
  708. return VLC->generaltexth->restypes[subID];
  709. }
  710. void CGResource::initObj(CRandomGenerator & rand)
  711. {
  712. blockVisit = true;
  713. if(amount == CGResource::RANDOM_AMOUNT)
  714. {
  715. switch(subID)
  716. {
  717. case Res::GOLD:
  718. amount = rand.nextInt(5, 10) * 100;
  719. break;
  720. case Res::WOOD: case Res::ORE:
  721. amount = rand.nextInt(6, 10);
  722. break;
  723. default:
  724. amount = rand.nextInt(3, 5);
  725. break;
  726. }
  727. }
  728. }
  729. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  730. {
  731. if(stacksCount())
  732. {
  733. if(!message.empty())
  734. {
  735. BlockingDialog ynd(true,false);
  736. ynd.player = h->getOwner();
  737. ynd.text << message;
  738. cb->showBlockingDialog(&ynd);
  739. }
  740. else
  741. {
  742. blockingDialogAnswered(h, true); //behave as if player accepted battle
  743. }
  744. }
  745. else
  746. collectRes(h->getOwner());
  747. }
  748. void CGResource::collectRes(const PlayerColor & player) const
  749. {
  750. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  751. InfoWindow sii;
  752. sii.player = player;
  753. if(!message.empty())
  754. {
  755. sii.type = EInfoWindowMode::AUTO;
  756. sii.text << message;
  757. }
  758. else
  759. {
  760. sii.type = EInfoWindowMode::INFO;
  761. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  762. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  763. }
  764. sii.components.emplace_back(Component::RESOURCE,subID,amount,0);
  765. sii.soundID = soundBase::pickup01 + CRandomGenerator::getDefault().nextInt(6);
  766. cb->showInfoDialog(&sii);
  767. cb->removeObject(this);
  768. }
  769. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  770. {
  771. if(result.winner == 0) //attacker won
  772. collectRes(hero->getOwner());
  773. }
  774. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  775. {
  776. if(answer)
  777. cb->startBattleI(hero, this);
  778. }
  779. void CGResource::serializeJsonOptions(JsonSerializeFormat & handler)
  780. {
  781. CCreatureSet::serializeJson(handler, "guards", 7);
  782. handler.serializeInt("amount", amount, 0);
  783. handler.serializeString("guardMessage", message);
  784. }
  785. bool CGTeleport::isEntrance() const
  786. {
  787. return type == BOTH || type == ENTRANCE;
  788. }
  789. bool CGTeleport::isExit() const
  790. {
  791. return type == BOTH || type == EXIT;
  792. }
  793. bool CGTeleport::isChannelEntrance(const ObjectInstanceID & id) const
  794. {
  795. return vstd::contains(getAllEntrances(), id);
  796. }
  797. bool CGTeleport::isChannelExit(const ObjectInstanceID & id) const
  798. {
  799. return vstd::contains(getAllExits(), id);
  800. }
  801. std::vector<ObjectInstanceID> CGTeleport::getAllEntrances(bool excludeCurrent) const
  802. {
  803. auto ret = cb->getTeleportChannelEntraces(channel);
  804. if(excludeCurrent)
  805. vstd::erase_if_present(ret, id);
  806. return ret;
  807. }
  808. std::vector<ObjectInstanceID> CGTeleport::getAllExits(bool excludeCurrent) const
  809. {
  810. auto ret = cb->getTeleportChannelExits(channel);
  811. if(excludeCurrent)
  812. vstd::erase_if_present(ret, id);
  813. return ret;
  814. }
  815. ObjectInstanceID CGTeleport::getRandomExit(const CGHeroInstance * h) const
  816. {
  817. auto passableExits = getPassableExits(cb->gameState(), h, getAllExits(true));
  818. if(!passableExits.empty())
  819. return *RandomGeneratorUtil::nextItem(passableExits, CRandomGenerator::getDefault());
  820. return ObjectInstanceID();
  821. }
  822. bool CGTeleport::isTeleport(const CGObjectInstance * obj)
  823. {
  824. return ((dynamic_cast<const CGTeleport *>(obj)));
  825. }
  826. bool CGTeleport::isConnected(const CGTeleport * src, const CGTeleport * dst)
  827. {
  828. return src && dst && src->isChannelExit(dst->id);
  829. }
  830. bool CGTeleport::isConnected(const CGObjectInstance * src, const CGObjectInstance * dst)
  831. {
  832. const auto * srcObj = dynamic_cast<const CGTeleport *>(src);
  833. const auto * dstObj = dynamic_cast<const CGTeleport *>(dst);
  834. return isConnected(srcObj, dstObj);
  835. }
  836. bool CGTeleport::isExitPassable(CGameState * gs, const CGHeroInstance * h, const CGObjectInstance * obj)
  837. {
  838. auto * objTopVisObj = gs->map->getTile(obj->visitablePos()).topVisitableObj();
  839. if(objTopVisObj->ID == Obj::HERO)
  840. {
  841. if(h->id == objTopVisObj->id) // Just to be sure it's won't happen.
  842. return false;
  843. // Check if it's friendly hero or not
  844. if(gs->getPlayerRelations(h->tempOwner, objTopVisObj->tempOwner) != PlayerRelations::ENEMIES)
  845. {
  846. // Exchange between heroes only possible via subterranean gates
  847. if(!dynamic_cast<const CGSubterraneanGate *>(obj))
  848. return false;
  849. }
  850. }
  851. return true;
  852. }
  853. std::vector<ObjectInstanceID> CGTeleport::getPassableExits(CGameState * gs, const CGHeroInstance * h, std::vector<ObjectInstanceID> exits)
  854. {
  855. vstd::erase_if(exits, [&](const ObjectInstanceID & exit) -> bool
  856. {
  857. return !isExitPassable(gs, h, gs->getObj(exit));
  858. });
  859. return exits;
  860. }
  861. void CGTeleport::addToChannel(std::map<TeleportChannelID, std::shared_ptr<TeleportChannel> > &channelsList, const CGTeleport * obj)
  862. {
  863. std::shared_ptr<TeleportChannel> tc;
  864. if(channelsList.find(obj->channel) == channelsList.end())
  865. {
  866. tc = std::make_shared<TeleportChannel>();
  867. channelsList.insert(std::make_pair(obj->channel, tc));
  868. }
  869. else
  870. tc = channelsList[obj->channel];
  871. if(obj->isEntrance() && !vstd::contains(tc->entrances, obj->id))
  872. tc->entrances.push_back(obj->id);
  873. if(obj->isExit() && !vstd::contains(tc->exits, obj->id))
  874. tc->exits.push_back(obj->id);
  875. if(!tc->entrances.empty() && !tc->exits.empty()
  876. && (tc->entrances.size() != 1 || tc->entrances != tc->exits))
  877. {
  878. tc->passability = TeleportChannel::PASSABLE;
  879. }
  880. }
  881. TeleportChannelID CGMonolith::findMeChannel(const std::vector<Obj> & IDs, int SubID) const
  882. {
  883. for(auto obj : cb->gameState()->map->objects)
  884. {
  885. if(!obj)
  886. continue;
  887. const auto * teleportObj = dynamic_cast<const CGTeleport *>(cb->getObj(obj->id));
  888. if(teleportObj && vstd::contains(IDs, teleportObj->ID) && teleportObj->subID == SubID)
  889. return teleportObj->channel;
  890. }
  891. return TeleportChannelID();
  892. }
  893. void CGMonolith::onHeroVisit( const CGHeroInstance * h ) const
  894. {
  895. TeleportDialog td(h->tempOwner, channel);
  896. if(isEntrance())
  897. {
  898. if(cb->isTeleportChannelBidirectional(channel) && 1 < cb->getTeleportChannelExits(channel).size())
  899. {
  900. auto exits = cb->getTeleportChannelExits(channel);
  901. for(const auto & exit : exits)
  902. {
  903. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  904. }
  905. }
  906. if(cb->isTeleportChannelImpassable(channel))
  907. {
  908. logGlobal->debug("Cannot find corresponding exit monolith for %d at %s", id.getNum(), pos.toString());
  909. td.impassable = true;
  910. }
  911. else if(getRandomExit(h) == ObjectInstanceID())
  912. logGlobal->debug("All exits blocked for monolith %d at %s", id.getNum(), pos.toString());
  913. }
  914. else
  915. h->showInfoDialog(70);
  916. cb->showTeleportDialog(&td);
  917. }
  918. void CGMonolith::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  919. {
  920. int3 dPos;
  921. auto randomExit = getRandomExit(hero);
  922. auto realExits = getAllExits(true);
  923. if(!isEntrance() // Do nothing if hero visited exit only object
  924. || (exits.empty() && realExits.empty()) // Do nothing if there no exits on this channel
  925. || ObjectInstanceID() == randomExit) // Do nothing if all exits are blocked by friendly hero and it's not subterranean gate
  926. {
  927. return;
  928. }
  929. else if(vstd::isValidIndex(exits, answer))
  930. dPos = exits[answer].second;
  931. else
  932. dPos = hero->convertFromVisitablePos(cb->getObj(randomExit)->visitablePos());
  933. cb->moveHero(hero->id, dPos, true);
  934. }
  935. void CGMonolith::initObj(CRandomGenerator & rand)
  936. {
  937. std::vector<Obj> IDs;
  938. IDs.push_back(ID);
  939. switch(ID)
  940. {
  941. case Obj::MONOLITH_ONE_WAY_ENTRANCE:
  942. type = ENTRANCE;
  943. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_EXIT);
  944. break;
  945. case Obj::MONOLITH_ONE_WAY_EXIT:
  946. type = EXIT;
  947. IDs.emplace_back(Obj::MONOLITH_ONE_WAY_ENTRANCE);
  948. break;
  949. case Obj::MONOLITH_TWO_WAY:
  950. default:
  951. type = BOTH;
  952. break;
  953. }
  954. channel = findMeChannel(IDs, subID);
  955. if(channel == TeleportChannelID())
  956. channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  957. addToChannel(cb->gameState()->map->teleportChannels, this);
  958. }
  959. void CGSubterraneanGate::onHeroVisit( const CGHeroInstance * h ) const
  960. {
  961. TeleportDialog td(h->tempOwner, channel);
  962. if(cb->isTeleportChannelImpassable(channel))
  963. {
  964. h->showInfoDialog(153);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  965. logGlobal->debug("Cannot find exit subterranean gate for %d at %s", id.getNum(), pos.toString());
  966. td.impassable = true;
  967. }
  968. else
  969. {
  970. auto exit = getRandomExit(h);
  971. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(cb->getObj(exit)->visitablePos())));
  972. }
  973. cb->showTeleportDialog(&td);
  974. }
  975. void CGSubterraneanGate::initObj(CRandomGenerator & rand)
  976. {
  977. type = BOTH;
  978. }
  979. void CGSubterraneanGate::postInit() //matches subterranean gates into pairs
  980. {
  981. //split on underground and surface gates
  982. std::vector<CGSubterraneanGate *> gatesSplit[2]; //surface and underground gates
  983. for(auto & obj : cb->gameState()->map->objects)
  984. {
  985. if(!obj) // FIXME: Find out why there are nullptr objects right after initialization
  986. continue;
  987. auto * hlp = dynamic_cast<CGSubterraneanGate *>(cb->gameState()->getObjInstance(obj->id));
  988. if(hlp)
  989. gatesSplit[hlp->pos.z].push_back(hlp);
  990. }
  991. //sort by position
  992. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  993. {
  994. return a->pos < b->pos;
  995. });
  996. auto assignToChannel = [&](CGSubterraneanGate * obj)
  997. {
  998. if(obj->channel == TeleportChannelID())
  999. { // if object not linked to channel then create new channel
  1000. obj->channel = TeleportChannelID(static_cast<si32>(cb->gameState()->map->teleportChannels.size()));
  1001. addToChannel(cb->gameState()->map->teleportChannels, obj);
  1002. }
  1003. };
  1004. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  1005. {
  1006. CGSubterraneanGate * objCurrent = gatesSplit[0][i];
  1007. //find nearest underground exit
  1008. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  1009. for(int j = 0; j < gatesSplit[1].size(); j++)
  1010. {
  1011. CGSubterraneanGate *checked = gatesSplit[1][j];
  1012. if(checked->channel != TeleportChannelID())
  1013. continue;
  1014. si32 hlp = checked->pos.dist2dSQ(objCurrent->pos);
  1015. if(hlp < best.second)
  1016. {
  1017. best.first = j;
  1018. best.second = hlp;
  1019. }
  1020. }
  1021. assignToChannel(objCurrent);
  1022. if(best.first >= 0) //found pair
  1023. {
  1024. gatesSplit[1][best.first]->channel = objCurrent->channel;
  1025. addToChannel(cb->gameState()->map->teleportChannels, gatesSplit[1][best.first]);
  1026. }
  1027. }
  1028. // we should assign empty channels to underground gates if they don't have matching overground gates
  1029. for(auto & i : gatesSplit[1])
  1030. assignToChannel(i);
  1031. }
  1032. void CGWhirlpool::onHeroVisit( const CGHeroInstance * h ) const
  1033. {
  1034. TeleportDialog td(h->tempOwner, channel);
  1035. if(cb->isTeleportChannelImpassable(channel))
  1036. {
  1037. logGlobal->debug("Cannot find exit whirlpool for %d at %s", id.getNum(), pos.toString());
  1038. td.impassable = true;
  1039. }
  1040. else if(getRandomExit(h) == ObjectInstanceID())
  1041. logGlobal->debug("All exits are blocked for whirlpool %d at %s", id.getNum(), pos.toString());
  1042. if(!isProtected(h))
  1043. {
  1044. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  1045. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  1046. {
  1047. if(h->getPower(targetstack) > h->getPower(i->first))
  1048. targetstack = (i->first);
  1049. }
  1050. auto countToTake = static_cast<TQuantity>(h->getStackCount(targetstack) * 0.5);
  1051. vstd::amax(countToTake, 1);
  1052. InfoWindow iw;
  1053. iw.type = EInfoWindowMode::AUTO;
  1054. iw.player = h->tempOwner;
  1055. iw.text.addTxt(MetaString::ADVOB_TXT, 168);
  1056. iw.components.emplace_back(CStackBasicDescriptor(h->getCreature(targetstack), countToTake));
  1057. cb->showInfoDialog(&iw);
  1058. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  1059. }
  1060. else
  1061. {
  1062. auto exits = getAllExits();
  1063. for(const auto & exit : exits)
  1064. {
  1065. auto blockedPosList = cb->getObj(exit)->getBlockedPos();
  1066. for(const auto & bPos : blockedPosList)
  1067. td.exits.push_back(std::make_pair(exit, h->convertFromVisitablePos(bPos)));
  1068. }
  1069. }
  1070. cb->showTeleportDialog(&td);
  1071. }
  1072. void CGWhirlpool::teleportDialogAnswered(const CGHeroInstance *hero, ui32 answer, TTeleportExitsList exits) const
  1073. {
  1074. int3 dPos;
  1075. auto realExits = getAllExits();
  1076. if(exits.empty() && realExits.empty())
  1077. return;
  1078. else if(vstd::isValidIndex(exits, answer))
  1079. dPos = exits[answer].second;
  1080. else
  1081. {
  1082. auto exit = getRandomExit(hero);
  1083. if(exit == ObjectInstanceID())
  1084. return;
  1085. const auto * obj = cb->getObj(exit);
  1086. std::set<int3> tiles = obj->getBlockedPos();
  1087. dPos = hero->convertFromVisitablePos(*RandomGeneratorUtil::nextItem(tiles, CRandomGenerator::getDefault()));
  1088. }
  1089. cb->moveHero(hero->id, dPos, true);
  1090. }
  1091. bool CGWhirlpool::isProtected(const CGHeroInstance * h)
  1092. {
  1093. return h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION)
  1094. || (h->stacksCount() == 1 && h->Slots().begin()->second->count == 1);
  1095. }
  1096. void CGArtifact::initObj(CRandomGenerator & rand)
  1097. {
  1098. blockVisit = true;
  1099. if(ID == Obj::ARTIFACT)
  1100. {
  1101. if (!storedArtifact)
  1102. {
  1103. auto * a = new CArtifactInstance();
  1104. cb->gameState()->map->addNewArtifactInstance(a);
  1105. storedArtifact = a;
  1106. }
  1107. if(!storedArtifact->artType)
  1108. storedArtifact->setType(VLC->arth->objects[subID]);
  1109. }
  1110. if(ID == Obj::SPELL_SCROLL)
  1111. subID = 1;
  1112. assert(storedArtifact->artType);
  1113. assert(storedArtifact->getParentNodes().size());
  1114. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  1115. }
  1116. std::string CGArtifact::getObjectName() const
  1117. {
  1118. return VLC->artifacts()->getByIndex(subID)->getNameTranslated();
  1119. }
  1120. void CGArtifact::onHeroVisit(const CGHeroInstance * h) const
  1121. {
  1122. if(!stacksCount())
  1123. {
  1124. InfoWindow iw;
  1125. iw.type = EInfoWindowMode::AUTO;
  1126. iw.player = h->tempOwner;
  1127. switch(ID)
  1128. {
  1129. case Obj::ARTIFACT:
  1130. {
  1131. iw.components.emplace_back(Component::ARTIFACT, subID, 0, 0);
  1132. if(message.length())
  1133. iw.text << message;
  1134. else
  1135. iw.text.addTxt(MetaString::ART_EVNTS, subID);
  1136. }
  1137. break;
  1138. case Obj::SPELL_SCROLL:
  1139. {
  1140. int spellID = storedArtifact->getGivenSpellID();
  1141. iw.components.emplace_back(Component::SPELL, spellID, 0, 0);
  1142. if(message.length())
  1143. iw.text << message;
  1144. else
  1145. {
  1146. iw.text.addTxt(MetaString::ADVOB_TXT,135);
  1147. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  1148. }
  1149. }
  1150. break;
  1151. }
  1152. cb->showInfoDialog(&iw);
  1153. pick(h);
  1154. }
  1155. else
  1156. {
  1157. switch(ID)
  1158. {
  1159. case Obj::ARTIFACT:
  1160. {
  1161. BlockingDialog ynd(true,false);
  1162. ynd.player = h->getOwner();
  1163. if(message.length())
  1164. ynd.text << message;
  1165. else
  1166. {
  1167. // TODO: Guard text is more complex in H3, see mantis issue 2325 for details
  1168. ynd.text.addTxt(MetaString::GENERAL_TXT, 420);
  1169. ynd.text.addReplacement("");
  1170. ynd.text.addReplacement(getArmyDescription());
  1171. ynd.text.addReplacement(MetaString::GENERAL_TXT, 43); // creatures
  1172. }
  1173. cb->showBlockingDialog(&ynd);
  1174. }
  1175. break;
  1176. case Obj::SPELL_SCROLL:
  1177. {
  1178. if(message.length())
  1179. {
  1180. BlockingDialog ynd(true,false);
  1181. ynd.player = h->getOwner();
  1182. ynd.text << message;
  1183. cb->showBlockingDialog(&ynd);
  1184. }
  1185. else
  1186. blockingDialogAnswered(h, true);
  1187. }
  1188. break;
  1189. }
  1190. }
  1191. }
  1192. void CGArtifact::pick(const CGHeroInstance * h) const
  1193. {
  1194. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  1195. cb->removeObject(this);
  1196. }
  1197. BattleField CGArtifact::getBattlefield() const
  1198. {
  1199. return BattleField::NONE;
  1200. }
  1201. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1202. {
  1203. if(result.winner == 0) //attacker won
  1204. pick(hero);
  1205. }
  1206. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1207. {
  1208. if(answer)
  1209. cb->startBattleI(hero, this);
  1210. }
  1211. void CGArtifact::afterAddToMap(CMap * map)
  1212. {
  1213. //Artifacts from map objects are never removed
  1214. //FIXME: This should be revertible in map editor
  1215. if(ID == Obj::SPELL_SCROLL && storedArtifact && storedArtifact->id.getNum() < 0)
  1216. map->addNewArtifactInstance(storedArtifact);
  1217. }
  1218. void CGArtifact::serializeJsonOptions(JsonSerializeFormat& handler)
  1219. {
  1220. handler.serializeString("guardMessage", message);
  1221. CCreatureSet::serializeJson(handler, "guards" ,7);
  1222. if(handler.saving && ID == Obj::SPELL_SCROLL)
  1223. {
  1224. const std::shared_ptr<Bonus> b = storedArtifact->getBonusLocalFirst(Selector::type()(Bonus::SPELL));
  1225. SpellID spellId(b->subtype);
  1226. handler.serializeId("spell", spellId, SpellID::NONE);
  1227. }
  1228. }
  1229. void CGWitchHut::initObj(CRandomGenerator & rand)
  1230. {
  1231. if (allowedAbilities.empty()) //this can happen for RMG. regular maps load abilities from map file
  1232. {
  1233. // Necromancy can't be learned on random maps
  1234. for(int i = 0; i < VLC->skillh->size(); i++)
  1235. if(VLC->skillh->getByIndex(i)->getId() != SecondarySkill::NECROMANCY)
  1236. allowedAbilities.push_back(i);
  1237. }
  1238. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, rand);
  1239. }
  1240. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  1241. {
  1242. InfoWindow iw;
  1243. iw.type = EInfoWindowMode::AUTO;
  1244. iw.player = h->getOwner();
  1245. if(!wasVisited(h->tempOwner))
  1246. cb->setObjProperty(id, CGWitchHut::OBJPROP_VISITED, h->tempOwner.getNum());
  1247. ui32 txt_id;
  1248. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  1249. {
  1250. txt_id =172;
  1251. }
  1252. else if(!h->canLearnSkill()) //already all skills slots used
  1253. {
  1254. txt_id = 173;
  1255. }
  1256. else //give sec skill
  1257. {
  1258. iw.components.emplace_back(Component::SEC_SKILL, ability, 1, 0);
  1259. txt_id = 171;
  1260. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  1261. }
  1262. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  1263. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  1264. cb->showInfoDialog(&iw);
  1265. }
  1266. std::string CGWitchHut::getHoverText(PlayerColor player) const
  1267. {
  1268. std::string hoverName = getObjectName();
  1269. if(wasVisited(player))
  1270. {
  1271. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  1272. boost::algorithm::replace_first(hoverName, "%s", VLC->skillh->getByIndex(ability)->getNameTranslated());
  1273. }
  1274. return hoverName;
  1275. }
  1276. std::string CGWitchHut::getHoverText(const CGHeroInstance * hero) const
  1277. {
  1278. std::string hoverName = getHoverText(hero->tempOwner);
  1279. if(wasVisited(hero->tempOwner) && hero->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  1280. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  1281. return hoverName;
  1282. }
  1283. void CGWitchHut::serializeJsonOptions(JsonSerializeFormat & handler)
  1284. {
  1285. //TODO: unify allowed abilities with others - make them std::vector<bool>
  1286. std::vector<bool> temp;
  1287. size_t skillCount = VLC->skillh->size();
  1288. temp.resize(skillCount, false);
  1289. auto standard = VLC->skillh->getDefaultAllowed(); //todo: for WitchHut default is all except Leadership and Necromancy
  1290. if(handler.saving)
  1291. {
  1292. for(si32 i = 0; i < skillCount; ++i)
  1293. if(vstd::contains(allowedAbilities, i))
  1294. temp[i] = true;
  1295. }
  1296. handler.serializeLIC("allowedSkills", &CSkillHandler::decodeSkill, &CSkillHandler::encodeSkill, standard, temp);
  1297. if(!handler.saving)
  1298. {
  1299. allowedAbilities.clear();
  1300. for(si32 i = 0; i < skillCount; ++i)
  1301. if(temp[i])
  1302. allowedAbilities.push_back(i);
  1303. }
  1304. }
  1305. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  1306. {
  1307. InfoWindow iw;
  1308. iw.type = EInfoWindowMode::AUTO;
  1309. iw.player = h->tempOwner;
  1310. switch (ID)
  1311. {
  1312. case Obj::REDWOOD_OBSERVATORY:
  1313. case Obj::PILLAR_OF_FIRE:
  1314. {
  1315. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  1316. FoWChange fw;
  1317. fw.player = h->tempOwner;
  1318. fw.mode = 1;
  1319. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  1320. cb->sendAndApply (&fw);
  1321. break;
  1322. }
  1323. case Obj::COVER_OF_DARKNESS:
  1324. {
  1325. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  1326. for (auto & player : cb->gameState()->players)
  1327. {
  1328. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1329. cb->getPlayerRelations(player.first, h->tempOwner) == PlayerRelations::ENEMIES)
  1330. cb->changeFogOfWar(visitablePos(), 20, player.first, true);
  1331. }
  1332. break;
  1333. }
  1334. }
  1335. cb->showInfoDialog(&iw);
  1336. }
  1337. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  1338. {
  1339. if(spell == SpellID::NONE)
  1340. {
  1341. logGlobal->error("Not initialized shrine visited!");
  1342. return;
  1343. }
  1344. if(!wasVisited(h->tempOwner))
  1345. cb->setObjProperty(id, CGShrine::OBJPROP_VISITED, h->tempOwner.getNum());
  1346. InfoWindow iw;
  1347. iw.type = EInfoWindowMode::AUTO;
  1348. iw.player = h->getOwner();
  1349. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  1350. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  1351. iw.text << ".";
  1352. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  1353. {
  1354. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  1355. }
  1356. else if(h->spellbookContainsSpell(spell))//hero already knows the spell
  1357. {
  1358. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  1359. }
  1360. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && h->maxSpellLevel() < 3) //it's third level spell and hero doesn't have wisdom
  1361. {
  1362. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  1363. }
  1364. else //give spell
  1365. {
  1366. std::set<SpellID> spells;
  1367. spells.insert(spell);
  1368. cb->changeSpells(h, true, spells);
  1369. iw.components.emplace_back(Component::SPELL, spell, 0, 0);
  1370. }
  1371. cb->showInfoDialog(&iw);
  1372. }
  1373. void CGShrine::initObj(CRandomGenerator & rand)
  1374. {
  1375. if(spell == SpellID::NONE) //spell not set
  1376. {
  1377. int level = ID-87;
  1378. std::vector<SpellID> possibilities;
  1379. cb->getAllowedSpells (possibilities, level);
  1380. if(possibilities.empty())
  1381. {
  1382. logGlobal->error("Error: cannot init shrine, no allowed spells!");
  1383. return;
  1384. }
  1385. spell = *RandomGeneratorUtil::nextItem(possibilities, rand);
  1386. }
  1387. }
  1388. std::string CGShrine::getHoverText(PlayerColor player) const
  1389. {
  1390. std::string hoverName = getObjectName();
  1391. if(wasVisited(player))
  1392. {
  1393. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  1394. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->getNameTranslated());
  1395. }
  1396. return hoverName;
  1397. }
  1398. std::string CGShrine::getHoverText(const CGHeroInstance * hero) const
  1399. {
  1400. std::string hoverName = getHoverText(hero->tempOwner);
  1401. if(wasVisited(hero->tempOwner) && hero->spellbookContainsSpell(spell)) //know what spell there is and hero knows that spell
  1402. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  1403. return hoverName;
  1404. }
  1405. void CGShrine::serializeJsonOptions(JsonSerializeFormat & handler)
  1406. {
  1407. handler.serializeId("spell", spell, SpellID::NONE);
  1408. }
  1409. void CGSignBottle::initObj(CRandomGenerator & rand)
  1410. {
  1411. //if no text is set than we pick random from the predefined ones
  1412. if(message.empty())
  1413. {
  1414. auto vector = VLC->generaltexth->findStringsWithPrefix("core.randsign");
  1415. std::string messageIdentifier = *RandomGeneratorUtil::nextItem(vector, rand);
  1416. message = VLC->generaltexth->translate(messageIdentifier);
  1417. }
  1418. if(ID == Obj::OCEAN_BOTTLE)
  1419. {
  1420. blockVisit = true;
  1421. }
  1422. }
  1423. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  1424. {
  1425. InfoWindow iw;
  1426. iw.player = h->getOwner();
  1427. iw.text << message;
  1428. cb->showInfoDialog(&iw);
  1429. if(ID == Obj::OCEAN_BOTTLE)
  1430. cb->removeObject(this);
  1431. }
  1432. void CGSignBottle::serializeJsonOptions(JsonSerializeFormat& handler)
  1433. {
  1434. handler.serializeString("text", message);
  1435. }
  1436. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  1437. {
  1438. EBonusType type = bonusType;
  1439. int bid = bonusID;
  1440. //check if the bonus if applicable, if not - give primary skill (always possible)
  1441. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  1442. 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)
  1443. || (type == SPELL && !h->canLearnSpell(SpellID(bid).toSpell())))
  1444. {
  1445. type = PRIM_SKILL;
  1446. bid = CRandomGenerator::getDefault().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1447. }
  1448. InfoWindow iw;
  1449. iw.type = EInfoWindowMode::AUTO;
  1450. iw.player = h->getOwner();
  1451. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  1452. switch (type)
  1453. {
  1454. case PRIM_SKILL:
  1455. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  1456. iw.components.emplace_back(Component::PRIM_SKILL, bid, +1, 0);
  1457. break;
  1458. case SECONDARY_SKILL:
  1459. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  1460. iw.components.emplace_back(Component::SEC_SKILL, bid, ssl + 1, 0);
  1461. break;
  1462. case SPELL:
  1463. {
  1464. std::set<SpellID> hlp;
  1465. hlp.insert(SpellID(bid));
  1466. cb->changeSpells(h,true,hlp);
  1467. iw.components.emplace_back(Component::SPELL, bid, 0, 0);
  1468. }
  1469. break;
  1470. default:
  1471. logGlobal->error("Error: wrong bonus type (%d) for Scholar!\n", static_cast<int>(type));
  1472. return;
  1473. }
  1474. cb->showInfoDialog(&iw);
  1475. cb->removeObject(this);
  1476. }
  1477. void CGScholar::initObj(CRandomGenerator & rand)
  1478. {
  1479. blockVisit = true;
  1480. if(bonusType == RANDOM)
  1481. {
  1482. bonusType = static_cast<EBonusType>(rand.nextInt(2));
  1483. switch(bonusType)
  1484. {
  1485. case PRIM_SKILL:
  1486. bonusID = rand.nextInt(GameConstants::PRIMARY_SKILLS -1);
  1487. break;
  1488. case SECONDARY_SKILL:
  1489. bonusID = rand.nextInt(static_cast<int>(VLC->skillh->size()) - 1);
  1490. break;
  1491. case SPELL:
  1492. std::vector<SpellID> possibilities;
  1493. for (int i = 1; i < 6; ++i)
  1494. cb->getAllowedSpells (possibilities, i);
  1495. bonusID = *RandomGeneratorUtil::nextItem(possibilities, rand);
  1496. break;
  1497. }
  1498. }
  1499. }
  1500. void CGScholar::serializeJsonOptions(JsonSerializeFormat & handler)
  1501. {
  1502. if(handler.saving)
  1503. {
  1504. std::string value;
  1505. switch(bonusType)
  1506. {
  1507. case PRIM_SKILL:
  1508. value = PrimarySkill::names[bonusID];
  1509. handler.serializeString("rewardPrimSkill", value);
  1510. break;
  1511. case SECONDARY_SKILL:
  1512. value = CSkillHandler::encodeSkill(bonusID);
  1513. handler.serializeString("rewardSkill", value);
  1514. break;
  1515. case SPELL:
  1516. value = SpellID::encode(bonusID);
  1517. handler.serializeString("rewardSpell", value);
  1518. break;
  1519. case RANDOM:
  1520. break;
  1521. }
  1522. }
  1523. else
  1524. {
  1525. //TODO: unify
  1526. const JsonNode & json = handler.getCurrent();
  1527. bonusType = RANDOM;
  1528. if(!json["rewardPrimSkill"].String().empty())
  1529. {
  1530. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "primSkill", json["rewardPrimSkill"].String());
  1531. if(raw)
  1532. {
  1533. bonusType = PRIM_SKILL;
  1534. bonusID = raw.get();
  1535. }
  1536. }
  1537. else if(!json["rewardSkill"].String().empty())
  1538. {
  1539. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "skill", json["rewardSkill"].String());
  1540. if(raw)
  1541. {
  1542. bonusType = SECONDARY_SKILL;
  1543. bonusID = raw.get();
  1544. }
  1545. }
  1546. else if(!json["rewardSpell"].String().empty())
  1547. {
  1548. auto raw = VLC->modh->identifiers.getIdentifier(CModHandler::scopeBuiltin(), "spell", json["rewardSpell"].String());
  1549. if(raw)
  1550. {
  1551. bonusType = SPELL;
  1552. bonusID = raw.get();
  1553. }
  1554. }
  1555. }
  1556. }
  1557. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1558. {
  1559. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1560. if (!ally && stacksCount() > 0) {
  1561. //TODO: Find a way to apply magic garrison effects in battle.
  1562. cb->startBattleI(h, this);
  1563. return;
  1564. }
  1565. //New owner.
  1566. if (!ally)
  1567. cb->setOwner(this, h->tempOwner);
  1568. cb->showGarrisonDialog(id, h->id, removableUnits);
  1569. }
  1570. bool CGGarrison::passableFor(PlayerColor player) const
  1571. {
  1572. //FIXME: identical to same method in CGTownInstance
  1573. if ( !stacksCount() )//empty - anyone can visit
  1574. return true;
  1575. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1576. return false;
  1577. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1578. return true;
  1579. return false;
  1580. }
  1581. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1582. {
  1583. if (result.winner == 0)
  1584. onHeroVisit(hero);
  1585. }
  1586. void CGGarrison::serializeJsonOptions(JsonSerializeFormat& handler)
  1587. {
  1588. handler.serializeBool("removableUnits", removableUnits);
  1589. serializeJsonOwner(handler);
  1590. CCreatureSet::serializeJson(handler, "army", 7);
  1591. }
  1592. void CGMagi::reset()
  1593. {
  1594. eyelist.clear();
  1595. }
  1596. void CGMagi::initObj(CRandomGenerator & rand)
  1597. {
  1598. if (ID == Obj::EYE_OF_MAGI)
  1599. {
  1600. blockVisit = true;
  1601. eyelist[subID].push_back(id);
  1602. }
  1603. }
  1604. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1605. {
  1606. if (ID == Obj::HUT_OF_MAGI)
  1607. {
  1608. h->showInfoDialog(61);
  1609. if (!eyelist[subID].empty())
  1610. {
  1611. CenterView cv;
  1612. cv.player = h->tempOwner;
  1613. cv.focusTime = 2000;
  1614. FoWChange fw;
  1615. fw.player = h->tempOwner;
  1616. fw.mode = 1;
  1617. fw.waitForDialogs = true;
  1618. for(const auto & it : eyelist[subID])
  1619. {
  1620. const CGObjectInstance *eye = cb->getObj(it);
  1621. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1622. cb->sendAndApply(&fw);
  1623. cv.pos = eye->pos;
  1624. cb->sendAndApply(&cv);
  1625. }
  1626. cv.pos = h->visitablePos();
  1627. cv.focusTime = 0;
  1628. cb->sendAndApply(&cv);
  1629. }
  1630. }
  1631. else if (ID == Obj::EYE_OF_MAGI)
  1632. {
  1633. h->showInfoDialog(48);
  1634. }
  1635. }
  1636. void CGBoat::initObj(CRandomGenerator & rand)
  1637. {
  1638. hero = nullptr;
  1639. }
  1640. void CGSirens::initObj(CRandomGenerator & rand)
  1641. {
  1642. blockVisit = true;
  1643. }
  1644. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1645. {
  1646. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(Bonus::OBJECT,ID));
  1647. }
  1648. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1649. {
  1650. InfoWindow iw;
  1651. iw.player = h->tempOwner;
  1652. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  1653. {
  1654. iw.type = EInfoWindowMode::AUTO;
  1655. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  1656. }
  1657. else
  1658. {
  1659. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  1660. TExpType xp = 0;
  1661. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1662. {
  1663. // 1-sized stacks are not affected by sirens
  1664. if (i->second->count == 1)
  1665. continue;
  1666. // tested H3 behavior: 30% (rounded up) of stack drowns
  1667. TQuantity drown = std::ceil(i->second->count * 0.3);
  1668. if(drown)
  1669. {
  1670. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1671. xp += drown * i->second->type->MaxHealth();
  1672. }
  1673. }
  1674. if(xp)
  1675. {
  1676. xp = h->calculateXp(static_cast<int>(xp));
  1677. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  1678. iw.text.addReplacement(static_cast<int>(xp));
  1679. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1680. }
  1681. else
  1682. {
  1683. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  1684. }
  1685. }
  1686. cb->showInfoDialog(&iw);
  1687. }
  1688. CGShipyard::CGShipyard()
  1689. :IShipyard(this)
  1690. {
  1691. }
  1692. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1693. {
  1694. // H J L K I
  1695. // A x S x B
  1696. // C E G F D
  1697. offsets = {
  1698. int3(-3,0,0), int3(1,0,0), //AB
  1699. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1700. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0) //HIJKL
  1701. };
  1702. }
  1703. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1704. {
  1705. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1706. cb->setOwner(this, h->tempOwner);
  1707. auto s = shipyardStatus();
  1708. if(s != IBoatGenerator::GOOD)
  1709. {
  1710. InfoWindow iw;
  1711. iw.type = EInfoWindowMode::AUTO;
  1712. iw.player = tempOwner;
  1713. getProblemText(iw.text, h);
  1714. cb->showInfoDialog(&iw);
  1715. }
  1716. else
  1717. {
  1718. openWindow(EOpenWindowMode::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1719. }
  1720. }
  1721. void CGShipyard::serializeJsonOptions(JsonSerializeFormat& handler)
  1722. {
  1723. serializeJsonOwner(handler);
  1724. }
  1725. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1726. {
  1727. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1728. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1729. {
  1730. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  1731. {
  1732. //ask if he wants to buy one
  1733. int text=0;
  1734. switch (subID)
  1735. {
  1736. case 0:
  1737. text = 25;
  1738. break;
  1739. case 1:
  1740. text = 26;
  1741. break;
  1742. case 2:
  1743. text = 27;
  1744. break;
  1745. default:
  1746. logGlobal->warn("Unrecognized subtype of cartographer");
  1747. }
  1748. assert(text);
  1749. BlockingDialog bd (true, false);
  1750. bd.player = h->getOwner();
  1751. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  1752. cb->showBlockingDialog (&bd);
  1753. }
  1754. else //if he cannot afford
  1755. {
  1756. h->showInfoDialog(28);
  1757. }
  1758. }
  1759. else //if he already visited carographer
  1760. {
  1761. h->showInfoDialog(24);
  1762. }
  1763. }
  1764. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1765. {
  1766. if(answer) //if hero wants to buy map
  1767. {
  1768. cb->giveResource(hero->tempOwner, Res::GOLD, -1000);
  1769. FoWChange fw;
  1770. fw.mode = 1;
  1771. fw.player = hero->tempOwner;
  1772. //subIDs of different types of cartographers:
  1773. //water = 0; land = 1; underground = 2;
  1774. IGameCallback::MapTerrainFilterMode tileFilterMode = IGameCallback::MapTerrainFilterMode::NONE;
  1775. switch(subID)
  1776. {
  1777. case 0:
  1778. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::WATER;
  1779. break;
  1780. case 1:
  1781. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::LAND_CARTOGRAPHER;
  1782. break;
  1783. case 2:
  1784. tileFilterMode = CPrivilegedInfoCallback::MapTerrainFilterMode::UNDERGROUND_CARTOGRAPHER;
  1785. break;
  1786. }
  1787. cb->getAllTiles(fw.tiles, hero->tempOwner, -1, tileFilterMode); //reveal appropriate tiles
  1788. cb->sendAndApply(&fw);
  1789. cb->setObjProperty(id, CCartographer::OBJPROP_VISITED, hero->tempOwner.getNum());
  1790. }
  1791. }
  1792. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1793. {
  1794. cb->showThievesGuildWindow(h->tempOwner, id);
  1795. }
  1796. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1797. {
  1798. InfoWindow iw;
  1799. iw.type = EInfoWindowMode::AUTO;
  1800. iw.player = h->tempOwner;
  1801. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1802. assert(ts);
  1803. TeamID team = ts->id;
  1804. if(!wasVisited(team))
  1805. {
  1806. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  1807. cb->sendAndApply(&iw);
  1808. // increment general visited obelisks counter
  1809. cb->setObjProperty(id, CGObelisk::OBJPROP_INC, team.getNum());
  1810. openWindow(EOpenWindowMode::PUZZLE_MAP, h->tempOwner.getNum());
  1811. // mark that particular obelisk as visited for all players in the team
  1812. for(const auto & color : ts->players)
  1813. {
  1814. cb->setObjProperty(id, CGObelisk::OBJPROP_VISITED, color.getNum());
  1815. }
  1816. }
  1817. else
  1818. {
  1819. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  1820. cb->sendAndApply(&iw);
  1821. }
  1822. }
  1823. void CGObelisk::initObj(CRandomGenerator & rand)
  1824. {
  1825. obeliskCount++;
  1826. }
  1827. void CGObelisk::reset()
  1828. {
  1829. obeliskCount = 0;
  1830. visited.clear();
  1831. }
  1832. std::string CGObelisk::getHoverText(PlayerColor player) const
  1833. {
  1834. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1835. }
  1836. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1837. {
  1838. switch(what)
  1839. {
  1840. case CGObelisk::OBJPROP_INC:
  1841. {
  1842. auto progress = ++visited[TeamID(val)];
  1843. logGlobal->debug("Player %d: obelisk progress %d / %d", val, static_cast<int>(progress) , static_cast<int>(obeliskCount));
  1844. if(progress > obeliskCount)
  1845. {
  1846. logGlobal->error("Visited %d of %d", static_cast<int>(progress), obeliskCount);
  1847. throw std::runtime_error("internal error");
  1848. }
  1849. break;
  1850. }
  1851. default:
  1852. CTeamVisited::setPropertyDer(what, val);
  1853. break;
  1854. }
  1855. }
  1856. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1857. {
  1858. if(h->tempOwner != tempOwner)
  1859. {
  1860. PlayerColor oldOwner = tempOwner;
  1861. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1862. h->showInfoDialog(69);
  1863. giveBonusTo(h->tempOwner);
  1864. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1865. {
  1866. RemoveBonus rb(RemoveBonus::PLAYER);
  1867. rb.whoID = oldOwner.getNum();
  1868. rb.source = Bonus::OBJECT;
  1869. rb.id = id.getNum();
  1870. cb->sendAndApply(&rb);
  1871. }
  1872. }
  1873. }
  1874. void CGLighthouse::initObj(CRandomGenerator & rand)
  1875. {
  1876. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1877. {
  1878. // FIXME: This is dirty hack
  1879. giveBonusTo(tempOwner, true);
  1880. }
  1881. }
  1882. void CGLighthouse::giveBonusTo(const PlayerColor & player, bool onInit) const
  1883. {
  1884. GiveBonus gb(GiveBonus::PLAYER);
  1885. gb.bonus.type = Bonus::SEA_MOVEMENT;
  1886. gb.bonus.val = 500;
  1887. gb.id = player.getNum();
  1888. gb.bonus.duration = Bonus::PERMANENT;
  1889. gb.bonus.source = Bonus::OBJECT;
  1890. gb.bonus.sid = id.getNum();
  1891. // FIXME: This is really dirty hack
  1892. // Proper fix would be to make CGLighthouse into bonus system node
  1893. // Unfortunately this will cause saves breakage
  1894. if(onInit)
  1895. gb.applyGs(cb->gameState());
  1896. else
  1897. cb->sendAndApply(&gb);
  1898. }
  1899. void CGLighthouse::serializeJsonOptions(JsonSerializeFormat& handler)
  1900. {
  1901. serializeJsonOwner(handler);
  1902. }
  1903. VCMI_LIB_NAMESPACE_END