MiscObjects.cpp 56 KB

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