CGameState.cpp 91 KB

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