CGameState.cpp 110 KB

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