CGameState.cpp 98 KB

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