CGameState.cpp 59 KB

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