2
0

MiscObjects.cpp 53 KB

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