MiscObjects.cpp 55 KB

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