CGameState.cpp 108 KB

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