CGameState.cpp 96 KB

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