CGameState.cpp 95 KB

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