MiscObjects.cpp 55 KB

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