CGameState.cpp 107 KB

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