CGameState.cpp 61 KB

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