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