CGameState.cpp 62 KB

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