CGameState.cpp 104 KB

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