MiscObjects.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  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 "../NetPacks.h"
  13. #include "../CGeneralTextHandler.h"
  14. #include "../CSoundBase.h"
  15. #include "../CModHandler.h"
  16. #include "CObjectClassesHandler.h"
  17. #include "../CSpellHandler.h"
  18. #include "../IGameCallback.h"
  19. #include "../CGameState.h"
  20. std::map<Obj, std::map<int, std::vector<ObjectInstanceID> > > CGTeleport::objs;
  21. std::vector<std::pair<ObjectInstanceID, ObjectInstanceID> > CGTeleport::gates;
  22. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  23. ui8 CGObelisk::obeliskCount; //how many obelisks are on map
  24. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  25. ///helpers
  26. static void openWindow(const OpenWindow::EWindow type, const int id1, const int id2 = -1)
  27. {
  28. OpenWindow ow;
  29. ow.window = type;
  30. ow.id1 = id1;
  31. ow.id2 = id2;
  32. IObjectInterface::cb->sendAndApply(&ow);
  33. }
  34. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  35. {
  36. InfoWindow iw;
  37. iw.soundID = soundID;
  38. iw.player = playerID;
  39. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  40. IObjectInterface::cb->sendAndApply(&iw);
  41. }
  42. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  43. {
  44. const PlayerColor playerID = h->getOwner();
  45. showInfoDialog(playerID,txtID,soundID);
  46. }
  47. static std::string & visitedTxt(const bool visited)
  48. {
  49. int id = visited ? 352 : 353;
  50. return VLC->generaltexth->allTexts[id];
  51. }
  52. void CPlayersVisited::setPropertyDer( ui8 what, ui32 val )
  53. {
  54. if(what == 10)
  55. players.insert(PlayerColor(val));
  56. }
  57. bool CPlayersVisited::wasVisited( PlayerColor player ) const
  58. {
  59. return vstd::contains(players,player);
  60. }
  61. bool CPlayersVisited::wasVisited( TeamID team ) const
  62. {
  63. for(auto i : players)
  64. {
  65. if(cb->getPlayer(i)->team == team)
  66. return true;
  67. }
  68. return false;
  69. }
  70. std::string CGCreature::getHoverText(PlayerColor player) const
  71. {
  72. if(stacks.empty())
  73. {
  74. //should not happen...
  75. logGlobal->errorStream() << "Invalid stack at tile " << pos << ": subID=" << subID << "; id=" << id;
  76. return "!!!INVALID_STACK!!!";
  77. }
  78. std::string hoverName;
  79. MetaString ms;
  80. int pom = stacks.begin()->second->getQuantityID();
  81. pom = 172 + 3*pom;
  82. ms.addTxt(MetaString::ARRAY_TXT,pom);
  83. ms << " " ;
  84. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  85. ms.toString(hoverName);
  86. return hoverName;
  87. }
  88. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  89. {
  90. std::string hoverName = getHoverText(hero->tempOwner);
  91. const JsonNode & texts = VLC->generaltexth->localizedTexts["adventureMap"]["monsterThreat"];
  92. hoverName += texts["title"].String();
  93. int choice;
  94. double ratio = ((double)getArmyStrength() / hero->getTotalStrength());
  95. if (ratio < 0.1) choice = 0;
  96. else if (ratio < 0.25) choice = 1;
  97. else if (ratio < 0.6) choice = 2;
  98. else if (ratio < 0.9) choice = 3;
  99. else if (ratio < 1.1) choice = 4;
  100. else if (ratio < 1.3) choice = 5;
  101. else if (ratio < 1.8) choice = 6;
  102. else if (ratio < 2.5) choice = 7;
  103. else if (ratio < 4) choice = 8;
  104. else if (ratio < 8) choice = 9;
  105. else if (ratio < 20) choice = 10;
  106. else choice = 11;
  107. hoverName += texts["levels"].Vector()[choice].String();
  108. return hoverName;
  109. }
  110. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  111. {
  112. int action = takenAction(h);
  113. switch( action ) //decide what we do...
  114. {
  115. case FIGHT:
  116. fight(h);
  117. break;
  118. case FLEE: //flee
  119. {
  120. flee(h);
  121. break;
  122. }
  123. case JOIN_FOR_FREE: //join for free
  124. {
  125. BlockingDialog ynd(true,false);
  126. ynd.player = h->tempOwner;
  127. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  128. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  129. cb->showBlockingDialog(&ynd);
  130. break;
  131. }
  132. default: //join for gold
  133. {
  134. assert(action > 0);
  135. //ask if player agrees to pay gold
  136. BlockingDialog ynd(true,false);
  137. ynd.player = h->tempOwner;
  138. std::string tmp = VLC->generaltexth->advobtxt[90];
  139. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  140. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  141. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  142. ynd.text << tmp;
  143. cb->showBlockingDialog(&ynd);
  144. break;
  145. }
  146. }
  147. }
  148. void CGCreature::initObj()
  149. {
  150. blockVisit = true;
  151. switch(character)
  152. {
  153. case 0:
  154. character = -4;
  155. break;
  156. case 1:
  157. character = cb->gameState()->getRandomGenerator().nextInt(1, 7);
  158. break;
  159. case 2:
  160. character = cb->gameState()->getRandomGenerator().nextInt(1, 10);
  161. break;
  162. case 3:
  163. character = cb->gameState()->getRandomGenerator().nextInt(4, 10);
  164. break;
  165. case 4:
  166. character = 10;
  167. break;
  168. }
  169. stacks[SlotID(0)]->setType(CreatureID(subID));
  170. TQuantity &amount = stacks[SlotID(0)]->count;
  171. CCreature &c = *VLC->creh->creatures[subID];
  172. if(amount == 0)
  173. {
  174. amount = cb->gameState()->getRandomGenerator().nextInt(c.ammMin, c.ammMax);
  175. if(amount == 0) //armies with 0 creatures are illegal
  176. {
  177. logGlobal->warnStream() << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName();
  178. amount = 1;
  179. }
  180. }
  181. temppower = stacks[SlotID(0)]->count * 1000;
  182. refusedJoining = false;
  183. }
  184. void CGCreature::newTurn() const
  185. {//Works only for stacks of single type of size up to 2 millions
  186. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  187. {
  188. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  189. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  190. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  191. }
  192. if (VLC->modh->modules.STACK_EXP)
  193. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  194. }
  195. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  196. {
  197. switch (what)
  198. {
  199. case ObjProperty::MONSTER_COUNT:
  200. stacks[SlotID(0)]->count = val;
  201. break;
  202. case ObjProperty::MONSTER_POWER:
  203. temppower = val;
  204. break;
  205. case ObjProperty::MONSTER_EXP:
  206. giveStackExp(val);
  207. break;
  208. case ObjProperty::MONSTER_RESTORE_TYPE:
  209. formation.basicType = val;
  210. break;
  211. case ObjProperty::MONSTER_REFUSED_JOIN:
  212. refusedJoining = val;
  213. break;
  214. }
  215. }
  216. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  217. {
  218. //calculate relative strength of hero and creatures armies
  219. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  220. int powerFactor;
  221. if(relStrength >= 7)
  222. powerFactor = 11;
  223. else if(relStrength >= 1)
  224. powerFactor = (int)(2*(relStrength-1));
  225. else if(relStrength >= 0.5)
  226. powerFactor = -1;
  227. else if(relStrength >= 0.333)
  228. powerFactor = -2;
  229. else
  230. powerFactor = -3;
  231. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  232. const CCreature * myCreature = VLC->creh->creatures[subID];
  233. myKindCres.insert(myCreature->idNumber); //we
  234. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  235. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->creatures)
  236. {
  237. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  238. myKindCres.insert(crea->idNumber);
  239. }
  240. int count = 0, //how many creatures of similar kind has hero
  241. totalCount = 0;
  242. for (auto & elem : h->Slots())
  243. {
  244. if(vstd::contains(myKindCres,elem.second->type->idNumber))
  245. count += elem.second->count;
  246. totalCount += elem.second->count;
  247. }
  248. int sympathy = 0; // 0 if hero have no similar creatures
  249. if(count)
  250. sympathy++; // 1 - if hero have at least 1 similar creature
  251. if(count*2 > totalCount)
  252. sympathy++; // 2 - hero have similar creatures more that 50%
  253. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  254. if(charisma < character) //creatures will fight
  255. return -2;
  256. if (allowJoin)
  257. {
  258. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  259. return 0; //join for free
  260. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  261. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  262. }
  263. //we are still here - creatures have not joined hero, flee or fight
  264. if (charisma > character)
  265. return -1; //flee
  266. else
  267. return -2; //fight
  268. }
  269. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  270. {
  271. if(refusedJoining)
  272. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  273. if(pursue)
  274. {
  275. fight(h);
  276. }
  277. else
  278. {
  279. cb->removeObject(this);
  280. }
  281. }
  282. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  283. {
  284. if(!accept)
  285. {
  286. if(takenAction(h,false) == -1) //they flee
  287. {
  288. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  289. flee(h);
  290. }
  291. else //they fight
  292. {
  293. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  294. fight(h);
  295. }
  296. }
  297. else //accepted
  298. {
  299. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  300. {
  301. InfoWindow iw;
  302. iw.player = h->tempOwner;
  303. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  304. cb->showInfoDialog(&iw);
  305. //act as if player refused
  306. joinDecision(h,cost,false);
  307. return;
  308. }
  309. //take gold
  310. if(cost)
  311. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  312. cb->tryJoiningArmy(this, h, true, true);
  313. }
  314. }
  315. void CGCreature::fight( const CGHeroInstance *h ) const
  316. {
  317. //split stacks
  318. //TODO: multiple creature types in a stack?
  319. int basicType = stacks.begin()->second->type->idNumber;
  320. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  321. int stacksCount = getNumberOfStacks(h);
  322. SlotID sourceSlot = stacks.begin()->first;
  323. SlotID destSlot;
  324. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  325. {
  326. int stackSize = stacks.begin()->second->count / stacksLeft;
  327. if (stackSize)
  328. {
  329. if ((destSlot = getFreeSlot()).validSlot())
  330. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  331. else
  332. {
  333. logGlobal->warnStream() <<"Warning! Not enough empty slots to split stack!";
  334. break;
  335. }
  336. }
  337. else break;
  338. }
  339. if (stacksCount > 1)
  340. {
  341. if (containsUpgradedStack()) //upgrade
  342. {
  343. SlotID slotId = SlotID(stacks.size() / 2);
  344. const auto & upgrades = getStack(slotId).type->upgrades;
  345. if(!upgrades.empty())
  346. {
  347. auto it = RandomGeneratorUtil::nextItem(upgrades, cb->gameState()->getRandomGenerator());
  348. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  349. }
  350. }
  351. }
  352. cb->startBattleI(h, this);
  353. }
  354. void CGCreature::flee( const CGHeroInstance * h ) const
  355. {
  356. BlockingDialog ynd(true,false);
  357. ynd.player = h->tempOwner;
  358. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  359. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  360. cb->showBlockingDialog(&ynd);
  361. }
  362. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  363. {
  364. if(result.winner==0)
  365. {
  366. cb->removeObject(this);
  367. }
  368. else
  369. {
  370. //merge stacks into one
  371. TSlots::const_iterator i;
  372. CCreature * cre = VLC->creh->creatures[formation.basicType];
  373. for (i = stacks.begin(); i != stacks.end(); i++)
  374. {
  375. if (cre->isMyUpgrade(i->second->type))
  376. {
  377. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  378. }
  379. }
  380. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  381. if(!hasStackAtSlot(SlotID(0)))
  382. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  383. while (stacks.size() > 1) //hopefully that's enough
  384. {
  385. // 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)
  386. i = stacks.end();
  387. i--;
  388. SlotID slot = getSlotFor(i->second->type);
  389. if (slot == i->first) //no reason to move stack to its own slot
  390. break;
  391. else
  392. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  393. }
  394. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  395. }
  396. }
  397. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  398. {
  399. auto action = takenAction(hero);
  400. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  401. joinDecision(hero, action, answer);
  402. else if(action != FIGHT)
  403. fleeDecision(hero, answer);
  404. else
  405. assert(0);
  406. }
  407. bool CGCreature::containsUpgradedStack() const
  408. {
  409. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  410. float a = 2992.911117;
  411. float b = 14174.264968;
  412. float c = 5325.181015;
  413. float d = 32788.727920;
  414. int val = std::floor (a*pos.x + b*pos.y + c*pos.z + d);
  415. return ((val % 32768) % 100) < 50;
  416. }
  417. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  418. {
  419. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  420. float strengthRatio = hero->getArmyStrength() / getArmyStrength();
  421. int split = 1;
  422. if (strengthRatio < 0.5f)
  423. split = 7;
  424. else if (strengthRatio < 0.67f)
  425. split = 6;
  426. else if (strengthRatio < 1)
  427. split = 5;
  428. else if (strengthRatio < 1.5f)
  429. split = 4;
  430. else if (strengthRatio < 2)
  431. split = 3;
  432. else
  433. split = 2;
  434. int a = 1550811371;
  435. int b = -935900487;
  436. int c = 1943276003;
  437. int d = -1120346418;
  438. int R1 = a * pos.x + b * pos.y + c * pos.z + d;
  439. int R2 = R1 / 65536;
  440. int R3 = R2 % 32768;
  441. if (R3 < 0)
  442. R3 += 32767; //is it ever needed if we do modulo calculus?
  443. int R4 = R3 % 100 + 1;
  444. if (R4 <= 20)
  445. split -= 1;
  446. else if (R4 >= 80)
  447. split += 1;
  448. vstd::amin(split, getStack(SlotID(0)).count); //can't divide into more stacks than creatures total
  449. vstd::amin(split, 7); //can't have more than 7 stacks
  450. return split;
  451. }
  452. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  453. {
  454. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  455. if(relations == 2) //we're visiting our mine
  456. {
  457. cb->showGarrisonDialog(id,h->id,true);
  458. return;
  459. }
  460. else if (relations == 1)//ally
  461. return;
  462. if(stacksCount()) //Mine is guarded
  463. {
  464. BlockingDialog ynd(true,false);
  465. ynd.player = h->tempOwner;
  466. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  467. cb->showBlockingDialog(&ynd);
  468. return;
  469. }
  470. flagMine(h->tempOwner);
  471. }
  472. void CGMine::newTurn() const
  473. {
  474. if(cb->getDate() == 1)
  475. return;
  476. if (tempOwner == PlayerColor::NEUTRAL)
  477. return;
  478. cb->giveResource(tempOwner, producedResource, producedQuantity);
  479. }
  480. void CGMine::initObj()
  481. {
  482. if(subID >= 7) //Abandoned Mine
  483. {
  484. //set guardians
  485. int howManyTroglodytes = cb->gameState()->getRandomGenerator().nextInt(100, 199);
  486. auto troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  487. putStack(SlotID(0), troglodytes);
  488. //after map reading tempOwner placeholds bitmask for allowed resources
  489. std::vector<Res::ERes> possibleResources;
  490. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  491. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  492. possibleResources.push_back(static_cast<Res::ERes>(i));
  493. assert(!possibleResources.empty());
  494. producedResource = *RandomGeneratorUtil::nextItem(possibleResources, cb->gameState()->getRandomGenerator());
  495. tempOwner = PlayerColor::NEUTRAL;
  496. }
  497. else
  498. {
  499. producedResource = static_cast<Res::ERes>(subID);
  500. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  501. tempOwner = PlayerColor::NEUTRAL;
  502. }
  503. producedQuantity = defaultResProduction();
  504. }
  505. std::string CGMine::getObjectName() const
  506. {
  507. return VLC->generaltexth->mines.at(subID).first;
  508. }
  509. std::string CGMine::getHoverText(PlayerColor player) const
  510. {
  511. std::string hoverName = getObjectName(); // Sawmill
  512. if (tempOwner != PlayerColor::NEUTRAL)
  513. {
  514. hoverName += "\n";
  515. hoverName += VLC->generaltexth->arraytxt[23 + tempOwner.getNum()]; // owned by Red Player
  516. hoverName += "\n(" + VLC->generaltexth->restypes[producedResource] + ")";
  517. }
  518. for (auto & slot : Slots()) // guarded by a few Pikeman
  519. {
  520. hoverName += "\n";
  521. hoverName += getRoughAmount(slot.first);
  522. hoverName += getCreature(slot.first)->namePl;
  523. }
  524. return hoverName;
  525. }
  526. void CGMine::flagMine(PlayerColor player) const
  527. {
  528. assert(tempOwner != player);
  529. cb->setOwner(this, player); //not ours? flag it!
  530. InfoWindow iw;
  531. iw.soundID = soundBase::FLAGMINE;
  532. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  533. iw.player = player;
  534. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  535. cb->showInfoDialog(&iw);
  536. }
  537. ui32 CGMine::defaultResProduction()
  538. {
  539. switch(producedResource)
  540. {
  541. case Res::WOOD:
  542. case Res::ORE:
  543. return 2;
  544. case Res::GOLD:
  545. return 1000;
  546. default:
  547. return 1;
  548. }
  549. }
  550. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  551. {
  552. if(result.winner == 0) //attacker won
  553. {
  554. if(subID == 7)
  555. {
  556. showInfoDialog(hero->tempOwner, 85, 0);
  557. }
  558. flagMine(hero->tempOwner);
  559. }
  560. }
  561. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  562. {
  563. if(answer)
  564. cb->startBattleI(hero, this);
  565. }
  566. std::string CGResource::getHoverText(PlayerColor player) const
  567. {
  568. return VLC->generaltexth->restypes[subID];
  569. }
  570. CGResource::CGResource()
  571. {
  572. amount = 0;
  573. }
  574. void CGResource::initObj()
  575. {
  576. blockVisit = true;
  577. if(!amount)
  578. {
  579. switch(subID)
  580. {
  581. case 6:
  582. amount = cb->gameState()->getRandomGenerator().nextInt(500, 1000);
  583. break;
  584. case 0: case 2:
  585. amount = cb->gameState()->getRandomGenerator().nextInt(6, 10);
  586. break;
  587. default:
  588. amount = cb->gameState()->getRandomGenerator().nextInt(3, 5);
  589. break;
  590. }
  591. }
  592. }
  593. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  594. {
  595. if(stacksCount())
  596. {
  597. if(message.size())
  598. {
  599. BlockingDialog ynd(true,false);
  600. ynd.player = h->getOwner();
  601. ynd.text << message;
  602. cb->showBlockingDialog(&ynd);
  603. }
  604. else
  605. {
  606. blockingDialogAnswered(h, true); //behave as if player accepted battle
  607. }
  608. }
  609. else
  610. {
  611. if(message.length())
  612. {
  613. InfoWindow iw;
  614. iw.player = h->tempOwner;
  615. iw.text << message;
  616. cb->showInfoDialog(&iw);
  617. }
  618. collectRes(h->getOwner());
  619. }
  620. }
  621. void CGResource::collectRes( PlayerColor player ) const
  622. {
  623. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  624. ShowInInfobox sii;
  625. sii.player = player;
  626. sii.c = Component(Component::RESOURCE,subID,amount,0);
  627. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  628. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  629. cb->showCompInfo(&sii);
  630. cb->removeObject(this);
  631. }
  632. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  633. {
  634. if(result.winner == 0) //attacker won
  635. collectRes(hero->getOwner());
  636. }
  637. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  638. {
  639. if(answer)
  640. cb->startBattleI(hero, this);
  641. }
  642. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  643. {
  644. ObjectInstanceID destinationid;
  645. switch(ID)
  646. {
  647. case Obj::MONOLITH_ONE_WAY_ENTRANCE: //one way - find corresponding exit monolith
  648. {
  649. if(vstd::contains(objs,Obj::MONOLITH_ONE_WAY_EXIT) && vstd::contains(objs[Obj::MONOLITH_ONE_WAY_EXIT],subID) && objs[Obj::MONOLITH_ONE_WAY_EXIT][subID].size())
  650. {
  651. destinationid = *RandomGeneratorUtil::nextItem(objs[Obj::MONOLITH_ONE_WAY_EXIT][subID], cb->gameState()->getRandomGenerator());
  652. }
  653. else
  654. {
  655. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  656. }
  657. break;
  658. }
  659. case Obj::MONOLITH_TWO_WAY://two way monolith - pick any other one
  660. case Obj::WHIRLPOOL: //Whirlpool
  661. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  662. {
  663. //choose another exit
  664. do
  665. {
  666. destinationid = *RandomGeneratorUtil::nextItem(objs[ID][subID], cb->gameState()->getRandomGenerator());
  667. } while(destinationid == id);
  668. if (ID == Obj::WHIRLPOOL)
  669. {
  670. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  671. {
  672. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  673. { //we can't remove last unit
  674. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  675. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  676. {
  677. if (h->getPower(targetstack) > h->getPower(i->first))
  678. {
  679. targetstack = (i->first);
  680. }
  681. }
  682. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  683. vstd::amax(countToTake, 1);
  684. InfoWindow iw;
  685. iw.player = h->tempOwner;
  686. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  687. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  688. cb->showInfoDialog(&iw);
  689. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  690. }
  691. }
  692. }
  693. }
  694. else
  695. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  696. break;
  697. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  698. {
  699. destinationid = getMatchingGate(id);
  700. if(destinationid == ObjectInstanceID()) //no exit
  701. {
  702. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  703. }
  704. break;
  705. }
  706. }
  707. if(destinationid == ObjectInstanceID())
  708. {
  709. logGlobal->warnStream() << "Cannot find exit... (obj at " << pos << ") :( ";
  710. return;
  711. }
  712. if (ID == Obj::WHIRLPOOL)
  713. {
  714. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  715. auto & tile = *RandomGeneratorUtil::nextItem(tiles, cb->gameState()->getRandomGenerator());
  716. cb->moveHero(h->id, tile + int3(1,0,0), true);
  717. }
  718. else
  719. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  720. }
  721. void CGTeleport::initObj()
  722. {
  723. int si = subID;
  724. switch (ID)
  725. {
  726. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  727. case Obj::WHIRLPOOL:
  728. {
  729. si = 0;
  730. break;
  731. }
  732. default:
  733. break;
  734. }
  735. objs[ID][si].push_back(id);
  736. }
  737. void CGTeleport::postInit() //matches subterranean gates into pairs
  738. {
  739. //split on underground and surface gates
  740. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  741. for(auto & elem : objs[Obj::SUBTERRANEAN_GATE][0])
  742. {
  743. const CGObjectInstance *hlp = cb->getObj(elem);
  744. gatesSplit[hlp->pos.z].push_back(hlp);
  745. }
  746. //sort by position
  747. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  748. {
  749. return a->pos < b->pos;
  750. });
  751. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  752. {
  753. const CGObjectInstance *cur = gatesSplit[0][i];
  754. //find nearest underground exit
  755. std::pair<int, si32> best(-1, std::numeric_limits<si32>::max()); //pair<pos_in_vector, distance^2>
  756. for(int j = 0; j < gatesSplit[1].size(); j++)
  757. {
  758. const CGObjectInstance *checked = gatesSplit[1][j];
  759. if(!checked)
  760. continue;
  761. si32 hlp = checked->pos.dist2dSQ(cur->pos);
  762. if(hlp < best.second)
  763. {
  764. best.first = j;
  765. best.second = hlp;
  766. }
  767. }
  768. if(best.first >= 0) //found pair
  769. {
  770. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  771. gatesSplit[1][best.first] = nullptr;
  772. }
  773. else
  774. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  775. }
  776. objs.erase(Obj::SUBTERRANEAN_GATE);
  777. }
  778. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  779. {
  780. for(auto & gate : gates)
  781. {
  782. if(gate.first == id)
  783. return gate.second;
  784. if(gate.second == id)
  785. return gate.first;
  786. }
  787. return ObjectInstanceID();
  788. }
  789. void CGArtifact::initObj()
  790. {
  791. blockVisit = true;
  792. if(ID == Obj::ARTIFACT)
  793. {
  794. if (!storedArtifact)
  795. {
  796. auto a = new CArtifactInstance();
  797. cb->gameState()->map->addNewArtifactInstance(a);
  798. storedArtifact = a;
  799. }
  800. if(!storedArtifact->artType)
  801. storedArtifact->setType(VLC->arth->artifacts[subID]);
  802. }
  803. if(ID == Obj::SPELL_SCROLL)
  804. subID = 1;
  805. assert(storedArtifact->artType);
  806. assert(storedArtifact->getParentNodes().size());
  807. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  808. }
  809. std::string CGArtifact::getObjectName() const
  810. {
  811. return VLC->arth->artifacts[subID]->Name();
  812. }
  813. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  814. {
  815. if(!stacksCount())
  816. {
  817. InfoWindow iw;
  818. iw.player = h->tempOwner;
  819. switch(ID)
  820. {
  821. case Obj::ARTIFACT:
  822. {
  823. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  824. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  825. if(message.length())
  826. iw.text << message;
  827. else
  828. {
  829. if (VLC->arth->artifacts[subID]->EventText().size())
  830. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  831. else //fix for mod artifacts with no event text
  832. {
  833. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  834. iw.text.addReplacement (h->name);
  835. }
  836. }
  837. }
  838. break;
  839. case Obj::SPELL_SCROLL:
  840. {
  841. int spellID = storedArtifact->getGivenSpellID();
  842. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  843. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  844. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  845. }
  846. break;
  847. }
  848. cb->showInfoDialog(&iw);
  849. pick(h);
  850. }
  851. else
  852. {
  853. if(message.size())
  854. {
  855. BlockingDialog ynd(true,false);
  856. ynd.player = h->getOwner();
  857. ynd.text << message;
  858. cb->showBlockingDialog(&ynd);
  859. }
  860. else
  861. {
  862. blockingDialogAnswered(h, true);
  863. }
  864. }
  865. }
  866. void CGArtifact::pick(const CGHeroInstance * h) const
  867. {
  868. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  869. cb->removeObject(this);
  870. }
  871. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  872. {
  873. if(result.winner == 0) //attacker won
  874. pick(hero);
  875. }
  876. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  877. {
  878. if(answer)
  879. cb->startBattleI(hero, this);
  880. }
  881. void CGWitchHut::initObj()
  882. {
  883. if (allowedAbilities.empty()) //this can happen for RMG. regular maps load abilities from map file
  884. {
  885. for (int i = 0; i < GameConstants::SKILL_QUANTITY; i++)
  886. allowedAbilities.push_back(i);
  887. }
  888. ability = *RandomGeneratorUtil::nextItem(allowedAbilities, cb->gameState()->getRandomGenerator());
  889. }
  890. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  891. {
  892. InfoWindow iw;
  893. iw.soundID = soundBase::gazebo;
  894. iw.player = h->getOwner();
  895. if(!wasVisited(h->tempOwner))
  896. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  897. ui32 txt_id;
  898. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  899. {
  900. txt_id =172;
  901. }
  902. else if(!h->canLearnSkill()) //already all skills slots used
  903. {
  904. txt_id = 173;
  905. }
  906. else //give sec skill
  907. {
  908. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  909. txt_id = 171;
  910. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  911. }
  912. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  913. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  914. cb->showInfoDialog(&iw);
  915. }
  916. std::string CGWitchHut::getHoverText(PlayerColor player) const
  917. {
  918. std::string hoverName = getObjectName();
  919. if(wasVisited(player))
  920. {
  921. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  922. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  923. }
  924. return hoverName;
  925. }
  926. std::string CGWitchHut::getHoverText(const CGHeroInstance * hero) const
  927. {
  928. std::string hoverName = getHoverText(hero->tempOwner);
  929. if(hero->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  930. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  931. return hoverName;
  932. }
  933. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  934. {
  935. int message;
  936. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  937. {
  938. message = 78;//"A second drink at the well in one day will not help you."
  939. }
  940. else if(h->mana < h->manaLimit())
  941. {
  942. giveDummyBonus(h->id);
  943. cb->setManaPoints(h->id,h->manaLimit());
  944. message = 77;
  945. }
  946. else
  947. {
  948. message = 79;
  949. }
  950. showInfoDialog(h,message,soundBase::faerie);
  951. }
  952. std::string CGMagicWell::getHoverText(const CGHeroInstance * hero) const
  953. {
  954. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(Bonus::OBJECT,ID));
  955. }
  956. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  957. {
  958. InfoWindow iw;
  959. iw.player = h->tempOwner;
  960. switch (ID)
  961. {
  962. case Obj::REDWOOD_OBSERVATORY:
  963. case Obj::PILLAR_OF_FIRE:
  964. {
  965. iw.soundID = soundBase::LIGHTHOUSE;
  966. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  967. FoWChange fw;
  968. fw.player = h->tempOwner;
  969. fw.mode = 1;
  970. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  971. cb->sendAndApply (&fw);
  972. break;
  973. }
  974. case Obj::COVER_OF_DARKNESS:
  975. {
  976. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  977. for (auto & player : cb->gameState()->players)
  978. {
  979. if (cb->getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  980. cb->getPlayerRelations(player.first, h->tempOwner) == PlayerRelations::ENEMIES)
  981. cb->changeFogOfWar(visitablePos(), 20, player.first, true);
  982. }
  983. break;
  984. }
  985. }
  986. cb->showInfoDialog(&iw);
  987. }
  988. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  989. {
  990. if(spell == SpellID::NONE)
  991. {
  992. logGlobal->errorStream() << "Not initialized shrine visited!";
  993. return;
  994. }
  995. if(!wasVisited(h->tempOwner))
  996. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  997. InfoWindow iw;
  998. iw.soundID = soundBase::temple;
  999. iw.player = h->getOwner();
  1000. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  1001. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  1002. iw.text << ".";
  1003. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  1004. {
  1005. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  1006. }
  1007. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  1008. {
  1009. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  1010. }
  1011. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  1012. {
  1013. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  1014. }
  1015. else //give spell
  1016. {
  1017. std::set<SpellID> spells;
  1018. spells.insert(spell);
  1019. cb->changeSpells(h, true, spells);
  1020. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  1021. }
  1022. cb->showInfoDialog(&iw);
  1023. }
  1024. void CGShrine::initObj()
  1025. {
  1026. if(spell == SpellID::NONE) //spell not set
  1027. {
  1028. int level = ID-87;
  1029. std::vector<SpellID> possibilities;
  1030. cb->getAllowedSpells (possibilities, level);
  1031. if(possibilities.empty())
  1032. {
  1033. logGlobal->errorStream() << "Error: cannot init shrine, no allowed spells!";
  1034. return;
  1035. }
  1036. spell = *RandomGeneratorUtil::nextItem(possibilities, cb->gameState()->getRandomGenerator());
  1037. }
  1038. }
  1039. std::string CGShrine::getHoverText(PlayerColor player) const
  1040. {
  1041. std::string hoverName = getObjectName();
  1042. if(wasVisited(player))
  1043. {
  1044. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  1045. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  1046. }
  1047. return hoverName;
  1048. }
  1049. std::string CGShrine::getHoverText(const CGHeroInstance * hero) const
  1050. {
  1051. std::string hoverName = getHoverText(hero->tempOwner);
  1052. if(vstd::contains(hero->spells, spell)) //hero knows that spell
  1053. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  1054. return hoverName;
  1055. }
  1056. void CGSignBottle::initObj()
  1057. {
  1058. //if no text is set than we pick random from the predefined ones
  1059. if(message.empty())
  1060. {
  1061. message = *RandomGeneratorUtil::nextItem(VLC->generaltexth->randsign, cb->gameState()->getRandomGenerator());
  1062. }
  1063. if(ID == Obj::OCEAN_BOTTLE)
  1064. {
  1065. blockVisit = true;
  1066. }
  1067. }
  1068. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  1069. {
  1070. InfoWindow iw;
  1071. iw.soundID = soundBase::STORE;
  1072. iw.player = h->getOwner();
  1073. iw.text << message;
  1074. cb->showInfoDialog(&iw);
  1075. if(ID == Obj::OCEAN_BOTTLE)
  1076. cb->removeObject(this);
  1077. }
  1078. //TODO: remove
  1079. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  1080. //{
  1081. //
  1082. //}
  1083. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  1084. {
  1085. EBonusType type = bonusType;
  1086. int bid = bonusID;
  1087. //check if the bonus if applicable, if not - give primary skill (always possible)
  1088. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  1089. if((type == SECONDARY_SKILL
  1090. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  1091. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  1092. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  1093. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  1094. {
  1095. type = PRIM_SKILL;
  1096. bid = cb->gameState()->getRandomGenerator().nextInt(GameConstants::PRIMARY_SKILLS - 1);
  1097. }
  1098. InfoWindow iw;
  1099. iw.soundID = soundBase::gazebo;
  1100. iw.player = h->getOwner();
  1101. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  1102. switch (type)
  1103. {
  1104. case PRIM_SKILL:
  1105. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  1106. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  1107. break;
  1108. case SECONDARY_SKILL:
  1109. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  1110. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  1111. break;
  1112. case SPELL:
  1113. {
  1114. std::set<SpellID> hlp;
  1115. hlp.insert(SpellID(bid));
  1116. cb->changeSpells(h,true,hlp);
  1117. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  1118. }
  1119. break;
  1120. default:
  1121. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  1122. return;
  1123. }
  1124. cb->showInfoDialog(&iw);
  1125. cb->removeObject(this);
  1126. }
  1127. void CGScholar::initObj()
  1128. {
  1129. blockVisit = true;
  1130. if(bonusType == RANDOM)
  1131. {
  1132. bonusType = static_cast<EBonusType>(cb->gameState()->getRandomGenerator().nextInt(2));
  1133. switch(bonusType)
  1134. {
  1135. case PRIM_SKILL:
  1136. bonusID = cb->gameState()->getRandomGenerator().nextInt(GameConstants::PRIMARY_SKILLS -1);
  1137. break;
  1138. case SECONDARY_SKILL:
  1139. bonusID = cb->gameState()->getRandomGenerator().nextInt(GameConstants::SKILL_QUANTITY -1);
  1140. break;
  1141. case SPELL:
  1142. std::vector<SpellID> possibilities;
  1143. for (int i = 1; i < 6; ++i)
  1144. cb->getAllowedSpells (possibilities, i);
  1145. bonusID = *RandomGeneratorUtil::nextItem(possibilities, cb->gameState()->getRandomGenerator());
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  1151. {
  1152. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  1153. if (!ally && stacksCount() > 0) {
  1154. //TODO: Find a way to apply magic garrison effects in battle.
  1155. cb->startBattleI(h, this);
  1156. return;
  1157. }
  1158. //New owner.
  1159. if (!ally)
  1160. cb->setOwner(this, h->tempOwner);
  1161. cb->showGarrisonDialog(id, h->id, removableUnits);
  1162. }
  1163. bool CGGarrison::passableFor(PlayerColor player) const
  1164. {
  1165. //FIXME: identical to same method in CGTownInstance
  1166. if ( !stacksCount() )//empty - anyone can visit
  1167. return true;
  1168. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  1169. return false;
  1170. if (cb->getPlayerRelations(tempOwner, player) != PlayerRelations::ENEMIES)
  1171. return true;
  1172. return false;
  1173. }
  1174. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1175. {
  1176. if (result.winner == 0)
  1177. onHeroVisit(hero);
  1178. }
  1179. void CGMagi::initObj()
  1180. {
  1181. if (ID == Obj::EYE_OF_MAGI)
  1182. {
  1183. blockVisit = true;
  1184. eyelist[subID].push_back(id);
  1185. }
  1186. }
  1187. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  1188. {
  1189. if (ID == Obj::HUT_OF_MAGI)
  1190. {
  1191. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  1192. if (!eyelist[subID].empty())
  1193. {
  1194. CenterView cv;
  1195. cv.player = h->tempOwner;
  1196. cv.focusTime = 2000;
  1197. FoWChange fw;
  1198. fw.player = h->tempOwner;
  1199. fw.mode = 1;
  1200. fw.waitForDialogs = true;
  1201. for(auto it : eyelist[subID])
  1202. {
  1203. const CGObjectInstance *eye = cb->getObj(it);
  1204. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  1205. cb->sendAndApply(&fw);
  1206. cv.pos = eye->pos;
  1207. cb->sendAndApply(&cv);
  1208. }
  1209. cv.pos = h->getPosition(false);
  1210. cb->sendAndApply(&cv);
  1211. }
  1212. }
  1213. else if (ID == Obj::EYE_OF_MAGI)
  1214. {
  1215. showInfoDialog(h,48,soundBase::invalid);
  1216. }
  1217. }
  1218. void CGBoat::initObj()
  1219. {
  1220. hero = nullptr;
  1221. }
  1222. void CGSirens::initObj()
  1223. {
  1224. blockVisit = true;
  1225. }
  1226. std::string CGSirens::getHoverText(const CGHeroInstance * hero) const
  1227. {
  1228. return getObjectName() + " " + visitedTxt(hero->hasBonusFrom(Bonus::OBJECT,ID));
  1229. }
  1230. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  1231. {
  1232. InfoWindow iw;
  1233. iw.soundID = soundBase::DANGER;
  1234. iw.player = h->tempOwner;
  1235. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  1236. {
  1237. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  1238. }
  1239. else
  1240. {
  1241. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  1242. TExpType xp = 0;
  1243. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  1244. {
  1245. TQuantity drown = i->second->count * 0.3;
  1246. if(drown)
  1247. {
  1248. cb->changeStackCount(StackLocation(h, i->first), -drown);
  1249. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  1250. }
  1251. }
  1252. if(xp)
  1253. {
  1254. xp = h->calculateXp(xp);
  1255. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  1256. iw.text.addReplacement(xp);
  1257. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  1258. }
  1259. else
  1260. {
  1261. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  1262. }
  1263. }
  1264. cb->showInfoDialog(&iw);
  1265. }
  1266. CGShipyard::CGShipyard()
  1267. :IShipyard(this)
  1268. {
  1269. }
  1270. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  1271. {
  1272. // H J L K I
  1273. // A x S x B
  1274. // C E G F D
  1275. offsets = {
  1276. int3(-3,0,0), int3(1,0,0), //AB
  1277. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  1278. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0) //HIJKL
  1279. };
  1280. }
  1281. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  1282. {
  1283. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  1284. cb->setOwner(this, h->tempOwner);
  1285. auto s = shipyardStatus();
  1286. if(s != IBoatGenerator::GOOD)
  1287. {
  1288. InfoWindow iw;
  1289. iw.player = tempOwner;
  1290. getProblemText(iw.text, h);
  1291. cb->showInfoDialog(&iw);
  1292. }
  1293. else
  1294. {
  1295. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  1296. }
  1297. }
  1298. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  1299. {
  1300. //if player has not bought map of this subtype yet and underground exist for stalagmite cartographer
  1301. if (!wasVisited(h->getOwner()) && (subID != 2 || cb->gameState()->map->twoLevel))
  1302. {
  1303. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  1304. {
  1305. //ask if he wants to buy one
  1306. int text=0;
  1307. switch (subID)
  1308. {
  1309. case 0:
  1310. text = 25;
  1311. break;
  1312. case 1:
  1313. text = 26;
  1314. break;
  1315. case 2:
  1316. text = 27;
  1317. break;
  1318. default:
  1319. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  1320. }
  1321. assert(text);
  1322. BlockingDialog bd (true, false);
  1323. bd.player = h->getOwner();
  1324. bd.soundID = soundBase::LIGHTHOUSE;
  1325. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  1326. cb->showBlockingDialog (&bd);
  1327. }
  1328. else //if he cannot afford
  1329. {
  1330. showInfoDialog(h,28,soundBase::CAVEHEAD);
  1331. }
  1332. }
  1333. else //if he already visited carographer
  1334. {
  1335. showInfoDialog(h,24,soundBase::CAVEHEAD);
  1336. }
  1337. }
  1338. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1339. {
  1340. if (answer) //if hero wants to buy map
  1341. {
  1342. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  1343. FoWChange fw;
  1344. fw.mode = 1;
  1345. fw.player = hero->tempOwner;
  1346. //subIDs of different types of cartographers:
  1347. //water = 0; land = 1; underground = 2;
  1348. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  1349. cb->sendAndApply (&fw);
  1350. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  1351. }
  1352. }
  1353. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  1354. {
  1355. cb->showThievesGuildWindow(h->tempOwner, id);
  1356. }
  1357. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  1358. {
  1359. InfoWindow iw;
  1360. iw.player = h->tempOwner;
  1361. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  1362. assert(ts);
  1363. TeamID team = ts->id;
  1364. if(!wasVisited(team))
  1365. {
  1366. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  1367. cb->sendAndApply(&iw);
  1368. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  1369. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  1370. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  1371. }
  1372. else
  1373. {
  1374. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  1375. cb->sendAndApply(&iw);
  1376. }
  1377. }
  1378. void CGObelisk::initObj()
  1379. {
  1380. obeliskCount++;
  1381. }
  1382. std::string CGObelisk::getHoverText(PlayerColor player) const
  1383. {
  1384. return getObjectName() + " " + visitedTxt(wasVisited(player));
  1385. }
  1386. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  1387. {
  1388. CPlayersVisited::setPropertyDer(what, val);
  1389. switch(what)
  1390. {
  1391. case 20:
  1392. assert(val < PlayerColor::PLAYER_LIMIT_I);
  1393. visited[TeamID(val)]++;
  1394. if(visited[TeamID(val)] > obeliskCount)
  1395. {
  1396. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  1397. assert(0);
  1398. }
  1399. break;
  1400. }
  1401. }
  1402. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  1403. {
  1404. if(h->tempOwner != tempOwner)
  1405. {
  1406. PlayerColor oldOwner = tempOwner;
  1407. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  1408. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  1409. giveBonusTo(h->tempOwner);
  1410. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  1411. {
  1412. RemoveBonus rb(RemoveBonus::PLAYER);
  1413. rb.whoID = oldOwner.getNum();
  1414. rb.source = Bonus::OBJECT;
  1415. rb.id = id.getNum();
  1416. cb->sendAndApply(&rb);
  1417. }
  1418. }
  1419. }
  1420. void CGLighthouse::initObj()
  1421. {
  1422. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  1423. {
  1424. giveBonusTo(tempOwner);
  1425. }
  1426. }
  1427. std::string CGLighthouse::getHoverText(PlayerColor player) const
  1428. {
  1429. //TODO: owned by %s player
  1430. return getObjectName();
  1431. }
  1432. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  1433. {
  1434. GiveBonus gb(GiveBonus::PLAYER);
  1435. gb.bonus.type = Bonus::SEA_MOVEMENT;
  1436. gb.bonus.val = 500;
  1437. gb.id = player.getNum();
  1438. gb.bonus.duration = Bonus::PERMANENT;
  1439. gb.bonus.source = Bonus::OBJECT;
  1440. gb.bonus.sid = id.getNum();
  1441. cb->sendAndApply(&gb);
  1442. }