CGameState.cpp 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049
  1. #define VCMI_DLL
  2. #include <algorithm>
  3. #include <queue>
  4. #include <fstream>
  5. #include "CGameState.h"
  6. #include <boost/random/linear_congruential.hpp>
  7. #include "../hch/CDefObjInfoHandler.h"
  8. #include "../hch/CArtHandler.h"
  9. #include "../hch/CBuildingHandler.h"
  10. #include "../hch/CGeneralTextHandler.h"
  11. #include "../hch/CTownHandler.h"
  12. #include "../hch/CSpellHandler.h"
  13. #include "../hch/CHeroHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CCreatureHandler.h"
  16. #include "VCMI_Lib.h"
  17. #include "Connection.h"
  18. #include "map.h"
  19. #include "../StartInfo.h"
  20. #include "NetPacks.h"
  21. #include <boost/foreach.hpp>
  22. #include <boost/lexical_cast.hpp>
  23. #include <boost/thread.hpp>
  24. #include <boost/thread/shared_mutex.hpp>
  25. #include "RegisterTypes.cpp"
  26. boost::rand48 ran;
  27. #ifdef min
  28. #undef min
  29. #endif
  30. #ifdef max
  31. #undef max
  32. #endif
  33. /*
  34. * CGameState.cpp, part of VCMI engine
  35. *
  36. * Authors: listed in file AUTHORS in main folder
  37. *
  38. * License: GNU General Public License v2.0 or later
  39. * Full text of license available in license.txt file, in main folder
  40. *
  41. */
  42. void foofoofoo()
  43. {
  44. //never called function to force instantation of templates
  45. int *ccc = NULL;
  46. registerTypes((CISer<CConnection>&)*ccc);
  47. registerTypes((COSer<CConnection>&)*ccc);
  48. registerTypes((CSaveFile&)*ccc);
  49. registerTypes((CLoadFile&)*ccc);
  50. registerTypes((CTypeList&)*ccc);
  51. }
  52. class CBaseForGSApply
  53. {
  54. public:
  55. virtual void applyOnGS(CGameState *gs, void *pack) const =0;
  56. };
  57. template <typename T> class CApplyOnGS : public CBaseForGSApply
  58. {
  59. public:
  60. void applyOnGS(CGameState *gs, void *pack) const
  61. {
  62. T *ptr = static_cast<T*>(pack);
  63. while(!gs->mx->try_lock())
  64. boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  65. ptr->applyGs(gs);
  66. gs->mx->unlock();
  67. }
  68. };
  69. class CGSApplier
  70. {
  71. public:
  72. std::map<ui16,CBaseForGSApply*> apps;
  73. CGSApplier()
  74. {
  75. registerTypes2(*this);
  76. }
  77. template<typename T> void registerType(const T * t=NULL)
  78. {
  79. ui16 ID = typeList.registerType(t);
  80. apps[ID] = new CApplyOnGS<T>;
  81. }
  82. } *applierGs = NULL;
  83. class IObjectCaller
  84. {
  85. public:
  86. virtual void preInit()=0;
  87. virtual void postInit()=0;
  88. };
  89. template <typename T>
  90. class CObjectCaller : public IObjectCaller
  91. {
  92. public:
  93. void preInit()
  94. {
  95. T::preInit();
  96. }
  97. void postInit()
  98. {
  99. T::postInit();
  100. }
  101. };
  102. class CObjectCallersHandler
  103. {
  104. public:
  105. std::vector<IObjectCaller*> apps;
  106. template<typename T> void registerType(const T * t=NULL)
  107. {
  108. apps.push_back(new CObjectCaller<T>);
  109. }
  110. CObjectCallersHandler()
  111. {
  112. registerTypes1(*this);
  113. }
  114. ~CObjectCallersHandler()
  115. {
  116. for (size_t i = 0; i < apps.size(); i++)
  117. delete apps[i];
  118. }
  119. void preInit()
  120. {
  121. for (size_t i = 0; i < apps.size(); i++)
  122. apps[i]->preInit();
  123. }
  124. void postInit()
  125. {
  126. for (size_t i = 0; i < apps.size(); i++)
  127. apps[i]->postInit();
  128. }
  129. } *objCaller = NULL;
  130. void MetaString::getLocalString(const std::pair<ui8,ui32> &txt, std::string &dst) const
  131. {
  132. int type = txt.first, ser = txt.second;
  133. if(type == ART_NAMES)
  134. {
  135. dst = VLC->arth->artifacts[ser].Name();
  136. }
  137. else if(type == CRE_PL_NAMES)
  138. {
  139. dst = VLC->creh->creatures[ser].namePl;
  140. }
  141. else if(type == MINE_NAMES)
  142. {
  143. dst = VLC->generaltexth->mines[ser].first;
  144. }
  145. else if(type == MINE_EVNTS)
  146. {
  147. dst = VLC->generaltexth->mines[ser].second;
  148. }
  149. else if(type == SPELL_NAME)
  150. {
  151. dst = VLC->spellh->spells[ser].name;
  152. }
  153. else if(type == CRE_SING_NAMES)
  154. {
  155. dst = VLC->creh->creatures[ser].nameSing;
  156. }
  157. else
  158. {
  159. std::vector<std::string> *vec;
  160. switch(type)
  161. {
  162. case GENERAL_TXT:
  163. vec = &VLC->generaltexth->allTexts;
  164. break;
  165. case XTRAINFO_TXT:
  166. vec = &VLC->generaltexth->xtrainfo;
  167. break;
  168. case OBJ_NAMES:
  169. vec = &VLC->generaltexth->names;
  170. break;
  171. case RES_NAMES:
  172. vec = &VLC->generaltexth->restypes;
  173. break;
  174. case ARRAY_TXT:
  175. vec = &VLC->generaltexth->arraytxt;
  176. break;
  177. case CREGENS:
  178. vec = &VLC->generaltexth->creGens;
  179. break;
  180. case CREGENS4:
  181. vec = &VLC->generaltexth->creGens4;
  182. break;
  183. case ADVOB_TXT:
  184. vec = &VLC->generaltexth->advobtxt;
  185. break;
  186. case ART_EVNTS:
  187. vec = &VLC->generaltexth->artifEvents;
  188. break;
  189. case SEC_SKILL_NAME:
  190. vec = &VLC->generaltexth->skillName;
  191. break;
  192. }
  193. dst = (*vec)[ser];
  194. }
  195. }
  196. DLL_EXPORT void MetaString::toString(std::string &dst) const
  197. {
  198. size_t exSt = 0, loSt = 0, nums = 0;
  199. dst.clear();
  200. for(size_t i=0;i<message.size();++i)
  201. {//TEXACT_STRING, TLOCAL_STRING, TNUMBER, TREPLACE_ESTRING, TREPLACE_LSTRING, TREPLACE_NUMBER
  202. switch(message[i])
  203. {
  204. case TEXACT_STRING:
  205. dst += exactStrings[exSt++];
  206. break;
  207. case TLOCAL_STRING:
  208. {
  209. std::string hlp;
  210. getLocalString(localStrings[loSt++], hlp);
  211. dst += hlp;
  212. }
  213. break;
  214. case TNUMBER:
  215. dst += boost::lexical_cast<std::string>(numbers[nums++]);
  216. break;
  217. case TREPLACE_ESTRING:
  218. dst.replace (dst.find("%s"), 2, exactStrings[exSt++]);
  219. break;
  220. case TREPLACE_LSTRING:
  221. {
  222. std::string hlp;
  223. getLocalString(localStrings[loSt++], hlp);
  224. dst.replace (dst.find("%s"), 2, hlp);
  225. }
  226. break;
  227. case TREPLACE_NUMBER:
  228. dst.replace (dst.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  229. break;
  230. default:
  231. tlog1 << "MetaString processing error!\n";
  232. break;
  233. }
  234. }
  235. }
  236. DLL_EXPORT std::string MetaString::buildList () const
  237. ///used to handle loot from creature bank
  238. {
  239. size_t exSt = 0, loSt = 0, nums = 0;
  240. std::string lista;
  241. for (int i = 0; i < message.size(); ++i)
  242. {
  243. if (i > 0 && message[i] == TEXACT_STRING || message[i] == TLOCAL_STRING)
  244. {
  245. if (exSt == exactStrings.size() - 1)
  246. lista += VLC->generaltexth->allTexts[141]; //" and "
  247. else
  248. lista += ", ";
  249. }
  250. switch (message[i])
  251. {
  252. case TEXACT_STRING:
  253. lista += exactStrings[exSt++];
  254. break;
  255. case TLOCAL_STRING:
  256. {
  257. std::string hlp;
  258. getLocalString (localStrings[loSt++], hlp);
  259. lista += hlp;
  260. }
  261. break;
  262. case TNUMBER:
  263. lista += boost::lexical_cast<std::string>(numbers[nums++]);
  264. break;
  265. case TREPLACE_ESTRING:
  266. lista.replace (lista.find("%s"), 2, exactStrings[exSt++]);
  267. break;
  268. case TREPLACE_LSTRING:
  269. {
  270. std::string hlp;
  271. getLocalString (localStrings[loSt++], hlp);
  272. lista.replace (lista.find("%s"), 2, hlp);
  273. }
  274. break;
  275. case TREPLACE_NUMBER:
  276. lista.replace (lista.find("%d"), 2, boost::lexical_cast<std::string>(numbers[nums++]));
  277. break;
  278. default:
  279. tlog1 << "MetaString processing error!\n";
  280. }
  281. }
  282. return lista;
  283. }
  284. static CGObjectInstance * createObject(int id, int subid, int3 pos, int owner)
  285. {
  286. CGObjectInstance * nobj;
  287. switch(id)
  288. {
  289. case HEROI_TYPE: //hero
  290. {
  291. CGHeroInstance * nobj = new CGHeroInstance();
  292. nobj->pos = pos;
  293. nobj->tempOwner = owner;
  294. nobj->subID = subid;
  295. //nobj->initHero(ran);
  296. return nobj;
  297. }
  298. case TOWNI_TYPE: //town
  299. nobj = new CGTownInstance;
  300. break;
  301. default: //rest of objects
  302. nobj = new CGObjectInstance;
  303. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  304. break;
  305. }
  306. nobj->ID = id;
  307. nobj->subID = subid;
  308. if(!nobj->defInfo)
  309. tlog3 <<"No def declaration for " <<id <<" "<<subid<<std::endl;
  310. nobj->pos = pos;
  311. //nobj->state = NULL;//new CLuaObjectScript();
  312. nobj->tempOwner = owner;
  313. nobj->info = NULL;
  314. nobj->defInfo->id = id;
  315. nobj->defInfo->subid = subid;
  316. //assigning defhandler
  317. if(nobj->ID==HEROI_TYPE || nobj->ID==TOWNI_TYPE)
  318. return nobj;
  319. nobj->defInfo = VLC->dobjinfo->gobjs[id][subid];
  320. return nobj;
  321. }
  322. CStack * BattleInfo::getStack(int stackID, bool onlyAlive)
  323. {
  324. for(unsigned int g=0; g<stacks.size(); ++g)
  325. {
  326. if(stacks[g]->ID == stackID && (!onlyAlive || stacks[g]->alive()))
  327. return stacks[g];
  328. }
  329. return NULL;
  330. }
  331. const CStack * BattleInfo::getStack(int stackID, bool onlyAlive) const
  332. {
  333. return const_cast<BattleInfo * const>(this)->getStack(stackID, onlyAlive);
  334. }
  335. CStack * BattleInfo::getStackT(int tileID, bool onlyAlive)
  336. {
  337. for(unsigned int g=0; g<stacks.size(); ++g)
  338. {
  339. if(stacks[g]->position == tileID
  340. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID)
  341. || (stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID))
  342. {
  343. if(!onlyAlive || stacks[g]->alive())
  344. {
  345. return stacks[g];
  346. }
  347. }
  348. }
  349. return NULL;
  350. }
  351. const CStack * BattleInfo::getStackT(int tileID, bool onlyAlive) const
  352. {
  353. return const_cast<BattleInfo * const>(this)->getStackT(tileID, onlyAlive);
  354. }
  355. void BattleInfo::getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit) const
  356. {
  357. memset(accessibility, 1, BFIELD_SIZE); //initialize array with trues
  358. //removing accessibility for side columns of hexes
  359. for(int v = 0; v < BFIELD_SIZE; ++v)
  360. {
  361. if( v % BFIELD_WIDTH == 0 || v % BFIELD_WIDTH == (BFIELD_WIDTH - 1) )
  362. accessibility[v] = false;
  363. }
  364. for(unsigned int g=0; g<stacks.size(); ++g)
  365. {
  366. if(!stacks[g]->alive() || stacks[g]->ID==stackToOmmit || stacks[g]->position < 0) //we don't want to lock position of this stack (eg. if it's a turret)
  367. continue;
  368. accessibility[stacks[g]->position] = false;
  369. if(stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)) //if it's a double hex creature
  370. {
  371. if(stacks[g]->attackerOwned)
  372. accessibility[stacks[g]->position-1] = false;
  373. else
  374. accessibility[stacks[g]->position+1] = false;
  375. }
  376. }
  377. //obstacles
  378. for(unsigned int b=0; b<obstacles.size(); ++b)
  379. {
  380. std::vector<int> blocked = VLC->heroh->obstacles[obstacles[b].ID].getBlocked(obstacles[b].pos);
  381. for(unsigned int c=0; c<blocked.size(); ++c)
  382. {
  383. if(blocked[c] >=0 && blocked[c] < BFIELD_SIZE)
  384. accessibility[blocked[c]] = false;
  385. }
  386. }
  387. //walls
  388. if(siege > 0)
  389. {
  390. static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
  391. for(int b=0; b<ARRAY_COUNT(permanentlyLocked); ++b)
  392. {
  393. accessibility[permanentlyLocked[b]] = false;
  394. }
  395. static const std::pair<int, int> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
  396. {std::make_pair(2, 182), std::make_pair(3, 130), std::make_pair(4, 62), std::make_pair(5, 29)};
  397. for(int b=0; b<ARRAY_COUNT(lockedIfNotDestroyed); ++b)
  398. {
  399. if(si.wallState[lockedIfNotDestroyed[b].first] < 3)
  400. {
  401. accessibility[lockedIfNotDestroyed[b].second] = false;
  402. }
  403. }
  404. //gate
  405. if(attackerOwned && si.wallState[7] < 3) //if it attacker's unit and gate is not destroyed
  406. {
  407. accessibility[95] = accessibility[96] = false; //block gate's hexes
  408. }
  409. }
  410. //occupyability
  411. if(addOccupiable && twoHex)
  412. {
  413. std::set<int> rem; //tiles to unlock
  414. for(int h=0; h<BFIELD_HEIGHT; ++h)
  415. {
  416. for(int w=1; w<BFIELD_WIDTH-1; ++w)
  417. {
  418. int hex = h * BFIELD_WIDTH + w;
  419. if(!isAccessible(hex, accessibility, twoHex, attackerOwned, flying, true)
  420. && (attackerOwned ? isAccessible(hex+1, accessibility, twoHex, attackerOwned, flying, true) : isAccessible(hex-1, accessibility, twoHex, attackerOwned, flying, true) )
  421. )
  422. rem.insert(hex);
  423. }
  424. }
  425. occupyable = rem;
  426. /*for(std::set<int>::const_iterator it = rem.begin(); it != rem.end(); ++it)
  427. {
  428. accessibility[*it] = true;
  429. }*/
  430. }
  431. }
  432. bool BattleInfo::isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos)
  433. {
  434. if(flying && !lastPos)
  435. return true;
  436. if(twoHex)
  437. {
  438. //if given hex is accessible and appropriate adjacent one is free too
  439. return accessibility[hex] && accessibility[hex + (attackerOwned ? -1 : 1 )];
  440. }
  441. else
  442. {
  443. return accessibility[hex];
  444. }
  445. }
  446. void BattleInfo::makeBFS(int start, bool *accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const //both pointers must point to the at least 187-elements int arrays
  447. {
  448. //inits
  449. for(int b=0; b<BFIELD_SIZE; ++b)
  450. predecessor[b] = -1;
  451. for(int g=0; g<BFIELD_SIZE; ++g)
  452. dists[g] = 100000000;
  453. std::queue< std::pair<int, bool> > hexq; //bfs queue <hex, accessible> (second filed used only if fillPredecessors is true)
  454. hexq.push(std::make_pair(start, true));
  455. dists[hexq.front().first] = 0;
  456. int curNext = -1; //for bfs loop only (helper var)
  457. while(!hexq.empty()) //bfs loop
  458. {
  459. std::pair<int, bool> curHex = hexq.front();
  460. std::vector<int> neighbours = neighbouringTiles(curHex.first);
  461. hexq.pop();
  462. for(unsigned int nr=0; nr<neighbours.size(); nr++)
  463. {
  464. curNext = neighbours[nr]; //if(!accessibility[curNext] || (dists[curHex]+1)>=dists[curNext])
  465. bool accessible = isAccessible(curNext, accessibility, twoHex, attackerOwned, flying, dists[curHex.first]+1 == dists[curNext]);
  466. if( dists[curHex.first]+1 >= dists[curNext] )
  467. continue;
  468. if(accessible && curHex.second)
  469. {
  470. hexq.push(std::make_pair(curNext, true));
  471. dists[curNext] = dists[curHex.first] + 1;
  472. }
  473. else if(fillPredecessors && !(accessible && !curHex.second))
  474. {
  475. hexq.push(std::make_pair(curNext, false));
  476. dists[curNext] = dists[curHex.first] + 1;
  477. }
  478. predecessor[curNext] = curHex.first;
  479. }
  480. }
  481. };
  482. std::vector<int> BattleInfo::getAccessibility(int stackID, bool addOccupiable) const
  483. {
  484. std::vector<int> ret;
  485. bool ac[BFIELD_SIZE];
  486. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  487. if(s->position < 0) //turrets
  488. return std::vector<int>();
  489. std::set<int> occupyable;
  490. getAccessibilityMap(ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, addOccupiable, occupyable, s->hasFeatureOfType(StackFeature::FLYING), stackID);
  491. int pr[BFIELD_SIZE], dist[BFIELD_SIZE];
  492. makeBFS(s->position, ac, pr, dist, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), false);
  493. if(s->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  494. {
  495. if(!addOccupiable)
  496. {
  497. std::vector<int> rem;
  498. for(int b=0; b<BFIELD_SIZE; ++b)
  499. {
  500. //don't take into account most left and most right columns of hexes
  501. if( b % BFIELD_WIDTH == 0 || b % BFIELD_WIDTH == BFIELD_WIDTH - 1 )
  502. continue;
  503. if( ac[b] && !(s->attackerOwned ? ac[b-1] : ac[b+1]) )
  504. {
  505. rem.push_back(b);
  506. }
  507. }
  508. for(unsigned int g=0; g<rem.size(); ++g)
  509. {
  510. ac[rem[g]] = false;
  511. }
  512. //removing accessibility for side hexes
  513. for(int v=0; v<BFIELD_SIZE; ++v)
  514. if(s->attackerOwned ? (v%BFIELD_WIDTH)==1 : (v%BFIELD_WIDTH)==(BFIELD_WIDTH - 2))
  515. ac[v] = false;
  516. }
  517. }
  518. for (int i=0; i < BFIELD_SIZE ; ++i) {
  519. if(
  520. ( ( !addOccupiable && dist[i] <= s->Speed() && ac[i] ) || ( addOccupiable && dist[i] <= s->Speed() && isAccessible(i, ac, s->hasFeatureOfType(StackFeature::DOUBLE_WIDE), s->attackerOwned, s->hasFeatureOfType(StackFeature::FLYING), true) ) )//we can reach it
  521. || (vstd::contains(occupyable, i) && ( dist[ i + (s->attackerOwned ? 1 : -1 ) ] <= s->Speed() ) &&
  522. ac[i + (s->attackerOwned ? 1 : -1 )] ) //it's occupyable and we can reach adjacent hex
  523. )
  524. {
  525. ret.push_back(i);
  526. }
  527. }
  528. return ret;
  529. }
  530. bool BattleInfo::isStackBlocked(int ID)
  531. {
  532. CStack *our = getStack(ID);
  533. if(our->hasFeatureOfType(StackFeature::SIEGE_WEAPON)) //siege weapons cannot be blocked
  534. return false;
  535. for(unsigned int i=0; i<stacks.size();i++)
  536. {
  537. if( !stacks[i]->alive()
  538. || stacks[i]->owner==our->owner
  539. )
  540. continue; //we omit dead and allied stacks
  541. if(stacks[i]->hasFeatureOfType(StackFeature::DOUBLE_WIDE))
  542. {
  543. if( mutualPosition(stacks[i]->position, our->position) >= 0
  544. || mutualPosition(stacks[i]->position + (stacks[i]->attackerOwned ? -1 : 1), our->position) >= 0)
  545. return true;
  546. }
  547. else
  548. {
  549. if( mutualPosition(stacks[i]->position, our->position) >= 0 )
  550. return true;
  551. }
  552. }
  553. return false;
  554. }
  555. signed char BattleInfo::mutualPosition(int hex1, int hex2)
  556. {
  557. if(hex2 == hex1 - ( (hex1/17)%2 ? 18 : 17 )) //top left
  558. return 0;
  559. if(hex2 == hex1 - ( (hex1/17)%2 ? 17 : 16 )) //top right
  560. return 1;
  561. if(hex2 == hex1 - 1 && hex1%17 != 0) //left
  562. return 5;
  563. if(hex2 == hex1 + 1 && hex1%17 != 16) //right
  564. return 2;
  565. if(hex2 == hex1 + ( (hex1/17)%2 ? 16 : 17 )) //bottom left
  566. return 4;
  567. if(hex2 == hex1 + ( (hex1/17)%2 ? 17 : 18 )) //bottom right
  568. return 3;
  569. return -1;
  570. }
  571. std::vector<int> BattleInfo::neighbouringTiles(int hex)
  572. {
  573. #define CHECK_AND_PUSH(tile) {int hlp = (tile); if(hlp>=0 && hlp<BFIELD_SIZE && (hlp%BFIELD_WIDTH!=16) && hlp%BFIELD_WIDTH) ret.push_back(hlp);}
  574. std::vector<int> ret;
  575. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 18 : 17 ));
  576. CHECK_AND_PUSH(hex - ( (hex/17)%2 ? 17 : 16 ));
  577. CHECK_AND_PUSH(hex - 1);
  578. CHECK_AND_PUSH(hex + 1);
  579. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 16 : 17 ));
  580. CHECK_AND_PUSH(hex + ( (hex/17)%2 ? 17 : 18 ));
  581. #undef CHECK_AND_PUSH
  582. return ret;
  583. }
  584. std::pair< std::vector<int>, int > BattleInfo::getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned)
  585. {
  586. int predecessor[BFIELD_SIZE]; //for getting the Path
  587. int dist[BFIELD_SIZE]; //calculated distances
  588. makeBFS(start, accessibility, predecessor, dist, twoHex, attackerOwned, flyingCreature, false);
  589. if(predecessor[dest] == -1) //cannot reach destination
  590. {
  591. return std::make_pair(std::vector<int>(), 0);
  592. }
  593. //making the Path
  594. std::vector<int> path;
  595. int curElem = dest;
  596. while(curElem != start)
  597. {
  598. path.push_back(curElem);
  599. curElem = predecessor[curElem];
  600. }
  601. return std::make_pair(path, dist[dest]);
  602. }
  603. int CStack::valOfFeatures(StackFeature::ECombatFeatures type, int subtype, int turn) const
  604. {
  605. int ret = 0;
  606. if(subtype == -1024) //any subtype
  607. {
  608. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  609. if(i->type == type && (!turn || i->turnsRemain > turn))
  610. ret += i->value;
  611. }
  612. else //given subtype
  613. {
  614. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  615. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  616. ret += i->value;
  617. }
  618. return ret;
  619. }
  620. bool CStack::hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype, int turn) const
  621. {
  622. if(subtype == -1024) //any subtype
  623. {
  624. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  625. if(i->type == type && (!turn || i->turnsRemain > turn))
  626. return true;
  627. }
  628. else //given subtype
  629. {
  630. for(std::vector<StackFeature>::const_iterator i=features.begin(); i != features.end(); i++)
  631. if(i->type == type && i->subtype == subtype && (!turn || i->turnsRemain > turn))
  632. return true;
  633. }
  634. return false;
  635. }
  636. CStack::CStack(CCreature * C, int A, int O, int I, bool AO, int S)
  637. :ID(I), creature(C), amount(A), baseAmount(A), firstHPleft(C->hitPoints), owner(O), slot(S), attackerOwned(AO), position(-1),
  638. counterAttacks(1), shots(C->shots), features(C->abilities)
  639. {
  640. //additional retaliations
  641. for(int h=0; h<C->abilities.size(); ++h)
  642. {
  643. if(C->abilities[h].type == StackFeature::ADDITIONAL_RETALIATION)
  644. {
  645. counterAttacks += C->abilities[h].value;
  646. }
  647. }
  648. //alive state indication
  649. state.insert(ALIVE);
  650. }
  651. ui32 CStack::Speed( int turn /*= 0*/ ) const
  652. {
  653. if(hasFeatureOfType(StackFeature::SIEGE_WEAPON, -1024, turn)) //war machnes cannot move
  654. return 0;
  655. int speed = creature->speed;
  656. speed += valOfFeatures(StackFeature::SPEED_BONUS, -1024, turn);
  657. int percentBonus = 0;
  658. for(int g=0; g<features.size(); ++g)
  659. {
  660. if(features[g].type == StackFeature::SPEED_BONUS)
  661. {
  662. percentBonus += features[g].additionalInfo;
  663. }
  664. }
  665. speed = ((100 + percentBonus) * speed)/100;
  666. //bind effect check
  667. if(getEffect(72))
  668. {
  669. return 0;
  670. }
  671. return speed;
  672. }
  673. const CStack::StackEffect * CStack::getEffect( ui16 id, int turn /*= 0*/ ) const
  674. {
  675. for (unsigned int i=0; i< effects.size(); i++)
  676. if(effects[i].id == id)
  677. if(!turn || effects[i].turnsRemain > turn)
  678. return &effects[i];
  679. return NULL;
  680. }
  681. ui8 CStack::howManyEffectsSet(ui16 id) const
  682. {
  683. ui8 ret = 0;
  684. for (unsigned int i=0; i< effects.size(); i++)
  685. if(effects[i].id == id) //effect found
  686. {
  687. ++ret;
  688. }
  689. return ret;
  690. }
  691. si8 CStack::Morale() const
  692. {
  693. si8 ret = morale;
  694. if(hasFeatureOfType(StackFeature::NON_LIVING) || hasFeatureOfType(StackFeature::UNDEAD) || hasFeatureOfType(StackFeature::NO_MORALE))
  695. return 0;
  696. ret += valOfFeatures(StackFeature::MORALE_BONUS); //mirth & sorrow & other
  697. if(hasFeatureOfType(StackFeature::SELF_MORALE)) //eg. minotaur
  698. {
  699. ret = std::max<si8>(ret, +1);
  700. }
  701. if(ret > 3) ret = 3;
  702. if(ret < -3) ret = -3;
  703. return ret;
  704. }
  705. si8 CStack::Luck() const
  706. {
  707. si8 ret = luck;
  708. if(hasFeatureOfType(StackFeature::NO_LUCK))
  709. return 0;
  710. ret += valOfFeatures(StackFeature::LUCK_BONUS); //fortune & misfortune & other
  711. if(hasFeatureOfType(StackFeature::SELF_LUCK)) //eg. halfling
  712. {
  713. ret = std::max<si8>(ret, +1);
  714. }
  715. if(ret > 3) ret = 3;
  716. if(ret < -3) ret = -3;
  717. return ret;
  718. }
  719. si32 CStack::Attack() const
  720. {
  721. si32 ret = creature->attack; //value to be returned
  722. if(hasFeatureOfType(StackFeature::IN_FRENZY)) //frenzy for attacker
  723. {
  724. ret += si32(VLC->spellh->spells[56].powers[getEffect(56)->level]/100.0) * Defense(false);
  725. }
  726. ret += valOfFeatures(StackFeature::ATTACK_BONUS);
  727. return ret;
  728. }
  729. si32 CStack::Defense(bool withFrenzy /*= true*/) const
  730. {
  731. si32 ret = creature->defence;
  732. if(withFrenzy && getEffect(56)) //frenzy for defender
  733. {
  734. return 0;
  735. }
  736. ret += valOfFeatures(StackFeature::DEFENCE_BONUS);
  737. return ret;
  738. }
  739. ui16 CStack::MaxHealth() const
  740. {
  741. return creature->hitPoints + valOfFeatures(StackFeature::HP_BONUS);
  742. }
  743. bool CStack::willMove(int turn /*= 0*/) const
  744. {
  745. return ( turn ? true : !vstd::contains(state, DEFENDING) )
  746. && !moved(turn)
  747. && canMove(turn);
  748. }
  749. bool CStack::canMove( int turn /*= 0*/ ) const
  750. {
  751. return alive()
  752. && !hasFeatureOfType(StackFeature::NOT_ACTIVE, -1024, turn); //eg. Ammo Cart
  753. }
  754. bool CStack::moved( int turn /*= 0*/ ) const
  755. {
  756. if(!turn)
  757. return vstd::contains(state, MOVED);
  758. else
  759. return false;
  760. }
  761. CGHeroInstance * CGameState::HeroesPool::pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const
  762. {
  763. CGHeroInstance *ret = NULL;
  764. if(player<0 || player>=PLAYER_LIMIT)
  765. {
  766. tlog1 << "Cannot pick hero for " << town->Name() << ". Wrong owner!\n";
  767. return NULL;
  768. }
  769. std::vector<CGHeroInstance *> pool;
  770. if(native)
  771. {
  772. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  773. {
  774. if(pavailable.find(i->first)->second & 1<<player
  775. && i->second->type->heroType/2 == town->typeID)
  776. {
  777. pool.push_back(i->second);
  778. }
  779. }
  780. if(!pool.size())
  781. {
  782. tlog1 << "Cannot pick native hero for " << player << ". Picking any...\n";
  783. return pickHeroFor(false, player, town, available);
  784. }
  785. else
  786. {
  787. ret = pool[rand()%pool.size()];
  788. }
  789. }
  790. else
  791. {
  792. int sum=0, r;
  793. for(std::map<ui32,CGHeroInstance *>::iterator i=available.begin(); i!=available.end(); i++)
  794. {
  795. if(pavailable.find(i->first)->second & 1<<player)
  796. {
  797. pool.push_back(i->second);
  798. sum += i->second->type->heroClass->selectionProbability[town->typeID];
  799. }
  800. }
  801. if(!pool.size())
  802. {
  803. tlog1 << "There are no heroes available for player " << player<<"!\n";
  804. return NULL;
  805. }
  806. r = rand()%sum;
  807. for(unsigned int i=0; i<pool.size(); i++)
  808. {
  809. r -= pool[i]->type->heroClass->selectionProbability[town->typeID];
  810. if(r<0)
  811. ret = pool[i];
  812. }
  813. if(!ret)
  814. ret = pool.back();
  815. }
  816. available.erase(ret->subID);
  817. return ret;
  818. }
  819. //void CGameState::apply(CPack * pack)
  820. //{
  821. // while(!mx->try_lock())
  822. // boost::this_thread::sleep(boost::posix_time::milliseconds(50)); //give other threads time to finish
  823. // //applyNL(pack);
  824. // mx->unlock();
  825. //}
  826. int CGameState::pickHero(int owner)
  827. {
  828. int h=-1;
  829. if(!map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero
  830. return h;
  831. int f = scenarioOps->getIthPlayersSettings(owner).castle;
  832. int i=0;
  833. do //try to find free hero of our faction
  834. {
  835. i++;
  836. h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC->
  837. } while( map->getHero(h) && i<175);
  838. if(i>174) //probably no free heroes - there's no point in further search, we'll take first free
  839. {
  840. tlog3 << "Warning: cannot find free hero - trying to get first available..."<<std::endl;
  841. for(int j=0; j<HEROES_PER_TYPE * 2 * F_NUMBER; j++)
  842. if(!map->getHero(j))
  843. h=j;
  844. }
  845. return h;
  846. }
  847. CGHeroInstance *CGameState::getHero(int objid)
  848. {
  849. if(objid<0 || objid>=map->objects.size() || map->objects[objid]->ID!=HEROI_TYPE)
  850. return NULL;
  851. return static_cast<CGHeroInstance *>(map->objects[objid]);
  852. }
  853. CGTownInstance *CGameState::getTown(int objid)
  854. {
  855. if(objid<0 || objid>=map->objects.size())
  856. return NULL;
  857. return static_cast<CGTownInstance *>(map->objects[objid]);
  858. }
  859. std::pair<int,int> CGameState::pickObject(CGObjectInstance *obj)
  860. {
  861. switch(obj->ID)
  862. {
  863. case 65: //random artifact
  864. return std::pair<int,int>(5,(ran()%136)+7); //the only reasonable range - there are siege weapons and blanks we must ommit
  865. case 66: //random treasure artifact
  866. return std::pair<int,int>(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id);
  867. case 67: //random minor artifact
  868. return std::pair<int,int>(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id);
  869. case 68: //random major artifact
  870. return std::pair<int,int>(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id);
  871. case 69: //random relic artifact
  872. return std::pair<int,int>(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id);
  873. case 70: //random hero
  874. {
  875. return std::pair<int,int>(HEROI_TYPE,pickHero(obj->tempOwner));
  876. }
  877. case 71: //random monster
  878. {
  879. int r;
  880. do
  881. {
  882. r = ran()%197;
  883. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  884. return std::pair<int,int>(54,r);
  885. }
  886. case 72: //random monster lvl1
  887. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  888. case 73: //random monster lvl2
  889. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  890. case 74: //random monster lvl3
  891. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  892. case 75: //random monster lvl4
  893. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  894. case 76: //random resource
  895. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  896. case 77: //random town
  897. {
  898. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  899. f;
  900. if(align>PLAYER_LIMIT-1)//same as owner / random
  901. {
  902. if(obj->tempOwner > PLAYER_LIMIT-1)
  903. f = -1; //random
  904. else
  905. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  906. }
  907. else
  908. {
  909. f = scenarioOps->getIthPlayersSettings(align).castle;
  910. }
  911. if(f<0) f = ran()%VLC->townh->towns.size();
  912. return std::pair<int,int>(TOWNI_TYPE,f);
  913. }
  914. case 162: //random monster lvl5
  915. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  916. case 163: //random monster lvl6
  917. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  918. case 164: //random monster lvl7
  919. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  920. case 216: //random dwelling
  921. {
  922. int faction = ran()%F_NUMBER;
  923. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(obj->info);
  924. if (info->asCastle)
  925. {
  926. for(unsigned int i=0;i<map->objects.size();i++)
  927. {
  928. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  929. {
  930. randomizeObject(map->objects[i]); //we have to randomize the castle first
  931. faction = map->objects[i]->subID;
  932. break;
  933. }
  934. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  935. {
  936. faction = map->objects[i]->subID;
  937. break;
  938. }
  939. }
  940. }
  941. else
  942. {
  943. while((!(info->castles[0]&(1<<faction))))
  944. {
  945. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  946. break;
  947. faction = ran()%F_NUMBER;
  948. }
  949. }
  950. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  951. int cid = VLC->townh->towns[faction].basicCreatures[level];
  952. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  953. if(VLC->objh->cregens[i]==cid)
  954. return std::pair<int,int>(17,i);
  955. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  956. return std::pair<int,int>(17,0);
  957. }
  958. case 217:
  959. {
  960. int faction = ran()%F_NUMBER;
  961. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(obj->info);
  962. if (info->asCastle)
  963. {
  964. for(unsigned int i=0;i<map->objects.size();i++)
  965. {
  966. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  967. {
  968. randomizeObject(map->objects[i]); //we have to randomize the castle first
  969. faction = map->objects[i]->subID;
  970. break;
  971. }
  972. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  973. {
  974. faction = map->objects[i]->subID;
  975. break;
  976. }
  977. }
  978. }
  979. else
  980. {
  981. while((!(info->castles[0]&(1<<faction))))
  982. {
  983. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  984. break;
  985. faction = ran()%F_NUMBER;
  986. }
  987. }
  988. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  989. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  990. if(VLC->objh->cregens[i]==cid)
  991. return std::pair<int,int>(17,i);
  992. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  993. return std::pair<int,int>(17,0);
  994. }
  995. case 218:
  996. {
  997. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(obj->info);
  998. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  999. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  1000. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  1001. if(VLC->objh->cregens[i]==cid)
  1002. return std::pair<int,int>(17,i);
  1003. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  1004. return std::pair<int,int>(17,0);
  1005. }
  1006. }
  1007. return std::pair<int,int>(-1,-1);
  1008. }
  1009. void CGameState::randomizeObject(CGObjectInstance *cur)
  1010. {
  1011. std::pair<int,int> ran = pickObject(cur);
  1012. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  1013. {
  1014. if(cur->ID==TOWNI_TYPE) //town - set def
  1015. {
  1016. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1017. if(t->hasCapitol())
  1018. t->defInfo = capitols[t->subID];
  1019. else if(t->hasFort())
  1020. t->defInfo = forts[t->subID];
  1021. else
  1022. t->defInfo = villages[t->subID];
  1023. }
  1024. return;
  1025. }
  1026. else if(ran.first==HEROI_TYPE)//special code for hero
  1027. {
  1028. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1029. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1030. cur->ID = ran.first;
  1031. h->portrait = cur->subID = ran.second;
  1032. h->type = VLC->heroh->heroes[ran.second];
  1033. map->heroes.push_back(h);
  1034. return; //TODO: maybe we should do something with definfo?
  1035. }
  1036. else if(ran.first==TOWNI_TYPE)//special code for town
  1037. {
  1038. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1039. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1040. cur->ID = ran.first;
  1041. cur->subID = ran.second;
  1042. t->town = &VLC->townh->towns[ran.second];
  1043. if(t->hasCapitol())
  1044. t->defInfo = capitols[t->subID];
  1045. else if(t->hasFort())
  1046. t->defInfo = forts[t->subID];
  1047. else
  1048. t->defInfo = villages[t->subID];
  1049. map->towns.push_back(t);
  1050. return;
  1051. }
  1052. //we have to replace normal random object
  1053. cur->ID = ran.first;
  1054. cur->subID = ran.second;
  1055. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1056. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1057. if(!cur->defInfo)
  1058. {
  1059. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1060. return;
  1061. }
  1062. map->addBlockVisTiles(cur);
  1063. }
  1064. int CGameState::getDate(int mode) const
  1065. {
  1066. int temp;
  1067. switch (mode)
  1068. {
  1069. case 0:
  1070. return day;
  1071. break;
  1072. case 1:
  1073. temp = (day)%7;
  1074. if (temp)
  1075. return temp;
  1076. else return 7;
  1077. break;
  1078. case 2:
  1079. temp = ((day-1)/7)+1;
  1080. if (!(temp%4))
  1081. return 4;
  1082. else
  1083. return (temp%4);
  1084. break;
  1085. case 3:
  1086. return ((day-1)/28)+1;
  1087. break;
  1088. }
  1089. return 0;
  1090. }
  1091. CGameState::CGameState()
  1092. {
  1093. mx = new boost::shared_mutex();
  1094. map = NULL;
  1095. curB = NULL;
  1096. scenarioOps = NULL;
  1097. applierGs = new CGSApplier;
  1098. objCaller = new CObjectCallersHandler;
  1099. }
  1100. CGameState::~CGameState()
  1101. {
  1102. delete mx;
  1103. delete map;
  1104. delete curB;
  1105. delete scenarioOps;
  1106. delete applierGs;
  1107. delete objCaller;
  1108. }
  1109. void CGameState::init(StartInfo * si, Mapa * map, int Seed)
  1110. {
  1111. day = 0;
  1112. seed = Seed;
  1113. ran.seed((boost::int32_t)seed);
  1114. scenarioOps = si;
  1115. this->map = map;
  1116. loadTownDInfos();
  1117. //picking random factions for players
  1118. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1119. {
  1120. if(scenarioOps->playerInfos[i].castle==-1)
  1121. {
  1122. int f;
  1123. do
  1124. {
  1125. f = ran()%F_NUMBER;
  1126. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1127. scenarioOps->playerInfos[i].castle = f;
  1128. }
  1129. }
  1130. //randomizing objects
  1131. for(unsigned int no=0; no<map->objects.size(); ++no)
  1132. {
  1133. randomizeObject(map->objects[no]);
  1134. if(map->objects[no]->ID==26)
  1135. {
  1136. map->objects[no]->defInfo->handler=NULL;
  1137. }
  1138. map->objects[no]->hoverName = VLC->generaltexth->names[map->objects[no]->ID];
  1139. }
  1140. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1141. /*********give starting hero****************************************/
  1142. for(int i=0;i<PLAYER_LIMIT;i++)
  1143. {
  1144. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1145. {
  1146. int3 hpos = map->players[i].posOfMainTown;
  1147. hpos.x+=1;// hpos.y+=1;
  1148. int j;
  1149. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1150. if(scenarioOps->playerInfos[j].color == i)
  1151. break;
  1152. if(j == scenarioOps->playerInfos.size())
  1153. continue;
  1154. int h=pickHero(i);
  1155. if(scenarioOps->playerInfos[j].hero == -1)
  1156. scenarioOps->playerInfos[j].hero = h;
  1157. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1158. nnn->id = map->objects.size();
  1159. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1160. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1161. {
  1162. if(map->towns[o]->pos == hpos)
  1163. {
  1164. map->towns[o]->visitingHero = nnn;
  1165. nnn->visitedTown = map->towns[o];
  1166. nnn->inTownGarrison = false;
  1167. break;
  1168. }
  1169. }
  1170. nnn->initHero();
  1171. map->heroes.push_back(nnn);
  1172. map->objects.push_back(nnn);
  1173. map->addBlockVisTiles(nnn);
  1174. }
  1175. }
  1176. /*********creating players entries in gs****************************************/
  1177. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1178. {
  1179. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1180. ins.second.color=ins.first;
  1181. ins.second.serial=i;
  1182. ins.second.human = scenarioOps->playerInfos[i].human;
  1183. players.insert(ins);
  1184. }
  1185. /******************RESOURCES****************************************************/
  1186. //TODO: computer player should receive other amount of resource than computer (depending on difficulty)
  1187. std::vector<int> startres;
  1188. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1189. int k;
  1190. for (int j=0;j<scenarioOps->difficulty;j++)
  1191. {
  1192. tis >> k;
  1193. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1194. tis>>k;
  1195. }
  1196. tis >> k;
  1197. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1198. {
  1199. tis >> k;
  1200. startres.push_back(k);
  1201. }
  1202. tis.close();
  1203. tis.clear();
  1204. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1205. {
  1206. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1207. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1208. (*i).second.resources[x] = startres[x];
  1209. }
  1210. tis.open(DATA_DIR "/config/resources.txt");
  1211. tis >> k;
  1212. int pom;
  1213. for(int i=0;i<k;i++)
  1214. {
  1215. tis >> pom;
  1216. resVals.push_back(pom);
  1217. }
  1218. /*************************HEROES************************************************/
  1219. std::set<int> hids;
  1220. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1221. if(map->allowedHeroes[i])
  1222. hids.insert(i);
  1223. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1224. {
  1225. if (map->heroes[i]->getOwner()<0)
  1226. {
  1227. tlog2 << "Warning - hero with uninitialized owner!\n";
  1228. continue;
  1229. }
  1230. CGHeroInstance * vhi = (map->heroes[i]);
  1231. vhi->initHero();
  1232. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1233. hids.erase(vhi->subID);
  1234. }
  1235. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1236. {
  1237. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1238. continue;
  1239. map->predefinedHeroes[i]->initHero();
  1240. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1241. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1242. hids.erase(map->predefinedHeroes[i]->subID);
  1243. }
  1244. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go into the pool
  1245. {
  1246. CGHeroInstance * vhi = new CGHeroInstance();
  1247. vhi->initHero(hid);
  1248. hpool.heroesPool[hid] = vhi;
  1249. hpool.pavailable[hid] = 0xff;
  1250. }
  1251. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1252. {
  1253. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1254. }
  1255. /*************************FOG**OF**WAR******************************************/
  1256. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1257. {
  1258. k->second.fogOfWarMap.resize(map->width);
  1259. for(int g=0; g<map->width; ++g)
  1260. k->second.fogOfWarMap[g].resize(map->height);
  1261. for(int g=-0; g<map->width; ++g)
  1262. for(int h=0; h<map->height; ++h)
  1263. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1264. for(int g=0; g<map->width; ++g)
  1265. for(int h=0; h<map->height; ++h)
  1266. for(int v=0; v<map->twoLevel+1; ++v)
  1267. k->second.fogOfWarMap[g][h][v] = 0;
  1268. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1269. {
  1270. if(obj->tempOwner != k->first) continue; //not a flagged object
  1271. int3 objCenter = obj->getSightCenter();
  1272. int radious = obj->getSightRadious();
  1273. for (int xd = std::max<int>(objCenter.x - radious , 0); xd <= std::min<int>(objCenter.x + radious, map->width - 1); xd++)
  1274. {
  1275. for (int yd = std::max<int>(objCenter.y - radious, 0); yd <= std::min<int>(objCenter.y + radious, map->height - 1); yd++)
  1276. {
  1277. double distance = objCenter.dist2d(int3(xd,yd,objCenter.z)) - 0.5;
  1278. if(distance <= radious)
  1279. k->second.fogOfWarMap[xd][yd][objCenter.z] = 1;
  1280. }
  1281. }
  1282. }
  1283. //for(int xd=0; xd<map->width; ++xd) //revealing part of map around heroes
  1284. //{
  1285. // for(int yd=0; yd<map->height; ++yd)
  1286. // {
  1287. // for(int ch=0; ch<k->second.heroes.size(); ++ch)
  1288. // {
  1289. // int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
  1290. // int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
  1291. // if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
  1292. // k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
  1293. // }
  1294. // }
  1295. //}
  1296. //starting bonus
  1297. if(si->playerInfos[k->second.serial].bonus==brandom)
  1298. si->playerInfos[k->second.serial].bonus = ran()%3;
  1299. switch(si->playerInfos[k->second.serial].bonus)
  1300. {
  1301. case bgold:
  1302. k->second.resources[6] += 500 + (ran()%6)*100;
  1303. break;
  1304. case bresource:
  1305. {
  1306. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1307. if(res == 127)
  1308. {
  1309. k->second.resources[0] += 5 + ran()%6;
  1310. k->second.resources[2] += 5 + ran()%6;
  1311. }
  1312. else
  1313. {
  1314. k->second.resources[res] += 3 + ran()%4;
  1315. }
  1316. break;
  1317. }
  1318. case bartifact:
  1319. {
  1320. if(!k->second.heroes.size())
  1321. {
  1322. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1323. break;
  1324. }
  1325. CArtifact *toGive;
  1326. do
  1327. {
  1328. toGive = VLC->arth->treasures[ran() % VLC->arth->treasures.size()];
  1329. } while (!map->allowedArtifact[toGive->id]);
  1330. CGHeroInstance *hero = k->second.heroes[0];
  1331. std::vector<ui16>::iterator slot = vstd::findFirstNot(hero->artifWorn,toGive->possibleSlots);
  1332. if(slot!=toGive->possibleSlots.end())
  1333. {
  1334. hero->artifWorn[*slot] = toGive->id;
  1335. hero->recreateArtBonuses();
  1336. }
  1337. else
  1338. hero->artifacts.push_back(toGive->id);
  1339. }
  1340. }
  1341. }
  1342. /****************************TOWNS************************************************/
  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. //init spells
  1361. vti->spells.resize(SPELL_LEVELS);
  1362. CSpell *s;
  1363. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1364. {
  1365. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1366. vti->spells[s->level-1].push_back(s->id);
  1367. vti->possibleSpells -= s->id;
  1368. }
  1369. while(vti->possibleSpells.size())
  1370. {
  1371. ui32 total=0, sel=-1;
  1372. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1373. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1374. int r = (total)? ran()%total : -1;
  1375. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1376. {
  1377. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1378. if(r<0)
  1379. {
  1380. sel = ps;
  1381. break;
  1382. }
  1383. }
  1384. if(sel<0)
  1385. sel=0;
  1386. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1387. vti->spells[s->level-1].push_back(s->id);
  1388. vti->possibleSpells -= s->id;
  1389. }
  1390. //init garrisons
  1391. for (std::map<si32,std::pair<ui32,si32> >::iterator j=vti->army.slots.begin(); j!=vti->army.slots.end();j++)
  1392. {
  1393. if(j->second.first > 196 && j->second.first < 211)
  1394. {
  1395. if(j->second.first%2)
  1396. j->second.first = vti->town->basicCreatures[ (j->second.first-197) / 2 ];
  1397. else
  1398. j->second.first = vti->town->upgradedCreatures[ (j->second.first-197) / 2 ];
  1399. }
  1400. }
  1401. if(vti->getOwner() != 255)
  1402. getPlayer(vti->getOwner())->towns.push_back(vti);
  1403. }
  1404. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1405. {
  1406. if(k->first==-1 || k->first==255)
  1407. continue;
  1408. //init visiting and garrisoned heroes
  1409. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1410. {
  1411. CGHeroInstance *h = k->second.heroes[l];
  1412. for(unsigned int m=0; m<k->second.towns.size();m++)
  1413. {
  1414. CGTownInstance *t = k->second.towns[m];
  1415. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1416. if(vistile == h->pos || h->pos==t->pos)
  1417. {
  1418. t->visitingHero = h;
  1419. h->visitedTown = t;
  1420. h->inTownGarrison = false;
  1421. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1422. {
  1423. map->removeBlockVisTiles(h);
  1424. h->pos.x -= 1;
  1425. map->addBlockVisTiles(h);
  1426. }
  1427. break;
  1428. }
  1429. }
  1430. }
  1431. }
  1432. for(unsigned int i=0; i<map->defy.size(); i++)
  1433. {
  1434. map->defy[i]->serial = i;
  1435. }
  1436. objCaller->preInit();
  1437. for(unsigned int i=0; i<map->objects.size(); i++)
  1438. {
  1439. map->objects[i]->initObj();
  1440. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1441. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1442. }
  1443. objCaller->postInit();
  1444. }
  1445. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1446. {
  1447. return true;
  1448. }
  1449. bool CGameState::battleCanFlee(int player)
  1450. {
  1451. if(!curB) //there is no battle
  1452. return false;
  1453. if(curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1454. || curB->heroes[0]->hasBonusOfType(HeroBonus::ENEMY_CANT_ESCAPE))
  1455. return false;
  1456. return true;
  1457. }
  1458. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1459. {
  1460. if(!curB)
  1461. return -1;
  1462. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1463. {
  1464. if((curB->stacks[g]->position == pos
  1465. || (curB->stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  1466. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1467. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1468. ))
  1469. && (!onlyAlive || curB->stacks[g]->alive())
  1470. )
  1471. return curB->stacks[g]->ID;
  1472. }
  1473. return -1;
  1474. }
  1475. int CGameState::battleGetBattlefieldType(int3 tile)
  1476. {
  1477. if(tile==int3() && curB)
  1478. tile = curB->tile;
  1479. else if(tile==int3() && !curB)
  1480. return -1;
  1481. const std::vector <CGObjectInstance*> & objs = map->objects;
  1482. for(int g=0; g<objs.size(); ++g)
  1483. {
  1484. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1485. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1486. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1487. ) //look only for objects covering given tile
  1488. continue;
  1489. switch(objs[g]->ID)
  1490. {
  1491. case 222: //clover field
  1492. return 19;
  1493. case 21: case 223: //cursed ground
  1494. return 22;
  1495. case 224: //evil fog
  1496. return 20;
  1497. case 225: //favourable winds
  1498. return 21;
  1499. case 226: //fiery fields
  1500. return 14;
  1501. case 227: //holy ground
  1502. return 18;
  1503. case 228: //lucid pools
  1504. return 17;
  1505. case 229: //magic clouds
  1506. return 16;
  1507. case 46: case 230: //magic plains
  1508. return 9;
  1509. case 231: //rocklands
  1510. return 15;
  1511. }
  1512. }
  1513. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1514. {
  1515. case TerrainTile::dirt:
  1516. return rand()%3+3;
  1517. case TerrainTile::sand:
  1518. return 2; //TODO: coast support
  1519. case TerrainTile::grass:
  1520. return rand()%2+6;
  1521. case TerrainTile::snow:
  1522. return rand()%2+10;
  1523. case TerrainTile::swamp:
  1524. return 13;
  1525. case TerrainTile::rough:
  1526. return 23;
  1527. case TerrainTile::subterranean:
  1528. return 12;
  1529. case TerrainTile::lava:
  1530. return 8;
  1531. case TerrainTile::water:
  1532. return 25;
  1533. case TerrainTile::rock:
  1534. return 15;
  1535. default:
  1536. return -1;
  1537. }
  1538. }
  1539. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1540. {
  1541. if(!curB)
  1542. return NULL;
  1543. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1544. }
  1545. UpgradeInfo CGameState::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
  1546. {
  1547. UpgradeInfo ret;
  1548. const CCreature *base = &VLC->creh->creatures[obj->army.slots.find(stackPos)->first];
  1549. if((obj->ID == TOWNI_TYPE) || ((obj->ID == HEROI_TYPE) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
  1550. {
  1551. const CGTownInstance * t;
  1552. if(obj->ID == TOWNI_TYPE)
  1553. t = static_cast<const CGTownInstance *>(obj);
  1554. else
  1555. t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
  1556. for(std::set<si32>::const_iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++)
  1557. {
  1558. if( (*i) >= 37 && (*i) < 44 ) //upgraded creature dwelling
  1559. {
  1560. int nid = t->town->upgradedCreatures[(*i)-37]; //upgrade offered by that building
  1561. if(base->upgrades.find(nid) != base->upgrades.end()) //possible upgrade
  1562. {
  1563. ret.newID.push_back(nid);
  1564. ret.cost.push_back(std::set<std::pair<int,int> >());
  1565. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1566. {
  1567. int dif = VLC->creh->creatures[nid].cost[j] - base->cost[j];
  1568. if(dif)
  1569. ret.cost[ret.cost.size()-1].insert(std::make_pair(j,dif));
  1570. }
  1571. }
  1572. }
  1573. }//end for
  1574. }
  1575. //TODO: check if hero ability makes some upgrades possible
  1576. if(ret.newID.size())
  1577. ret.oldID = base->idNumber;
  1578. return ret;
  1579. }
  1580. float CGameState::getMarketEfficiency( int player, int mode/*=0*/ )
  1581. {
  1582. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1583. if(mode) return -1; //todo - support other modes
  1584. int mcount = 0;
  1585. for(unsigned int i=0;i<getPlayer(player)->towns.size();i++)
  1586. if(vstd::contains(getPlayer(player)->towns[i]->builtBuildings,14))
  1587. mcount++;
  1588. float ret = std::min(((float)mcount+1.0f)/20.0f,0.5f);
  1589. return ret;
  1590. }
  1591. void CGameState::loadTownDInfos()
  1592. {
  1593. for(int i=0;i<F_NUMBER;i++)
  1594. {
  1595. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1596. forts[i] = VLC->dobjinfo->castles[i];
  1597. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1598. }
  1599. }
  1600. void CGameState::getNeighbours( const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand )
  1601. {
  1602. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1603. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1604. vec.clear();
  1605. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1606. {
  1607. const int3 hlp = tile + dirs[i];
  1608. if(!map->isInTheMap(hlp))
  1609. continue;
  1610. const TerrainTile &hlpt = map->getTile(hlp);
  1611. if((indeterminate(onLand) || onLand == (hlpt.tertype!=8) )
  1612. && hlpt.tertype!=9)
  1613. {
  1614. vec.push_back(hlp);
  1615. }
  1616. }
  1617. }
  1618. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1619. {
  1620. if(src == dest) //same tile
  1621. return 0;
  1622. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1623. &d = map->terrain[dest.x][dest.y][dest.z];
  1624. //get basic cost
  1625. int ret = h->getTileCost(d,s);
  1626. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1627. {
  1628. int old = ret;
  1629. ret *= 1.414213;
  1630. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1631. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1632. {
  1633. return remainingMovePoints;
  1634. }
  1635. }
  1636. int left = remainingMovePoints-ret;
  1637. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1638. {
  1639. std::vector<int3> vec;
  1640. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water);
  1641. for(size_t i=0; i < vec.size(); i++)
  1642. {
  1643. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1644. if(fcost <= left)
  1645. {
  1646. return ret;
  1647. }
  1648. }
  1649. ret = remainingMovePoints;
  1650. }
  1651. return ret;
  1652. }
  1653. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1654. {
  1655. int ret = 7; //allowed by default
  1656. //checking resources
  1657. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1658. if(!pom)return 8;
  1659. if(pom->Name().size()==0||pom->resources.size()==0)return 2;//TODO: why does this happen?
  1660. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1661. {
  1662. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1663. ret = 6; //lack of res
  1664. }
  1665. //checking for requirements
  1666. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][ID].begin();
  1667. ri != VLC->townh->requirements[t->subID][ID].end();
  1668. ri++ )
  1669. {
  1670. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1671. ret = 8; //lack of requirements - cannot build
  1672. }
  1673. //can we build it?
  1674. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1675. ret = 2; //forbidden
  1676. else if(t->builded >= MAX_BUILDING_PER_TURN)
  1677. ret = 5; //building limit
  1678. if(ID == 13) //capitol
  1679. {
  1680. for(unsigned int in = 0; in < map->towns.size(); in++)
  1681. {
  1682. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1683. {
  1684. ret = 0; //no more than one capitol
  1685. break;
  1686. }
  1687. }
  1688. }
  1689. else if(ID == 6) //shipyard
  1690. {
  1691. int3 t1(t->pos + int3(-1,3,0)),
  1692. t2(t->pos + int3(-3,3,0));
  1693. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1694. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1695. ret = 1; //lack of water
  1696. }
  1697. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1698. ret = 4;
  1699. return ret;
  1700. }
  1701. void CGameState::apply(CPack *pack)
  1702. {
  1703. ui16 typ = typeList.getTypeID(pack);
  1704. assert(typ >= 0);
  1705. applierGs->apps[typ]->applyOnGS(this,pack);
  1706. }
  1707. PlayerState * CGameState::getPlayer( ui8 color )
  1708. {
  1709. if(vstd::contains(players,color))
  1710. {
  1711. return &players[color];
  1712. }
  1713. else
  1714. {
  1715. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1716. return NULL;
  1717. }
  1718. }
  1719. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1720. {
  1721. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1722. return false;
  1723. int3 hpos = hero->getPosition(false);
  1724. tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1725. if (!hero->canWalkOnSea())
  1726. blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1727. else
  1728. blockLandSea = boost::logic::indeterminate;
  1729. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1730. //graph initialization
  1731. std::vector< std::vector<CPathNode> > graph;
  1732. graph.resize(map->width);
  1733. for(size_t i=0; i<graph.size(); ++i)
  1734. {
  1735. graph[i].resize(map->height);
  1736. for(size_t j=0; j<graph[i].size(); ++j)
  1737. {
  1738. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1739. CPathNode &node = graph[i][j];
  1740. node.accessible = !tinfo->blocked;
  1741. node.dist = -1;
  1742. node.theNodeBefore = NULL;
  1743. node.visited = false;
  1744. node.coord.x = i;
  1745. node.coord.y = j;
  1746. node.coord.z = dest.z;
  1747. if ((tinfo->tertype == TerrainTile::rock) //it's rock
  1748. || ((blockLandSea) && (tinfo->tertype == TerrainTile::water)) //it's sea and we cannot walk on sea
  1749. || ((!blockLandSea) && (tinfo->tertype != TerrainTile::water)) //it's land and we cannot walk on land
  1750. || !FoW[i][j][src.z] //tile is covered by the FoW
  1751. )
  1752. {
  1753. node.accessible = false;
  1754. }
  1755. }
  1756. }
  1757. //Special rules for the destination tile
  1758. {
  1759. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1760. CPathNode &d = graph[dest.x][dest.y];
  1761. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1762. if(t->visitable)
  1763. {
  1764. d.accessible = true; //for allowing visiting objects
  1765. }
  1766. if(blockLandSea && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1767. {
  1768. size_t i = 0;
  1769. for(; i < t->visitableObjects.size(); i++)
  1770. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1771. break;
  1772. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1773. }
  1774. else if(!blockLandSea && t->tertype != TerrainTile::water) //hero is moving by water
  1775. {
  1776. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1777. }
  1778. }
  1779. //graph initialized
  1780. //initial tile - set cost on 0 and add to the queue
  1781. graph[src.x][src.y].dist = 0;
  1782. std::queue<CPathNode> mq;
  1783. mq.push(graph[src.x][src.y]);
  1784. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1785. std::vector<int3> neighbours;
  1786. neighbours.reserve(8);
  1787. while(!mq.empty())
  1788. {
  1789. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1790. mq.pop();
  1791. if (cp.coord == dest) //it's destination tile
  1792. {
  1793. if (cp.dist < curDist) //that path is better than previous one
  1794. curDist = cp.dist;
  1795. continue;
  1796. }
  1797. else
  1798. {
  1799. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1800. continue;
  1801. }
  1802. //add accessible neighbouring nodes to the queue
  1803. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate);
  1804. for(unsigned int i=0; i < neighbours.size(); i++)
  1805. {
  1806. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1807. if(dp.accessible)
  1808. {
  1809. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1810. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1811. {
  1812. dp.dist = cp.dist + cost;
  1813. dp.theNodeBefore = &cp;
  1814. mq.push(dp);
  1815. }
  1816. }
  1817. }
  1818. }
  1819. CPathNode *curNode = &graph[dest.x][dest.y];
  1820. if(!curNode->theNodeBefore) //destination is not accessible
  1821. return false;
  1822. //fill ret with found path
  1823. ret.nodes.clear();
  1824. while(curNode->coord != graph[src.x][src.y].coord)
  1825. {
  1826. ret.nodes.push_back(*curNode);
  1827. curNode = curNode->theNodeBefore;
  1828. }
  1829. ret.nodes.push_back(graph[src.x][src.y]);
  1830. return true;
  1831. }
  1832. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1833. {
  1834. assert(hero);
  1835. if(src.x < 0)
  1836. src = hero->getPosition(false);
  1837. if(movement < 0)
  1838. movement = hero->movement;
  1839. out.hero = hero;
  1840. out.hpos = src;
  1841. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1842. {
  1843. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1844. return;
  1845. }
  1846. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1847. if (!hero->canWalkOnSea())
  1848. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1849. else
  1850. onLand = boost::logic::indeterminate;
  1851. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1852. //graph initialization
  1853. CGPathNode ***graph = out.nodes;
  1854. for(size_t i=0; i < out.sizes.x; ++i)
  1855. {
  1856. for(size_t j=0; j < out.sizes.y; ++j)
  1857. {
  1858. for(size_t k=0; k < out.sizes.z; ++k)
  1859. {
  1860. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1861. CGPathNode &node = graph[i][j][k];
  1862. node.accessible = (tinfo->blocked ? CGPathNode::BLOCKED : CGPathNode::ACCESSIBLE);
  1863. node.turns = 0xff;
  1864. node.moveRemains = 0;
  1865. node.coord.x = i;
  1866. node.coord.y = j;
  1867. node.coord.z = k;
  1868. node.land = tinfo->tertype != TerrainTile::water;
  1869. node.theNodeBefore = NULL;
  1870. if ( tinfo->tertype == TerrainTile::rock//it's rock
  1871. || onLand && !node.land //it's sea and we cannot walk on sea
  1872. || !onLand && node.land //it's land and we cannot walk on land
  1873. || !FoW[i][j][k] //tile is covered by the FoW
  1874. )
  1875. {
  1876. node.accessible = CGPathNode::BLOCKED;
  1877. }
  1878. else if(tinfo->visitable)
  1879. {
  1880. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  1881. {
  1882. if(tinfo->visitableObjects[ii]->blockVisit)
  1883. {
  1884. node.accessible = CGPathNode::BLOCKVIS;
  1885. break;
  1886. }
  1887. else
  1888. node.accessible = CGPathNode::VISITABLE;
  1889. }
  1890. }
  1891. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  1892. {
  1893. size_t i = 0;
  1894. for(; i < tinfo->visitableObjects.size(); i++)
  1895. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1896. break;
  1897. if(i < tinfo->visitableObjects.size())
  1898. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  1899. }
  1900. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  1901. {
  1902. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  1903. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  1904. }
  1905. }
  1906. }
  1907. }
  1908. //graph initialized
  1909. //initial tile - set cost on 0 and add to the queue
  1910. graph[src.x][src.y][src.z].turns = 0;
  1911. graph[src.x][src.y][src.z].moveRemains = movement;
  1912. std::queue<CGPathNode*> mq;
  1913. mq.push(&graph[src.x][src.y][src.z]);
  1914. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1915. std::vector<int3> neighbours;
  1916. neighbours.reserve(8);
  1917. while(!mq.empty())
  1918. {
  1919. CGPathNode *cp = mq.front();
  1920. mq.pop();
  1921. const TerrainTile &ct = map->getTile(cp->coord);
  1922. int movement = cp->moveRemains, turn = cp->turns;
  1923. if(!movement)
  1924. {
  1925. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1926. turn++;
  1927. }
  1928. //add accessible neighbouring nodes to the queue
  1929. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate);
  1930. for(unsigned int i=0; i < neighbours.size(); i++)
  1931. {
  1932. const int3 &n = neighbours[i]; //current neighbor
  1933. CGPathNode & dp = graph[n.x][n.y][n.z];
  1934. if( !checkForVisitableDir(cp->coord, dp.coord)
  1935. || !checkForVisitableDir(dp.coord, cp->coord)
  1936. || dp.accessible == CGPathNode::BLOCKED )
  1937. {
  1938. continue;
  1939. }
  1940. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  1941. int remains = movement - cost;
  1942. if(remains < 0)
  1943. {
  1944. //occurs rarely, when hero with low movepoints tries to go leave the road
  1945. turn++;
  1946. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  1947. cost = getMovementCost(hero, cp->coord, dp.coord, movement); //cost must be updated, movement points changed :(
  1948. remains = movement - cost;
  1949. }
  1950. if(dp.turns==0xff //we haven't been here before
  1951. || dp.turns > turn
  1952. || (dp.turns >= turn && dp.moveRemains < remains)) //this route is faster
  1953. {
  1954. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  1955. dp.moveRemains = remains;
  1956. dp.turns = turn;
  1957. dp.theNodeBefore = cp;
  1958. if(dp.accessible == CGPathNode::ACCESSIBLE)
  1959. {
  1960. mq.push(&dp);
  1961. }
  1962. }
  1963. } //neighbours loop
  1964. } //queue loop
  1965. }
  1966. bool CGameState::isVisible(int3 pos, int player)
  1967. {
  1968. if(player == 255) //neutral player
  1969. return false;
  1970. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  1971. }
  1972. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  1973. {
  1974. if(player == 255) //neutral player
  1975. return false;
  1976. //object is visible when at least one blocked tile is visible
  1977. for(int fx=0; fx<8; ++fx)
  1978. {
  1979. for(int fy=0; fy<6; ++fy)
  1980. {
  1981. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  1982. if(map->isInTheMap(pos)
  1983. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  1984. && isVisible(pos, player) )
  1985. return true;
  1986. }
  1987. }
  1988. return false;
  1989. }
  1990. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  1991. {
  1992. const TerrainTile * pom = &map->getTile(dst);
  1993. return checkForVisitableDir(src, pom, dst);
  1994. }
  1995. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  1996. {
  1997. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  1998. {
  1999. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2000. continue;
  2001. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2002. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2003. {
  2004. return false;
  2005. }
  2006. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2007. {
  2008. return false;
  2009. }
  2010. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2011. {
  2012. return false;
  2013. }
  2014. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2015. {
  2016. return false;
  2017. }
  2018. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2019. {
  2020. return false;
  2021. }
  2022. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2023. {
  2024. return false;
  2025. }
  2026. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2027. {
  2028. return false;
  2029. }
  2030. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2031. {
  2032. return false;
  2033. }
  2034. }
  2035. return true;
  2036. }
  2037. std::pair<ui32, ui32> BattleInfo::calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2038. {
  2039. float attackDefenseBonus,
  2040. minDmg = attacker->creature->damageMin * attacker->amount,
  2041. maxDmg = attacker->creature->damageMax * attacker->amount;
  2042. if(attacker->creature->idNumber == 149) //arrow turret
  2043. {
  2044. switch(attacker->position)
  2045. {
  2046. case -2: //keep
  2047. minDmg = 15;
  2048. maxDmg = 15;
  2049. break;
  2050. case -3: case -4: //turrets
  2051. minDmg = 7.5f;
  2052. maxDmg = 7.5f;
  2053. break;
  2054. }
  2055. }
  2056. if(attacker->hasFeatureOfType(StackFeature::SIEGE_WEAPON) && attacker->creature->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2057. { //minDmg and maxDmg are multiplied by hero attack + 1
  2058. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2059. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2060. }
  2061. if(attacker->hasFeatureOfType(StackFeature::GENERAL_ATTACK_REDUCTION))
  2062. {
  2063. attackDefenseBonus = attacker->Attack() * (attacker->valOfFeatures(StackFeature::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f) - defender->Defense();
  2064. }
  2065. else
  2066. {
  2067. attackDefenseBonus = attacker->Attack() - defender->Defense();
  2068. }
  2069. //calculating total attack/defense skills modifier
  2070. if(!shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 0)) //bloodlust handling (etc.)
  2071. {
  2072. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 0);
  2073. }
  2074. if(shooting && attacker->hasFeatureOfType(StackFeature::ATTACK_BONUS, 1)) //precision handling (etc.)
  2075. {
  2076. attackDefenseBonus += attacker->valOfFeatures(StackFeature::ATTACK_BONUS, 1);
  2077. }
  2078. if(attacker->getEffect(55)) //slayer handling
  2079. {
  2080. std::vector<int> affectedIds;
  2081. switch(attacker->getEffect(55)->level)
  2082. {
  2083. case 3: //expert
  2084. {
  2085. affectedIds.push_back(40); //giant
  2086. affectedIds.push_back(41); //titan
  2087. affectedIds.push_back(152); //lord of thunder
  2088. } //continue adding ...
  2089. case 2: //advanced
  2090. {
  2091. affectedIds.push_back(12); //angel
  2092. affectedIds.push_back(13); //archangel
  2093. affectedIds.push_back(54); //devil
  2094. affectedIds.push_back(55); //arch devil
  2095. affectedIds.push_back(150); //supreme archangel
  2096. affectedIds.push_back(153); //antichrist
  2097. } //continue adding ...
  2098. case 0: case 1: //none and basic
  2099. {
  2100. affectedIds.push_back(26); //green dragon
  2101. affectedIds.push_back(27); //gold dragon
  2102. affectedIds.push_back(82); //red dragon
  2103. affectedIds.push_back(83); //black dragon
  2104. affectedIds.push_back(96); //behemot
  2105. affectedIds.push_back(97); //ancient behemot
  2106. affectedIds.push_back(110); //hydra
  2107. affectedIds.push_back(111); //chaos hydra
  2108. affectedIds.push_back(132); //azure dragon
  2109. affectedIds.push_back(133); //crystal dragon
  2110. affectedIds.push_back(134); //faerie dragon
  2111. affectedIds.push_back(135); //rust dragon
  2112. affectedIds.push_back(151); //diamond dragon
  2113. affectedIds.push_back(154); //blood dragon
  2114. affectedIds.push_back(155); //darkness dragon
  2115. affectedIds.push_back(156); //ghost behemoth
  2116. affectedIds.push_back(157); //hell hydra
  2117. break;
  2118. }
  2119. }
  2120. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2121. {
  2122. if(defender->creature->idNumber == affectedIds[g])
  2123. {
  2124. attackDefenseBonus += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2125. break;
  2126. }
  2127. }
  2128. }
  2129. float dmgBonusMultiplier = 1.0f;
  2130. //applying jousting bonus
  2131. if( attacker->hasFeatureOfType(StackFeature::JOUSTING) && !defender->hasFeatureOfType(StackFeature::CHARGE_IMMUNITY) )
  2132. dmgBonusMultiplier += charge * 0.05f;
  2133. //bonus from attack/defense skills
  2134. if(attackDefenseBonus < 0) //decreasing dmg
  2135. {
  2136. if(0.02f * (-attackDefenseBonus) > 0.3f)
  2137. {
  2138. dmgBonusMultiplier += -0.3f;
  2139. }
  2140. else
  2141. {
  2142. dmgBonusMultiplier += 0.02f * attackDefenseBonus;
  2143. }
  2144. }
  2145. else //increasing dmg
  2146. {
  2147. if(0.05f * attackDefenseBonus > 4.0f)
  2148. {
  2149. dmgBonusMultiplier += 4.0f;
  2150. }
  2151. else
  2152. {
  2153. dmgBonusMultiplier += 0.05f * attackDefenseBonus;
  2154. }
  2155. }
  2156. //handling secondary abilities and artifacts giving premies to them
  2157. if(attackerHero)
  2158. {
  2159. if(shooting)
  2160. {
  2161. switch(attackerHero->getSecSkillLevel(1)) //archery
  2162. {
  2163. case 1: //basic
  2164. dmgBonusMultiplier += 0.1f;
  2165. break;
  2166. case 2: //advanced
  2167. dmgBonusMultiplier += 0.25f;
  2168. break;
  2169. case 3: //expert
  2170. dmgBonusMultiplier += 0.5f;
  2171. break;
  2172. }
  2173. if(attackerHero->getSecSkillLevel(1) > 0) //non-none level
  2174. {
  2175. //apply artifact premy to archery
  2176. dmgBonusMultiplier += attackerHero->valOfBonuses(HeroBonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2177. }
  2178. }
  2179. else
  2180. {
  2181. switch(attackerHero->getSecSkillLevel(22)) //offense
  2182. {
  2183. case 1: //basic
  2184. dmgBonusMultiplier += 0.1f;
  2185. break;
  2186. case 2: //advanced
  2187. dmgBonusMultiplier += 0.2f;
  2188. break;
  2189. case 3: //expert
  2190. dmgBonusMultiplier += 0.3f;
  2191. break;
  2192. }
  2193. }
  2194. }
  2195. if(defendingHero)
  2196. {
  2197. switch(defendingHero->getSecSkillLevel(23)) //armorer
  2198. {
  2199. case 1: //basic
  2200. dmgBonusMultiplier *= 0.95f;
  2201. break;
  2202. case 2: //advanced
  2203. dmgBonusMultiplier *= 0.9f;
  2204. break;
  2205. case 3: //expert
  2206. dmgBonusMultiplier *= 0.85f;
  2207. break;
  2208. }
  2209. }
  2210. //handling hate effect
  2211. if( attacker->hasFeatureOfType(StackFeature::HATE, defender->creature->idNumber) )
  2212. dmgBonusMultiplier += 0.5f;
  2213. //handling spell effects
  2214. if(!shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2215. {
  2216. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2217. }
  2218. else if(shooting && defender->hasFeatureOfType(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2219. {
  2220. dmgBonusMultiplier *= float(defender->valOfFeatures(StackFeature::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2221. }
  2222. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2223. {
  2224. dmgBonusMultiplier *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2225. }
  2226. minDmg *= dmgBonusMultiplier;
  2227. maxDmg *= dmgBonusMultiplier;
  2228. if(attacker->getEffect(42)) //curse handling (rest)
  2229. {
  2230. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2231. return std::make_pair(int(minDmg), int(minDmg));
  2232. }
  2233. else if(attacker->getEffect(41)) //bless handling
  2234. {
  2235. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2236. return std::make_pair(int(maxDmg), int(maxDmg));
  2237. }
  2238. else
  2239. {
  2240. return std::make_pair(int(minDmg), int(maxDmg));
  2241. }
  2242. tlog1 << "We are too far in calculateDmg...\n";
  2243. return std::make_pair(0, 0);
  2244. }
  2245. ui32 BattleInfo::calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge)
  2246. {
  2247. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge);
  2248. if(range.first != range.second)
  2249. return range.first + rand() % (range.second - range.first + 1);
  2250. else
  2251. return range.first;
  2252. }
  2253. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2254. {
  2255. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2256. {
  2257. const CStack * const st = stacks[i];
  2258. si32 killed = (st->alive() ? st->baseAmount - st->amount : st->baseAmount);
  2259. amax(killed, 0);
  2260. if(killed)
  2261. casualties[!st->attackerOwned][st->creature->idNumber] += killed;
  2262. }
  2263. }
  2264. si8 CGameState::battleMaxSpellLevel()
  2265. {
  2266. if(!curB) //there is not battle
  2267. {
  2268. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2269. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2270. }
  2271. si8 levelLimit = SPELL_LEVELS;
  2272. const CGHeroInstance *h1 = curB->heroes[0];
  2273. if(h1)
  2274. {
  2275. for(std::list<HeroBonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2276. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2277. amin(levelLimit, i->val);
  2278. }
  2279. const CGHeroInstance *h2 = curB->heroes[1];
  2280. if(h2)
  2281. {
  2282. for(std::list<HeroBonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2283. if(i->type == HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2284. amin(levelLimit, i->val);
  2285. }
  2286. return levelLimit;
  2287. }
  2288. std::set<CStack*> BattleInfo::getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile)
  2289. {
  2290. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, caster->getSpellSchoolLevel(s));
  2291. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2292. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2293. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2294. {
  2295. for(int it=0; it<stacks.size(); ++it)
  2296. {
  2297. if((s->id == 24 && !stacks[it]->creature->isUndead()) //death ripple
  2298. || (s->id == 25 && stacks[it]->creature->isUndead()) //destroy undead
  2299. || (s->id == 26) //Armageddon
  2300. )
  2301. {
  2302. if(stacks[it]->alive())
  2303. attackedCres.insert(stacks[it]);
  2304. }
  2305. }
  2306. }
  2307. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2308. || VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_2") != std::string::npos) //spell to be cast on a specific creature but massive on expert
  2309. {
  2310. if(caster->getSpellSchoolLevel(s) < 3) /*not expert */
  2311. {
  2312. CStack * st = getStackT(destinationTile, onlyAlive);
  2313. if(st)
  2314. attackedCres.insert(st);
  2315. }
  2316. else
  2317. {
  2318. for(int it=0; it<stacks.size(); ++it)
  2319. {
  2320. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2321. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == caster->tempOwner)
  2322. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != caster->tempOwner )
  2323. )
  2324. {
  2325. if(!onlyAlive || stacks[it]->alive())
  2326. attackedCres.insert(stacks[it]);
  2327. }
  2328. }
  2329. } //if(caster->getSpellSchoolLevel(s) < 3)
  2330. }
  2331. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2332. {
  2333. CStack * st = getStackT(destinationTile, onlyAlive);
  2334. if(st)
  2335. attackedCres.insert(st);
  2336. }
  2337. else //custom range from attackedHexes
  2338. {
  2339. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2340. {
  2341. CStack * st = getStackT(*it, onlyAlive);
  2342. if(st)
  2343. attackedCres.insert(st);
  2344. }
  2345. }
  2346. return attackedCres;
  2347. }
  2348. int BattleInfo::calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster)
  2349. {
  2350. switch(spell->id)
  2351. {
  2352. case 56: //frenzy
  2353. return 1;
  2354. default: //other spells
  2355. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(HeroBonus::SPELL_DURATION);
  2356. }
  2357. }
  2358. CStack * BattleInfo::generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2359. {
  2360. CStack * ret = new CStack(&VLC->creh->creatures[creatureID], amount, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2361. if(owner)
  2362. {
  2363. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACKS_SPEED), StackFeature::BONUS_FROM_HERO));
  2364. //base luck/morale calculations
  2365. ret->morale = owner->getCurrentMorale(slot, false);
  2366. ret->luck = owner->getCurrentLuck(slot, false);
  2367. //other bonuses
  2368. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(0), StackFeature::BONUS_FROM_HERO));
  2369. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->getPrimSkillLevel(1), StackFeature::BONUS_FROM_HERO));
  2370. if ( owner->hasBonusOfType(HeroBonus::STACK_HEALTH_PERCENT) ) // e.g. Elixir of Life
  2371. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0,
  2372. (ret->creature->hitPoints * owner->valOfBonuses(HeroBonus::STACK_HEALTH_PERCENT)) / 100,
  2373. StackFeature::BONUS_FROM_HERO));
  2374. if (owner->hasBonusOfType(HeroBonus::HP_REGENERATION)) // e.g. Elixir of Life
  2375. ret->features.push_back(makeFeature(StackFeature::HP_REGENERATION, StackFeature::WHOLE_BATTLE, 0,
  2376. owner->valOfBonuses(HeroBonus::HP_REGENERATION), StackFeature::BONUS_FROM_HERO));
  2377. if (owner->hasBonusOfType(HeroBonus::LEVEL_SPELL_IMMUNITY)) // e.g. Power of the Dragon Father
  2378. ret->features.push_back(makeFeature(StackFeature::LEVEL_SPELL_IMMUNITY, StackFeature::WHOLE_BATTLE, 0,
  2379. owner->valOfBonuses(HeroBonus::LEVEL_SPELL_IMMUNITY), StackFeature::BONUS_FROM_HERO));
  2380. ret->features.push_back(makeFeature(StackFeature::HP_BONUS, StackFeature::WHOLE_BATTLE, 0, owner->valOfBonuses(HeroBonus::STACK_HEALTH), StackFeature::BONUS_FROM_HERO));
  2381. ret->firstHPleft = ret->MaxHealth();
  2382. }
  2383. else
  2384. {
  2385. ret->morale = 0;
  2386. ret->luck = 0;
  2387. }
  2388. //native terrain bonuses
  2389. int faction = ret->creature->faction;
  2390. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2391. {
  2392. ret->features.push_back(makeFeature(StackFeature::SPEED_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2393. ret->features.push_back(makeFeature(StackFeature::ATTACK_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2394. ret->features.push_back(makeFeature(StackFeature::DEFENCE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  2395. }
  2396. ret->position = position;
  2397. return ret;
  2398. }
  2399. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2400. {
  2401. ui32 ret = VLC->spellh->spells[sp->id].costs[caster->getSpellSchoolLevel(sp)];
  2402. //checking for friendly stacks reducing cost of the spell
  2403. si32 manaReduction = 0;
  2404. for(int g=0; g<stacks.size(); ++g)
  2405. {
  2406. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasFeatureOfType(StackFeature::CHANGES_SPELL_COST_FOR_ALLY) )
  2407. {
  2408. amin(manaReduction, stacks[g]->valOfFeatures(StackFeature::CHANGES_SPELL_COST_FOR_ALLY));
  2409. }
  2410. }
  2411. return ret + manaReduction;
  2412. }
  2413. int BattleInfo::hexToWallPart(int hex) const
  2414. {
  2415. if(siege == 0) //there is no battle!
  2416. return -1;
  2417. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2418. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2419. std::make_pair(62, 4), std::make_pair(29, 5), std::make_pair(12, 6), std::make_pair(95, 7), std::make_pair(96, 7)};
  2420. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2421. {
  2422. if(attackable[g].first == hex)
  2423. return attackable[g].second;
  2424. }
  2425. return -1; //not found!
  2426. }
  2427. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2428. {
  2429. bool ac[BFIELD_SIZE];
  2430. std::set<int> occupyable;
  2431. getAccessibilityMap(ac, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, false, occupyable, closest->hasFeatureOfType(StackFeature::FLYING), closest->ID);
  2432. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2433. makeBFS(closest->position, ac, predecessor, dist, closest->hasFeatureOfType(StackFeature::DOUBLE_WIDE), closest->attackerOwned, closest->hasFeatureOfType(StackFeature::FLYING), true);
  2434. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2435. for(int g=0; g<BFIELD_SIZE; ++g)
  2436. {
  2437. const CStack * atG = getStackT(g);
  2438. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2439. continue;
  2440. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2441. {
  2442. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2443. continue;
  2444. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2445. }
  2446. }
  2447. if(stackPairs.size() > 0)
  2448. {
  2449. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2450. minimalPairs.push_back(stackPairs[0]);
  2451. for(int b=1; b<stackPairs.size(); ++b)
  2452. {
  2453. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2454. {
  2455. minimalPairs.clear();
  2456. minimalPairs.push_back(stackPairs[b]);
  2457. }
  2458. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2459. {
  2460. minimalPairs.push_back(stackPairs[b]);
  2461. }
  2462. }
  2463. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2464. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2465. }
  2466. return std::make_pair<const CStack * , int>(NULL, -1);
  2467. }
  2468. bool CGameState::battleCanShoot(int ID, int dest)
  2469. {
  2470. if(!curB)
  2471. return false;
  2472. const CStack *our = curB->getStack(ID),
  2473. *dst = curB->getStackT(dest);
  2474. if(!our || !dst) return false;
  2475. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2476. if(our->hasFeatureOfType(StackFeature::FORGETFULL)) //forgetfulness
  2477. return false;
  2478. if(our->hasFeatureOfType(StackFeature::SHOOTER)//it's shooter
  2479. && our->owner != dst->owner
  2480. && dst->alive()
  2481. && (!curB->isStackBlocked(ID)
  2482. || ourHero->hasBonusOfType(HeroBonus::FREE_SHOOTING))
  2483. && our->shots
  2484. )
  2485. return true;
  2486. return false;
  2487. }
  2488. const CStack * BattleInfo::getNextStack() const
  2489. {
  2490. std::vector<const CStack *> hlp;
  2491. getStackQueue(hlp, 1, -1);
  2492. if(hlp.size())
  2493. return hlp[0];
  2494. else
  2495. return NULL;
  2496. }
  2497. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  2498. {
  2499. const CStack *ret = NULL;
  2500. unsigned i, //fastest stack
  2501. j; //fastest stack of the other side
  2502. for(i = 0; i < st.size(); i++)
  2503. if(st[i])
  2504. break;
  2505. //no stacks left
  2506. if(i == st.size())
  2507. return NULL;
  2508. const CStack *fastest = st[i], *other = NULL;
  2509. int bestSpeed = fastest->Speed(turn);
  2510. if(fastest->attackerOwned != curside)
  2511. {
  2512. ret = fastest;
  2513. }
  2514. else
  2515. {
  2516. for(j = i + 1; j < st.size(); j++)
  2517. {
  2518. if(!st[j]) continue;
  2519. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  2520. break;
  2521. }
  2522. if(j >= st.size())
  2523. {
  2524. ret = fastest;
  2525. }
  2526. else
  2527. {
  2528. other = st[j];
  2529. if(other->Speed(turn) != bestSpeed)
  2530. ret = fastest;
  2531. else
  2532. ret = other;
  2533. }
  2534. }
  2535. assert(ret);
  2536. if(ret == fastest)
  2537. st[i] = NULL;
  2538. else
  2539. st[j] = NULL;
  2540. curside = ret->attackerOwned;
  2541. return ret;
  2542. }
  2543. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  2544. {
  2545. //we'll split creatures with remaining movement to 4 parts
  2546. std::vector<const CStack *> phase[4]; //0 - turrets/catapult, 1 - normal (unmoved) creatures, other war machines, 2 - waited cres that had morale, 3 - rest of waited cres
  2547. int toMove = 0; //how many stacks still has move
  2548. const CStack *active = getStack(activeStack);
  2549. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  2550. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  2551. {
  2552. out.push_back(active);
  2553. if(out.size() == howMany)
  2554. return;
  2555. }
  2556. for(unsigned int i=0; i<stacks.size(); ++i)
  2557. {
  2558. const CStack * const s = stacks[i];
  2559. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  2560. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  2561. || turn <= 0 && s == active) //it's active stack already added at the beginning of queue
  2562. {
  2563. continue;
  2564. }
  2565. int p = -1; //in which phase this tack will move?
  2566. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  2567. {
  2568. if(vstd::contains(s->state, HAD_MORALE))
  2569. p = 2;
  2570. else
  2571. p = 3;
  2572. }
  2573. else if(s->creature->idNumber == 145 || s->creature->idNumber == 149) //catapult and turrets are first
  2574. {
  2575. p = 0;
  2576. }
  2577. else
  2578. {
  2579. p = 1;
  2580. }
  2581. phase[p].push_back(s);
  2582. toMove++;
  2583. }
  2584. for(int i = 0; i < 4; i++)
  2585. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  2586. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  2587. out.push_back(phase[0][i]);
  2588. if(out.size() == howMany)
  2589. return;
  2590. if(lastMoved == -1)
  2591. {
  2592. if(active)
  2593. {
  2594. if(out.size() && out.front() == active)
  2595. lastMoved = active->attackerOwned;
  2596. else
  2597. lastMoved = active->attackerOwned;
  2598. }
  2599. else
  2600. {
  2601. lastMoved = 0;
  2602. }
  2603. }
  2604. int pi = 1;
  2605. while(out.size() < howMany)
  2606. {
  2607. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  2608. if(!hlp)
  2609. {
  2610. pi++;
  2611. if(pi > 3)
  2612. {
  2613. //if(turn != 2)
  2614. getStackQueue(out, howMany, turn + 1, lastMoved);
  2615. return;
  2616. }
  2617. }
  2618. else
  2619. {
  2620. out.push_back(hlp);
  2621. }
  2622. }
  2623. }
  2624. int3 CPath::startPos() const
  2625. {
  2626. return nodes[nodes.size()-1].coord;
  2627. }
  2628. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  2629. {
  2630. if (mode==0)
  2631. {
  2632. for (unsigned int i=0;i<nodes.size();i++)
  2633. {
  2634. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2635. }
  2636. }
  2637. }
  2638. int3 CPath::endPos() const
  2639. {
  2640. return nodes[0].coord;
  2641. }
  2642. CGPathNode::CGPathNode()
  2643. :coord(-1,-1,-1)
  2644. {
  2645. accessible = 0;
  2646. land = 0;
  2647. moveRemains = 0;
  2648. turns = 255;
  2649. theNodeBefore = NULL;
  2650. }
  2651. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  2652. {
  2653. out.nodes.clear();
  2654. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  2655. if(!curnode->theNodeBefore)
  2656. return false;
  2657. while(curnode)
  2658. {
  2659. out.nodes.push_back(*curnode);
  2660. curnode = curnode->theNodeBefore;
  2661. }
  2662. return true;
  2663. }
  2664. CPathsInfo::CPathsInfo( const int3 &Sizes )
  2665. :sizes(Sizes)
  2666. {
  2667. nodes = new CGPathNode**[sizes.x];
  2668. for(int i = 0; i < sizes.x; i++)
  2669. {
  2670. nodes[i] = new CGPathNode*[sizes.y];
  2671. for (int j = 0; j < sizes.y; j++)
  2672. {
  2673. nodes[i][j] = new CGPathNode[sizes.z];
  2674. }
  2675. }
  2676. }
  2677. CPathsInfo::~CPathsInfo()
  2678. {
  2679. for(int i = 0; i < sizes.x; i++)
  2680. {
  2681. for (int j = 0; j < sizes.y; j++)
  2682. {
  2683. delete [] nodes[i][j];
  2684. }
  2685. delete [] nodes[i];
  2686. }
  2687. delete [] nodes;
  2688. }
  2689. int3 CGPath::startPos() const
  2690. {
  2691. return nodes[nodes.size()-1].coord;
  2692. }
  2693. int3 CGPath::endPos() const
  2694. {
  2695. return nodes[0].coord;
  2696. }
  2697. void CGPath::convert( ui8 mode )
  2698. {
  2699. if(mode==0)
  2700. {
  2701. for(unsigned int i=0;i<nodes.size();i++)
  2702. {
  2703. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  2704. }
  2705. }
  2706. }
  2707. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  2708. {
  2709. switch(phase)
  2710. {
  2711. case 0: //catapult moves after turrets
  2712. return a->creature->idNumber < b->creature->idNumber; //catapult is 145 and turrets are 149
  2713. //TODO? turrets order
  2714. case 1: //fastest first, upper slot first
  2715. {
  2716. int as = a->Speed(turn), bs = b->Speed(turn);
  2717. if(as != bs)
  2718. return as > bs;
  2719. else
  2720. return a->slot < b->slot;
  2721. }
  2722. case 2: //fastest last, upper slot first
  2723. //TODO: should be replaced with order of receiving morale!
  2724. case 3: //fastest last, upper slot first
  2725. {
  2726. int as = a->Speed(turn), bs = b->Speed(turn);
  2727. if(as != bs)
  2728. return as < bs;
  2729. else
  2730. return a->slot < b->slot;
  2731. }
  2732. default:
  2733. assert(0);
  2734. return false;
  2735. }
  2736. }
  2737. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  2738. {
  2739. phase = Phase;
  2740. turn = Turn;
  2741. }
  2742. PlayerState::PlayerState()
  2743. : color(-1), currentSelection(0xffffffff)
  2744. {
  2745. }