2
0

CGameState.cpp 86 KB

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