CGameState.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086
  1. #include "StdInc.h"
  2. #include "CGameState.h"
  3. #include "mapping/CCampaignHandler.h"
  4. #include "mapObjects/CObjectClassesHandler.h"
  5. #include "CArtHandler.h"
  6. #include "CBuildingHandler.h"
  7. #include "CGeneralTextHandler.h"
  8. #include "CTownHandler.h"
  9. #include "spells/CSpellHandler.h"
  10. #include "CHeroHandler.h"
  11. #include "mapObjects/CObjectHandler.h"
  12. #include "CModHandler.h"
  13. #include "mapping/CMap.h"
  14. #include "mapping/CMapService.h"
  15. #include "StartInfo.h"
  16. #include "NetPacks.h"
  17. #include "registerTypes/RegisterTypes.h"
  18. #include "battle/BattleInfo.h"
  19. #include "JsonNode.h"
  20. #include "filesystem/Filesystem.h"
  21. #include "GameConstants.h"
  22. #include "rmg/CMapGenerator.h"
  23. #include "CStopWatch.h"
  24. #include "mapping/CMapEditManager.h"
  25. #include "mapping/CMapService.h"
  26. #include "serializer/CTypeList.h"
  27. #include "serializer/CMemorySerializer.h"
  28. #include "VCMIDirs.h"
  29. #ifdef min
  30. #undef min
  31. #endif
  32. #ifdef max
  33. #undef max
  34. #endif
  35. /*
  36. * CGameState.cpp, part of VCMI engine
  37. *
  38. * Authors: listed in file AUTHORS in main folder
  39. *
  40. * License: GNU General Public License v2.0 or later
  41. * Full text of license available in license.txt file, in main folder
  42. *
  43. */
  44. boost::shared_mutex CGameState::mutex;
  45. template <typename T> class CApplyOnGS;
  46. class CBaseForGSApply
  47. {
  48. public:
  49. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  50. virtual ~CBaseForGSApply(){};
  51. template<typename U> static CBaseForGSApply *getApplier(const U * t=nullptr)
  52. {
  53. return new CApplyOnGS<U>;
  54. }
  55. };
  56. template <typename T> class CApplyOnGS : public CBaseForGSApply
  57. {
  58. public:
  59. void applyOnGS(CGameState *gs, void *pack) const override
  60. {
  61. T *ptr = static_cast<T*>(pack);
  62. boost::unique_lock<boost::shared_mutex> lock(CGameState::mutex);
  63. ptr->applyGs(gs);
  64. }
  65. };
  66. static CApplier<CBaseForGSApply> *applierGs = nullptr;
  67. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  68. {
  69. int type = txt.first, ser = txt.second;
  70. if(type == ART_NAMES)
  71. {
  72. dst = VLC->arth->artifacts[ser]->Name();
  73. }
  74. else if(type == CRE_PL_NAMES)
  75. {
  76. dst = VLC->creh->creatures[ser]->namePl;
  77. }
  78. else if(type == MINE_NAMES)
  79. {
  80. dst = VLC->generaltexth->mines[ser].first;
  81. }
  82. else if(type == MINE_EVNTS)
  83. {
  84. dst = VLC->generaltexth->mines[ser].second;
  85. }
  86. else if(type == SPELL_NAME)
  87. {
  88. dst = SpellID(ser).toSpell()->name;
  89. }
  90. else if(type == CRE_SING_NAMES)
  91. {
  92. dst = VLC->creh->creatures[ser]->nameSing;
  93. }
  94. else if(type == ART_DESCR)
  95. {
  96. dst = VLC->arth->artifacts[ser]->Description();
  97. }
  98. else if (type == ART_EVNTS)
  99. {
  100. dst = VLC->arth->artifacts[ser]->EventText();
  101. }
  102. else if (type == OBJ_NAMES)
  103. {
  104. dst = VLC->objtypeh->getObjectName(ser);
  105. }
  106. else
  107. {
  108. std::vector<std::string> *vec;
  109. switch(type)
  110. {
  111. case GENERAL_TXT:
  112. vec = &VLC->generaltexth->allTexts;
  113. break;
  114. case XTRAINFO_TXT:
  115. vec = &VLC->generaltexth->xtrainfo;
  116. break;
  117. case RES_NAMES:
  118. vec = &VLC->generaltexth->restypes;
  119. break;
  120. case ARRAY_TXT:
  121. vec = &VLC->generaltexth->arraytxt;
  122. break;
  123. case CREGENS:
  124. vec = &VLC->generaltexth->creGens;
  125. break;
  126. case CREGENS4:
  127. vec = &VLC->generaltexth->creGens4;
  128. break;
  129. case ADVOB_TXT:
  130. vec = &VLC->generaltexth->advobtxt;
  131. break;
  132. case SEC_SKILL_NAME:
  133. vec = &VLC->generaltexth->skillName;
  134. break;
  135. case COLOR:
  136. vec = &VLC->generaltexth->capColors;
  137. break;
  138. default:
  139. logGlobal->errorStream() << "Failed string substitution because type is " << type;
  140. dst = "#@#";
  141. return;
  142. }
  143. if(vec->size() <= ser)
  144. {
  145. logGlobal->errorStream() << "Failed string substitution with type " << type << " because index " << ser << " is out of bounds!";
  146. dst = "#!#";
  147. }
  148. else
  149. dst = (*vec)[ser];
  150. }
  151. }
  152. DLL_LINKAGE void MetaString::toString(std::string &dst) const
  153. {
  154. size_t exSt = 0, loSt = 0, nums = 0;
  155. dst.clear();
  156. for(auto & elem : message)
  157. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  158. switch(elem)
  159. {
  160. case TEXACT_STRING:
  161. dst += exactStrings[exSt++];
  162. break;
  163. case TLOCAL_STRING:
  164. {
  165. std::string hlp;
  166. getLocalString(localStrings[loSt++], hlp);
  167. dst += hlp;
  168. }
  169. break;
  170. case TNUMBER:
  171. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  172. break;
  173. case TREPLACE_ESTRING:
  174. boost::replace_first(dst, "%s", exactStrings[exSt++]);
  175. break;
  176. case TREPLACE_LSTRING:
  177. {
  178. std::string hlp;
  179. getLocalString(localStrings[loSt++], hlp);
  180. boost::replace_first(dst, "%s", hlp);
  181. }
  182. break;
  183. case TREPLACE_NUMBER:
  184. boost::replace_first(dst, "%d", boost::lexical_cast<std::string>(numbers[nums++]));
  185. break;
  186. case TREPLACE_PLUSNUMBER:
  187. boost::replace_first(dst, "%+d", '+' + boost::lexical_cast<std::string>(numbers[nums++]));
  188. break;
  189. default:
  190. logGlobal->errorStream() << "MetaString processing error! Received message of type " << int(elem);
  191. break;
  192. }
  193. }
  194. }
  195. DLL_LINKAGE std::string MetaString::toString() const
  196. {
  197. std::string ret;
  198. toString(ret);
  199. return ret;
  200. }
  201. DLL_LINKAGE std::string MetaString::buildList () const
  202. ///used to handle loot from creature bank
  203. {
  204. size_t exSt = 0, loSt = 0, nums = 0;
  205. std::string lista;
  206. for (int i = 0; i < message.size(); ++i)
  207. {
  208. if (i > 0 && (message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING))
  209. {
  210. if (exSt == exactStrings.size() - 1)
  211. lista += VLC->generaltexth->allTexts[141]; //" and "
  212. else
  213. lista += ", ";
  214. }
  215. switch (message[i])
  216. {
  217. case TEXACT_STRING:
  218. lista += exactStrings[exSt++];
  219. break;
  220. case TLOCAL_STRING:
  221. {
  222. std::string hlp;
  223. getLocalString (localStrings[loSt++], hlp);
  224. lista += hlp;
  225. }
  226. break;
  227. case TNUMBER:
  228. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  229. break;
  230. case TREPLACE_ESTRING:
  231. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  232. break;
  233. case TREPLACE_LSTRING:
  234. {
  235. std::string hlp;
  236. getLocalString (localStrings[loSt++], hlp);
  237. lista.replace (lista.find("%s"), 2, hlp);
  238. }
  239. break;
  240. case TREPLACE_NUMBER:
  241. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  242. break;
  243. default:
  244. logGlobal->errorStream() << "MetaString processing error! Received message of type " << int(message[i]);
  245. }
  246. }
  247. return lista;
  248. }
  249. void MetaString::addCreReplacement(CreatureID id, TQuantity count) //adds sing or plural name;
  250. {
  251. if (!count)
  252. addReplacement (CRE_PL_NAMES, id); //no creatures - just empty name (eg. defeat Angels)
  253. else if (count == 1)
  254. addReplacement (CRE_SING_NAMES, id);
  255. else
  256. addReplacement (CRE_PL_NAMES, id);
  257. }
  258. void MetaString::addReplacement(const CStackBasicDescriptor &stack)
  259. {
  260. assert(stack.type); //valid type
  261. addCreReplacement(stack.type->idNumber, stack.count);
  262. }
  263. static CGObjectInstance * createObject(Obj id, int subid, int3 pos, PlayerColor owner)
  264. {
  265. CGObjectInstance * nobj;
  266. switch(id)
  267. {
  268. case Obj::HERO:
  269. {
  270. auto handler = VLC->objtypeh->getHandlerFor(id, VLC->heroh->heroes[subid]->heroClass->id);
  271. nobj = handler->create(handler->getTemplates().front());
  272. break;
  273. }
  274. case Obj::TOWN:
  275. nobj = new CGTownInstance;
  276. break;
  277. default: //rest of objects
  278. nobj = new CGObjectInstance;
  279. break;
  280. }
  281. nobj->ID = id;
  282. nobj->subID = subid;
  283. nobj->pos = pos;
  284. nobj->tempOwner = owner;
  285. if (id != Obj::HERO)
  286. nobj->appearance = VLC->objtypeh->getHandlerFor(id, subid)->getTemplates().front();
  287. return nobj;
  288. }
  289. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, PlayerColor player, const CTown *town,
  290. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, CRandomGenerator & rand, const CHeroClass * bannedClass /*= nullptr*/) const
  291. {
  292. CGHeroInstance *ret = nullptr;
  293. if(player>=PlayerColor::PLAYER_LIMIT)
  294. {
  295. logGlobal->errorStream() << "Cannot pick hero for " << town->faction->index << ". Wrong owner!";
  296. return nullptr;
  297. }
  298. std::vector<CGHeroInstance *> pool;
  299. if(native)
  300. {
  301. for(auto & elem : available)
  302. {
  303. if(pavailable.find(elem.first)->second & 1<<player.getNum()
  304. && elem.second->type->heroClass->faction == town->faction->index)
  305. {
  306. pool.push_back(elem.second); //get all available heroes
  307. }
  308. }
  309. if(!pool.size())
  310. {
  311. logGlobal->errorStream() << "Cannot pick native hero for " << player << ". Picking any...";
  312. return pickHeroFor(false, player, town, available, rand);
  313. }
  314. else
  315. {
  316. ret = *RandomGeneratorUtil::nextItem(pool, rand);
  317. }
  318. }
  319. else
  320. {
  321. int sum=0, r;
  322. for(auto & elem : available)
  323. {
  324. if (pavailable.find(elem.first)->second & (1<<player.getNum()) && // hero is available
  325. ( !bannedClass || elem.second->type->heroClass != bannedClass) ) // and his class is not same as other hero
  326. {
  327. pool.push_back(elem.second);
  328. sum += elem.second->type->heroClass->selectionProbability[town->faction->index]; //total weight
  329. }
  330. }
  331. if(!pool.size() || sum == 0)
  332. {
  333. logGlobal->errorStream() << "There are no heroes available for player " << player<<"!";
  334. return nullptr;
  335. }
  336. r = rand.nextInt(sum - 1);
  337. for (auto & elem : pool)
  338. {
  339. r -= elem->type->heroClass->selectionProbability[town->faction->index];
  340. if(r < 0)
  341. {
  342. ret = elem;
  343. break;
  344. }
  345. }
  346. if(!ret)
  347. ret = pool.back();
  348. }
  349. available.erase(ret->subID);
  350. return ret;
  351. }
  352. void CGameState::CrossoverHeroesList::addHeroToBothLists(CGHeroInstance * hero)
  353. {
  354. heroesFromPreviousScenario.push_back(hero);
  355. heroesFromAnyPreviousScenarios.push_back(hero);
  356. }
  357. void CGameState::CrossoverHeroesList::removeHeroFromBothLists(CGHeroInstance * hero)
  358. {
  359. heroesFromPreviousScenario -= hero;
  360. heroesFromAnyPreviousScenarios -= hero;
  361. }
  362. CGameState::CampaignHeroReplacement::CampaignHeroReplacement(CGHeroInstance * hero, ObjectInstanceID heroPlaceholderId) : hero(hero), heroPlaceholderId(heroPlaceholderId)
  363. {
  364. }
  365. int CGameState::pickNextHeroType(PlayerColor owner)
  366. {
  367. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  368. if(ps.hero >= 0 && !isUsedHero(HeroTypeID(ps.hero))) //we haven't used selected hero
  369. {
  370. return ps.hero;
  371. }
  372. return pickUnusedHeroTypeRandomly(owner);
  373. }
  374. int CGameState::pickUnusedHeroTypeRandomly(PlayerColor owner)
  375. {
  376. //list of available heroes for this faction and others
  377. std::vector<HeroTypeID> factionHeroes, otherHeroes;
  378. const PlayerSettings &ps = scenarioOps->getIthPlayersSettings(owner);
  379. for(HeroTypeID hid : getUnusedAllowedHeroes())
  380. {
  381. if(VLC->heroh->heroes[hid.getNum()]->heroClass->faction == ps.castle)
  382. factionHeroes.push_back(hid);
  383. else
  384. otherHeroes.push_back(hid);
  385. }
  386. // select random hero native to "our" faction
  387. if(!factionHeroes.empty())
  388. {
  389. return RandomGeneratorUtil::nextItem(factionHeroes, getRandomGenerator())->getNum();
  390. }
  391. logGlobal->warnStream() << "Cannot find free hero of appropriate faction for player " << owner << " - trying to get first available...";
  392. if(!otherHeroes.empty())
  393. {
  394. return RandomGeneratorUtil::nextItem(otherHeroes, getRandomGenerator())->getNum();
  395. }
  396. logGlobal->error("No free allowed heroes!");
  397. auto notAllowedHeroesButStillBetterThanCrash = getUnusedAllowedHeroes(true);
  398. if(notAllowedHeroesButStillBetterThanCrash.size())
  399. return notAllowedHeroesButStillBetterThanCrash.begin()->getNum();
  400. logGlobal->error("No free heroes at all!");
  401. assert(0); //current code can't handle this situation
  402. return -1; // no available heroes at all
  403. }
  404. std::pair<Obj,int> CGameState::pickObject (CGObjectInstance *obj)
  405. {
  406. switch(obj->ID)
  407. {
  408. case Obj::RANDOM_ART:
  409. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR | CArtifact::ART_RELIC));
  410. case Obj::RANDOM_TREASURE_ART:
  411. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE));
  412. case Obj::RANDOM_MINOR_ART:
  413. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MINOR));
  414. case Obj::RANDOM_MAJOR_ART:
  415. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_MAJOR));
  416. case Obj::RANDOM_RELIC_ART:
  417. return std::make_pair(Obj::ARTIFACT, VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_RELIC));
  418. case Obj::RANDOM_HERO:
  419. return std::make_pair(Obj::HERO, pickNextHeroType(obj->tempOwner));
  420. case Obj::RANDOM_MONSTER:
  421. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator()));
  422. case Obj::RANDOM_MONSTER_L1:
  423. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 1));
  424. case Obj::RANDOM_MONSTER_L2:
  425. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 2));
  426. case Obj::RANDOM_MONSTER_L3:
  427. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 3));
  428. case Obj::RANDOM_MONSTER_L4:
  429. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 4));
  430. case Obj::RANDOM_RESOURCE:
  431. return std::make_pair(Obj::RESOURCE,getRandomGenerator().nextInt(6)); //now it's OH3 style, use %8 for mithril
  432. case Obj::RANDOM_TOWN:
  433. {
  434. PlayerColor align = PlayerColor((static_cast<CGTownInstance*>(obj))->alignment);
  435. si32 f; // can be negative (for random)
  436. if(align >= PlayerColor::PLAYER_LIMIT)//same as owner / random
  437. {
  438. if(obj->tempOwner >= PlayerColor::PLAYER_LIMIT)
  439. f = -1; //random
  440. else
  441. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  442. }
  443. else
  444. {
  445. f = scenarioOps->getIthPlayersSettings(align).castle;
  446. }
  447. if(f<0)
  448. {
  449. do
  450. {
  451. f = getRandomGenerator().nextInt(VLC->townh->factions.size() - 1);
  452. }
  453. while (VLC->townh->factions[f]->town == nullptr); // find playable faction
  454. }
  455. return std::make_pair(Obj::TOWN,f);
  456. }
  457. case Obj::RANDOM_MONSTER_L5:
  458. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 5));
  459. case Obj::RANDOM_MONSTER_L6:
  460. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 6));
  461. case Obj::RANDOM_MONSTER_L7:
  462. return std::make_pair(Obj::MONSTER, VLC->creh->pickRandomMonster(getRandomGenerator(), 7));
  463. case Obj::RANDOM_DWELLING:
  464. case Obj::RANDOM_DWELLING_LVL:
  465. case Obj::RANDOM_DWELLING_FACTION:
  466. {
  467. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  468. int faction;
  469. //if castle alignment available
  470. if (auto info = dynamic_cast<CCreGenAsCastleInfo*>(dwl->info))
  471. {
  472. faction = getRandomGenerator().nextInt(VLC->townh->factions.size() - 1);
  473. if(info->asCastle && info->instanceId != "")
  474. {
  475. auto iter = map->instanceNames.find(info->instanceId);
  476. if(iter == map->instanceNames.end())
  477. logGlobal->errorStream() << "Map object not found: " << info->instanceId;
  478. else
  479. {
  480. auto elem = iter->second;
  481. if(elem->ID==Obj::RANDOM_TOWN)
  482. {
  483. randomizeObject(elem.get()); //we have to randomize the castle first
  484. faction = elem->subID;
  485. }
  486. else if(elem->ID==Obj::TOWN)
  487. faction = elem->subID;
  488. else
  489. logGlobal->errorStream() << "Map object must be town: " << info->instanceId;
  490. }
  491. }
  492. else if(info->asCastle)
  493. {
  494. for(auto & elem : map->objects)
  495. {
  496. if(!elem)
  497. continue;
  498. if(elem->ID==Obj::RANDOM_TOWN
  499. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  500. {
  501. randomizeObject(elem); //we have to randomize the castle first
  502. faction = elem->subID;
  503. break;
  504. }
  505. else if(elem->ID==Obj::TOWN
  506. && dynamic_cast<CGTownInstance*>(elem.get())->identifier == info->identifier)
  507. {
  508. faction = elem->subID;
  509. break;
  510. }
  511. }
  512. }
  513. else
  514. {
  515. std::set<int> temp;
  516. for(int i = 0; i < info->allowedFactions.size(); i++)
  517. if(info->allowedFactions[i])
  518. temp.insert(i);
  519. if(temp.empty())
  520. logGlobal->error("Random faction selection failed. Nothing is allowed. Fall back to random.");
  521. else
  522. faction = *RandomGeneratorUtil::nextItem(temp, getRandomGenerator());
  523. }
  524. }
  525. else // castle alignment fixed
  526. faction = obj->subID;
  527. int level;
  528. //if level set to range
  529. if (auto info = dynamic_cast<CCreGenLeveledInfo*>(dwl->info))
  530. {
  531. level = getRandomGenerator().nextInt(info->minLevel, info->maxLevel);
  532. }
  533. else // fixed level
  534. {
  535. level = obj->subID;
  536. }
  537. delete dwl->info;
  538. dwl->info = nullptr;
  539. std::pair<Obj, int> result(Obj::NO_OBJ, -1);
  540. CreatureID cid = VLC->townh->factions[faction]->town->creatures[level][0];
  541. //NOTE: this will pick last dwelling with this creature (Mantis #900)
  542. //check for block map equality is better but more complex solution
  543. auto testID = [&](Obj primaryID) -> void
  544. {
  545. auto dwellingIDs = VLC->objtypeh->knownSubObjects(primaryID);
  546. for (si32 entry : dwellingIDs)
  547. {
  548. auto handler = dynamic_cast<const CDwellingInstanceConstructor*>(VLC->objtypeh->getHandlerFor(primaryID, entry).get());
  549. if (handler->producesCreature(VLC->creh->creatures[cid]))
  550. result = std::make_pair(primaryID, entry);
  551. }
  552. };
  553. testID(Obj::CREATURE_GENERATOR1);
  554. if (result.first == Obj::NO_OBJ)
  555. testID(Obj::CREATURE_GENERATOR4);
  556. if (result.first == Obj::NO_OBJ)
  557. {
  558. logGlobal->errorStream() << "Error: failed to find dwelling for "<< VLC->townh->factions[faction]->name << " of level " << int(level);
  559. result = std::make_pair(Obj::CREATURE_GENERATOR1, *RandomGeneratorUtil::nextItem(VLC->objtypeh->knownSubObjects(Obj::CREATURE_GENERATOR1), getRandomGenerator()));
  560. }
  561. return result;
  562. }
  563. }
  564. return std::make_pair(Obj::NO_OBJ,-1);
  565. }
  566. void CGameState::randomizeObject(CGObjectInstance *cur)
  567. {
  568. std::pair<Obj,int> ran = pickObject(cur);
  569. if(ran.first == Obj::NO_OBJ || ran.second<0) //this is not a random object, or we couldn't find anything
  570. {
  571. if(cur->ID==Obj::TOWN)
  572. cur->setType(cur->ID, cur->subID); // update def, if necessary
  573. }
  574. else if(ran.first==Obj::HERO)//special code for hero
  575. {
  576. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  577. cur->setType(ran.first, ran.second);
  578. map->heroesOnMap.push_back(h);
  579. }
  580. else if(ran.first==Obj::TOWN)//special code for town
  581. {
  582. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  583. cur->setType(ran.first, ran.second);
  584. map->towns.push_back(t);
  585. }
  586. else
  587. {
  588. cur->setType(ran.first, ran.second);
  589. }
  590. }
  591. int CGameState::getDate(Date::EDateType mode) const
  592. {
  593. int temp;
  594. switch (mode)
  595. {
  596. case Date::DAY:
  597. return day;
  598. case Date::DAY_OF_WEEK: //day of week
  599. temp = (day)%7; // 1 - Monday, 7 - Sunday
  600. return temp ? temp : 7;
  601. case Date::WEEK: //current week
  602. temp = ((day-1)/7)+1;
  603. if (!(temp%4))
  604. return 4;
  605. else
  606. return (temp%4);
  607. case Date::MONTH: //current month
  608. return ((day-1)/28)+1;
  609. case Date::DAY_OF_MONTH: //day of month
  610. temp = (day)%28;
  611. if (temp)
  612. return temp;
  613. else return 28;
  614. }
  615. return 0;
  616. }
  617. CGameState::CGameState()
  618. {
  619. gs = this;
  620. applierGs = new CApplier<CBaseForGSApply>;
  621. registerTypesClientPacks1(*applierGs);
  622. registerTypesClientPacks2(*applierGs);
  623. //objCaller = new CObjectCallersHandler;
  624. globalEffects.setDescription("Global effects");
  625. globalEffects.setNodeType(CBonusSystemNode::GLOBAL_EFFECTS);
  626. day = 0;
  627. }
  628. CGameState::~CGameState()
  629. {
  630. map.dellNull();
  631. curB.dellNull();
  632. //delete scenarioOps; //TODO: fix for loading ind delete
  633. //delete initialOpts;
  634. delete applierGs;
  635. //delete objCaller;
  636. for(auto ptr : hpool.heroesPool) // clean hero pool
  637. ptr.second.dellNull();
  638. }
  639. void CGameState::init(StartInfo * si, bool allowSavingRandomMap)
  640. {
  641. logGlobal->infoStream() << "\tUsing random seed: "<< si->seedToBeUsed;
  642. getRandomGenerator().setSeed(si->seedToBeUsed);
  643. scenarioOps = CMemorySerializer::deepCopy(*si).release();
  644. initialOpts = CMemorySerializer::deepCopy(*si).release();
  645. si = nullptr;
  646. switch(scenarioOps->mode)
  647. {
  648. case StartInfo::NEW_GAME:
  649. initNewGame(allowSavingRandomMap);
  650. break;
  651. case StartInfo::CAMPAIGN:
  652. initCampaign();
  653. break;
  654. default:
  655. logGlobal->errorStream() << "Wrong mode: " << (int)scenarioOps->mode;
  656. return;
  657. }
  658. VLC->arth->initAllowedArtifactsList(map->allowedArtifact);
  659. logGlobal->info("Map loaded!");
  660. checkMapChecksum();
  661. day = 0;
  662. logGlobal->debug("Initialization:");
  663. initPlayerStates();
  664. placeCampaignHeroes();
  665. initGrailPosition();
  666. initRandomFactionsForPlayers();
  667. randomizeMapObjects();
  668. placeStartingHeroes();
  669. initStartingResources();
  670. initHeroes();
  671. initStartingBonus();
  672. initTowns();
  673. initMapObjects();
  674. buildBonusSystemTree();
  675. initVisitingAndGarrisonedHeroes();
  676. initFogOfWar();
  677. // Explicitly initialize static variables
  678. for(auto & elem : players)
  679. {
  680. CGKeys::playerKeyMap[elem.first] = std::set<ui8>();
  681. }
  682. for(auto & elem : teams)
  683. {
  684. CGObelisk::visited[elem.first] = 0;
  685. }
  686. logGlobal->debug("\tChecking objectives");
  687. map->checkForObjectives(); //needs to be run when all objects are properly placed
  688. auto seedAfterInit = getRandomGenerator().nextInt();
  689. logGlobal->infoStream() << "Seed after init is " << seedAfterInit << " (before was " << scenarioOps->seedToBeUsed << ")";
  690. if(scenarioOps->seedPostInit > 0)
  691. {
  692. //RNG must be in the same state on all machines when initialization is done (otherwise we have desync)
  693. assert(scenarioOps->seedPostInit == seedAfterInit);
  694. }
  695. else
  696. {
  697. scenarioOps->seedPostInit = seedAfterInit; //store the post init "seed"
  698. }
  699. }
  700. void CGameState::initNewGame(bool allowSavingRandomMap)
  701. {
  702. if(scenarioOps->createRandomMap())
  703. {
  704. logGlobal->info("Create random map.");
  705. CStopWatch sw;
  706. // Gen map
  707. CMapGenerator mapGenerator;
  708. std::unique_ptr<CMap> randomMap = mapGenerator.generate(scenarioOps->mapGenOptions.get(), scenarioOps->seedToBeUsed);
  709. if(allowSavingRandomMap)
  710. {
  711. try
  712. {
  713. auto path = VCMIDirs::get().userCachePath() / "RandomMaps";
  714. boost::filesystem::create_directories(path);
  715. std::shared_ptr<CMapGenOptions> options = scenarioOps->mapGenOptions;
  716. const std::string templateName = options->getMapTemplate()->getName();
  717. const ui32 seed = scenarioOps->seedToBeUsed;
  718. const std::string fileName = boost::str(boost::format("%s_%d.vmap") % templateName % seed );
  719. const auto fullPath = path / fileName;
  720. CMapService::saveMap(randomMap, fullPath);
  721. logGlobal->info("Random map has been saved to:");
  722. logGlobal->info(fullPath.string());
  723. }
  724. catch(...)
  725. {
  726. logGlobal->error("Saving random map failed with exception");
  727. handleException();
  728. }
  729. }
  730. map = randomMap.release();
  731. // Update starting options
  732. for(int i = 0; i < map->players.size(); ++i)
  733. {
  734. const auto & playerInfo = map->players[i];
  735. if(playerInfo.canAnyonePlay())
  736. {
  737. PlayerSettings & playerSettings = scenarioOps->playerInfos[PlayerColor(i)];
  738. playerSettings.compOnly = !playerInfo.canHumanPlay;
  739. playerSettings.team = playerInfo.team;
  740. playerSettings.castle = playerInfo.defaultCastle();
  741. if(playerSettings.playerID == PlayerSettings::PLAYER_AI && playerSettings.name.empty())
  742. {
  743. playerSettings.name = VLC->generaltexth->allTexts[468];
  744. }
  745. playerSettings.color = PlayerColor(i);
  746. }
  747. else
  748. {
  749. scenarioOps->playerInfos.erase(PlayerColor(i));
  750. }
  751. }
  752. logGlobal->infoStream() << boost::format("Generated random map in %i ms.") % sw.getDiff();
  753. }
  754. else
  755. {
  756. logGlobal->infoStream() << "Open map file: " << scenarioOps->mapname;
  757. const ResourceID mapURI(scenarioOps->mapname, EResType::MAP);
  758. map = CMapService::loadMap(mapURI).release();
  759. }
  760. }
  761. void CGameState::initCampaign()
  762. {
  763. logGlobal->infoStream() << "Open campaign map file: " << scenarioOps->campState->currentMap;
  764. auto campaign = scenarioOps->campState;
  765. assert(vstd::contains(campaign->camp->mapPieces, *scenarioOps->campState->currentMap));
  766. std::string scenarioName = scenarioOps->mapname.substr(0, scenarioOps->mapname.find('.'));
  767. boost::to_lower(scenarioName);
  768. scenarioName += ':' + boost::lexical_cast<std::string>(*campaign->currentMap);
  769. std::string & mapContent = campaign->camp->mapPieces[*campaign->currentMap];
  770. auto buffer = reinterpret_cast<const ui8 *>(mapContent.data());
  771. map = CMapService::loadMap(buffer, mapContent.size(), scenarioName).release();
  772. }
  773. void CGameState::checkMapChecksum()
  774. {
  775. logGlobal->infoStream() << "\tOur checksum for the map: "<< map->checksum;
  776. if(scenarioOps->mapfileChecksum)
  777. {
  778. logGlobal->infoStream() << "\tServer checksum for " << scenarioOps->mapname <<": "<< scenarioOps->mapfileChecksum;
  779. if(map->checksum != scenarioOps->mapfileChecksum)
  780. {
  781. logGlobal->error("Wrong map checksum!!!");
  782. throw std::runtime_error("Wrong checksum");
  783. }
  784. }
  785. else
  786. {
  787. scenarioOps->mapfileChecksum = map->checksum;
  788. }
  789. }
  790. void CGameState::initGrailPosition()
  791. {
  792. logGlobal->debug("\tPicking grail position");
  793. //pick grail location
  794. if(map->grailPos.x < 0 || map->grailRadius) //grail not set or set within a radius around some place
  795. {
  796. if(!map->grailRadius) //radius not given -> anywhere on map
  797. map->grailRadius = map->width * 2;
  798. std::vector<int3> allowedPos;
  799. static const int BORDER_WIDTH = 9; // grail must be at least 9 tiles away from border
  800. // add all not blocked tiles in range
  801. for (int i = BORDER_WIDTH; i < map->width - BORDER_WIDTH ; i++)
  802. {
  803. for (int j = BORDER_WIDTH; j < map->height - BORDER_WIDTH; j++)
  804. {
  805. for (int k = 0; k < (map->twoLevel ? 2 : 1); k++)
  806. {
  807. const TerrainTile &t = map->getTile(int3(i, j, k));
  808. if(!t.blocked
  809. && !t.visitable
  810. && t.terType != ETerrainType::WATER
  811. && t.terType != ETerrainType::ROCK
  812. && map->grailPos.dist2dSQ(int3(i, j, k)) <= (map->grailRadius * map->grailRadius))
  813. allowedPos.push_back(int3(i,j,k));
  814. }
  815. }
  816. }
  817. //remove tiles with holes
  818. for(auto & elem : map->objects)
  819. if(elem && elem->ID == Obj::HOLE)
  820. allowedPos -= elem->pos;
  821. if(!allowedPos.empty())
  822. {
  823. map->grailPos = *RandomGeneratorUtil::nextItem(allowedPos, getRandomGenerator());
  824. }
  825. else
  826. {
  827. logGlobal->warn("Grail cannot be placed, no appropriate tile found!");
  828. }
  829. }
  830. }
  831. void CGameState::initRandomFactionsForPlayers()
  832. {
  833. logGlobal->debug("\tPicking random factions for players");
  834. for(auto & elem : scenarioOps->playerInfos)
  835. {
  836. if(elem.second.castle==-1)
  837. {
  838. auto randomID = getRandomGenerator().nextInt(map->players[elem.first.getNum()].allowedFactions.size() - 1);
  839. auto iter = map->players[elem.first.getNum()].allowedFactions.begin();
  840. std::advance(iter, randomID);
  841. elem.second.castle = *iter;
  842. }
  843. }
  844. }
  845. void CGameState::randomizeMapObjects()
  846. {
  847. logGlobal->debug("\tRandomizing objects");
  848. for(CGObjectInstance *obj : map->objects)
  849. {
  850. if(!obj) continue;
  851. randomizeObject(obj);
  852. //handle Favouring Winds - mark tiles under it
  853. if(obj->ID == Obj::FAVORABLE_WINDS)
  854. {
  855. for (int i = 0; i < obj->getWidth() ; i++)
  856. {
  857. for (int j = 0; j < obj->getHeight() ; j++)
  858. {
  859. int3 pos = obj->pos - int3(i,j,0);
  860. if(map->isInTheMap(pos)) map->getTile(pos).extTileFlags |= 128;
  861. }
  862. }
  863. }
  864. }
  865. }
  866. void CGameState::initPlayerStates()
  867. {
  868. logGlobal->debug("\tCreating player entries in gs");
  869. for(auto & elem : scenarioOps->playerInfos)
  870. {
  871. PlayerState & p = players[elem.first];
  872. //std::pair<PlayerColor, PlayerState> ins(elem.first,PlayerState());
  873. p.color=elem.first;
  874. p.human = elem.second.playerID;
  875. p.team = map->players[elem.first.getNum()].team;
  876. teams[p.team].id = p.team;//init team
  877. teams[p.team].players.insert(elem.first);//add player to team
  878. //players.insert(ins);
  879. }
  880. }
  881. void CGameState::placeCampaignHeroes()
  882. {
  883. if (scenarioOps->campState)
  884. {
  885. // place bonus hero
  886. auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap();
  887. bool campaignGiveHero = campaignBonus && campaignBonus.get().type == CScenarioTravel::STravelBonus::HERO;
  888. if(campaignGiveHero)
  889. {
  890. auto playerColor = PlayerColor(campaignBonus->info1);
  891. auto it = scenarioOps->playerInfos.find(playerColor);
  892. if(it != scenarioOps->playerInfos.end())
  893. {
  894. auto heroTypeId = campaignBonus->info2;
  895. if(heroTypeId == 0xffff) // random bonus hero
  896. {
  897. heroTypeId = pickUnusedHeroTypeRandomly(playerColor);
  898. }
  899. placeStartingHero(playerColor, HeroTypeID(heroTypeId), map->players[playerColor.getNum()].posOfMainTown);
  900. }
  901. }
  902. // replace heroes placeholders
  903. auto crossoverHeroes = getCrossoverHeroesFromPreviousScenarios();
  904. if(!crossoverHeroes.heroesFromAnyPreviousScenarios.empty())
  905. {
  906. logGlobal->debug("\tGenerate list of hero placeholders");
  907. auto campaignHeroReplacements = generateCampaignHeroesToReplace(crossoverHeroes);
  908. logGlobal->debug("\tPrepare crossover heroes");
  909. prepareCrossoverHeroes(campaignHeroReplacements, scenarioOps->campState->getCurrentScenario().travelOptions);
  910. // remove same heroes on the map which will be added through crossover heroes
  911. // INFO: we will remove heroes because later it may be possible that the API doesn't allow having heroes
  912. // with the same hero type id
  913. std::vector<CGHeroInstance *> removedHeroes;
  914. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  915. {
  916. auto hero = getUsedHero(HeroTypeID(campaignHeroReplacement.hero->subID));
  917. if(hero)
  918. {
  919. removedHeroes.push_back(hero);
  920. map->heroesOnMap -= hero;
  921. map->objects[hero->id.getNum()] = nullptr;
  922. map->removeBlockVisTiles(hero, true);
  923. }
  924. }
  925. logGlobal->debug("\tReplace placeholders with heroes");
  926. replaceHeroesPlaceholders(campaignHeroReplacements);
  927. // remove hero placeholders on map
  928. for(auto obj : map->objects)
  929. {
  930. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  931. {
  932. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  933. map->removeBlockVisTiles(heroPlaceholder, true);
  934. map->objects[heroPlaceholder->id.getNum()] = nullptr;
  935. delete heroPlaceholder;
  936. }
  937. }
  938. // now add removed heroes again with unused type ID
  939. for(auto hero : removedHeroes)
  940. {
  941. si32 heroTypeId = 0;
  942. if(hero->ID == Obj::HERO)
  943. {
  944. heroTypeId = pickUnusedHeroTypeRandomly(hero->tempOwner);
  945. }
  946. else if(hero->ID == Obj::PRISON)
  947. {
  948. auto unusedHeroTypeIds = getUnusedAllowedHeroes();
  949. if(!unusedHeroTypeIds.empty())
  950. {
  951. heroTypeId = (*RandomGeneratorUtil::nextItem(unusedHeroTypeIds, getRandomGenerator())).getNum();
  952. }
  953. else
  954. {
  955. logGlobal->error("No free hero type ID found to replace prison.");
  956. assert(0);
  957. }
  958. }
  959. else
  960. {
  961. assert(0); // should not happen
  962. }
  963. hero->subID = heroTypeId;
  964. hero->portrait = hero->subID;
  965. map->getEditManager()->insertObject(hero);
  966. }
  967. }
  968. }
  969. }
  970. void CGameState::placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos)
  971. {
  972. townPos.x -= 2; //FIXME: use actual visitable offset of town
  973. CGObjectInstance * hero = createObject(Obj::HERO, heroTypeId.getNum(), townPos, playerColor);
  974. hero->pos += hero->getVisitableOffset();
  975. map->getEditManager()->insertObject(hero);
  976. }
  977. CGameState::CrossoverHeroesList CGameState::getCrossoverHeroesFromPreviousScenarios() const
  978. {
  979. CrossoverHeroesList crossoverHeroes;
  980. auto campaignState = scenarioOps->campState;
  981. auto bonus = campaignState->getBonusForCurrentMap();
  982. if (bonus && bonus->type == CScenarioTravel::STravelBonus::HEROES_FROM_PREVIOUS_SCENARIO)
  983. {
  984. crossoverHeroes.heroesFromAnyPreviousScenarios = crossoverHeroes.heroesFromPreviousScenario = campaignState->camp->scenarios[bonus->info2].crossoverHeroes;
  985. }
  986. else
  987. {
  988. if(!campaignState->mapsConquered.empty())
  989. {
  990. crossoverHeroes.heroesFromPreviousScenario = campaignState->camp->scenarios[campaignState->mapsConquered.back()].crossoverHeroes;
  991. for(auto mapNr : campaignState->mapsConquered)
  992. {
  993. // create a list of deleted heroes
  994. auto & scenario = campaignState->camp->scenarios[mapNr];
  995. auto lostCrossoverHeroes = scenario.getLostCrossoverHeroes();
  996. // remove heroes which didn't reached the end of the scenario, but were available at the start
  997. for(auto hero : lostCrossoverHeroes)
  998. {
  999. vstd::erase_if(crossoverHeroes.heroesFromAnyPreviousScenarios,
  1000. CGObjectInstanceBySubIdFinder(hero));
  1001. }
  1002. // now add heroes which completed the scenario
  1003. for(auto hero : scenario.crossoverHeroes)
  1004. {
  1005. // add new heroes and replace old heroes with newer ones
  1006. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, CGObjectInstanceBySubIdFinder(hero));
  1007. if (it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  1008. {
  1009. // replace old hero with newer one
  1010. crossoverHeroes.heroesFromAnyPreviousScenarios[it - crossoverHeroes.heroesFromAnyPreviousScenarios.begin()] = hero;
  1011. }
  1012. else
  1013. {
  1014. // add new hero
  1015. crossoverHeroes.heroesFromAnyPreviousScenarios.push_back(hero);
  1016. }
  1017. }
  1018. }
  1019. }
  1020. }
  1021. return crossoverHeroes;
  1022. }
  1023. void CGameState::prepareCrossoverHeroes(std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements, const CScenarioTravel & travelOptions)
  1024. {
  1025. // create heroes list for convenience iterating
  1026. std::vector<CGHeroInstance *> crossoverHeroes;
  1027. for(auto & campaignHeroReplacement : campaignHeroReplacements)
  1028. {
  1029. crossoverHeroes.push_back(campaignHeroReplacement.hero);
  1030. }
  1031. // TODO replace magic numbers with named constants
  1032. // TODO this logic (what should be kept) should be part of CScenarioTravel and be exposed via some clean set of methods
  1033. if(!(travelOptions.whatHeroKeeps & 1))
  1034. {
  1035. //trimming experience
  1036. for(CGHeroInstance * cgh : crossoverHeroes)
  1037. {
  1038. cgh->initExp(getRandomGenerator());
  1039. }
  1040. }
  1041. if(!(travelOptions.whatHeroKeeps & 2))
  1042. {
  1043. //trimming prim skills
  1044. for(CGHeroInstance * cgh : crossoverHeroes)
  1045. {
  1046. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1047. {
  1048. auto sel = Selector::type(Bonus::PRIMARY_SKILL)
  1049. .And(Selector::subtype(g))
  1050. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL));
  1051. cgh->getBonusLocalFirst(sel)->val = cgh->type->heroClass->primarySkillInitial[g];
  1052. }
  1053. }
  1054. }
  1055. if(!(travelOptions.whatHeroKeeps & 4))
  1056. {
  1057. //trimming sec skills
  1058. for(CGHeroInstance * cgh : crossoverHeroes)
  1059. {
  1060. cgh->secSkills = cgh->type->secSkillsInit;
  1061. cgh->recreateSecondarySkillsBonuses();
  1062. }
  1063. }
  1064. if(!(travelOptions.whatHeroKeeps & 8))
  1065. {
  1066. for(CGHeroInstance * cgh : crossoverHeroes)
  1067. {
  1068. // Trimming spells
  1069. cgh->spells.clear();
  1070. // Spellbook will also be removed
  1071. if (cgh->hasSpellbook())
  1072. ArtifactLocation(cgh, ArtifactPosition(ArtifactPosition::SPELLBOOK)).removeArtifact();
  1073. }
  1074. }
  1075. if(!(travelOptions.whatHeroKeeps & 16))
  1076. {
  1077. //trimming artifacts
  1078. for(CGHeroInstance * hero : crossoverHeroes)
  1079. {
  1080. size_t totalArts = GameConstants::BACKPACK_START + hero->artifactsInBackpack.size();
  1081. for (size_t i = 0; i < totalArts; i++ )
  1082. {
  1083. auto artifactPosition = ArtifactPosition(i);
  1084. if(artifactPosition == ArtifactPosition::SPELLBOOK) continue; // do not handle spellbook this way
  1085. const ArtSlotInfo *info = hero->getSlot(artifactPosition);
  1086. if(!info)
  1087. continue;
  1088. // TODO: why would there be nullptr artifacts?
  1089. const CArtifactInstance *art = info->artifact;
  1090. if(!art)
  1091. continue;
  1092. int id = art->artType->id;
  1093. assert( 8*18 > id );//number of arts that fits into h3m format
  1094. bool takeable = travelOptions.artifsKeptByHero[id / 8] & ( 1 << (id%8) );
  1095. ArtifactLocation al(hero, artifactPosition);
  1096. if(!takeable && !al.getSlot()->locked) //don't try removing locked artifacts -> it crashes #1719
  1097. al.removeArtifact();
  1098. }
  1099. }
  1100. }
  1101. //trimming creatures
  1102. for(CGHeroInstance * cgh : crossoverHeroes)
  1103. {
  1104. auto shouldSlotBeErased = [&](const std::pair<SlotID, CStackInstance *> & j) -> bool
  1105. {
  1106. CreatureID::ECreatureID crid = j.second->getCreatureID().toEnum();
  1107. return !(travelOptions.monstersKeptByHero[crid / 8] & (1 << (crid % 8)));
  1108. };
  1109. auto stacksCopy = cgh->stacks; //copy of the map, so we can iterate iover it and remove stacks
  1110. for(auto &slotPair : stacksCopy)
  1111. if(shouldSlotBeErased(slotPair))
  1112. cgh->eraseStack(slotPair.first);
  1113. }
  1114. // Removing short-term bonuses
  1115. for(CGHeroInstance * cgh : crossoverHeroes)
  1116. {
  1117. cgh->popBonuses(CSelector(Bonus::OneDay)
  1118. .Or(CSelector(Bonus::OneWeek))
  1119. .Or(CSelector(Bonus::NTurns))
  1120. .Or(CSelector(Bonus::NDays))
  1121. .Or(CSelector(Bonus::OneBattle)));
  1122. }
  1123. }
  1124. void CGameState::placeStartingHeroes()
  1125. {
  1126. logGlobal->debug("\tGiving starting hero");
  1127. for(auto & playerSettingPair : scenarioOps->playerInfos)
  1128. {
  1129. auto playerColor = playerSettingPair.first;
  1130. auto & playerInfo = map->players[playerColor.getNum()];
  1131. if(playerInfo.generateHeroAtMainTown && playerInfo.hasMainTown)
  1132. {
  1133. // Do not place a starting hero if the hero was already placed due to a campaign bonus
  1134. if(scenarioOps->campState)
  1135. {
  1136. if(auto campaignBonus = scenarioOps->campState->getBonusForCurrentMap())
  1137. {
  1138. if(campaignBonus->type == CScenarioTravel::STravelBonus::HERO && playerColor == PlayerColor(campaignBonus->info1)) continue;
  1139. }
  1140. }
  1141. int heroTypeId = pickNextHeroType(playerColor);
  1142. if(playerSettingPair.second.hero == -1)
  1143. playerSettingPair.second.hero = heroTypeId;
  1144. placeStartingHero(playerColor, HeroTypeID(heroTypeId), playerInfo.posOfMainTown);
  1145. }
  1146. }
  1147. }
  1148. void CGameState::initStartingResources()
  1149. {
  1150. logGlobal->debug("\tSetting up resources");
  1151. const JsonNode config(ResourceID("config/startres.json"));
  1152. const JsonVector &vector = config["difficulty"].Vector();
  1153. const JsonNode &level = vector[scenarioOps->difficulty];
  1154. TResources startresAI(level["ai"]);
  1155. TResources startresHuman(level["human"]);
  1156. for (auto & elem : players)
  1157. {
  1158. PlayerState &p = elem.second;
  1159. if (p.human)
  1160. p.resources = startresHuman;
  1161. else
  1162. p.resources = startresAI;
  1163. }
  1164. auto getHumanPlayerInfo = [&]() -> std::vector<const PlayerSettings *>
  1165. {
  1166. std::vector<const PlayerSettings *> ret;
  1167. for(auto it = scenarioOps->playerInfos.cbegin();
  1168. it != scenarioOps->playerInfos.cend(); ++it)
  1169. {
  1170. if(it->second.playerID != PlayerSettings::PLAYER_AI)
  1171. ret.push_back(&it->second);
  1172. }
  1173. return ret;
  1174. };
  1175. //give start resource bonus in case of campaign
  1176. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1177. {
  1178. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1179. if(chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::RESOURCE)
  1180. {
  1181. std::vector<const PlayerSettings *> people = getHumanPlayerInfo(); //players we will give resource bonus
  1182. for(const PlayerSettings *ps : people)
  1183. {
  1184. std::vector<int> res; //resources we will give
  1185. switch (chosenBonus->info1)
  1186. {
  1187. case 0: case 1: case 2: case 3: case 4: case 5: case 6:
  1188. res.push_back(chosenBonus->info1);
  1189. break;
  1190. case 0xFD: //wood+ore
  1191. res.push_back(Res::WOOD); res.push_back(Res::ORE);
  1192. break;
  1193. case 0xFE: //rare
  1194. res.push_back(Res::MERCURY); res.push_back(Res::SULFUR); res.push_back(Res::CRYSTAL); res.push_back(Res::GEMS);
  1195. break;
  1196. default:
  1197. assert(0);
  1198. break;
  1199. }
  1200. //increasing resource quantity
  1201. for (auto & re : res)
  1202. {
  1203. players[ps->color].resources[re] += chosenBonus->info2;
  1204. }
  1205. }
  1206. }
  1207. }
  1208. }
  1209. void CGameState::initHeroes()
  1210. {
  1211. for(auto hero : map->heroesOnMap) //heroes instances initialization
  1212. {
  1213. if (hero->getOwner() == PlayerColor::UNFLAGGABLE)
  1214. {
  1215. logGlobal->warn("Hero with uninitialized owner!");
  1216. continue;
  1217. }
  1218. hero->initHero(getRandomGenerator());
  1219. getPlayer(hero->getOwner())->heroes.push_back(hero);
  1220. map->allHeroes[hero->type->ID.getNum()] = hero;
  1221. }
  1222. for(auto obj : map->objects) //prisons
  1223. {
  1224. if(obj && obj->ID == Obj::PRISON)
  1225. map->allHeroes[obj->subID] = dynamic_cast<CGHeroInstance*>(obj.get());
  1226. }
  1227. std::set<HeroTypeID> heroesToCreate = getUnusedAllowedHeroes(); //ids of heroes to be created and put into the pool
  1228. for(auto ph : map->predefinedHeroes)
  1229. {
  1230. if(!vstd::contains(heroesToCreate, HeroTypeID(ph->subID)))
  1231. continue;
  1232. ph->initHero(getRandomGenerator());
  1233. hpool.heroesPool[ph->subID] = ph;
  1234. hpool.pavailable[ph->subID] = 0xff;
  1235. heroesToCreate.erase(ph->type->ID);
  1236. map->allHeroes[ph->subID] = ph;
  1237. }
  1238. for(HeroTypeID htype : heroesToCreate) //all not used allowed heroes go with default state into the pool
  1239. {
  1240. auto vhi = new CGHeroInstance();
  1241. vhi->initHero(getRandomGenerator(), htype);
  1242. int typeID = htype.getNum();
  1243. map->allHeroes[typeID] = vhi;
  1244. hpool.heroesPool[typeID] = vhi;
  1245. hpool.pavailable[typeID] = 0xff;
  1246. }
  1247. for(auto & elem : map->disposedHeroes)
  1248. {
  1249. hpool.pavailable[elem.heroId] = elem.players;
  1250. }
  1251. if (scenarioOps->mode == StartInfo::CAMPAIGN) //give campaign bonuses for specific / best hero
  1252. {
  1253. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1254. if (chosenBonus && chosenBonus->isBonusForHero() && chosenBonus->info1 != 0xFFFE) //exclude generated heroes
  1255. {
  1256. //find human player
  1257. PlayerColor humanPlayer=PlayerColor::NEUTRAL;
  1258. for (auto & elem : players)
  1259. {
  1260. if(elem.second.human)
  1261. {
  1262. humanPlayer = elem.first;
  1263. break;
  1264. }
  1265. }
  1266. assert(humanPlayer != PlayerColor::NEUTRAL);
  1267. std::vector<ConstTransitivePtr<CGHeroInstance> > & heroes = players[humanPlayer].heroes;
  1268. if (chosenBonus->info1 == 0xFFFD) //most powerful
  1269. {
  1270. int maxB = -1;
  1271. for (int b=0; b<heroes.size(); ++b)
  1272. {
  1273. if (maxB == -1 || heroes[b]->getTotalStrength() > heroes[maxB]->getTotalStrength())
  1274. {
  1275. maxB = b;
  1276. }
  1277. }
  1278. if(maxB < 0)
  1279. logGlobal->warn("Cannot give bonus to hero cause there are no heroes!");
  1280. else
  1281. giveCampaignBonusToHero(heroes[maxB]);
  1282. }
  1283. else //specific hero
  1284. {
  1285. for (auto & heroe : heroes)
  1286. {
  1287. if (heroe->subID == chosenBonus->info1)
  1288. {
  1289. giveCampaignBonusToHero(heroe);
  1290. break;
  1291. }
  1292. }
  1293. }
  1294. }
  1295. }
  1296. }
  1297. void CGameState::giveCampaignBonusToHero(CGHeroInstance * hero)
  1298. {
  1299. const boost::optional<CScenarioTravel::STravelBonus> & curBonus = scenarioOps->campState->getBonusForCurrentMap();
  1300. if(!curBonus)
  1301. return;
  1302. if(curBonus->isBonusForHero())
  1303. {
  1304. //apply bonus
  1305. switch (curBonus->type)
  1306. {
  1307. case CScenarioTravel::STravelBonus::SPELL:
  1308. hero->spells.insert(SpellID(curBonus->info2));
  1309. break;
  1310. case CScenarioTravel::STravelBonus::MONSTER:
  1311. {
  1312. for(int i=0; i<GameConstants::ARMY_SIZE; i++)
  1313. {
  1314. if(hero->slotEmpty(SlotID(i)))
  1315. {
  1316. hero->addToSlot(SlotID(i), CreatureID(curBonus->info2), curBonus->info3);
  1317. break;
  1318. }
  1319. }
  1320. }
  1321. break;
  1322. case CScenarioTravel::STravelBonus::ARTIFACT:
  1323. gs->giveHeroArtifact(hero, static_cast<ArtifactID>(curBonus->info2));
  1324. break;
  1325. case CScenarioTravel::STravelBonus::SPELL_SCROLL:
  1326. {
  1327. CArtifactInstance * scroll = CArtifactInstance::createScroll(SpellID(curBonus->info2).toSpell());
  1328. scroll->putAt(ArtifactLocation(hero, scroll->firstAvailableSlot(hero)));
  1329. }
  1330. break;
  1331. case CScenarioTravel::STravelBonus::PRIMARY_SKILL:
  1332. {
  1333. const ui8* ptr = reinterpret_cast<const ui8*>(&curBonus->info2);
  1334. for (int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  1335. {
  1336. int val = ptr[g];
  1337. if (val == 0)
  1338. {
  1339. continue;
  1340. }
  1341. auto bb = std::make_shared<Bonus>(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::CAMPAIGN_BONUS, val, *scenarioOps->campState->currentMap, g);
  1342. hero->addNewBonus(bb);
  1343. }
  1344. }
  1345. break;
  1346. case CScenarioTravel::STravelBonus::SECONDARY_SKILL:
  1347. hero->setSecSkillLevel(SecondarySkill(curBonus->info2), curBonus->info3, true);
  1348. break;
  1349. }
  1350. }
  1351. }
  1352. void CGameState::initFogOfWar()
  1353. {
  1354. logGlobal->debug("\tFog of war"); //FIXME: should be initialized after all bonuses are set
  1355. for(auto & elem : teams)
  1356. {
  1357. elem.second.fogOfWarMap.resize(map->width);
  1358. for(int g=0; g<map->width; ++g)
  1359. elem.second.fogOfWarMap[g].resize(map->height);
  1360. for(int g=-0; g<map->width; ++g)
  1361. for(int h=0; h<map->height; ++h)
  1362. elem.second.fogOfWarMap[g][h].resize(map->twoLevel ? 2 : 1, 0);
  1363. for(int g=0; g<map->width; ++g)
  1364. for(int h=0; h<map->height; ++h)
  1365. for(int v = 0; v < (map->twoLevel ? 2 : 1); ++v)
  1366. elem.second.fogOfWarMap[g][h][v] = 0;
  1367. for(CGObjectInstance *obj : map->objects)
  1368. {
  1369. if(!obj || !vstd::contains(elem.second.players, obj->tempOwner)) continue; //not a flagged object
  1370. std::unordered_set<int3, ShashInt3> tiles;
  1371. getTilesInRange(tiles, obj->getSightCenter(), obj->getSightRadius(), obj->tempOwner, 1);
  1372. for(int3 tile : tiles)
  1373. {
  1374. elem.second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1375. }
  1376. }
  1377. }
  1378. }
  1379. void CGameState::initStartingBonus()
  1380. {
  1381. logGlobal->debug("\tStarting bonuses");
  1382. for(auto & elem : players)
  1383. {
  1384. //starting bonus
  1385. if(scenarioOps->playerInfos[elem.first].bonus==PlayerSettings::RANDOM)
  1386. scenarioOps->playerInfos[elem.first].bonus = static_cast<PlayerSettings::Ebonus>(getRandomGenerator().nextInt(2));
  1387. switch(scenarioOps->playerInfos[elem.first].bonus)
  1388. {
  1389. case PlayerSettings::GOLD:
  1390. elem.second.resources[Res::GOLD] += getRandomGenerator().nextInt(5, 10) * 100;
  1391. break;
  1392. case PlayerSettings::RESOURCE:
  1393. {
  1394. int res = VLC->townh->factions[scenarioOps->playerInfos[elem.first].castle]->town->primaryRes;
  1395. if(res == Res::WOOD_AND_ORE)
  1396. {
  1397. int amount = getRandomGenerator().nextInt(5, 10);
  1398. elem.second.resources[Res::WOOD] += amount;
  1399. elem.second.resources[Res::ORE] += amount;
  1400. }
  1401. else
  1402. {
  1403. elem.second.resources[res] += getRandomGenerator().nextInt(3, 6);
  1404. }
  1405. break;
  1406. }
  1407. case PlayerSettings::ARTIFACT:
  1408. {
  1409. if(!elem.second.heroes.size())
  1410. {
  1411. logGlobal->error("Cannot give starting artifact - no heroes!");
  1412. break;
  1413. }
  1414. CArtifact *toGive;
  1415. toGive = VLC->arth->artifacts[VLC->arth->pickRandomArtifact(getRandomGenerator(), CArtifact::ART_TREASURE)];
  1416. CGHeroInstance *hero = elem.second.heroes[0];
  1417. giveHeroArtifact(hero, toGive->id);
  1418. }
  1419. break;
  1420. }
  1421. }
  1422. }
  1423. void CGameState::initTowns()
  1424. {
  1425. logGlobal->debug("\tTowns");
  1426. //campaign bonuses for towns
  1427. if (scenarioOps->mode == StartInfo::CAMPAIGN)
  1428. {
  1429. auto chosenBonus = scenarioOps->campState->getBonusForCurrentMap();
  1430. if (chosenBonus && chosenBonus->type == CScenarioTravel::STravelBonus::BUILDING)
  1431. {
  1432. for (int g=0; g<map->towns.size(); ++g)
  1433. {
  1434. PlayerState * owner = getPlayer(map->towns[g]->getOwner());
  1435. if (owner)
  1436. {
  1437. PlayerInfo & pi = map->players[owner->color.getNum()];
  1438. if (owner->human && //human-owned
  1439. map->towns[g]->pos == pi.posOfMainTown)
  1440. {
  1441. map->towns[g]->builtBuildings.insert(
  1442. CBuildingHandler::campToERMU(chosenBonus->info1, map->towns[g]->subID, map->towns[g]->builtBuildings));
  1443. break;
  1444. }
  1445. }
  1446. }
  1447. }
  1448. }
  1449. CGTownInstance::universitySkills.clear();
  1450. for ( int i=0; i<4; i++)
  1451. CGTownInstance::universitySkills.push_back(14+i);//skills for university
  1452. for (auto & elem : map->towns)
  1453. {
  1454. CGTownInstance * vti =(elem);
  1455. if(!vti->town)
  1456. {
  1457. vti->town = VLC->townh->factions[vti->subID]->town;
  1458. }
  1459. if(vti->name.empty())
  1460. {
  1461. vti->name = *RandomGeneratorUtil::nextItem(vti->town->names, getRandomGenerator());
  1462. }
  1463. //init buildings
  1464. if(vstd::contains(vti->builtBuildings, BuildingID::DEFAULT)) //give standard set of buildings
  1465. {
  1466. vti->builtBuildings.erase(BuildingID::DEFAULT);
  1467. vti->builtBuildings.insert(BuildingID::VILLAGE_HALL);
  1468. if(vti->tempOwner != PlayerColor::NEUTRAL)
  1469. vti->builtBuildings.insert(BuildingID::TAVERN);
  1470. vti->builtBuildings.insert(BuildingID::DWELL_FIRST);
  1471. if(getRandomGenerator().nextInt(1) == 1)
  1472. {
  1473. vti->builtBuildings.insert(BuildingID::DWELL_LVL_2);
  1474. }
  1475. }
  1476. //#1444 - remove entries that don't have buildings defined (like some unused extra town hall buildings)
  1477. vstd::erase_if(vti->builtBuildings, [vti](BuildingID bid){
  1478. return !vti->town->buildings.count(bid) || !vti->town->buildings.at(bid); });
  1479. if (vstd::contains(vti->builtBuildings, BuildingID::SHIPYARD) && vti->shipyardStatus()==IBoatGenerator::TILE_BLOCKED)
  1480. vti->builtBuildings.erase(BuildingID::SHIPYARD);//if we have harbor without water - erase it (this is H3 behaviour)
  1481. //init hordes
  1482. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1483. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1484. {
  1485. vti->builtBuildings.erase(BuildingID(-31-i));//remove old ID
  1486. if (vti->town->hordeLvl.at(0) == i)//if town first horde is this one
  1487. {
  1488. vti->builtBuildings.insert(BuildingID::HORDE_1);//add it
  1489. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))//if we have upgraded dwelling as well
  1490. vti->builtBuildings.insert(BuildingID::HORDE_1_UPGR);//add it as well
  1491. }
  1492. if (vti->town->hordeLvl.at(1) == i)//if town second horde is this one
  1493. {
  1494. vti->builtBuildings.insert(BuildingID::HORDE_2);
  1495. if (vstd::contains(vti->builtBuildings,(BuildingID::DWELL_UP_FIRST+i)))
  1496. vti->builtBuildings.insert(BuildingID::HORDE_2_UPGR);
  1497. }
  1498. }
  1499. //Early check for #1444-like problems
  1500. for(auto building : vti->builtBuildings)
  1501. {
  1502. assert(vti->town->buildings.at(building) != nullptr);
  1503. UNUSED(building);
  1504. }
  1505. //town events
  1506. for(CCastleEvent &ev : vti->events)
  1507. {
  1508. for (int i = 0; i<GameConstants::CREATURES_PER_TOWN; i++)
  1509. if (vstd::contains(ev.buildings,(-31-i))) //if we have horde for this level
  1510. {
  1511. ev.buildings.erase(BuildingID(-31-i));
  1512. if (vti->town->hordeLvl.at(0) == i)
  1513. ev.buildings.insert(BuildingID::HORDE_1);
  1514. if (vti->town->hordeLvl.at(1) == i)
  1515. ev.buildings.insert(BuildingID::HORDE_2);
  1516. }
  1517. }
  1518. //init spells
  1519. vti->spells.resize(GameConstants::SPELL_LEVELS);
  1520. for(ui32 z=0; z<vti->obligatorySpells.size();z++)
  1521. {
  1522. auto s = vti->obligatorySpells[z].toSpell();
  1523. vti->spells[s->level-1].push_back(s->id);
  1524. vti->possibleSpells -= s->id;
  1525. }
  1526. while(vti->possibleSpells.size())
  1527. {
  1528. ui32 total=0;
  1529. int sel = -1;
  1530. for(ui32 ps=0;ps<vti->possibleSpells.size();ps++)
  1531. total += vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1532. if (total == 0) // remaining spells have 0 probability
  1533. break;
  1534. auto r = getRandomGenerator().nextInt(total - 1);
  1535. for(ui32 ps=0; ps<vti->possibleSpells.size();ps++)
  1536. {
  1537. r -= vti->possibleSpells[ps].toSpell()->getProbability(vti->subID);
  1538. if(r<0)
  1539. {
  1540. sel = ps;
  1541. break;
  1542. }
  1543. }
  1544. if(sel<0)
  1545. sel=0;
  1546. auto s = vti->possibleSpells[sel].toSpell();
  1547. vti->spells[s->level-1].push_back(s->id);
  1548. vti->possibleSpells -= s->id;
  1549. }
  1550. vti->possibleSpells.clear();
  1551. if(vti->getOwner() != PlayerColor::NEUTRAL)
  1552. getPlayer(vti->getOwner())->towns.push_back(vti);
  1553. }
  1554. }
  1555. void CGameState::initMapObjects()
  1556. {
  1557. logGlobal->debug("\tObject initialization");
  1558. // objCaller->preInit();
  1559. for(CGObjectInstance *obj : map->objects)
  1560. {
  1561. if(obj)
  1562. {
  1563. logGlobal->traceStream() << boost::format ("Calling Init for object %d, %s, %s") % obj->id.getNum() % obj->typeName % obj->subTypeName;
  1564. obj->initObj(getRandomGenerator());
  1565. }
  1566. }
  1567. for(CGObjectInstance *obj : map->objects)
  1568. {
  1569. if(!obj)
  1570. continue;
  1571. switch (obj->ID)
  1572. {
  1573. case Obj::QUEST_GUARD:
  1574. case Obj::SEER_HUT:
  1575. {
  1576. auto q = static_cast<CGSeerHut*>(obj);
  1577. assert (q);
  1578. q->setObjToKill();
  1579. }
  1580. }
  1581. }
  1582. CGSubterraneanGate::postInit(); //pairing subterranean gates
  1583. map->calculateGuardingGreaturePositions(); //calculate once again when all the guards are placed and initialized
  1584. }
  1585. void CGameState::initVisitingAndGarrisonedHeroes()
  1586. {
  1587. for(auto k=players.begin(); k!=players.end(); ++k)
  1588. {
  1589. if(k->first==PlayerColor::NEUTRAL)
  1590. continue;
  1591. //init visiting and garrisoned heroes
  1592. for(CGHeroInstance *h : k->second.heroes)
  1593. {
  1594. for(CGTownInstance *t : k->second.towns)
  1595. {
  1596. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1597. if(vistile == h->pos || h->pos==t->pos)
  1598. {
  1599. t->setVisitingHero(h);
  1600. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1601. {
  1602. map->removeBlockVisTiles(h);
  1603. h->pos.x -= 1;
  1604. map->addBlockVisTiles(h);
  1605. }
  1606. break;
  1607. }
  1608. }
  1609. }
  1610. }
  1611. for (auto hero : map->heroesOnMap)
  1612. {
  1613. if (hero->visitedTown)
  1614. {
  1615. assert (hero->visitedTown->visitingHero == hero);
  1616. }
  1617. }
  1618. }
  1619. BFieldType CGameState::battleGetBattlefieldType(int3 tile, CRandomGenerator & rand)
  1620. {
  1621. if(!tile.valid() && curB)
  1622. tile = curB->tile;
  1623. else if(!tile.valid() && !curB)
  1624. return BFieldType::NONE;
  1625. const TerrainTile &t = map->getTile(tile);
  1626. //fight in mine -> subterranean
  1627. if(dynamic_cast<const CGMine *>(t.visitableObjects.front()))
  1628. return BFieldType::SUBTERRANEAN;
  1629. for(auto &obj : map->objects)
  1630. {
  1631. //look only for objects covering given tile
  1632. if( !obj || obj->pos.z != tile.z || !obj->coveringAt(tile.x, tile.y))
  1633. continue;
  1634. switch(obj->ID)
  1635. {
  1636. case Obj::CLOVER_FIELD:
  1637. return BFieldType::CLOVER_FIELD;
  1638. case Obj::CURSED_GROUND1: case Obj::CURSED_GROUND2:
  1639. return BFieldType::CURSED_GROUND;
  1640. case Obj::EVIL_FOG:
  1641. return BFieldType::EVIL_FOG;
  1642. case Obj::FAVORABLE_WINDS:
  1643. return BFieldType::FAVORABLE_WINDS;
  1644. case Obj::FIERY_FIELDS:
  1645. return BFieldType::FIERY_FIELDS;
  1646. case Obj::HOLY_GROUNDS:
  1647. return BFieldType::HOLY_GROUND;
  1648. case Obj::LUCID_POOLS:
  1649. return BFieldType::LUCID_POOLS;
  1650. case Obj::MAGIC_CLOUDS:
  1651. return BFieldType::MAGIC_CLOUDS;
  1652. case Obj::MAGIC_PLAINS1: case Obj::MAGIC_PLAINS2:
  1653. return BFieldType::MAGIC_PLAINS;
  1654. case Obj::ROCKLANDS:
  1655. return BFieldType::ROCKLANDS;
  1656. }
  1657. }
  1658. if(map->isCoastalTile(tile)) //coastal tile is always ground
  1659. return BFieldType::SAND_SHORE;
  1660. switch(t.terType)
  1661. {
  1662. case ETerrainType::DIRT:
  1663. return BFieldType(rand.nextInt(3, 5));
  1664. case ETerrainType::SAND:
  1665. return BFieldType::SAND_MESAS; //TODO: coast support
  1666. case ETerrainType::GRASS:
  1667. return BFieldType(rand.nextInt(6, 7));
  1668. case ETerrainType::SNOW:
  1669. return BFieldType(rand.nextInt(10, 11));
  1670. case ETerrainType::SWAMP:
  1671. return BFieldType::SWAMP_TREES;
  1672. case ETerrainType::ROUGH:
  1673. return BFieldType::ROUGH;
  1674. case ETerrainType::SUBTERRANEAN:
  1675. return BFieldType::SUBTERRANEAN;
  1676. case ETerrainType::LAVA:
  1677. return BFieldType::LAVA;
  1678. case ETerrainType::WATER:
  1679. return BFieldType::SHIP;
  1680. case ETerrainType::ROCK:
  1681. return BFieldType::ROCKLANDS;
  1682. default:
  1683. return BFieldType::NONE;
  1684. }
  1685. }
  1686. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1687. {
  1688. UpgradeInfo ret;
  1689. const CCreature *base = stack.type;
  1690. const CGHeroInstance *h = stack.armyObj->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(stack.armyObj) : nullptr;
  1691. const CGTownInstance *t = nullptr;
  1692. if(stack.armyObj->ID == Obj::TOWN)
  1693. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1694. else if(h)
  1695. { //hero specialty
  1696. TBonusListPtr lista = h->getBonuses(Selector::typeSubtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1697. for(const std::shared_ptr<Bonus> it : *lista)
  1698. {
  1699. auto nid = CreatureID(it->additionalInfo);
  1700. if (nid != base->idNumber) //in very specific case the upgrade is available by default (?)
  1701. {
  1702. ret.newID.push_back(nid);
  1703. ret.cost.push_back(VLC->creh->creatures[nid]->cost - base->cost);
  1704. }
  1705. }
  1706. t = h->visitedTown;
  1707. }
  1708. if(t)
  1709. {
  1710. for(const CGTownInstance::TCreaturesSet::value_type & dwelling : t->creatures)
  1711. {
  1712. if (vstd::contains(dwelling.second, base->idNumber)) //Dwelling with our creature
  1713. {
  1714. for(auto upgrID : dwelling.second)
  1715. {
  1716. if(vstd::contains(base->upgrades, upgrID)) //possible upgrade
  1717. {
  1718. ret.newID.push_back(upgrID);
  1719. ret.cost.push_back(VLC->creh->creatures[upgrID]->cost - base->cost);
  1720. }
  1721. }
  1722. }
  1723. }
  1724. }
  1725. //hero is visiting Hill Fort
  1726. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == Obj::HILL_FORT)
  1727. {
  1728. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1729. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1730. for(auto nid : base->upgrades)
  1731. {
  1732. ret.newID.push_back(nid);
  1733. ret.cost.push_back((VLC->creh->creatures[nid]->cost - base->cost) * costModifier / 100);
  1734. }
  1735. }
  1736. if(ret.newID.size())
  1737. ret.oldID = base->idNumber;
  1738. for (Res::ResourceSet &cost : ret.cost)
  1739. cost.positive(); //upgrade cost can't be negative, ignore missing resources
  1740. return ret;
  1741. }
  1742. PlayerRelations::PlayerRelations CGameState::getPlayerRelations( PlayerColor color1, PlayerColor color2 )
  1743. {
  1744. if ( color1 == color2 )
  1745. return PlayerRelations::SAME_PLAYER;
  1746. if(color1 == PlayerColor::NEUTRAL || color2 == PlayerColor::NEUTRAL) //neutral player has no friends
  1747. return PlayerRelations::ENEMIES;
  1748. const TeamState * ts = getPlayerTeam(color1);
  1749. if (ts && vstd::contains(ts->players, color2))
  1750. return PlayerRelations::ALLIES;
  1751. return PlayerRelations::ENEMIES;
  1752. }
  1753. void CGameState::apply(CPack *pack)
  1754. {
  1755. ui16 typ = typeList.getTypeID(pack);
  1756. applierGs->getApplier(typ)->applyOnGS(this,pack);
  1757. }
  1758. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out)
  1759. {
  1760. CPathfinder pathfinder(out, this, hero);
  1761. pathfinder.calculatePaths();
  1762. }
  1763. /**
  1764. * Tells if the tile is guarded by a monster as well as the position
  1765. * of the monster that will attack on it.
  1766. *
  1767. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  1768. * the monster guarding the tile.
  1769. */
  1770. std::vector<CGObjectInstance*> CGameState::guardingCreatures (int3 pos) const
  1771. {
  1772. std::vector<CGObjectInstance*> guards;
  1773. const int3 originalPos = pos;
  1774. if (!map->isInTheMap(pos))
  1775. return guards;
  1776. const TerrainTile &posTile = map->getTile(pos);
  1777. if (posTile.visitable)
  1778. {
  1779. for (CGObjectInstance* obj : posTile.visitableObjects)
  1780. {
  1781. if(obj->blockVisit)
  1782. {
  1783. if (obj->ID == Obj::MONSTER) // Monster
  1784. guards.push_back(obj);
  1785. }
  1786. }
  1787. }
  1788. pos -= int3(1, 1, 0); // Start with top left.
  1789. for (int dx = 0; dx < 3; dx++)
  1790. {
  1791. for (int dy = 0; dy < 3; dy++)
  1792. {
  1793. if (map->isInTheMap(pos))
  1794. {
  1795. const auto & tile = map->getTile(pos);
  1796. if (tile.visitable && (tile.isWater() == posTile.isWater()))
  1797. {
  1798. for (CGObjectInstance* obj : tile.visitableObjects)
  1799. {
  1800. if (obj->ID == Obj::MONSTER && map->checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  1801. {
  1802. guards.push_back(obj);
  1803. }
  1804. }
  1805. }
  1806. }
  1807. pos.y++;
  1808. }
  1809. pos.y -= 3;
  1810. pos.x++;
  1811. }
  1812. return guards;
  1813. }
  1814. int3 CGameState::guardingCreaturePosition (int3 pos) const
  1815. {
  1816. return gs->map->guardingCreaturePositions[pos.x][pos.y][pos.z];
  1817. }
  1818. void CGameState::updateRumor()
  1819. {
  1820. static std::vector<RumorState::ERumorType> rumorTypes = {RumorState::TYPE_MAP, RumorState::TYPE_SPECIAL, RumorState::TYPE_RAND, RumorState::TYPE_RAND};
  1821. std::vector<RumorState::ERumorTypeSpecial> sRumorTypes = {
  1822. RumorState::RUMOR_OBELISKS, RumorState::RUMOR_ARTIFACTS, RumorState::RUMOR_ARMY, RumorState::RUMOR_INCOME};
  1823. if(map->grailPos.valid()) // Grail should always be on map, but I had related crash I didn't manage to reproduce
  1824. sRumorTypes.push_back(RumorState::RUMOR_GRAIL);
  1825. int rumorId = -1, rumorExtra = -1;
  1826. auto & rand = getRandomGenerator();
  1827. rumor.type = *RandomGeneratorUtil::nextItem(rumorTypes, rand);
  1828. do
  1829. {
  1830. switch(rumor.type)
  1831. {
  1832. case RumorState::TYPE_SPECIAL:
  1833. {
  1834. SThievesGuildInfo tgi;
  1835. obtainPlayersStats(tgi, 20);
  1836. rumorId = *RandomGeneratorUtil::nextItem(sRumorTypes, rand);
  1837. if(rumorId == RumorState::RUMOR_GRAIL)
  1838. {
  1839. rumorExtra = getTile(map->grailPos)->terType;
  1840. break;
  1841. }
  1842. std::vector<PlayerColor> players = {};
  1843. switch(rumorId)
  1844. {
  1845. case RumorState::RUMOR_OBELISKS:
  1846. players = tgi.obelisks[0];
  1847. break;
  1848. case RumorState::RUMOR_ARTIFACTS:
  1849. players = tgi.artifacts[0];
  1850. break;
  1851. case RumorState::RUMOR_ARMY:
  1852. players = tgi.army[0];
  1853. break;
  1854. case RumorState::RUMOR_INCOME:
  1855. players = tgi.income[0];
  1856. break;
  1857. }
  1858. rumorExtra = RandomGeneratorUtil::nextItem(players, rand)->getNum();
  1859. break;
  1860. }
  1861. case RumorState::TYPE_MAP:
  1862. // Makes sure that map rumors only used if there enough rumors too choose from
  1863. if(map->rumors.size() && (map->rumors.size() > 1 || !rumor.last.count(RumorState::TYPE_MAP)))
  1864. {
  1865. rumorId = rand.nextInt(map->rumors.size() - 1);
  1866. break;
  1867. }
  1868. else
  1869. rumor.type = RumorState::TYPE_RAND;
  1870. case RumorState::TYPE_RAND:
  1871. do
  1872. {
  1873. rumorId = rand.nextInt(VLC->generaltexth->tavernRumors.size() - 1);
  1874. }
  1875. while(!VLC->generaltexth->tavernRumors[rumorId].length());
  1876. break;
  1877. }
  1878. }
  1879. while(!rumor.update(rumorId, rumorExtra));
  1880. }
  1881. bool CGameState::isVisible(int3 pos, PlayerColor player)
  1882. {
  1883. if(player == PlayerColor::NEUTRAL)
  1884. return false;
  1885. if(player.isSpectator())
  1886. return true;
  1887. return getPlayerTeam(player)->fogOfWarMap[pos.x][pos.y][pos.z];
  1888. }
  1889. bool CGameState::isVisible( const CGObjectInstance *obj, boost::optional<PlayerColor> player )
  1890. {
  1891. if(!player)
  1892. return true;
  1893. //we should always see our own heroes - but sometimes not visible heroes cause crash :?
  1894. if (player == obj->tempOwner)
  1895. return true;
  1896. if(*player == PlayerColor::NEUTRAL) //-> TODO ??? needed?
  1897. return false;
  1898. //object is visible when at least one blocked tile is visible
  1899. for(int fy=0; fy < obj->getHeight(); ++fy)
  1900. {
  1901. for(int fx=0; fx < obj->getWidth(); ++fx)
  1902. {
  1903. int3 pos = obj->pos + int3(-fx, -fy, 0);
  1904. if ( map->isInTheMap(pos) &&
  1905. obj->coveringAt(pos.x, pos.y) &&
  1906. isVisible(pos, *player))
  1907. return true;
  1908. }
  1909. }
  1910. return false;
  1911. }
  1912. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1913. {
  1914. const TerrainTile * pom = &map->getTile(dst);
  1915. return map->checkForVisitableDir(src, pom, dst);
  1916. }
  1917. EVictoryLossCheckResult CGameState::checkForVictoryAndLoss(PlayerColor player) const
  1918. {
  1919. const std::string & messageWonSelf = VLC->generaltexth->allTexts[659];
  1920. const std::string & messageWonOther = VLC->generaltexth->allTexts[5];
  1921. const std::string & messageLostSelf = VLC->generaltexth->allTexts[7];
  1922. const std::string & messageLostOther = VLC->generaltexth->allTexts[8];
  1923. auto evaluateEvent = [=](const EventCondition & condition)
  1924. {
  1925. return this->checkForVictory(player, condition);
  1926. };
  1927. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1928. //cheater or tester, but has entered the code...
  1929. if (p->enteredWinningCheatCode)
  1930. return EVictoryLossCheckResult::victory(messageWonSelf, messageWonOther);
  1931. if (p->enteredLosingCheatCode)
  1932. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1933. for (const TriggeredEvent & event : map->triggeredEvents)
  1934. {
  1935. if (event.trigger.test(evaluateEvent))
  1936. {
  1937. if (event.effect.type == EventEffect::VICTORY)
  1938. return EVictoryLossCheckResult::victory(event.onFulfill, event.effect.toOtherMessage);
  1939. if (event.effect.type == EventEffect::DEFEAT)
  1940. return EVictoryLossCheckResult::defeat(event.onFulfill, event.effect.toOtherMessage);
  1941. }
  1942. }
  1943. if (checkForStandardLoss(player))
  1944. {
  1945. return EVictoryLossCheckResult::defeat(messageLostSelf, messageLostOther);
  1946. }
  1947. return EVictoryLossCheckResult();
  1948. }
  1949. bool CGameState::checkForVictory(PlayerColor player, const EventCondition & condition) const
  1950. {
  1951. const PlayerState *p = CGameInfoCallback::getPlayer(player);
  1952. switch (condition.condition)
  1953. {
  1954. case EventCondition::STANDARD_WIN:
  1955. {
  1956. return player == checkForStandardWin();
  1957. }
  1958. case EventCondition::HAVE_ARTIFACT: //check if any hero has winning artifact
  1959. {
  1960. for(auto & elem : p->heroes)
  1961. if(elem->hasArt(condition.objectType))
  1962. return true;
  1963. return false;
  1964. }
  1965. case EventCondition::HAVE_CREATURES:
  1966. {
  1967. //check if in players armies there is enough creatures
  1968. int total = 0; //creature counter
  1969. for(size_t i = 0; i < map->objects.size(); i++)
  1970. {
  1971. const CArmedInstance *ai = nullptr;
  1972. if(map->objects[i]
  1973. && map->objects[i]->tempOwner == player //object controlled by player
  1974. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i].get()))) //contains army
  1975. {
  1976. for(auto & elem : ai->Slots()) //iterate through army
  1977. if(elem.second->type->idNumber == condition.objectType) //it's searched creature
  1978. total += elem.second->count;
  1979. }
  1980. }
  1981. return total >= condition.value;
  1982. }
  1983. case EventCondition::HAVE_RESOURCES:
  1984. {
  1985. return p->resources[condition.objectType] >= condition.value;
  1986. }
  1987. case EventCondition::HAVE_BUILDING:
  1988. {
  1989. if (condition.object) // specific town
  1990. {
  1991. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  1992. return (t->tempOwner == player && t->hasBuilt(BuildingID(condition.objectType)));
  1993. }
  1994. else // any town
  1995. {
  1996. for (const CGTownInstance * t : p->towns)
  1997. {
  1998. if (t->hasBuilt(BuildingID(condition.objectType)))
  1999. return true;
  2000. }
  2001. return false;
  2002. }
  2003. }
  2004. case EventCondition::DESTROY:
  2005. {
  2006. if (condition.object) // mode A - destroy specific object of this type
  2007. {
  2008. if (auto hero = dynamic_cast<const CGHeroInstance*>(condition.object))
  2009. return boost::range::find(gs->map->heroesOnMap, hero) == gs->map->heroesOnMap.end();
  2010. else
  2011. return getObj(condition.object->id) == nullptr;
  2012. }
  2013. else
  2014. {
  2015. for(auto & elem : map->objects) // mode B - destroy all objects of this type
  2016. {
  2017. if(elem && elem->ID == condition.objectType)
  2018. return false;
  2019. }
  2020. return true;
  2021. }
  2022. }
  2023. case EventCondition::CONTROL:
  2024. {
  2025. // list of players that need to control object to fulfull condition
  2026. // NOTE: cgameinfocallback specified explicitly in order to get const version
  2027. auto & team = CGameInfoCallback::getPlayerTeam(player)->players;
  2028. if (condition.object) // mode A - flag one specific object, like town
  2029. {
  2030. return team.count(condition.object->tempOwner) != 0;
  2031. }
  2032. else
  2033. {
  2034. for(auto & elem : map->objects) // mode B - flag all objects of this type
  2035. {
  2036. //check not flagged objs
  2037. if ( elem && elem->ID == condition.objectType && team.count(elem->tempOwner) == 0 )
  2038. return false;
  2039. }
  2040. return true;
  2041. }
  2042. }
  2043. case EventCondition::TRANSPORT:
  2044. {
  2045. const CGTownInstance *t = static_cast<const CGTownInstance *>(condition.object);
  2046. if((t->visitingHero && t->visitingHero->hasArt(condition.objectType))
  2047. || (t->garrisonHero && t->garrisonHero->hasArt(condition.objectType)))
  2048. {
  2049. return true;
  2050. }
  2051. return false;
  2052. }
  2053. case EventCondition::DAYS_PASSED:
  2054. {
  2055. return gs->day > condition.value;
  2056. }
  2057. case EventCondition::IS_HUMAN:
  2058. {
  2059. return p->human ? condition.value == 1 : condition.value == 0;
  2060. }
  2061. case EventCondition::DAYS_WITHOUT_TOWN:
  2062. {
  2063. if (p->daysWithoutCastle)
  2064. return p->daysWithoutCastle.get() >= condition.value;
  2065. else
  2066. return false;
  2067. }
  2068. case EventCondition::CONST_VALUE:
  2069. {
  2070. return condition.value; // just convert to bool
  2071. }
  2072. case EventCondition::HAVE_0:
  2073. {
  2074. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2075. //TODO: support new condition format
  2076. return false;
  2077. }
  2078. case EventCondition::HAVE_BUILDING_0:
  2079. {
  2080. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2081. //TODO: support new condition format
  2082. return false;
  2083. }
  2084. case EventCondition::DESTROY_0:
  2085. {
  2086. logGlobal->debug("Not implemented event condition type: %d", (int)condition.condition);
  2087. //TODO: support new condition format
  2088. return false;
  2089. }
  2090. default:
  2091. logGlobal->error("Invalid event condition type: %d", (int)condition.condition);
  2092. return false;
  2093. }
  2094. }
  2095. PlayerColor CGameState::checkForStandardWin() const
  2096. {
  2097. //std victory condition is:
  2098. //all enemies lost
  2099. PlayerColor supposedWinner = PlayerColor::NEUTRAL;
  2100. TeamID winnerTeam = TeamID::NO_TEAM;
  2101. for(auto & elem : players)
  2102. {
  2103. if(elem.second.status == EPlayerStatus::INGAME && elem.first < PlayerColor::PLAYER_LIMIT)
  2104. {
  2105. if(supposedWinner == PlayerColor::NEUTRAL)
  2106. {
  2107. //first player remaining ingame - candidate for victory
  2108. supposedWinner = elem.second.color;
  2109. winnerTeam = elem.second.team;
  2110. }
  2111. else if(winnerTeam != elem.second.team)
  2112. {
  2113. //current candidate has enemy remaining in game -> no vicotry
  2114. return PlayerColor::NEUTRAL;
  2115. }
  2116. }
  2117. }
  2118. return supposedWinner;
  2119. }
  2120. bool CGameState::checkForStandardLoss( PlayerColor player ) const
  2121. {
  2122. //std loss condition is: player lost all towns and heroes
  2123. const PlayerState &p = *CGameInfoCallback::getPlayer(player);
  2124. return !p.heroes.size() && !p.towns.size();
  2125. }
  2126. struct statsHLP
  2127. {
  2128. typedef std::pair< PlayerColor, si64 > TStat;
  2129. //converts [<player's color, value>] to vec[place] -> platers
  2130. static std::vector< std::vector< PlayerColor > > getRank( std::vector<TStat> stats )
  2131. {
  2132. std::sort(stats.begin(), stats.end(), statsHLP());
  2133. //put first element
  2134. std::vector< std::vector<PlayerColor> > ret;
  2135. std::vector<PlayerColor> tmp;
  2136. tmp.push_back( stats[0].first );
  2137. ret.push_back( tmp );
  2138. //the rest of elements
  2139. for(int g=1; g<stats.size(); ++g)
  2140. {
  2141. if(stats[g].second == stats[g-1].second)
  2142. {
  2143. (ret.end()-1)->push_back( stats[g].first );
  2144. }
  2145. else
  2146. {
  2147. //create next occupied rank
  2148. std::vector<PlayerColor> tmp;
  2149. tmp.push_back(stats[g].first);
  2150. ret.push_back(tmp);
  2151. }
  2152. }
  2153. return ret;
  2154. }
  2155. bool operator()(const TStat & a, const TStat & b) const
  2156. {
  2157. return a.second > b.second;
  2158. }
  2159. static const CGHeroInstance * findBestHero(CGameState * gs, PlayerColor color)
  2160. {
  2161. std::vector<ConstTransitivePtr<CGHeroInstance> > &h = gs->players[color].heroes;
  2162. if(!h.size())
  2163. return nullptr;
  2164. //best hero will be that with highest exp
  2165. int best = 0;
  2166. for(int b=1; b<h.size(); ++b)
  2167. {
  2168. if(h[b]->exp > h[best]->exp)
  2169. {
  2170. best = b;
  2171. }
  2172. }
  2173. return h[best];
  2174. }
  2175. //calculates total number of artifacts that belong to given player
  2176. static int getNumberOfArts(const PlayerState * ps)
  2177. {
  2178. int ret = 0;
  2179. for(auto h : ps->heroes)
  2180. {
  2181. ret += h->artifactsInBackpack.size() + h->artifactsWorn.size();
  2182. }
  2183. return ret;
  2184. }
  2185. // get total strength of player army
  2186. static si64 getArmyStrength(const PlayerState * ps)
  2187. {
  2188. si64 str = 0;
  2189. for(auto h : ps->heroes)
  2190. {
  2191. if(!h->inTownGarrison) //original h3 behavior
  2192. str += h->getArmyStrength();
  2193. }
  2194. return str;
  2195. }
  2196. // get total gold income
  2197. static int getIncome(const PlayerState * ps)
  2198. {
  2199. int totalIncome = 0;
  2200. const CGObjectInstance * heroOrTown = nullptr;
  2201. //Heroes can produce gold as well - skill, specialty or arts
  2202. for(auto & h : ps->heroes)
  2203. {
  2204. totalIncome += h->valOfBonuses(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ESTATES));
  2205. totalIncome += h->valOfBonuses(Selector::typeSubtype(Bonus::GENERATE_RESOURCE, Res::GOLD));
  2206. if(!heroOrTown)
  2207. heroOrTown = h;
  2208. }
  2209. //Add town income of all towns
  2210. for(auto & t : ps->towns)
  2211. {
  2212. totalIncome += t->dailyIncome()[Res::GOLD];
  2213. if(!heroOrTown)
  2214. heroOrTown = t;
  2215. }
  2216. /// FIXME: Dirty dirty hack
  2217. /// Stats helper need some access to gamestate.
  2218. std::vector<const CGObjectInstance *> ownedObjects;
  2219. for(const CGObjectInstance * obj : heroOrTown->cb->gameState()->map->objects)
  2220. {
  2221. if(obj && obj->tempOwner == ps->color)
  2222. ownedObjects.push_back(obj);
  2223. }
  2224. /// This is code from CPlayerSpecificInfoCallback::getMyObjects
  2225. /// I'm really need to find out about callback interface design...
  2226. for(auto object : ownedObjects)
  2227. {
  2228. //Mines
  2229. if ( object->ID == Obj::MINE )
  2230. {
  2231. const CGMine *mine = dynamic_cast<const CGMine*>(object);
  2232. assert(mine);
  2233. if (mine->producedResource == Res::GOLD)
  2234. totalIncome += mine->producedQuantity;
  2235. }
  2236. }
  2237. return totalIncome;
  2238. }
  2239. };
  2240. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2241. {
  2242. auto playerInactive = [&](PlayerColor color)
  2243. {
  2244. return color == PlayerColor::NEUTRAL || players.at(color).status != EPlayerStatus::INGAME;
  2245. };
  2246. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2247. { \
  2248. std::vector< std::pair< PlayerColor, si64 > > stats; \
  2249. for(auto g = players.begin(); g != players.end(); ++g) \
  2250. { \
  2251. if(playerInactive(g->second.color)) \
  2252. continue; \
  2253. std::pair< PlayerColor, si64 > stat; \
  2254. stat.first = g->second.color; \
  2255. stat.second = VAL_GETTER; \
  2256. stats.push_back(stat); \
  2257. } \
  2258. tgi.FIELD = statsHLP::getRank(stats); \
  2259. }
  2260. for(auto & elem : players)
  2261. {
  2262. if(!playerInactive(elem.second.color))
  2263. tgi.playerColors.push_back(elem.second.color);
  2264. }
  2265. if(level >= 0) //num of towns & num of heroes
  2266. {
  2267. //num of towns
  2268. FILL_FIELD(numOfTowns, g->second.towns.size())
  2269. //num of heroes
  2270. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2271. }
  2272. if(level >= 1) //best hero's portrait
  2273. {
  2274. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2275. {
  2276. if(playerInactive(g->second.color))
  2277. continue;
  2278. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2279. InfoAboutHero iah;
  2280. iah.initFromHero(best, (level >= 2) ? InfoAboutHero::EInfoLevel::DETAILED : InfoAboutHero::EInfoLevel::BASIC);
  2281. iah.army.clear();
  2282. tgi.colorToBestHero[g->second.color] = iah;
  2283. }
  2284. }
  2285. if(level >= 2) //gold
  2286. {
  2287. FILL_FIELD(gold, g->second.resources[Res::GOLD])
  2288. }
  2289. if(level >= 2) //wood & ore
  2290. {
  2291. FILL_FIELD(woodOre, g->second.resources[Res::WOOD] + g->second.resources[Res::ORE])
  2292. }
  2293. if(level >= 3) //mercury, sulfur, crystal, gems
  2294. {
  2295. FILL_FIELD(mercSulfCrystGems, g->second.resources[Res::MERCURY] + g->second.resources[Res::SULFUR] + g->second.resources[Res::CRYSTAL] + g->second.resources[Res::GEMS])
  2296. }
  2297. if(level >= 3) //obelisks found
  2298. {
  2299. auto getObeliskVisited = [](TeamID t)
  2300. {
  2301. if(CGObelisk::visited.count(t))
  2302. return CGObelisk::visited[t];
  2303. else
  2304. return ui8(0);
  2305. };
  2306. FILL_FIELD(obelisks, getObeliskVisited(gs->getPlayerTeam(g->second.color)->id))
  2307. }
  2308. if(level >= 4) //artifacts
  2309. {
  2310. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  2311. }
  2312. if(level >= 4) //army strength
  2313. {
  2314. FILL_FIELD(army, statsHLP::getArmyStrength(&g->second))
  2315. }
  2316. if(level >= 5) //income
  2317. {
  2318. FILL_FIELD(income, statsHLP::getIncome(&g->second))
  2319. }
  2320. if(level >= 2) //best hero's stats
  2321. {
  2322. //already set in lvl 1 handling
  2323. }
  2324. if(level >= 3) //personality
  2325. {
  2326. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2327. {
  2328. if(playerInactive(g->second.color)) //do nothing for neutral player
  2329. continue;
  2330. if(g->second.human)
  2331. {
  2332. tgi.personality[g->second.color] = EAiTactic::NONE;
  2333. }
  2334. else //AI
  2335. {
  2336. tgi.personality[g->second.color] = map->players[g->second.color.getNum()].aiTactic;
  2337. }
  2338. }
  2339. }
  2340. if(level >= 4) //best creature
  2341. {
  2342. //best creatures belonging to player (highest AI value)
  2343. for(auto g = players.cbegin(); g != players.cend(); ++g)
  2344. {
  2345. if(playerInactive(g->second.color)) //do nothing for neutral player
  2346. continue;
  2347. int bestCre = -1; //best creature's ID
  2348. for(auto & elem : g->second.heroes)
  2349. {
  2350. for(auto it = elem->Slots().begin(); it != elem->Slots().end(); ++it)
  2351. {
  2352. int toCmp = it->second->type->idNumber; //ID of creature we should compare with the best one
  2353. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  2354. {
  2355. bestCre = toCmp;
  2356. }
  2357. }
  2358. }
  2359. tgi.bestCreature[g->second.color] = bestCre;
  2360. }
  2361. }
  2362. #undef FILL_FIELD
  2363. }
  2364. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > CGameState::unusedHeroesFromPool()
  2365. {
  2366. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > pool = hpool.heroesPool;
  2367. for ( auto i = players.cbegin() ; i != players.cend();i++)
  2368. for(auto j = i->second.availableHeroes.cbegin(); j != i->second.availableHeroes.cend(); j++)
  2369. if(*j)
  2370. pool.erase((**j).subID);
  2371. return pool;
  2372. }
  2373. void CGameState::buildBonusSystemTree()
  2374. {
  2375. buildGlobalTeamPlayerTree();
  2376. attachArmedObjects();
  2377. for(CGTownInstance *t : map->towns)
  2378. {
  2379. t->deserializationFix();
  2380. }
  2381. // CStackInstance <-> CCreature, CStackInstance <-> CArmedInstance, CArtifactInstance <-> CArtifact
  2382. // are provided on initializing / deserializing
  2383. }
  2384. void CGameState::deserializationFix()
  2385. {
  2386. buildGlobalTeamPlayerTree();
  2387. attachArmedObjects();
  2388. }
  2389. void CGameState::buildGlobalTeamPlayerTree()
  2390. {
  2391. for(auto k=teams.begin(); k!=teams.end(); ++k)
  2392. {
  2393. TeamState *t = &k->second;
  2394. t->attachTo(&globalEffects);
  2395. for(PlayerColor teamMember : k->second.players)
  2396. {
  2397. PlayerState *p = getPlayer(teamMember);
  2398. assert(p);
  2399. p->attachTo(t);
  2400. }
  2401. }
  2402. }
  2403. void CGameState::attachArmedObjects()
  2404. {
  2405. for(CGObjectInstance *obj : map->objects)
  2406. {
  2407. if(CArmedInstance *armed = dynamic_cast<CArmedInstance*>(obj))
  2408. armed->whatShouldBeAttached()->attachTo(armed->whereShouldBeAttached(this));
  2409. }
  2410. }
  2411. void CGameState::giveHeroArtifact(CGHeroInstance *h, ArtifactID aid)
  2412. {
  2413. CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  2414. CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  2415. map->addNewArtifactInstance(ai);
  2416. ai->putAt(ArtifactLocation(h, ai->firstAvailableSlot(h)));
  2417. }
  2418. std::set<HeroTypeID> CGameState::getUnusedAllowedHeroes(bool alsoIncludeNotAllowed /*= false*/) const
  2419. {
  2420. std::set<HeroTypeID> ret;
  2421. for(int i = 0; i < map->allowedHeroes.size(); i++)
  2422. if(map->allowedHeroes[i] || alsoIncludeNotAllowed)
  2423. ret.insert(HeroTypeID(i));
  2424. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2425. {
  2426. if(hero->type)
  2427. ret -= hero->type->ID;
  2428. else
  2429. ret -= HeroTypeID(hero->subID);
  2430. }
  2431. for(auto obj : map->objects) //prisons
  2432. if(obj && obj->ID == Obj::PRISON)
  2433. ret -= HeroTypeID(obj->subID);
  2434. return ret;
  2435. }
  2436. std::vector<CGameState::CampaignHeroReplacement> CGameState::generateCampaignHeroesToReplace(CrossoverHeroesList & crossoverHeroes)
  2437. {
  2438. std::vector<CampaignHeroReplacement> campaignHeroReplacements;
  2439. //selecting heroes by type
  2440. for(auto obj : map->objects)
  2441. {
  2442. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2443. {
  2444. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2445. if(heroPlaceholder->subID != 0xFF) //select by type
  2446. {
  2447. auto it = range::find_if(crossoverHeroes.heroesFromAnyPreviousScenarios, [heroPlaceholder](CGHeroInstance * hero)
  2448. {
  2449. return hero->subID == heroPlaceholder->subID;
  2450. });
  2451. if(it != crossoverHeroes.heroesFromAnyPreviousScenarios.end())
  2452. {
  2453. auto hero = *it;
  2454. crossoverHeroes.removeHeroFromBothLists(hero);
  2455. campaignHeroReplacements.push_back(CampaignHeroReplacement(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id));
  2456. }
  2457. }
  2458. }
  2459. }
  2460. //selecting heroes by power
  2461. range::sort(crossoverHeroes.heroesFromPreviousScenario, [](const CGHeroInstance * a, const CGHeroInstance * b)
  2462. {
  2463. return a->getHeroStrength() > b->getHeroStrength();
  2464. }); //sort, descending strength
  2465. // sort hero placeholders descending power
  2466. std::vector<CGHeroPlaceholder *> heroPlaceholders;
  2467. for(auto obj : map->objects)
  2468. {
  2469. if(obj && obj->ID == Obj::HERO_PLACEHOLDER)
  2470. {
  2471. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder *>(obj.get());
  2472. if(heroPlaceholder->subID == 0xFF) //select by power
  2473. {
  2474. heroPlaceholders.push_back(heroPlaceholder);
  2475. }
  2476. }
  2477. }
  2478. range::sort(heroPlaceholders, [](const CGHeroPlaceholder * a, const CGHeroPlaceholder * b)
  2479. {
  2480. return a->power > b->power;
  2481. });
  2482. for(int i = 0; i < heroPlaceholders.size(); ++i)
  2483. {
  2484. auto heroPlaceholder = heroPlaceholders[i];
  2485. if(crossoverHeroes.heroesFromPreviousScenario.size() > i)
  2486. {
  2487. auto hero = crossoverHeroes.heroesFromPreviousScenario[i];
  2488. campaignHeroReplacements.push_back(CampaignHeroReplacement(CMemorySerializer::deepCopy(*hero).release(), heroPlaceholder->id));
  2489. }
  2490. }
  2491. return campaignHeroReplacements;
  2492. }
  2493. void CGameState::replaceHeroesPlaceholders(const std::vector<CGameState::CampaignHeroReplacement> & campaignHeroReplacements)
  2494. {
  2495. for(auto campaignHeroReplacement : campaignHeroReplacements)
  2496. {
  2497. auto heroPlaceholder = dynamic_cast<CGHeroPlaceholder*>(getObjInstance(campaignHeroReplacement.heroPlaceholderId));
  2498. CGHeroInstance *heroToPlace = campaignHeroReplacement.hero;
  2499. heroToPlace->id = campaignHeroReplacement.heroPlaceholderId;
  2500. heroToPlace->tempOwner = heroPlaceholder->tempOwner;
  2501. heroToPlace->pos = heroPlaceholder->pos;
  2502. heroToPlace->type = VLC->heroh->heroes[heroToPlace->subID];
  2503. for(auto &&i : heroToPlace->stacks)
  2504. i.second->type = VLC->creh->creatures[i.second->getCreatureID()];
  2505. auto fixArtifact = [&](CArtifactInstance * art)
  2506. {
  2507. art->artType = VLC->arth->artifacts[art->artType->id];
  2508. gs->map->artInstances.push_back(art);
  2509. art->id = ArtifactInstanceID(gs->map->artInstances.size() - 1);
  2510. };
  2511. for(auto &&i : heroToPlace->artifactsWorn)
  2512. fixArtifact(i.second.artifact);
  2513. for(auto &&i : heroToPlace->artifactsInBackpack)
  2514. fixArtifact(i.artifact);
  2515. map->heroesOnMap.push_back(heroToPlace);
  2516. map->objects[heroToPlace->id.getNum()] = heroToPlace;
  2517. map->addBlockVisTiles(heroToPlace);
  2518. scenarioOps->campState->getCurrentScenario().placedCrossoverHeroes.push_back(heroToPlace);
  2519. }
  2520. }
  2521. bool CGameState::isUsedHero(HeroTypeID hid) const
  2522. {
  2523. return getUsedHero(hid);
  2524. }
  2525. CGHeroInstance * CGameState::getUsedHero(HeroTypeID hid) const
  2526. {
  2527. for(auto hero : map->heroesOnMap) //heroes instances initialization
  2528. {
  2529. if(hero->type && hero->type->ID == hid)
  2530. {
  2531. return hero;
  2532. }
  2533. }
  2534. for(auto obj : map->objects) //prisons
  2535. {
  2536. if(obj && obj->ID == Obj::PRISON )
  2537. {
  2538. auto hero = dynamic_cast<CGHeroInstance *>(obj.get());
  2539. assert(hero);
  2540. if ( hero->type && hero->type->ID == hid )
  2541. return hero;
  2542. }
  2543. }
  2544. return nullptr;
  2545. }
  2546. PlayerState::PlayerState()
  2547. : color(-1), human(false), enteredWinningCheatCode(false),
  2548. enteredLosingCheatCode(false), status(EPlayerStatus::INGAME)
  2549. {
  2550. setNodeType(PLAYER);
  2551. }
  2552. PlayerState::PlayerState(PlayerState && other):
  2553. CBonusSystemNode(std::move(other)),
  2554. color(other.color),
  2555. human(other.human),
  2556. team(other.team),
  2557. resources(other.resources),
  2558. enteredWinningCheatCode(other.enteredWinningCheatCode),
  2559. enteredLosingCheatCode(other.enteredLosingCheatCode),
  2560. status(other.status),
  2561. daysWithoutCastle(other.daysWithoutCastle)
  2562. {
  2563. std::swap(visitedObjects, other.visitedObjects);
  2564. std::swap(heroes, other.heroes);
  2565. std::swap(towns, other.towns);
  2566. std::swap(availableHeroes, other.availableHeroes);
  2567. std::swap(dwellings, other.dwellings);
  2568. std::swap(quests, other.quests);
  2569. }
  2570. std::string PlayerState::nodeName() const
  2571. {
  2572. return "Player " + (color.getNum() < VLC->generaltexth->capColors.size() ? VLC->generaltexth->capColors[color.getNum()] : boost::lexical_cast<std::string>(color));
  2573. }
  2574. bool RumorState::update(int id, int extra)
  2575. {
  2576. if(vstd::contains(last, type))
  2577. {
  2578. if(last[type].first != id)
  2579. {
  2580. last[type].first = id;
  2581. last[type].second = extra;
  2582. }
  2583. else
  2584. return false;
  2585. }
  2586. else
  2587. last[type] = std::make_pair(id, extra);
  2588. return true;
  2589. }
  2590. InfoAboutArmy::InfoAboutArmy():
  2591. owner(PlayerColor::NEUTRAL)
  2592. {}
  2593. InfoAboutArmy::InfoAboutArmy(const CArmedInstance *Army, bool detailed)
  2594. {
  2595. initFromArmy(Army, detailed);
  2596. }
  2597. void InfoAboutArmy::initFromArmy(const CArmedInstance *Army, bool detailed)
  2598. {
  2599. army = ArmyDescriptor(Army, detailed);
  2600. owner = Army->tempOwner;
  2601. name = Army->getObjectName();
  2602. }
  2603. void InfoAboutHero::assign(const InfoAboutHero & iah)
  2604. {
  2605. vstd::clear_pointer(details);
  2606. InfoAboutArmy::operator = (iah);
  2607. details = (iah.details ? new Details(*iah.details) : nullptr);
  2608. hclass = iah.hclass;
  2609. portrait = iah.portrait;
  2610. }
  2611. InfoAboutHero::InfoAboutHero():
  2612. details(nullptr),
  2613. hclass(nullptr),
  2614. portrait(-1)
  2615. {}
  2616. InfoAboutHero::InfoAboutHero(const InfoAboutHero & iah):
  2617. InfoAboutArmy()
  2618. {
  2619. assign(iah);
  2620. }
  2621. InfoAboutHero::InfoAboutHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2622. : details(nullptr),
  2623. hclass(nullptr),
  2624. portrait(-1)
  2625. {
  2626. initFromHero(h, infoLevel);
  2627. }
  2628. InfoAboutHero::~InfoAboutHero()
  2629. {
  2630. vstd::clear_pointer(details);
  2631. }
  2632. InfoAboutHero & InfoAboutHero::operator=(const InfoAboutHero & iah)
  2633. {
  2634. assign(iah);
  2635. return *this;
  2636. }
  2637. void InfoAboutHero::initFromHero(const CGHeroInstance *h, InfoAboutHero::EInfoLevel infoLevel)
  2638. {
  2639. vstd::clear_pointer(details);
  2640. if(!h)
  2641. return;
  2642. bool detailed = ( (infoLevel == EInfoLevel::DETAILED) || (infoLevel == EInfoLevel::INBATTLE) );
  2643. initFromArmy(h, detailed);
  2644. hclass = h->type->heroClass;
  2645. name = h->name;
  2646. portrait = h->portrait;
  2647. if(detailed)
  2648. {
  2649. //include details about hero
  2650. details = new Details;
  2651. details->luck = h->LuckVal();
  2652. details->morale = h->MoraleVal();
  2653. details->mana = h->mana;
  2654. details->primskills.resize(GameConstants::PRIMARY_SKILLS);
  2655. for (int i = 0; i < GameConstants::PRIMARY_SKILLS ; i++)
  2656. {
  2657. details->primskills[i] = h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i));
  2658. }
  2659. if (infoLevel == EInfoLevel::INBATTLE)
  2660. details->manaLimit = h->manaLimit();
  2661. else
  2662. details->manaLimit = -1; //we do not want to leak max mana info outside battle so set to meaningless value
  2663. }
  2664. }
  2665. InfoAboutTown::InfoAboutTown():
  2666. details(nullptr),
  2667. tType(nullptr),
  2668. built(0),
  2669. fortLevel(0)
  2670. {
  2671. }
  2672. InfoAboutTown::InfoAboutTown(const CGTownInstance *t, bool detailed):
  2673. details(nullptr),
  2674. tType(nullptr),
  2675. built(0),
  2676. fortLevel(0)
  2677. {
  2678. initFromTown(t, detailed);
  2679. }
  2680. InfoAboutTown::~InfoAboutTown()
  2681. {
  2682. vstd::clear_pointer(details);
  2683. }
  2684. void InfoAboutTown::initFromTown(const CGTownInstance *t, bool detailed)
  2685. {
  2686. initFromArmy(t, detailed);
  2687. army = ArmyDescriptor(t->getUpperArmy(), detailed);
  2688. built = t->builded;
  2689. fortLevel = t->fortLevel();
  2690. name = t->name;
  2691. tType = t->town;
  2692. vstd::clear_pointer(details);
  2693. if(detailed)
  2694. {
  2695. //include details about hero
  2696. details = new Details;
  2697. TResources income = t->dailyIncome();
  2698. details->goldIncome = income[Res::GOLD];
  2699. details->customRes = t->hasBuilt(BuildingID::RESOURCE_SILO);
  2700. details->hallLevel = t->hallLevel();
  2701. details->garrisonedHero = t->garrisonHero;
  2702. }
  2703. }
  2704. ArmyDescriptor::ArmyDescriptor(const CArmedInstance *army, bool detailed)
  2705. : isDetailed(detailed)
  2706. {
  2707. for(auto & elem : army->Slots())
  2708. {
  2709. if(detailed)
  2710. (*this)[elem.first] = *elem.second;
  2711. else
  2712. (*this)[elem.first] = CStackBasicDescriptor(elem.second->type, elem.second->getQuantityID());
  2713. }
  2714. }
  2715. ArmyDescriptor::ArmyDescriptor()
  2716. : isDetailed(false)
  2717. {
  2718. }
  2719. int ArmyDescriptor::getStrength() const
  2720. {
  2721. ui64 ret = 0;
  2722. if(isDetailed)
  2723. {
  2724. for(auto & elem : *this)
  2725. ret += elem.second.type->AIValue * elem.second.count;
  2726. }
  2727. else
  2728. {
  2729. for(auto & elem : *this)
  2730. ret += elem.second.type->AIValue * CCreature::estimateCreatureCount(elem.second.count);
  2731. }
  2732. return ret;
  2733. }
  2734. TeamState::TeamState()
  2735. {
  2736. setNodeType(TEAM);
  2737. }
  2738. TeamState::TeamState(TeamState && other):
  2739. CBonusSystemNode(std::move(other)),
  2740. id(other.id)
  2741. {
  2742. std::swap(players, other.players);
  2743. std::swap(fogOfWarMap, other.fogOfWarMap);
  2744. }
  2745. CRandomGenerator & CGameState::getRandomGenerator()
  2746. {
  2747. //if(scenarioOps && scenarioOps->seedPostInit)
  2748. //{
  2749. // logGlobal->trace("CGameState::getRandomGenerator used after initialization!");
  2750. //}
  2751. //logGlobal->traceStream() << "Fetching CGameState::rand with seed " << rand.nextInt();
  2752. return rand;
  2753. }