CGameState.cpp 92 KB

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