CGameState.cpp 106 KB

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