CGameState.cpp 98 KB

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