MiscObjects.cpp 55 KB

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