CGameState.cpp 98 KB

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