CGameState.cpp 102 KB

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