MiscObjects.cpp 41 KB

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