MiscObjects.cpp 56 KB

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