CGameState.cpp 103 KB

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