CGameState.cpp 83 KB

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