CGameState.cpp 85 KB

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