CGameState.cpp 86 KB

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