2
0

CGameState.cpp 85 KB

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