CGameState.cpp 92 KB

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