MiscObjects.cpp 56 KB

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