CGameState.cpp 76 KB

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