CGameState.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966
  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. int r;
  843. do
  844. {
  845. r = ran()%197;
  846. } while (vstd::contains(VLC->creh->notUsedMonsters,r));
  847. return std::pair<int,int>(54,r);
  848. }
  849. case 72: //random monster lvl1
  850. return std::pair<int,int>(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber);
  851. case 73: //random monster lvl2
  852. return std::pair<int,int>(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber);
  853. case 74: //random monster lvl3
  854. return std::pair<int,int>(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber);
  855. case 75: //random monster lvl4
  856. return std::pair<int,int>(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber);
  857. case 76: //random resource
  858. return std::pair<int,int>(79,ran()%7); //now it's OH3 style, use %8 for mithril
  859. case 77: //random town
  860. {
  861. int align = (static_cast<CGTownInstance*>(obj))->alignment,
  862. f;
  863. if(align>PLAYER_LIMIT-1)//same as owner / random
  864. {
  865. if(obj->tempOwner > PLAYER_LIMIT-1)
  866. f = -1; //random
  867. else
  868. f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle;
  869. }
  870. else
  871. {
  872. f = scenarioOps->getIthPlayersSettings(align).castle;
  873. }
  874. if(f<0) f = ran()%VLC->townh->towns.size();
  875. return std::pair<int,int>(TOWNI_TYPE,f);
  876. }
  877. case 162: //random monster lvl5
  878. return std::pair<int,int>(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber);
  879. case 163: //random monster lvl6
  880. return std::pair<int,int>(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber);
  881. case 164: //random monster lvl7
  882. return std::pair<int,int>(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber);
  883. case 216: //random dwelling
  884. {
  885. int faction = ran()%F_NUMBER;
  886. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  887. CCreGen2ObjInfo* info = static_cast<CCreGen2ObjInfo*>(dwl->info);
  888. if (info->asCastle)
  889. {
  890. for(unsigned int i=0;i<map->objects.size();i++)
  891. {
  892. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  893. {
  894. randomizeObject(map->objects[i]); //we have to randomize the castle first
  895. faction = map->objects[i]->subID;
  896. break;
  897. }
  898. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  899. {
  900. faction = map->objects[i]->subID;
  901. break;
  902. }
  903. }
  904. }
  905. else
  906. {
  907. while((!(info->castles[0]&(1<<faction))))
  908. {
  909. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  910. break;
  911. faction = ran()%F_NUMBER;
  912. }
  913. }
  914. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  915. int cid = VLC->townh->towns[faction].basicCreatures[level];
  916. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  917. if(VLC->objh->cregens[i]==cid)
  918. return std::pair<int,int>(17,i);
  919. tlog3 << "Cannot find a dwelling for creature "<< cid << std::endl;
  920. return std::pair<int,int>(17,0);
  921. delete dwl->info;
  922. dwl->info = NULL;
  923. }
  924. case 217:
  925. {
  926. int faction = ran()%F_NUMBER;
  927. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  928. CCreGenObjInfo* info = static_cast<CCreGenObjInfo*>(dwl->info);
  929. if (info->asCastle)
  930. {
  931. for(unsigned int i=0;i<map->objects.size();i++)
  932. {
  933. if(map->objects[i]->ID==77 && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  934. {
  935. randomizeObject(map->objects[i]); //we have to randomize the castle first
  936. faction = map->objects[i]->subID;
  937. break;
  938. }
  939. else if(map->objects[i]->ID==TOWNI_TYPE && dynamic_cast<CGTownInstance*>(map->objects[i])->identifier == info->identifier)
  940. {
  941. faction = map->objects[i]->subID;
  942. break;
  943. }
  944. }
  945. }
  946. else
  947. {
  948. while((!(info->castles[0]&(1<<faction))))
  949. {
  950. if((faction>7) && (info->castles[1]&(1<<(faction-8))))
  951. break;
  952. faction = ran()%F_NUMBER;
  953. }
  954. }
  955. int cid = VLC->townh->towns[faction].basicCreatures[obj->subID];
  956. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  957. if(VLC->objh->cregens[i]==cid)
  958. return std::pair<int,int>(17,i);
  959. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  960. return std::pair<int,int>(17,0);
  961. delete dwl->info;
  962. dwl->info = NULL;
  963. }
  964. case 218:
  965. {
  966. CGDwelling * dwl = static_cast<CGDwelling*>(obj);
  967. CCreGen3ObjInfo* info = static_cast<CCreGen3ObjInfo*>(dwl->info);
  968. int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel));
  969. int cid = VLC->townh->towns[obj->subID].basicCreatures[level];
  970. for(unsigned int i=0;i<VLC->objh->cregens.size();i++)
  971. if(VLC->objh->cregens[i]==cid)
  972. return std::pair<int,int>(17,i);
  973. tlog3 << "Cannot find a dwelling for creature "<<cid <<std::endl;
  974. return std::pair<int,int>(17,0);
  975. delete dwl->info;
  976. dwl->info = NULL;
  977. }
  978. }
  979. return std::pair<int,int>(-1,-1);
  980. }
  981. void CGameState::randomizeObject(CGObjectInstance *cur)
  982. {
  983. std::pair<int,int> ran = pickObject(cur);
  984. if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything
  985. {
  986. if(cur->ID==TOWNI_TYPE) //town - set def
  987. {
  988. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  989. t->town = &VLC->townh->towns[t->subID];
  990. if(t->hasCapitol())
  991. t->defInfo = capitols[t->subID];
  992. else if(t->hasFort())
  993. t->defInfo = forts[t->subID];
  994. else
  995. t->defInfo = villages[t->subID];
  996. }
  997. return;
  998. }
  999. else if(ran.first==HEROI_TYPE)//special code for hero
  1000. {
  1001. CGHeroInstance *h = dynamic_cast<CGHeroInstance *>(cur);
  1002. if(!h) {tlog2<<"Wrong random hero at "<<cur->pos<<std::endl; return;}
  1003. cur->ID = ran.first;
  1004. h->portrait = cur->subID = ran.second;
  1005. h->type = VLC->heroh->heroes[ran.second];
  1006. h->randomizeArmy(h->type->heroType/2);
  1007. map->heroes.push_back(h);
  1008. return; //TODO: maybe we should do something with definfo?
  1009. }
  1010. else if(ran.first==TOWNI_TYPE)//special code for town
  1011. {
  1012. CGTownInstance *t = dynamic_cast<CGTownInstance*>(cur);
  1013. if(!t) {tlog2<<"Wrong random town at "<<cur->pos<<std::endl; return;}
  1014. cur->ID = ran.first;
  1015. cur->subID = ran.second;
  1016. t->town = &VLC->townh->towns[ran.second];
  1017. if(t->hasCapitol())
  1018. t->defInfo = capitols[t->subID];
  1019. else if(t->hasFort())
  1020. t->defInfo = forts[t->subID];
  1021. else
  1022. t->defInfo = villages[t->subID];
  1023. t->randomizeArmy(t->subID);
  1024. map->towns.push_back(t);
  1025. return;
  1026. }
  1027. //we have to replace normal random object
  1028. cur->ID = ran.first;
  1029. cur->subID = ran.second;
  1030. map->removeBlockVisTiles(cur); //recalculate blockvis tiles - picked object might have different than random placeholder
  1031. map->defy.push_back(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]);
  1032. if(!cur->defInfo)
  1033. {
  1034. tlog1<<"*BIG* WARNING: Missing def declaration for "<<cur->ID<<" "<<cur->subID<<std::endl;
  1035. return;
  1036. }
  1037. map->addBlockVisTiles(cur);
  1038. }
  1039. int CGameState::getDate(int mode) const
  1040. {
  1041. int temp;
  1042. switch (mode)
  1043. {
  1044. case 0: //day number
  1045. return day;
  1046. break;
  1047. case 1: //day of week
  1048. temp = (day)%7;
  1049. if (temp)
  1050. return temp;
  1051. else return 7;
  1052. break;
  1053. case 2: //current week
  1054. temp = ((day-1)/7)+1;
  1055. if (!(temp%4))
  1056. return 4;
  1057. else
  1058. return (temp%4);
  1059. break;
  1060. case 3: //current month
  1061. return ((day-1)/28)+1;
  1062. break;
  1063. }
  1064. return 0;
  1065. }
  1066. CGameState::CGameState()
  1067. {
  1068. mx = new boost::shared_mutex();
  1069. map = NULL;
  1070. curB = NULL;
  1071. scenarioOps = NULL;
  1072. applierGs = new CGSApplier;
  1073. objCaller = new CObjectCallersHandler;
  1074. campaign = NULL;
  1075. }
  1076. CGameState::~CGameState()
  1077. {
  1078. delete mx;
  1079. delete map;
  1080. delete curB;
  1081. //delete scenarioOps;
  1082. delete applierGs;
  1083. delete objCaller;
  1084. }
  1085. void CGameState::init( StartInfo * si, ui32 checksum, int Seed )
  1086. {
  1087. switch(si->mode)
  1088. {
  1089. case 0:
  1090. map = new Mapa(si->mapname);
  1091. for (int i=0; i<144; ++i) //yes, 144
  1092. {
  1093. if (map->allowedArtifact[i])
  1094. VLC->arth->allowedArtifacts.push_back(VLC->arth->artifacts[i]);
  1095. }
  1096. break;
  1097. case 2:
  1098. campaign = new CCampaignState();
  1099. campaign->initNewCampaign(*si);
  1100. std::string &mapContent = campaign->camp->mapPieces[si->whichMapInCampaign];
  1101. map = new Mapa();
  1102. map->initFromBytes((const unsigned char*)mapContent.c_str());
  1103. for (int i=0; i<144; ++i)
  1104. {
  1105. if (map->allowedArtifact[i])
  1106. VLC->arth->allowedArtifacts.push_back(VLC->arth->artifacts[i]);
  1107. }
  1108. break;
  1109. }
  1110. tlog0 << "Map loaded!" << std::endl;
  1111. //tlog0 <<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
  1112. if(checksum)
  1113. {
  1114. tlog0 << "\tServer checksum for " << si->mapname <<": "<< checksum << std::endl;
  1115. tlog0 << "\tOur checksum for the map: "<< map->checksum << std::endl;
  1116. if(map->checksum != checksum)
  1117. {
  1118. tlog1 << "Wrong map checksum!!!" << std::endl;
  1119. throw std::string("Wrong checksum");
  1120. }
  1121. }
  1122. day = 0;
  1123. seed = Seed;
  1124. ran.seed((boost::int32_t)seed);
  1125. scenarioOps = si;
  1126. loadTownDInfos();
  1127. //pick grail location
  1128. if(map->grailPos.x < 0 || map->grailRadious) //grail not set or set within a radius around some place
  1129. {
  1130. if(!map->grailRadious) //radius not given -> anywhere on map
  1131. map->grailRadious = map->width * 2;
  1132. std::vector<int3> allowedPos;
  1133. // add all not blocked tiles in range
  1134. for (int i = 0; i < map->width ; i++)
  1135. {
  1136. for (int j = 0; j < map->height ; j++)
  1137. {
  1138. for (int k = 0; k <= map->twoLevel ; k++)
  1139. {
  1140. const TerrainTile &t = map->terrain[i][j][k];
  1141. if(!t.blocked
  1142. && !t.visitable
  1143. && t.tertype != TerrainTile::water
  1144. && t.tertype != TerrainTile::rock
  1145. && map->grailPos.dist2d(int3(i,j,k)) <= map->grailRadious)
  1146. allowedPos.push_back(int3(i,j,k));
  1147. }
  1148. }
  1149. }
  1150. //remove tiles with holes
  1151. for(unsigned int no=0; no<map->objects.size(); ++no)
  1152. if(map->objects[no]->ID == 124)
  1153. allowedPos -= map->objects[no]->pos;
  1154. if(allowedPos.size())
  1155. map->grailPos = allowedPos[ran() % allowedPos.size()];
  1156. else
  1157. tlog2 << "Warning: Grail cannot be placed, no appropriate tile found!\n";
  1158. }
  1159. //picking random factions for players
  1160. for(unsigned int i=0;i<scenarioOps->playerInfos.size();i++)
  1161. {
  1162. if(scenarioOps->playerInfos[i].castle==-1)
  1163. {
  1164. int f;
  1165. do
  1166. {
  1167. f = ran()%F_NUMBER;
  1168. }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<<f));
  1169. scenarioOps->playerInfos[i].castle = f;
  1170. }
  1171. }
  1172. //randomizing objects
  1173. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1174. {
  1175. randomizeObject(obj);
  1176. if(obj->ID==EVENTI_TYPE)
  1177. {
  1178. obj->defInfo->handler=NULL;
  1179. }
  1180. obj->hoverName = VLC->generaltexth->names[obj->ID];
  1181. //handle Favouring Winds - mark tiles under it
  1182. if(obj->ID == 225)
  1183. for (int i = 0; i < obj->getWidth() ; i++)
  1184. for (int j = 0; j < obj->getHeight() ; j++)
  1185. {
  1186. int3 pos = obj->pos - int3(i,j,0);
  1187. if(map->isInTheMap(pos))
  1188. map->getTile(pos).siodmyTajemniczyBajt |= 128;
  1189. }
  1190. }
  1191. //std::cout<<"\tRandomizing objects: "<<th.getDif()<<std::endl;
  1192. /*********give starting hero****************************************/
  1193. for(int i=0;i<PLAYER_LIMIT;i++)
  1194. {
  1195. if((map->players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==CMapHeader::RoE))
  1196. {
  1197. int3 hpos = map->players[i].posOfMainTown;
  1198. hpos.x+=1;// hpos.y+=1;
  1199. int j;
  1200. for(j=0; j<scenarioOps->playerInfos.size(); j++) //don't add unsigned here - we are refering to the variable above
  1201. if(scenarioOps->playerInfos[j].color == i)
  1202. break;
  1203. if(j == scenarioOps->playerInfos.size())
  1204. continue;
  1205. int h=pickHero(i);
  1206. if(scenarioOps->playerInfos[j].hero == -1)
  1207. scenarioOps->playerInfos[j].hero = h;
  1208. CGHeroInstance * nnn = static_cast<CGHeroInstance*>(createObject(HEROI_TYPE,h,hpos,i));
  1209. nnn->id = map->objects.size();
  1210. hpos = map->players[i].posOfMainTown;hpos.x+=2;
  1211. for(unsigned int o=0;o<map->towns.size();o++) //find main town
  1212. {
  1213. if(map->towns[o]->pos == hpos)
  1214. {
  1215. map->towns[o]->visitingHero = nnn;
  1216. nnn->visitedTown = map->towns[o];
  1217. nnn->inTownGarrison = false;
  1218. break;
  1219. }
  1220. }
  1221. nnn->initHero();
  1222. map->heroes.push_back(nnn);
  1223. map->objects.push_back(nnn);
  1224. map->addBlockVisTiles(nnn);
  1225. }
  1226. }
  1227. /*********creating players entries in gs****************************************/
  1228. for (unsigned int i=0; i<scenarioOps->playerInfos.size();i++)
  1229. {
  1230. std::pair<int,PlayerState> ins(scenarioOps->playerInfos[i].color,PlayerState());
  1231. ins.second.color=ins.first;
  1232. ins.second.serial=i;
  1233. ins.second.human = scenarioOps->playerInfos[i].human;
  1234. players.insert(ins);
  1235. }
  1236. /******************RESOURCES****************************************************/
  1237. //TODO: computer player should receive other amount of resource than player (depending on difficulty)
  1238. std::vector<int> startres;
  1239. std::ifstream tis(DATA_DIR "/config/startres.txt");
  1240. int k;
  1241. for (int j=0;j<scenarioOps->difficulty;j++)
  1242. {
  1243. tis >> k;
  1244. for (int z=0;z<RESOURCE_QUANTITY;z++)
  1245. tis>>k;
  1246. }
  1247. tis >> k;
  1248. for (int i=0;i<RESOURCE_QUANTITY;i++)
  1249. {
  1250. tis >> k;
  1251. startres.push_back(k);
  1252. }
  1253. tis.close();
  1254. tis.clear();
  1255. for (std::map<ui8,PlayerState>::iterator i = players.begin(); i!=players.end(); i++)
  1256. {
  1257. (*i).second.resources.resize(RESOURCE_QUANTITY);
  1258. for (int x=0;x<RESOURCE_QUANTITY;x++)
  1259. (*i).second.resources[x] = startres[x];
  1260. }
  1261. /*************************HEROES************************************************/
  1262. std::set<int> hids; //hero ids to create pool
  1263. for(unsigned int i=0; i<map->allowedHeroes.size(); i++) //add to hids all allowed heroes
  1264. if(map->allowedHeroes[i])
  1265. hids.insert(i);
  1266. for (unsigned int i=0; i<map->heroes.size();i++) //heroes instances initialization
  1267. {
  1268. if (map->heroes[i]->getOwner()<0)
  1269. {
  1270. tlog2 << "Warning - hero with uninitialized owner!\n";
  1271. continue;
  1272. }
  1273. CGHeroInstance * vhi = (map->heroes[i]);
  1274. vhi->initHero();
  1275. players.find(vhi->getOwner())->second.heroes.push_back(vhi);
  1276. hids.erase(vhi->subID);
  1277. }
  1278. for (unsigned int i=0; i<map->objects.size();i++) //prisons
  1279. {
  1280. if (map->objects[i]->ID == 62)
  1281. hids.erase(map->objects[i]->subID);
  1282. }
  1283. for(unsigned int i=0; i<map->predefinedHeroes.size(); i++)
  1284. {
  1285. if(!vstd::contains(hids,map->predefinedHeroes[i]->subID))
  1286. continue;
  1287. map->predefinedHeroes[i]->initHero();
  1288. hpool.heroesPool[map->predefinedHeroes[i]->subID] = map->predefinedHeroes[i];
  1289. hpool.pavailable[map->predefinedHeroes[i]->subID] = 0xff;
  1290. hids.erase(map->predefinedHeroes[i]->subID);
  1291. }
  1292. BOOST_FOREACH(int hid, hids) //all not used allowed heroes go with default state into the pool
  1293. {
  1294. CGHeroInstance * vhi = new CGHeroInstance();
  1295. vhi->initHero(hid);
  1296. hpool.heroesPool[hid] = vhi;
  1297. hpool.pavailable[hid] = 0xff;
  1298. }
  1299. for(unsigned int i=0; i<map->disposedHeroes.size(); i++)
  1300. {
  1301. hpool.pavailable[map->disposedHeroes[i].ID] = map->disposedHeroes[i].players;
  1302. }
  1303. /*************************FOG**OF**WAR******************************************/
  1304. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1305. {
  1306. k->second.fogOfWarMap.resize(map->width);
  1307. for(int g=0; g<map->width; ++g)
  1308. k->second.fogOfWarMap[g].resize(map->height);
  1309. for(int g=-0; g<map->width; ++g)
  1310. for(int h=0; h<map->height; ++h)
  1311. k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0);
  1312. for(int g=0; g<map->width; ++g)
  1313. for(int h=0; h<map->height; ++h)
  1314. for(int v=0; v<map->twoLevel+1; ++v)
  1315. k->second.fogOfWarMap[g][h][v] = 0;
  1316. BOOST_FOREACH(CGObjectInstance *obj, map->objects)
  1317. {
  1318. if(obj->tempOwner != k->first) continue; //not a flagged object
  1319. std::set<int3> tiles;
  1320. obj->getSightTiles(tiles);
  1321. BOOST_FOREACH(int3 tile, tiles)
  1322. {
  1323. k->second.fogOfWarMap[tile.x][tile.y][tile.z] = 1;
  1324. }
  1325. }
  1326. //starting bonus
  1327. if(si->playerInfos[k->second.serial].bonus==brandom)
  1328. si->playerInfos[k->second.serial].bonus = ran()%3;
  1329. switch(si->playerInfos[k->second.serial].bonus)
  1330. {
  1331. case bgold:
  1332. k->second.resources[6] += 500 + (ran()%6)*100;
  1333. break;
  1334. case bresource:
  1335. {
  1336. int res = VLC->townh->towns[si->playerInfos[k->second.serial].castle].primaryRes;
  1337. if(res == 127)
  1338. {
  1339. k->second.resources[0] += 5 + ran()%6;
  1340. k->second.resources[2] += 5 + ran()%6;
  1341. }
  1342. else
  1343. {
  1344. k->second.resources[res] += 3 + ran()%4;
  1345. }
  1346. break;
  1347. }
  1348. case bartifact:
  1349. {
  1350. if(!k->second.heroes.size())
  1351. {
  1352. tlog5 << "Cannot give starting artifact - no heroes!" << std::endl;
  1353. break;
  1354. }
  1355. CArtifact *toGive;
  1356. toGive = VLC->arth->artifacts[VLC->arth->getRandomArt (CArtifact::ART_TREASURE)];
  1357. CGHeroInstance *hero = k->second.heroes[0];
  1358. std::vector<ui16>::iterator slot = vstd::findFirstNot (hero->artifWorn, toGive->possibleSlots);
  1359. if(slot!=toGive->possibleSlots.end())
  1360. {
  1361. VLC->arth->equipArtifact(hero->artifWorn, *slot, toGive->id, &hero->bonuses);
  1362. }
  1363. else
  1364. hero->giveArtifact(toGive->id);
  1365. }
  1366. }
  1367. }
  1368. /****************************TOWNS************************************************/
  1369. for (unsigned int i=0;i<map->towns.size();i++)
  1370. {
  1371. CGTownInstance * vti =(map->towns[i]);
  1372. if(!vti->town)
  1373. vti->town = &VLC->townh->towns[vti->subID];
  1374. if (vti->name.length()==0) // if town hasn't name we draw it
  1375. vti->name = vti->town->Names()[ran()%vti->town->Names().size()];
  1376. //init buildings
  1377. if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings
  1378. {
  1379. vti->builtBuildings.erase(-50);
  1380. vti->builtBuildings.insert(10);
  1381. vti->builtBuildings.insert(5);
  1382. vti->builtBuildings.insert(30);
  1383. if(ran()%2)
  1384. vti->builtBuildings.insert(31);
  1385. }
  1386. if (vstd::contains(vti->builtBuildings,(6)) && vti->state()==3)
  1387. vti->builtBuildings.erase(6);//if we have harbor without water - erase it (this is H3 behaviour)
  1388. //init hordes
  1389. for (int i = 0; i<CREATURES_PER_TOWN; i++)
  1390. if (vstd::contains(vti->builtBuildings,(-31-i))) //if we have horde for this level
  1391. {
  1392. vti->builtBuildings.erase(-31-i);//remove old ID
  1393. if (vti->town->hordeLvl[0] == i)//if town first horde is this one
  1394. {
  1395. vti->builtBuildings.insert(18);//add it
  1396. if (vstd::contains(vti->builtBuildings,(37+i)))//if we have upgraded dwelling as well
  1397. vti->builtBuildings.insert(19);//add it as well
  1398. }
  1399. if (vti->town->hordeLvl[1] == i)//if town second horde is this one
  1400. {
  1401. vti->builtBuildings.insert(24);
  1402. if (vstd::contains(vti->builtBuildings,(37+i)))
  1403. vti->builtBuildings.insert(25);
  1404. }
  1405. }
  1406. //init spells
  1407. vti->spells.resize(SPELL_LEVELS);
  1408. CSpell *s;
  1409. for(unsigned int z=0; z<vti->obligatorySpells.size();z++)
  1410. {
  1411. s = &VLC->spellh->spells[vti->obligatorySpells[z]];
  1412. vti->spells[s->level-1].push_back(s->id);
  1413. vti->possibleSpells -= s->id;
  1414. }
  1415. while(vti->possibleSpells.size())
  1416. {
  1417. ui32 total=0, sel=-1;
  1418. for(unsigned int ps=0;ps<vti->possibleSpells.size();ps++)
  1419. total += VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1420. int r = (total)? ran()%total : -1;
  1421. for(unsigned int ps=0; ps<vti->possibleSpells.size();ps++)
  1422. {
  1423. r -= VLC->spellh->spells[vti->possibleSpells[ps]].probabilities[vti->subID];
  1424. if(r<0)
  1425. {
  1426. sel = ps;
  1427. break;
  1428. }
  1429. }
  1430. if(sel<0)
  1431. sel=0;
  1432. CSpell *s = &VLC->spellh->spells[vti->possibleSpells[sel]];
  1433. vti->spells[s->level-1].push_back(s->id);
  1434. vti->possibleSpells -= s->id;
  1435. }
  1436. if(vti->getOwner() != 255)
  1437. getPlayer(vti->getOwner())->towns.push_back(vti);
  1438. }
  1439. for(std::map<ui8, PlayerState>::iterator k=players.begin(); k!=players.end(); ++k)
  1440. {
  1441. if(k->first==-1 || k->first==255)
  1442. continue;
  1443. //init visiting and garrisoned heroes
  1444. for(unsigned int l=0; l<k->second.heroes.size();l++)
  1445. {
  1446. CGHeroInstance *h = k->second.heroes[l];
  1447. for(unsigned int m=0; m<k->second.towns.size();m++)
  1448. {
  1449. CGTownInstance *t = k->second.towns[m];
  1450. int3 vistile = t->pos; vistile.x--; //tile next to the entrance
  1451. if(vistile == h->pos || h->pos==t->pos)
  1452. {
  1453. t->visitingHero = h;
  1454. h->visitedTown = t;
  1455. h->inTownGarrison = false;
  1456. if(h->pos == t->pos) //visiting hero placed in the editor has same pos as the town - we need to correct it
  1457. {
  1458. map->removeBlockVisTiles(h);
  1459. h->pos.x -= 1;
  1460. map->addBlockVisTiles(h);
  1461. }
  1462. break;
  1463. }
  1464. }
  1465. }
  1466. }
  1467. for(unsigned int i=0; i<map->defy.size(); i++)
  1468. {
  1469. map->defy[i]->serial = i;
  1470. }
  1471. objCaller->preInit();
  1472. for(unsigned int i=0; i<map->objects.size(); i++)
  1473. {
  1474. map->objects[i]->initObj();
  1475. if(map->objects[i]->ID == 62) //prison also needs to initialize hero
  1476. static_cast<CGHeroInstance*>(map->objects[i])->initHero();
  1477. }
  1478. objCaller->postInit();
  1479. }
  1480. bool CGameState::battleShootCreatureStack(int ID, int dest)
  1481. {
  1482. return true;
  1483. }
  1484. bool CGameState::battleCanFlee(int player)
  1485. {
  1486. if(!curB) //there is no battle
  1487. return false;
  1488. if(curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE) //eg. one of heroes is wearing shakles of war
  1489. || curB->heroes[0]->hasBonusOfType(Bonus::ENEMY_CANT_ESCAPE))
  1490. return false;
  1491. return true;
  1492. }
  1493. int CGameState::battleGetStack(int pos, bool onlyAlive)
  1494. {
  1495. if(!curB)
  1496. return -1;
  1497. for(unsigned int g=0; g<curB->stacks.size(); ++g)
  1498. {
  1499. if((curB->stacks[g]->position == pos
  1500. || (curB->stacks[g]->doubleWide()
  1501. &&( (curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == pos)
  1502. || (!curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == pos) )
  1503. ))
  1504. && (!onlyAlive || curB->stacks[g]->alive())
  1505. )
  1506. return curB->stacks[g]->ID;
  1507. }
  1508. return -1;
  1509. }
  1510. int CGameState::battleGetBattlefieldType(int3 tile)
  1511. {
  1512. if(tile==int3() && curB)
  1513. tile = curB->tile;
  1514. else if(tile==int3() && !curB)
  1515. return -1;
  1516. const std::vector <CGObjectInstance*> & objs = map->objects;
  1517. for(int g=0; g<objs.size(); ++g)
  1518. {
  1519. if( !objs[g] || objs[g]->pos.x - tile.x < 0 || objs[g]->pos.x - tile.x >= 8
  1520. || tile.y - objs[g]->pos.y + 5 < 0 || tile.y - objs[g]->pos.y + 5 >=6
  1521. || !objs[g]->coveringAt(objs[g]->pos.x - tile.x, tile.y - objs[g]->pos.y + 5)
  1522. ) //look only for objects covering given tile
  1523. continue;
  1524. switch(objs[g]->ID)
  1525. {
  1526. case 222: //clover field
  1527. return 19;
  1528. case 21: case 223: //cursed ground
  1529. return 22;
  1530. case 224: //evil fog
  1531. return 20;
  1532. case 225: //favourable winds
  1533. return 21;
  1534. case 226: //fiery fields
  1535. return 14;
  1536. case 227: //holy ground
  1537. return 18;
  1538. case 228: //lucid pools
  1539. return 17;
  1540. case 229: //magic clouds
  1541. return 16;
  1542. case 46: case 230: //magic plains
  1543. return 9;
  1544. case 231: //rocklands
  1545. return 15;
  1546. }
  1547. }
  1548. switch(map->terrain[tile.x][tile.y][tile.z].tertype)
  1549. {
  1550. case TerrainTile::dirt:
  1551. return rand()%3+3;
  1552. case TerrainTile::sand:
  1553. return 2; //TODO: coast support
  1554. case TerrainTile::grass:
  1555. return rand()%2+6;
  1556. case TerrainTile::snow:
  1557. return rand()%2+10;
  1558. case TerrainTile::swamp:
  1559. return 13;
  1560. case TerrainTile::rough:
  1561. return 23;
  1562. case TerrainTile::subterranean:
  1563. return 12;
  1564. case TerrainTile::lava:
  1565. return 8;
  1566. case TerrainTile::water:
  1567. return 25;
  1568. case TerrainTile::rock:
  1569. return 15;
  1570. default:
  1571. return -1;
  1572. }
  1573. }
  1574. const CGHeroInstance * CGameState::battleGetOwner(int stackID)
  1575. {
  1576. if(!curB)
  1577. return NULL;
  1578. return curB->heroes[!curB->getStack(stackID)->attackerOwned];
  1579. }
  1580. std::set<std::pair<int, int> > costDiff(const std::vector<ui32> &a, const std::vector<ui32> &b, const int modifier = 100) //modifer %
  1581. {
  1582. std::set<std::pair<int, int> > ret;
  1583. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1584. {
  1585. assert(a[j] >= b[j]);
  1586. if(int dif = modifier * (a[j] - b[j]) / 100)
  1587. ret.insert(std::make_pair(j,dif));
  1588. }
  1589. return ret;
  1590. }
  1591. UpgradeInfo CGameState::getUpgradeInfo(const CStackInstance &stack)
  1592. {
  1593. UpgradeInfo ret;
  1594. const CCreature *base = stack.type;
  1595. const CGHeroInstance *h = stack.armyObj->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(stack.armyObj) : NULL;
  1596. const CGTownInstance *t = NULL;
  1597. if(stack.armyObj->ID == TOWNI_TYPE)
  1598. t = static_cast<const CGTownInstance *>(stack.armyObj);
  1599. else if(h)
  1600. { //TODO: check if hero specialty makes some upgrades possible
  1601. BonusList lista = h->speciality.getBonuses(Selector::typeSybtype(Bonus::SPECIAL_UPGRADE, base->idNumber));
  1602. for (BonusList::iterator it = lista.begin(); it != lista.end(); it++)
  1603. {
  1604. ui16 nid = it->additionalInfo;
  1605. if (nid != base->idNumber) //sharpshooter appears to be default upgrade of minor creatures (?)
  1606. {
  1607. ret.newID.push_back(nid);
  1608. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1609. }
  1610. }
  1611. t = h->visitedTown;
  1612. }
  1613. if(t)
  1614. {
  1615. BOOST_FOREACH(si32 bid, t->builtBuildings)
  1616. {
  1617. if( bid >= 37 && bid < 44 ) //upgraded creature dwelling
  1618. {
  1619. int nid = t->town->upgradedCreatures[bid-37]; //upgrade offered by that building
  1620. if(vstd::contains(base->upgrades, nid)) //possible upgrade
  1621. {
  1622. ret.newID.push_back(nid);
  1623. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost));
  1624. }
  1625. }
  1626. }
  1627. }
  1628. //hero is visiting Hill Fort
  1629. if(h && map->getTile(h->visitablePos()).visitableObjects.front()->ID == 35)
  1630. {
  1631. static const int costModifiers[] = {0, 25, 50, 75, 100}; //we get cheaper upgrades depending on level
  1632. const int costModifier = costModifiers[std::min<int>(std::max((int)base->level - 1, 0), ARRAY_COUNT(costModifiers) - 1)];
  1633. BOOST_FOREACH(si32 nid, base->upgrades)
  1634. {
  1635. ret.newID.push_back(nid);
  1636. ret.cost.push_back(costDiff(VLC->creh->creatures[nid]->cost, base->cost, costModifier));
  1637. }
  1638. }
  1639. if(ret.newID.size())
  1640. ret.oldID = base->idNumber;
  1641. return ret;
  1642. }
  1643. void CGameState::loadTownDInfos()
  1644. {
  1645. for(int i=0;i<F_NUMBER;i++)
  1646. {
  1647. villages[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1648. forts[i] = VLC->dobjinfo->castles[i];
  1649. capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]);
  1650. }
  1651. }
  1652. void CGameState::getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing)
  1653. {
  1654. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0),
  1655. int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1656. vec.clear();
  1657. for (size_t i = 0; i < ARRAY_COUNT(dirs); i++)
  1658. {
  1659. const int3 hlp = tile + dirs[i];
  1660. if(!map->isInTheMap(hlp))
  1661. continue;
  1662. const TerrainTile &hlpt = map->getTile(hlp);
  1663. //we cannot visit things from blocked tiles
  1664. if(srct.blocked && !srct.visitable && hlpt.visitable && srct.blockingObjects.front()->ID != HEROI_TYPE)
  1665. {
  1666. continue;
  1667. }
  1668. if(srct.tertype == TerrainTile::water && limitCoastSailing && hlpt.tertype == TerrainTile::water && dirs[i].x && dirs[i].y) //diagonal move through water
  1669. {
  1670. int3 hlp1 = tile,
  1671. hlp2 = tile;
  1672. hlp1.x += dirs[i].x;
  1673. hlp2.y += dirs[i].y;
  1674. if(map->getTile(hlp1).tertype != TerrainTile::water || map->getTile(hlp2).tertype != TerrainTile::water)
  1675. continue;
  1676. }
  1677. if((indeterminate(onLand) || onLand == (hlpt.tertype!=TerrainTile::water) )
  1678. && hlpt.tertype != TerrainTile::rock)
  1679. {
  1680. vec.push_back(hlp);
  1681. }
  1682. }
  1683. }
  1684. int CGameState::getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints, bool checkLast)
  1685. {
  1686. if(src == dest) //same tile
  1687. return 0;
  1688. TerrainTile &s = map->terrain[src.x][src.y][src.z],
  1689. &d = map->terrain[dest.x][dest.y][dest.z];
  1690. //get basic cost
  1691. int ret = h->getTileCost(d,s);
  1692. if(d.blocked && h->hasBonusOfType(Bonus::FLYING_MOVEMENT))
  1693. {
  1694. bool freeFlying = h->getBonusesCount(Selector::typeSybtype(Bonus::FLYING_MOVEMENT, 1)) > 0;
  1695. if(!freeFlying)
  1696. {
  1697. ret *= 1.4f; //40% penalty for movement over blocked tile
  1698. }
  1699. }
  1700. else if (d.tertype == TerrainTile::water)
  1701. {
  1702. if(h->boat && s.siodmyTajemniczyBajt & 128 && d.siodmyTajemniczyBajt & 128) //Favourable Winds
  1703. ret *= 0.666f;
  1704. else if (!h->boat && h->getBonusesCount(Selector::typeSybtype(Bonus::WATER_WALKING, 1)) > 0)
  1705. ret *= 1.4f; //40% penalty for water walking
  1706. }
  1707. if(src.x != dest.x && src.y != dest.y) //it's diagonal move
  1708. {
  1709. int old = ret;
  1710. ret *= 1.414213;
  1711. //diagonal move costs too much but normal move is possible - allow diagonal move for remaining move points
  1712. if(ret > remainingMovePoints && remainingMovePoints >= old)
  1713. {
  1714. return remainingMovePoints;
  1715. }
  1716. }
  1717. int left = remainingMovePoints-ret;
  1718. if(checkLast && left > 0 && remainingMovePoints-ret < 250) //it might be the last tile - if no further move possible we take all move points
  1719. {
  1720. std::vector<int3> vec;
  1721. getNeighbours(d, dest, vec, s.tertype != TerrainTile::water, true);
  1722. for(size_t i=0; i < vec.size(); i++)
  1723. {
  1724. int fcost = getMovementCost(h,dest,vec[i],left,false);
  1725. if(fcost <= left)
  1726. {
  1727. return ret;
  1728. }
  1729. }
  1730. ret = remainingMovePoints;
  1731. }
  1732. return ret;
  1733. }
  1734. std::set<int> CGameState::getBuildingRequiments(const CGTownInstance *t, int ID)
  1735. {
  1736. std::set<int> used;
  1737. used.insert(ID);
  1738. std::set<int> reqs = VLC->townh->requirements[t->subID][ID];
  1739. while(true)
  1740. {
  1741. size_t noloop=0;
  1742. for(std::set<int>::iterator i=reqs.begin();i!=reqs.end();i++)
  1743. {
  1744. if(used.find(*i)==used.end()) //we haven't added requirements for this building
  1745. {
  1746. used.insert(*i);
  1747. for(
  1748. std::set<int>::iterator j=VLC->townh->requirements[t->subID][*i].begin();
  1749. j!=VLC->townh->requirements[t->subID][*i].end();
  1750. j++)
  1751. {
  1752. reqs.insert(*j);//creating full list of requirements
  1753. }
  1754. }
  1755. else
  1756. {
  1757. noloop++;
  1758. }
  1759. }
  1760. if(noloop==reqs.size())
  1761. break;
  1762. }
  1763. return reqs;
  1764. }
  1765. int CGameState::canBuildStructure( const CGTownInstance *t, int ID )
  1766. {
  1767. int ret = 7; //allowed by default
  1768. if(t->builded >= MAX_BUILDING_PER_TURN)
  1769. ret = 5; //building limit
  1770. //checking resources
  1771. CBuilding * pom = VLC->buildh->buildings[t->subID][ID];
  1772. if(!pom)
  1773. return 8;
  1774. // if(pom->Name().size()==0||pom->resources.size()==0)
  1775. // return 2;//TODO: why does this happen?
  1776. for(int res=0;res<pom->resources.size();res++) //TODO: support custom amount of resources
  1777. {
  1778. if(pom->resources[res] > getPlayer(t->tempOwner)->resources[res])
  1779. ret = 6; //lack of res
  1780. }
  1781. //checking for requirements
  1782. std::set<int> reqs = getBuildingRequiments(t, ID);//getting all requiments
  1783. for( std::set<int>::iterator ri = reqs.begin(); ri != reqs.end(); ri++ )
  1784. {
  1785. if(t->builtBuildings.find(*ri)==t->builtBuildings.end())
  1786. ret = 8; //lack of requirements - cannot build
  1787. }
  1788. //can we build it?
  1789. if(t->forbiddenBuildings.find(ID)!=t->forbiddenBuildings.end())
  1790. ret = 2; //forbidden
  1791. if(ID == 13) //capitol
  1792. {
  1793. for(unsigned int in = 0; in < map->towns.size(); in++)
  1794. {
  1795. if(map->towns[in]->tempOwner==t->tempOwner && vstd::contains(map->towns[in]->builtBuildings,13))
  1796. {
  1797. ret = 0; //no more than one capitol
  1798. break;
  1799. }
  1800. }
  1801. }
  1802. else if(ID == 6) //shipyard
  1803. {
  1804. int3 t1(t->pos + int3(-1,3,0)),
  1805. t2(t->pos + int3(-3,3,0));
  1806. if(map->isInTheMap(t1) && map->getTile(t1).tertype != TerrainTile::water
  1807. && (map->isInTheMap(t2) && map->getTile(t2).tertype != TerrainTile::water))
  1808. ret = 1; //lack of water
  1809. }
  1810. if(t->builtBuildings.find(ID)!=t->builtBuildings.end()) //already built
  1811. ret = 4;
  1812. return ret;
  1813. }
  1814. void CGameState::apply(CPack *pack)
  1815. {
  1816. ui16 typ = typeList.getTypeID(pack);
  1817. assert(typ >= 0);
  1818. applierGs->apps[typ]->applyOnGS(this,pack);
  1819. }
  1820. PlayerState * CGameState::getPlayer( ui8 color, bool verbose )
  1821. {
  1822. if(vstd::contains(players,color))
  1823. {
  1824. return &players[color];
  1825. }
  1826. else
  1827. {
  1828. if(verbose)
  1829. tlog2 << "Warning: Cannot find info for player " << int(color) << std::endl;
  1830. return NULL;
  1831. }
  1832. }
  1833. const PlayerState * CGameState::getPlayer( ui8 color, bool verbose ) const
  1834. {
  1835. return (const_cast<CGameState *>(this))->getPlayer(color, verbose);
  1836. }
  1837. bool CGameState::getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret)
  1838. {
  1839. if(!map->isInTheMap(src) || !map->isInTheMap(dest)) //check input
  1840. return false;
  1841. int3 hpos = hero->getPosition(false);
  1842. bool flying = false; //hero is under flying effect TODO
  1843. bool waterWalking = false; //hero is on land and can walk on water TODO
  1844. bool onLand = map->getTile(hpos).tertype != TerrainTile::water;
  1845. // tribool blockLandSea; //true - blocks sea, false - blocks land, indeterminate - allows all
  1846. //
  1847. // if (!hero->canWalkOnSea())
  1848. // blockLandSea = (map->getTile(hpos).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1849. // else
  1850. // blockLandSea = boost::logic::indeterminate;
  1851. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1852. //graph initialization
  1853. std::vector< std::vector<CPathNode> > graph;
  1854. graph.resize(map->width);
  1855. for(size_t i=0; i<graph.size(); ++i)
  1856. {
  1857. graph[i].resize(map->height);
  1858. for(size_t j=0; j<graph[i].size(); ++j)
  1859. {
  1860. const TerrainTile *tinfo = &map->terrain[i][j][src.z];
  1861. CPathNode &node = graph[i][j];
  1862. node.accessible = !tinfo->blocked;
  1863. node.dist = -1;
  1864. node.theNodeBefore = NULL;
  1865. node.visited = false;
  1866. node.coord.x = i;
  1867. node.coord.y = j;
  1868. node.coord.z = dest.z;
  1869. if(!tinfo->entrableTerrain(onLand, flying || waterWalking)
  1870. || !FoW[i][j][src.z] //tile is covered by the FoW
  1871. )
  1872. {
  1873. node.accessible = false;
  1874. }
  1875. }
  1876. }
  1877. //Special rules for the destination tile
  1878. {
  1879. const TerrainTile *t = &map->terrain[dest.x][dest.y][dest.z];
  1880. CPathNode &d = graph[dest.x][dest.y];
  1881. //tile may be blocked by blockvis / normal vis obj but it still must be accessible
  1882. if(t->visitable)
  1883. {
  1884. d.accessible = true; //for allowing visiting objects
  1885. }
  1886. if(onLand && t->tertype == TerrainTile::water) //hero can walk only on land and dst lays on the water
  1887. {
  1888. size_t i = 0;
  1889. for(; i < t->visitableObjects.size(); i++)
  1890. if(t->visitableObjects[i]->ID == 8 || t->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  1891. break;
  1892. d.accessible = (i < t->visitableObjects.size()); //dest is accessible only if there is boat/hero
  1893. }
  1894. else if(!onLand && t->tertype != TerrainTile::water) //hero is moving by water
  1895. {
  1896. d.accessible = (t->siodmyTajemniczyBajt & 64) && !t->blocked; //tile is accessible if it's coastal and not blocked
  1897. }
  1898. }
  1899. //graph initialized
  1900. //initial tile - set cost on 0 and add to the queue
  1901. graph[src.x][src.y].dist = 0;
  1902. std::queue<CPathNode> mq;
  1903. mq.push(graph[src.x][src.y]);
  1904. ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  1905. std::vector<int3> neighbours;
  1906. neighbours.reserve(8);
  1907. while(!mq.empty())
  1908. {
  1909. CPathNode &cp = graph[mq.front().coord.x][mq.front().coord.y];
  1910. mq.pop();
  1911. if (cp.coord == dest) //it's destination tile
  1912. {
  1913. if (cp.dist < curDist) //that path is better than previous one
  1914. curDist = cp.dist;
  1915. continue;
  1916. }
  1917. else
  1918. {
  1919. if (cp.dist > curDist) //it's not dest and current length is greater than cost of already found path
  1920. continue;
  1921. }
  1922. //add accessible neighbouring nodes to the queue
  1923. getNeighbours(map->getTile(cp.coord), cp.coord, neighbours, boost::logic::indeterminate, true);
  1924. for(unsigned int i=0; i < neighbours.size(); i++)
  1925. {
  1926. CPathNode & dp = graph[neighbours[i].x][neighbours[i].y];
  1927. if(dp.accessible)
  1928. {
  1929. int cost = getMovementCost(hero,cp.coord,dp.coord,hero->movement - cp.dist);
  1930. if((dp.dist==-1 || (dp.dist > cp.dist + cost)) && dp.accessible && checkForVisitableDir(cp.coord, dp.coord) && checkForVisitableDir(dp.coord, cp.coord))
  1931. {
  1932. dp.dist = cp.dist + cost;
  1933. dp.theNodeBefore = &cp;
  1934. mq.push(dp);
  1935. }
  1936. }
  1937. }
  1938. }
  1939. CPathNode *curNode = &graph[dest.x][dest.y];
  1940. if(!curNode->theNodeBefore) //destination is not accessible
  1941. return false;
  1942. //fill ret with found path
  1943. ret.nodes.clear();
  1944. while(curNode->coord != graph[src.x][src.y].coord)
  1945. {
  1946. ret.nodes.push_back(*curNode);
  1947. curNode = curNode->theNodeBefore;
  1948. }
  1949. ret.nodes.push_back(graph[src.x][src.y]);
  1950. return true;
  1951. }
  1952. void CGameState::calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src, int movement)
  1953. {
  1954. assert(hero);
  1955. boost::shared_lock<boost::shared_mutex> lock(*mx);
  1956. if(src.x < 0)
  1957. src = hero->getPosition(false);
  1958. if(movement < 0)
  1959. movement = hero->movement;
  1960. out.hero = hero;
  1961. out.hpos = src;
  1962. if(!map->isInTheMap(src)/* || !map->isInTheMap(dest)*/) //check input
  1963. {
  1964. tlog1 << "CGameState::calculatePaths: Hero outside the map? How dare you...\n";
  1965. return;
  1966. }
  1967. tribool onLand; //true - blocks sea, false - blocks land, indeterminate - allows all
  1968. if (!hero->canWalkOnSea())
  1969. onLand = (map->getTile(src).tertype != TerrainTile::water); //block land if hero is on water and vice versa
  1970. else
  1971. onLand = boost::logic::indeterminate;
  1972. const std::vector<std::vector<std::vector<ui8> > > &FoW = getPlayer(hero->tempOwner)->fogOfWarMap;
  1973. bool flying = hero->hasBonusOfType(Bonus::FLYING_MOVEMENT);
  1974. bool waterWalk = hero->hasBonusOfType(Bonus::WATER_WALKING);
  1975. //graph initialization
  1976. CGPathNode ***graph = out.nodes;
  1977. for(size_t i=0; i < out.sizes.x; ++i)
  1978. {
  1979. for(size_t j=0; j < out.sizes.y; ++j)
  1980. {
  1981. for(size_t k=0; k < out.sizes.z; ++k)
  1982. {
  1983. const TerrainTile *tinfo = &map->terrain[i][j][k];
  1984. CGPathNode &node = graph[i][j][k];
  1985. node.accessible = (tinfo->blocked ? CGPathNode::FLYABLE : CGPathNode::ACCESSIBLE);
  1986. if(!flying && node.accessible == CGPathNode::FLYABLE)
  1987. {
  1988. node.accessible = CGPathNode::BLOCKED;
  1989. }
  1990. node.turns = 0xff;
  1991. node.moveRemains = 0;
  1992. node.coord.x = i;
  1993. node.coord.y = j;
  1994. node.coord.z = k;
  1995. node.land = tinfo->tertype != TerrainTile::water;
  1996. node.theNodeBefore = NULL;
  1997. bool leaveAsBlocked = false;
  1998. if((onLand || indeterminate(onLand)) && !node.land)//it's sea and we cannot walk on sea
  1999. {
  2000. if (waterWalk || flying)
  2001. {
  2002. node.accessible = CGPathNode::FLYABLE;
  2003. }
  2004. else
  2005. {
  2006. node.accessible = CGPathNode::BLOCKED;
  2007. leaveAsBlocked = true;
  2008. }
  2009. }
  2010. if ( tinfo->tertype == TerrainTile::rock//it's rock
  2011. || !onLand && node.land //it's land and we cannot walk on land (complementary condition is handled above)
  2012. || !FoW[i][j][k] //tile is covered by the FoW
  2013. || leaveAsBlocked
  2014. )
  2015. {
  2016. node.accessible = CGPathNode::BLOCKED;
  2017. }
  2018. else if(tinfo->visitable)
  2019. {
  2020. //hero is protected in Sanctuary
  2021. if(tinfo->visitableObjects.front()->ID == 80 && tinfo->visitableObjects.back()->ID == HEROI_TYPE && tinfo->visitableObjects.back()->tempOwner != hero->tempOwner)
  2022. node.accessible = CGPathNode::BLOCKED;
  2023. else
  2024. {
  2025. for(size_t ii = 0; ii < tinfo->visitableObjects.size(); ii++)
  2026. {
  2027. const CGObjectInstance * const obj = tinfo->visitableObjects[ii];
  2028. if(obj->getPassableness() & 1<<hero->tempOwner) //special object instance specific passableness flag - overwrites other accessibility flags
  2029. {
  2030. node.accessible = CGPathNode::ACCESSIBLE;
  2031. }
  2032. else if(obj->blockVisit)
  2033. {
  2034. node.accessible = CGPathNode::BLOCKVIS;
  2035. break;
  2036. }
  2037. else if(obj->ID != EVENTI_TYPE) //pathfinder should ignore placed events
  2038. {
  2039. node.accessible = CGPathNode::VISITABLE;
  2040. }
  2041. }
  2042. }
  2043. }
  2044. else if (map->isInTheMap(guardingCreaturePosition(int3(i, j, k)))
  2045. && tinfo->blockingObjects.size() == 0)
  2046. {
  2047. // Monster close by; blocked visit for battle.
  2048. node.accessible = CGPathNode::BLOCKVIS;
  2049. }
  2050. if(onLand && !node.land) //hero can walk only on land and tile lays on the water
  2051. {
  2052. size_t i = 0;
  2053. for(; i < tinfo->visitableObjects.size(); i++)
  2054. if(tinfo->visitableObjects[i]->ID == 8 || tinfo->visitableObjects[i]->ID == HEROI_TYPE) //it's a Boat
  2055. break;
  2056. if(i < tinfo->visitableObjects.size())
  2057. node.accessible = CGPathNode::BLOCKVIS; //dest is accessible only if there is boat/hero
  2058. }
  2059. else if(!onLand && tinfo->tertype != TerrainTile::water) //hero is moving by water
  2060. {
  2061. if((tinfo->siodmyTajemniczyBajt & 64) && !tinfo->blocked)
  2062. node.accessible = CGPathNode::VISITABLE; //tile is accessible if it's coastal and not blocked
  2063. }
  2064. }
  2065. }
  2066. }
  2067. //graph initialized
  2068. //initial tile - set cost on 0 and add to the queue
  2069. graph[src.x][src.y][src.z].turns = 0;
  2070. graph[src.x][src.y][src.z].moveRemains = movement;
  2071. std::queue<CGPathNode*> mq;
  2072. mq.push(&graph[src.x][src.y][src.z]);
  2073. //ui32 curDist = 0xffffffff; //total cost of path - init with max possible val
  2074. std::vector<int3> neighbours;
  2075. neighbours.reserve(8);
  2076. while(!mq.empty())
  2077. {
  2078. CGPathNode *cp = mq.front();
  2079. mq.pop();
  2080. const int3 guardPosition = guardingCreaturePosition(cp->coord);
  2081. const bool guardedPosition = (guardPosition != int3(-1, -1, -1) && cp->coord != src);
  2082. const TerrainTile &ct = map->getTile(cp->coord);
  2083. int movement = cp->moveRemains, turn = cp->turns;
  2084. if(!movement)
  2085. {
  2086. movement = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2087. turn++;
  2088. }
  2089. //add accessible neighbouring nodes to the queue
  2090. getNeighbours(ct, cp->coord, neighbours, boost::logic::indeterminate, !onLand);
  2091. for(unsigned int i=0; i < neighbours.size(); i++)
  2092. {
  2093. int moveAtNextTile = movement;
  2094. int turnAtNextTile = turn;
  2095. const int3 &n = neighbours[i]; //current neighbor
  2096. CGPathNode & dp = graph[n.x][n.y][n.z];
  2097. if( !checkForVisitableDir(cp->coord, dp.coord)
  2098. || !checkForVisitableDir(dp.coord, cp->coord)
  2099. || dp.accessible == CGPathNode::BLOCKED )
  2100. {
  2101. continue;
  2102. }
  2103. int cost = getMovementCost(hero, cp->coord, dp.coord, movement);
  2104. int remains = movement - cost;
  2105. if(remains < 0)
  2106. {
  2107. //occurs rarely, when hero with low movepoints tries to go leave the road
  2108. turnAtNextTile++;
  2109. moveAtNextTile = hero->maxMovePoints(ct.tertype != TerrainTile::water);
  2110. cost = getMovementCost(hero, cp->coord, dp.coord, moveAtNextTile); //cost must be updated, movement points changed :(
  2111. remains = moveAtNextTile - cost;
  2112. }
  2113. const bool neighborIsGuard = guardingCreaturePosition(cp->coord) == dp.coord;
  2114. if((dp.turns==0xff //we haven't been here before
  2115. || dp.turns > turnAtNextTile
  2116. || (dp.turns >= turnAtNextTile && dp.moveRemains < remains)) //this route is faster
  2117. && (!guardedPosition || neighborIsGuard)) // Can step into tile of guard
  2118. {
  2119. assert(&dp != cp->theNodeBefore); //two tiles can't point to each other
  2120. dp.moveRemains = remains;
  2121. dp.turns = turnAtNextTile;
  2122. dp.theNodeBefore = cp;
  2123. const bool guardedNeighbor = guardingCreaturePosition(dp.coord) != int3(-1, -1, -1);
  2124. //const bool positionIsGuard = guardingCreaturePosition(cp->coord) == cp->coord; //can this be true? hero never passes from monster tile...
  2125. if (dp.accessible == CGPathNode::ACCESSIBLE || dp.accessible == CGPathNode::FLYABLE
  2126. || (guardedNeighbor && !guardedPosition)) // Can step into a hostile tile once.
  2127. {
  2128. mq.push(&dp);
  2129. }
  2130. }
  2131. } //neighbours loop
  2132. } //queue loop
  2133. }
  2134. /**
  2135. * Tells if the tile is guarded by a monster as well as the position
  2136. * of the monster that will attack on it.
  2137. *
  2138. * @return int3(-1, -1, -1) if the tile is unguarded, or the position of
  2139. * the monster guarding the tile.
  2140. */
  2141. int3 CGameState::guardingCreaturePosition (int3 pos) const
  2142. {
  2143. const int3 originalPos = pos;
  2144. // Give monster at position priority.
  2145. if (!map->isInTheMap(pos))
  2146. return int3(-1, -1, -1);
  2147. const TerrainTile &posTile = map->terrain[pos.x][pos.y][pos.z];
  2148. if (posTile.visitable)
  2149. {
  2150. BOOST_FOREACH (CGObjectInstance* obj, posTile.visitableObjects)
  2151. {
  2152. if(obj->blockVisit)
  2153. {
  2154. if (obj->ID == 54) // Monster
  2155. return pos;
  2156. else
  2157. return int3(-1, -1, -1); //blockvis objects are not guarded by neighbouring creatures
  2158. }
  2159. }
  2160. }
  2161. // See if there are any monsters adjacent.
  2162. pos -= int3(1, 1, 0); // Start with top left.
  2163. for (int dx = 0; dx < 3; dx++)
  2164. {
  2165. for (int dy = 0; dy < 3; dy++)
  2166. {
  2167. if (map->isInTheMap(pos))
  2168. {
  2169. TerrainTile &tile = map->terrain[pos.x][pos.y][pos.z];
  2170. if (tile.visitable && (tile.tertype == TerrainTile::water) == (posTile.tertype == TerrainTile::water))
  2171. {
  2172. BOOST_FOREACH (CGObjectInstance* obj, tile.visitableObjects)
  2173. {
  2174. if (obj->ID == 54 && checkForVisitableDir(pos, &map->getTile(originalPos), originalPos)) // Monster being able to attack investigated tile
  2175. {
  2176. return pos;
  2177. }
  2178. }
  2179. }
  2180. }
  2181. pos.y++;
  2182. }
  2183. pos.y -= 3;
  2184. pos.x++;
  2185. }
  2186. return int3(-1, -1, -1);
  2187. }
  2188. bool CGameState::isVisible(int3 pos, int player)
  2189. {
  2190. if(player == 255) //neutral player
  2191. return false;
  2192. return players[player].fogOfWarMap[pos.x][pos.y][pos.z];
  2193. }
  2194. bool CGameState::isVisible( const CGObjectInstance *obj, int player )
  2195. {
  2196. if(player == 255) //neutral player
  2197. return false;
  2198. //object is visible when at least one blocked tile is visible
  2199. for(int fx=0; fx<8; ++fx)
  2200. {
  2201. for(int fy=0; fy<6; ++fy)
  2202. {
  2203. int3 pos = obj->pos + int3(fx-7,fy-5,0);
  2204. if(map->isInTheMap(pos)
  2205. && !((obj->defInfo->blockMap[fy] >> (7 - fx)) & 1)
  2206. && isVisible(pos, player) )
  2207. return true;
  2208. }
  2209. }
  2210. return false;
  2211. }
  2212. bool CGameState::checkForVisitableDir(const int3 & src, const int3 & dst) const
  2213. {
  2214. const TerrainTile * pom = &map->getTile(dst);
  2215. return checkForVisitableDir(src, pom, dst);
  2216. }
  2217. bool CGameState::checkForVisitableDir( const int3 & src, const TerrainTile *pom, const int3 & dst ) const
  2218. {
  2219. for(unsigned int b=0; b<pom->visitableObjects.size(); ++b) //checking destination tile
  2220. {
  2221. if(!vstd::contains(pom->blockingObjects, pom->visitableObjects[b])) //this visitable object is not blocking, ignore
  2222. continue;
  2223. CGDefInfo * di = pom->visitableObjects[b]->defInfo;
  2224. if( (dst.x == src.x-1 && dst.y == src.y-1) && !(di->visitDir & (1<<4)) )
  2225. {
  2226. return false;
  2227. }
  2228. if( (dst.x == src.x && dst.y == src.y-1) && !(di->visitDir & (1<<5)) )
  2229. {
  2230. return false;
  2231. }
  2232. if( (dst.x == src.x+1 && dst.y == src.y-1) && !(di->visitDir & (1<<6)) )
  2233. {
  2234. return false;
  2235. }
  2236. if( (dst.x == src.x+1 && dst.y == src.y) && !(di->visitDir & (1<<7)) )
  2237. {
  2238. return false;
  2239. }
  2240. if( (dst.x == src.x+1 && dst.y == src.y+1) && !(di->visitDir & (1<<0)) )
  2241. {
  2242. return false;
  2243. }
  2244. if( (dst.x == src.x && dst.y == src.y+1) && !(di->visitDir & (1<<1)) )
  2245. {
  2246. return false;
  2247. }
  2248. if( (dst.x == src.x-1 && dst.y == src.y+1) && !(di->visitDir & (1<<2)) )
  2249. {
  2250. return false;
  2251. }
  2252. if( (dst.x == src.x-1 && dst.y == src.y) && !(di->visitDir & (1<<3)) )
  2253. {
  2254. return false;
  2255. }
  2256. }
  2257. return true;
  2258. }
  2259. std::pair<ui32, ui32> BattleInfo::calculateDmgRange( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2260. {
  2261. float additiveBonus=1.0f, multBonus=1.0f,
  2262. minDmg = attacker->getMinDamage() * attacker->count,
  2263. maxDmg = attacker->getMaxDamage() * attacker->count;
  2264. if(attacker->type->idNumber == 149) //arrow turret
  2265. {
  2266. switch(attacker->position)
  2267. {
  2268. case -2: //keep
  2269. minDmg = 15;
  2270. maxDmg = 15;
  2271. break;
  2272. case -3: case -4: //turrets
  2273. minDmg = 7.5f;
  2274. maxDmg = 7.5f;
  2275. break;
  2276. }
  2277. }
  2278. if(attacker->hasBonusOfType(Bonus::SIEGE_WEAPON) && attacker->type->idNumber != 149) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
  2279. { //minDmg and maxDmg are multiplied by hero attack + 1
  2280. minDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2281. maxDmg *= attackerHero->getPrimSkillLevel(0) + 1;
  2282. }
  2283. int attackDefenceDifference = 0;
  2284. if(attacker->hasBonusOfType(Bonus::GENERAL_ATTACK_REDUCTION))
  2285. {
  2286. float multAttackReduction = attacker->valOfBonuses(Bonus::GENERAL_ATTACK_REDUCTION, -1024) / 100.0f;
  2287. attackDefenceDifference = attacker->Attack() * multAttackReduction;
  2288. }
  2289. else
  2290. {
  2291. attackDefenceDifference = attacker->Attack();
  2292. }
  2293. if(attacker->hasBonusOfType(Bonus::ENEMY_DEFENCE_REDUCTION))
  2294. {
  2295. float multDefenceReduction = (100.0f - attacker->valOfBonuses(Bonus::ENEMY_DEFENCE_REDUCTION, -1024)) / 100.0f;
  2296. attackDefenceDifference -= defender->Defense() * multDefenceReduction;
  2297. }
  2298. else
  2299. {
  2300. attackDefenceDifference -= defender->Defense();
  2301. }
  2302. //calculating total attack/defense skills modifier
  2303. if(shooting) //precision handling (etc.)
  2304. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)).totalValue();
  2305. else //bloodlust handling (etc.)
  2306. attackDefenceDifference += attacker->getBonuses(Selector::typeSybtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK), Selector::effectRange(Bonus::ONLY_MELEE_FIGHT)).totalValue();
  2307. if(attacker->getEffect(55)) //slayer handling
  2308. {
  2309. std::vector<int> affectedIds;
  2310. int spLevel = attacker->getEffect(55)->level;
  2311. for(int g = 0; g < VLC->creh->creatures.size(); ++g)
  2312. {
  2313. BOOST_FOREACH(const Bonus &b, VLC->creh->creatures[g]->bonuses)
  2314. {
  2315. if ( (b.type == Bonus::KING3 && spLevel >= 3) || //expert
  2316. (b.type == Bonus::KING2 && spLevel >= 2) || //adv +
  2317. (b.type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
  2318. {
  2319. affectedIds.push_back(g);
  2320. break;
  2321. }
  2322. }
  2323. }
  2324. for(unsigned int g=0; g<affectedIds.size(); ++g)
  2325. {
  2326. if(defender->type->idNumber == affectedIds[g])
  2327. {
  2328. attackDefenceDifference += VLC->spellh->spells[55].powers[attacker->getEffect(55)->level];
  2329. break;
  2330. }
  2331. }
  2332. }
  2333. //bonus from attack/defense skills
  2334. if(attackDefenceDifference < 0) //decreasing dmg
  2335. {
  2336. float dec = 0.025f * (-attackDefenceDifference);
  2337. if(dec > 0.7f)
  2338. {
  2339. multBonus *= 0.3f; //1.0 - 0.7
  2340. }
  2341. else
  2342. {
  2343. multBonus *= 1.0f - dec;
  2344. }
  2345. }
  2346. else //increasing dmg
  2347. {
  2348. float inc = 0.05f * attackDefenceDifference;
  2349. if(inc > 4.0f)
  2350. {
  2351. additiveBonus += 4.0f;
  2352. }
  2353. else
  2354. {
  2355. additiveBonus += inc;
  2356. }
  2357. }
  2358. //applying jousting bonus
  2359. if( attacker->hasBonusOfType(Bonus::JOUSTING) && !defender->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
  2360. additiveBonus += charge * 0.05f;
  2361. //handling secondary abilities and artifacts giving premies to them
  2362. if(attackerHero)
  2363. {
  2364. if(shooting)
  2365. {
  2366. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 1) / 100.0f;
  2367. }
  2368. else
  2369. {
  2370. additiveBonus += attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 22) / 100.0f;
  2371. }
  2372. }
  2373. if(defendingHero)
  2374. {
  2375. multBonus *= (std::max(0, 100-attackerHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 23))) / 100.0f;
  2376. }
  2377. //handling hate effect
  2378. if( attacker->hasBonusOfType(Bonus::HATE, defender->type->idNumber) )
  2379. additiveBonus += 0.5f;
  2380. //luck bonus
  2381. if (lucky)
  2382. {
  2383. additiveBonus += 1.0f;
  2384. }
  2385. //handling spell effects
  2386. if(!shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) //eg. shield
  2387. {
  2388. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0f;
  2389. }
  2390. else if(shooting && defender->hasBonusOfType(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) //eg. air shield
  2391. {
  2392. multBonus *= float(defender->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0f;
  2393. }
  2394. if(attacker->getEffect(42)) //curse handling (partial, the rest is below)
  2395. {
  2396. multBonus *= 0.8f * float(VLC->spellh->spells[42].powers[attacker->getEffect(42)->level]); //the second factor is 1 or 0
  2397. }
  2398. class HLP
  2399. {
  2400. public:
  2401. static bool hasAdvancedAirShield(const CStack * stack)
  2402. {
  2403. for(int g=0; g<stack->effects.size(); ++g)
  2404. {
  2405. if (stack->effects[g].id == 28 && stack->effects[g].level >= 2)
  2406. {
  2407. return true;
  2408. }
  2409. }
  2410. return false;
  2411. }
  2412. };
  2413. //wall / distance penalty + advanced air shield
  2414. if (shooting && !NBonus::hasOfType(attackerHero, Bonus::NO_SHOTING_PENALTY) && (
  2415. hasDistancePenalty(attacker->ID, defender->position) || hasWallPenalty(attacker->ID, defender->position) ||
  2416. HLP::hasAdvancedAirShield(defender) )
  2417. )
  2418. {
  2419. multBonus *= 0.5;
  2420. }
  2421. if (!shooting && attacker->hasBonusOfType(Bonus::SHOOTER) && !attacker->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
  2422. {
  2423. multBonus *= 0.5;
  2424. }
  2425. minDmg *= additiveBonus * multBonus;
  2426. maxDmg *= additiveBonus * multBonus;
  2427. std::pair<ui32, ui32> returnedVal;
  2428. if(attacker->getEffect(42)) //curse handling (rest)
  2429. {
  2430. minDmg -= VLC->spellh->spells[42].powers[attacker->getEffect(42)->level];
  2431. returnedVal = std::make_pair(int(minDmg), int(minDmg));
  2432. }
  2433. else if(attacker->getEffect(41)) //bless handling
  2434. {
  2435. maxDmg += VLC->spellh->spells[41].powers[attacker->getEffect(41)->level];
  2436. returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
  2437. }
  2438. else
  2439. {
  2440. returnedVal = std::make_pair(int(minDmg), int(maxDmg));
  2441. }
  2442. //damage cannot be less than 1
  2443. amax(returnedVal.first, 1);
  2444. amax(returnedVal.second, 1);
  2445. return returnedVal;
  2446. }
  2447. ui32 BattleInfo::calculateDmg( const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky )
  2448. {
  2449. std::pair<ui32, ui32> range = calculateDmgRange(attacker, defender, attackerHero, defendingHero, shooting, charge, lucky);
  2450. if(range.first != range.second)
  2451. {
  2452. int valuesToAverage[10];
  2453. int howManyToAv = std::min<ui32>(10, attacker->count);
  2454. for (int g=0; g<howManyToAv; ++g)
  2455. {
  2456. valuesToAverage[g] = range.first + rand() % (range.second - range.first + 1);
  2457. }
  2458. return std::accumulate(valuesToAverage, valuesToAverage + howManyToAv, 0) / howManyToAv;
  2459. }
  2460. else
  2461. return range.first;
  2462. }
  2463. void BattleInfo::calculateCasualties( std::map<ui32,si32> *casualties ) const
  2464. {
  2465. for(unsigned int i=0; i<stacks.size();i++)//setting casualties
  2466. {
  2467. const CStack * const st = stacks[i];
  2468. si32 killed = (st->alive() ? st->baseAmount - st->count : st->baseAmount);
  2469. amax(killed, 0);
  2470. if(killed)
  2471. casualties[!st->attackerOwned][st->type->idNumber] += killed;
  2472. }
  2473. }
  2474. si8 CGameState::battleMaxSpellLevel()
  2475. {
  2476. if(!curB) //there is not battle
  2477. {
  2478. tlog1 << "si8 CGameState::maxSpellLevel() call when there is no battle!" << std::endl;
  2479. throw "si8 CGameState::maxSpellLevel() call when there is no battle!";
  2480. }
  2481. si8 levelLimit = SPELL_LEVELS;
  2482. const CGHeroInstance *h1 = curB->heroes[0];
  2483. if(h1)
  2484. {
  2485. for(std::list<Bonus>::const_iterator i = h1->bonuses.begin(); i != h1->bonuses.end(); i++)
  2486. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2487. amin(levelLimit, i->val);
  2488. }
  2489. const CGHeroInstance *h2 = curB->heroes[1];
  2490. if(h2)
  2491. {
  2492. for(std::list<Bonus>::const_iterator i = h2->bonuses.begin(); i != h2->bonuses.end(); i++)
  2493. if(i->type == Bonus::BLOCK_SPELLS_ABOVE_LEVEL)
  2494. amin(levelLimit, i->val);
  2495. }
  2496. return levelLimit;
  2497. }
  2498. std::set<CStack*> BattleInfo::getAttackedCreatures( const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile )
  2499. {
  2500. std::set<ui16> attackedHexes = s->rangeInHexes(destinationTile, skillLevel);
  2501. std::set<CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
  2502. bool onlyAlive = s->id != 38 && s->id != 39; //when casting resurrection or animate dead we should be allow to select dead stack
  2503. if(s->id == 24 || s->id == 25 || s->id == 26) //death ripple, destroy undead and Armageddon
  2504. {
  2505. for(int it=0; it<stacks.size(); ++it)
  2506. {
  2507. if((s->id == 24 && !stacks[it]->type->isUndead()) //death ripple
  2508. || (s->id == 25 && stacks[it]->type->isUndead()) //destroy undead
  2509. || (s->id == 26) //Armageddon
  2510. )
  2511. {
  2512. if(stacks[it]->alive())
  2513. attackedCres.insert(stacks[it]);
  2514. }
  2515. }
  2516. }
  2517. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET_1") != std::string::npos
  2518. || 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
  2519. {
  2520. if(skillLevel < 3) /*not expert */
  2521. {
  2522. CStack * st = getStackT(destinationTile, onlyAlive);
  2523. if(st)
  2524. attackedCres.insert(st);
  2525. }
  2526. else
  2527. {
  2528. for(int it=0; it<stacks.size(); ++it)
  2529. {
  2530. /*if it's non negative spell and our unit or non positive spell and hostile unit */
  2531. if((VLC->spellh->spells[s->id].positiveness >= 0 && stacks[it]->owner == attackerOwner)
  2532. ||(VLC->spellh->spells[s->id].positiveness <= 0 && stacks[it]->owner != attackerOwner )
  2533. )
  2534. {
  2535. if(!onlyAlive || stacks[it]->alive())
  2536. attackedCres.insert(stacks[it]);
  2537. }
  2538. }
  2539. } //if(caster->getSpellSchoolLevel(s) < 3)
  2540. }
  2541. else if(VLC->spellh->spells[s->id].attributes.find("CREATURE_TARGET") != std::string::npos) //spell to be cast on one specific creature
  2542. {
  2543. CStack * st = getStackT(destinationTile, onlyAlive);
  2544. if(st)
  2545. attackedCres.insert(st);
  2546. }
  2547. else //custom range from attackedHexes
  2548. {
  2549. for(std::set<ui16>::iterator it = attackedHexes.begin(); it != attackedHexes.end(); ++it)
  2550. {
  2551. CStack * st = getStackT(*it, onlyAlive);
  2552. if(st)
  2553. attackedCres.insert(st);
  2554. }
  2555. }
  2556. return attackedCres;
  2557. }
  2558. int BattleInfo::calculateSpellDuration( const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower )
  2559. {
  2560. if(!caster) //TODO: something better
  2561. return std::max(5, usedSpellPower);
  2562. switch(spell->id)
  2563. {
  2564. case 56: //frenzy
  2565. return 1;
  2566. default: //other spells
  2567. return caster->getPrimSkillLevel(2) + caster->valOfBonuses(Bonus::SPELL_DURATION);
  2568. }
  2569. }
  2570. CStack * BattleInfo::generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const
  2571. {
  2572. CStack * ret = new CStack(&base, attackerOwned ? side1 : side2, stackID, attackerOwned, slot);
  2573. //native terrain bonuses
  2574. int faction = ret->type->faction;
  2575. if(faction >= 0 && VLC->heroh->nativeTerrains[faction] == terrain)
  2576. {
  2577. ret->bonuses.push_back(makeFeature(Bonus::STACKS_SPEED, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_NATIVE));
  2578. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::ATTACK, 1, Bonus::TERRAIN_NATIVE));
  2579. ret->bonuses.push_back(makeFeature(Bonus::PRIMARY_SKILL, Bonus::ONE_BATTLE, PrimarySkill::DEFENSE, 1, Bonus::TERRAIN_NATIVE));
  2580. }
  2581. ret->position = position;
  2582. return ret;
  2583. }
  2584. ui32 BattleInfo::getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
  2585. {
  2586. ui32 ret = caster->getSpellCost(sp);
  2587. //checking for friendly stacks reducing cost of the spell and
  2588. //enemy stacks increasing it
  2589. si32 manaReduction = 0;
  2590. si32 manaIncrease = 0;
  2591. for(int g=0; g<stacks.size(); ++g)
  2592. {
  2593. if( stacks[g]->owner == caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
  2594. {
  2595. amin(manaReduction, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
  2596. }
  2597. if( stacks[g]->owner != caster->tempOwner && stacks[g]->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
  2598. {
  2599. amax(manaIncrease, stacks[g]->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
  2600. }
  2601. }
  2602. return ret + manaReduction + manaIncrease;
  2603. }
  2604. int BattleInfo::hexToWallPart(int hex) const
  2605. {
  2606. if(siege == 0) //there is no battle!
  2607. return -1;
  2608. static const std::pair<int, int> attackable[] = //potentially attackable parts of wall
  2609. {std::make_pair(50, 0), std::make_pair(183, 1), std::make_pair(182, 2), std::make_pair(130, 3),
  2610. 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)};
  2611. for(int g = 0; g < ARRAY_COUNT(attackable); ++g)
  2612. {
  2613. if(attackable[g].first == hex)
  2614. return attackable[g].second;
  2615. }
  2616. return -1; //not found!
  2617. }
  2618. int BattleInfo::lineToWallHex( int line ) const
  2619. {
  2620. static const int lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
  2621. return lineToHex[line];
  2622. }
  2623. std::pair<const CStack *, int> BattleInfo::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
  2624. {
  2625. bool ac[BFIELD_SIZE];
  2626. std::set<int> occupyable;
  2627. getAccessibilityMap(ac, closest->doubleWide(), closest->attackerOwned, false, occupyable, closest->hasBonusOfType(Bonus::FLYING), closest->ID);
  2628. int predecessor[BFIELD_SIZE], dist[BFIELD_SIZE];
  2629. makeBFS(closest->position, ac, predecessor, dist, closest->doubleWide(), closest->attackerOwned, closest->hasBonusOfType(Bonus::FLYING), true);
  2630. std::vector< std::pair< std::pair<int, int>, const CStack *> > stackPairs; //pairs <<distance, hex>, stack>
  2631. for(int g=0; g<BFIELD_SIZE; ++g)
  2632. {
  2633. const CStack * atG = getStackT(g);
  2634. if(!atG || atG->ID == closest->ID) //if there is not stack or we are the closest one
  2635. continue;
  2636. if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
  2637. {
  2638. if(predecessor[g] == -1) //TODO: is it really the best solution?
  2639. continue;
  2640. stackPairs.push_back( std::make_pair( std::make_pair(dist[predecessor[g]], g), atG) );
  2641. }
  2642. }
  2643. if(stackPairs.size() > 0)
  2644. {
  2645. std::vector< std::pair< std::pair<int, int>, const CStack *> > minimalPairs;
  2646. minimalPairs.push_back(stackPairs[0]);
  2647. for(int b=1; b<stackPairs.size(); ++b)
  2648. {
  2649. if(stackPairs[b].first.first < minimalPairs[0].first.first)
  2650. {
  2651. minimalPairs.clear();
  2652. minimalPairs.push_back(stackPairs[b]);
  2653. }
  2654. else if(stackPairs[b].first.first == minimalPairs[0].first.first)
  2655. {
  2656. minimalPairs.push_back(stackPairs[b]);
  2657. }
  2658. }
  2659. std::pair< std::pair<int, int>, const CStack *> minPair = minimalPairs[minimalPairs.size()/2];
  2660. return std::make_pair(minPair.second, predecessor[minPair.first.second]);
  2661. }
  2662. return std::make_pair<const CStack * , int>(NULL, -1);
  2663. }
  2664. ui32 BattleInfo::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
  2665. {
  2666. ui32 ret = 0; //value to return
  2667. //15 - magic arrows, 16 - ice bolt, 17 - lightning bolt, 18 - implosion, 20 - frost ring, 21 - fireball, 22 - inferno, 23 - meteor shower,
  2668. //24 - death ripple, 25 - destroy undead, 26 - armageddon, 77 - thunderbolt
  2669. 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);
  2670. //check if spell really does damage - if not, return 0
  2671. if(dmgMultipliers.find(sp->id) == dmgMultipliers.end())
  2672. return 0;
  2673. ret = usedSpellPower * dmgMultipliers[sp->id];
  2674. ret += sp->powers[spellSchoolLevel];
  2675. //applying sorcerery secondary skill
  2676. if(caster)
  2677. {
  2678. switch(caster->getSecSkillLevel(25))
  2679. {
  2680. case 1: //basic
  2681. ret *= 1.05f;
  2682. break;
  2683. case 2: //advanced
  2684. ret *= 1.1f;
  2685. break;
  2686. case 3: //expert
  2687. ret *= 1.15f;
  2688. break;
  2689. }
  2690. //applying hero bonuses
  2691. ret *= (100.f + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id)) / 100.0f;
  2692. if(sp->air)
  2693. ret *= (100.0f + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0f;
  2694. else if(sp->fire) //only one type of bonus for Magic Arrow
  2695. ret *= (100.0f + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0f;
  2696. else if(sp->water)
  2697. ret *= (100.0f + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0f;
  2698. else if(sp->earth)
  2699. ret *= (100.0f + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0f;
  2700. }
  2701. //affected creature-specific part
  2702. if(affectedCreature)
  2703. {
  2704. //applying protections - when spell has more then one elements, only one protection should be applied (I think)
  2705. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
  2706. {
  2707. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
  2708. ret /= 100;
  2709. }
  2710. else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
  2711. {
  2712. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
  2713. ret /= 100;
  2714. }
  2715. else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
  2716. {
  2717. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
  2718. ret /= 100;
  2719. }
  2720. else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
  2721. {
  2722. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
  2723. ret /= 100;
  2724. }
  2725. //general spell dmg reduction
  2726. if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1)) //air spell & protection from air
  2727. {
  2728. ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
  2729. ret /= 100;
  2730. }
  2731. //dmg increasing
  2732. if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
  2733. {
  2734. ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id);
  2735. ret /= 100;
  2736. }
  2737. if (caster) //Hero specials like Solmyr, Deemer
  2738. ret *= (100.f + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id) * caster->level) / affectedCreature->type->level)) / 100.0f;
  2739. }
  2740. return ret;
  2741. }
  2742. bool CGameState::battleCanShoot(int ID, int dest)
  2743. {
  2744. if(!curB)
  2745. return false;
  2746. const CStack *our = curB->getStack(ID),
  2747. *dst = curB->getStackT(dest);
  2748. if(!our || !dst) return false;
  2749. const CGHeroInstance * ourHero = battleGetOwner(our->ID);
  2750. if(our->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
  2751. return false;
  2752. if(our->type->idNumber == 145 && dst) //catapult cannot attack creatures
  2753. return false;
  2754. if(our->hasBonusOfType(Bonus::SHOOTER)//it's shooter
  2755. && our->owner != dst->owner
  2756. && dst->alive()
  2757. && (!curB->isStackBlocked(ID) || NBonus::hasOfType(ourHero, Bonus::FREE_SHOOTING))
  2758. && our->shots
  2759. )
  2760. return true;
  2761. return false;
  2762. }
  2763. int CGameState::victoryCheck( ui8 player ) const
  2764. {
  2765. const PlayerState *p = getPlayer(player);
  2766. if(map->victoryCondition.condition == winStandard || map->victoryCondition.allowNormalVictory)
  2767. if(player == checkForStandardWin())
  2768. return -1;
  2769. if(p->human || map->victoryCondition.appliesToAI)
  2770. {
  2771. switch(map->victoryCondition.condition)
  2772. {
  2773. case artifact:
  2774. //check if any hero has winning artifact
  2775. for(size_t i = 0; i < p->heroes.size(); i++)
  2776. if(p->heroes[i]->hasArt(map->victoryCondition.ID))
  2777. return 1;
  2778. break;
  2779. case gatherTroop:
  2780. {
  2781. //check if in players armies there is enough creatures
  2782. int total = 0; //creature counter
  2783. for(size_t i = 0; i < map->objects.size(); i++)
  2784. {
  2785. const CArmedInstance *ai = NULL;
  2786. if(map->objects[i]
  2787. && map->objects[i]->tempOwner == player //object controlled by player
  2788. && (ai = dynamic_cast<const CArmedInstance*>(map->objects[i]))) //contains army
  2789. {
  2790. for(TSlots::const_iterator i=ai->Slots().begin(); i!=ai->Slots().end(); ++i) //iterate through army
  2791. if(i->second.type->idNumber == map->victoryCondition.ID) //it's searched creature
  2792. total += i->second.count;
  2793. }
  2794. }
  2795. if(total >= map->victoryCondition.count)
  2796. return 1;
  2797. }
  2798. break;
  2799. case gatherResource:
  2800. if(p->resources[map->victoryCondition.ID] >= map->victoryCondition.count)
  2801. return 1;
  2802. break;
  2803. case buildCity:
  2804. {
  2805. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2806. if(t->tempOwner == player && t->fortLevel()-1 >= map->victoryCondition.ID && t->hallLevel()-1 >= map->victoryCondition.count)
  2807. return 1;
  2808. }
  2809. break;
  2810. case buildGrail:
  2811. BOOST_FOREACH(const CGTownInstance *t, map->towns)
  2812. if((t == map->victoryCondition.obj || !map->victoryCondition.obj)
  2813. && t->tempOwner == player
  2814. && vstd::contains(t->builtBuildings, 26))
  2815. return 1;
  2816. break;
  2817. case beatHero:
  2818. if(map->victoryCondition.obj->tempOwner >= PLAYER_LIMIT) //target hero not present on map
  2819. return 1;
  2820. break;
  2821. case captureCity:
  2822. {
  2823. if(map->victoryCondition.obj->tempOwner == player)
  2824. return 1;
  2825. }
  2826. break;
  2827. case beatMonster:
  2828. if(!map->objects[map->victoryCondition.obj->id]) //target monster not present on map
  2829. return 1;
  2830. break;
  2831. case takeDwellings:
  2832. for(size_t i = 0; i < map->objects.size(); i++)
  2833. {
  2834. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2835. {
  2836. switch(map->objects[i]->ID)
  2837. {
  2838. case 17: case 18: case 19: case 20: //dwellings
  2839. case 216: case 217: case 218:
  2840. return 0; //found not flagged dwelling - player not won
  2841. }
  2842. }
  2843. }
  2844. return 1;
  2845. break;
  2846. case takeMines:
  2847. for(size_t i = 0; i < map->objects.size(); i++)
  2848. {
  2849. if(map->objects[i] && map->objects[i]->tempOwner != player) //check not flagged objs
  2850. {
  2851. switch(map->objects[i]->ID)
  2852. {
  2853. case 53: case 220:
  2854. return 0; //found not flagged mine - player not won
  2855. }
  2856. }
  2857. }
  2858. return 1;
  2859. break;
  2860. case transportItem:
  2861. {
  2862. const CGTownInstance *t = static_cast<const CGTownInstance *>(map->victoryCondition.obj);
  2863. if(t->visitingHero && t->visitingHero->hasArt(map->victoryCondition.ID)
  2864. || t->garrisonHero && t->garrisonHero->hasArt(map->victoryCondition.ID))
  2865. {
  2866. return 1;
  2867. }
  2868. }
  2869. break;
  2870. }
  2871. }
  2872. return 0;
  2873. }
  2874. ui8 CGameState::checkForStandardWin() const
  2875. {
  2876. //std victory condition is:
  2877. //all enemies lost
  2878. ui8 supposedWinner = 255, winnerTeam = 255;
  2879. for(std::map<ui8,PlayerState>::const_iterator i = players.begin(); i != players.end(); i++)
  2880. {
  2881. if(i->second.status == PlayerState::INGAME && i->first < PLAYER_LIMIT)
  2882. {
  2883. if(supposedWinner == 255)
  2884. {
  2885. //first player remaining ingame - candidate for victory
  2886. supposedWinner = i->second.color;
  2887. winnerTeam = map->players[supposedWinner].team;
  2888. }
  2889. else if(winnerTeam != map->players[i->second.color].team)
  2890. {
  2891. //current candidate has enemy remaining in game -> no vicotry
  2892. return 255;
  2893. }
  2894. }
  2895. }
  2896. return supposedWinner;
  2897. }
  2898. bool CGameState::checkForStandardLoss( ui8 player ) const
  2899. {
  2900. //std loss condition is: player lost all towns and heroes
  2901. const PlayerState &p = *getPlayer(player);
  2902. return !p.heroes.size() && !p.towns.size();
  2903. }
  2904. struct statsHLP
  2905. {
  2906. typedef std::pair< ui8, si64 > TStat;
  2907. //converts [<player's color, value>] to vec[place] -> platers
  2908. static std::vector< std::list< ui8 > > getRank( std::vector<TStat> stats )
  2909. {
  2910. std::sort(stats.begin(), stats.end(), statsHLP());
  2911. //put first element
  2912. std::vector< std::list<ui8> > ret;
  2913. std::list<ui8> tmp;
  2914. tmp.push_back( stats[0].first );
  2915. ret.push_back( tmp );
  2916. //the rest of elements
  2917. for(int g=1; g<stats.size(); ++g)
  2918. {
  2919. if(stats[g].second == stats[g-1].second)
  2920. {
  2921. (ret.end()-1)->push_back( stats[g].first );
  2922. }
  2923. else
  2924. {
  2925. //create next occupied rank
  2926. std::list<ui8> tmp;
  2927. tmp.push_back(stats[g].first);
  2928. ret.push_back(tmp);
  2929. }
  2930. }
  2931. return ret;
  2932. }
  2933. bool operator()(const TStat & a, const TStat & b) const
  2934. {
  2935. return a.second > b.second;
  2936. }
  2937. static const CGHeroInstance * findBestHero(CGameState * gs, int color)
  2938. {
  2939. std::vector<CGHeroInstance *> &h = gs->players[color].heroes;
  2940. if(!h.size())
  2941. return NULL;
  2942. //best hero will be that with highest exp
  2943. int best = 0;
  2944. for(int b=1; b<h.size(); ++b)
  2945. {
  2946. if(h[b]->exp > h[best]->exp)
  2947. {
  2948. best = b;
  2949. }
  2950. }
  2951. return h[best];
  2952. }
  2953. //calculates total number of artifacts that belong to given player
  2954. static int getNumberOfArts(const PlayerState * ps)
  2955. {
  2956. int ret = 0;
  2957. for(int g=0; g<ps->heroes.size(); ++g)
  2958. {
  2959. ret += ps->heroes[g]->artifacts.size() + ps->heroes[g]->artifWorn.size();
  2960. }
  2961. return ret;
  2962. }
  2963. };
  2964. void CGameState::obtainPlayersStats(SThievesGuildInfo & tgi, int level)
  2965. {
  2966. #define FILL_FIELD(FIELD, VAL_GETTER) \
  2967. { \
  2968. std::vector< std::pair< ui8, si64 > > stats; \
  2969. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g) \
  2970. { \
  2971. if(g->second.color == 255) \
  2972. continue; \
  2973. std::pair< ui8, si64 > stat; \
  2974. stat.first = g->second.color; \
  2975. stat.second = VAL_GETTER; \
  2976. stats.push_back(stat); \
  2977. } \
  2978. tgi.FIELD = statsHLP::getRank(stats); \
  2979. }
  2980. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2981. {
  2982. if(g->second.color != 255)
  2983. tgi.playerColors.push_back(g->second.color);
  2984. }
  2985. if(level >= 1) //num of towns & num of heroes
  2986. {
  2987. //num of towns
  2988. FILL_FIELD(numOfTowns, g->second.towns.size())
  2989. //num of heroes
  2990. FILL_FIELD(numOfHeroes, g->second.heroes.size())
  2991. //best hero's portrait
  2992. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  2993. {
  2994. if(g->second.color == 255)
  2995. continue;
  2996. const CGHeroInstance * best = statsHLP::findBestHero(this, g->second.color);
  2997. InfoAboutHero iah;
  2998. iah.initFromHero(best, level >= 8);
  2999. iah.army.clear();
  3000. tgi.colorToBestHero[g->second.color] = iah;
  3001. }
  3002. }
  3003. if(level >= 2) //gold
  3004. {
  3005. FILL_FIELD(gold, g->second.resources[6])
  3006. }
  3007. if(level >= 2) //wood & ore
  3008. {
  3009. FILL_FIELD(woodOre, g->second.resources[0] + g->second.resources[1])
  3010. }
  3011. if(level >= 3) //mercury, sulfur, crystal, gems
  3012. {
  3013. FILL_FIELD(mercSulfCrystGems, g->second.resources[2] + g->second.resources[3] + g->second.resources[4] + g->second.resources[5])
  3014. }
  3015. if(level >= 4) //obelisks found
  3016. {
  3017. //TODO
  3018. }
  3019. if(level >= 5) //artifacts
  3020. {
  3021. FILL_FIELD(artifacts, statsHLP::getNumberOfArts(&g->second))
  3022. }
  3023. if(level >= 6) //army strength
  3024. {
  3025. //TODO
  3026. }
  3027. if(level >= 7) //income
  3028. {
  3029. //TODO
  3030. }
  3031. if(level >= 8) //best hero's stats
  3032. {
  3033. //already set in lvl 1 handling
  3034. }
  3035. if(level >= 9) //personality
  3036. {
  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. if(g->second.human)
  3042. {
  3043. tgi.personality[g->second.color] = -1;
  3044. }
  3045. else //AI
  3046. {
  3047. tgi.personality[g->second.color] = map->players[g->second.serial].AITactic;
  3048. }
  3049. }
  3050. }
  3051. if(level >= 10) //best creature
  3052. {
  3053. //best creatures belonging to player (highest AI value)
  3054. for(std::map<ui8, PlayerState>::const_iterator g = players.begin(); g != players.end(); ++g)
  3055. {
  3056. if(g->second.color == 255) //do nothing for neutral player
  3057. continue;
  3058. int bestCre = -1; //best creature's ID
  3059. for(int b=0; b<g->second.heroes.size(); ++b)
  3060. {
  3061. for(TSlots::const_iterator it = g->second.heroes[b]->Slots().begin(); it != g->second.heroes[b]->Slots().end(); ++it)
  3062. {
  3063. int toCmp = it->second.type->idNumber; //ID of creature we should compare with the best one
  3064. if(bestCre == -1 || VLC->creh->creatures[bestCre]->AIValue < VLC->creh->creatures[toCmp]->AIValue)
  3065. {
  3066. bestCre = toCmp;
  3067. }
  3068. }
  3069. }
  3070. tgi.bestCreature[g->second.color] = bestCre;
  3071. }
  3072. }
  3073. #undef FILL_FIELD
  3074. }
  3075. int CGameState::lossCheck( ui8 player ) const
  3076. {
  3077. const PlayerState *p = getPlayer(player);
  3078. //if(map->lossCondition.typeOfLossCon == lossStandard)
  3079. if(checkForStandardLoss(player))
  3080. return -1;
  3081. if(p->human) //special loss condition applies only to human player
  3082. {
  3083. switch(map->lossCondition.typeOfLossCon)
  3084. {
  3085. case lossCastle:
  3086. {
  3087. const CGTownInstance *t = dynamic_cast<const CGTownInstance *>(map->lossCondition.obj);
  3088. assert(t);
  3089. if(t->tempOwner != player)
  3090. return 1;
  3091. }
  3092. break;
  3093. case lossHero:
  3094. {
  3095. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance *>(map->lossCondition.obj);
  3096. assert(h);
  3097. if(h->tempOwner != player)
  3098. return 1;
  3099. }
  3100. break;
  3101. case timeExpires:
  3102. if(map->lossCondition.timeLimit < day)
  3103. return 1;
  3104. break;
  3105. }
  3106. }
  3107. if(!p->towns.size() && p->daysWithoutCastle >= 7)
  3108. return 2;
  3109. return false;
  3110. }
  3111. std::map<ui32,CGHeroInstance *> CGameState::unusedHeroesFromPool()
  3112. {
  3113. std::map<ui32,CGHeroInstance *> pool = hpool.heroesPool;
  3114. for ( std::map<ui8, PlayerState>::iterator i = players.begin() ; i != players.end();i++)
  3115. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  3116. if(*j)
  3117. pool.erase((**j).subID);
  3118. return pool;
  3119. }
  3120. const CStack * BattleInfo::getNextStack() const
  3121. {
  3122. std::vector<const CStack *> hlp;
  3123. getStackQueue(hlp, 1, -1);
  3124. if(hlp.size())
  3125. return hlp[0];
  3126. else
  3127. return NULL;
  3128. }
  3129. static const CStack *takeStack(std::vector<const CStack *> &st, int &curside, int turn)
  3130. {
  3131. const CStack *ret = NULL;
  3132. unsigned i, //fastest stack
  3133. j; //fastest stack of the other side
  3134. for(i = 0; i < st.size(); i++)
  3135. if(st[i])
  3136. break;
  3137. //no stacks left
  3138. if(i == st.size())
  3139. return NULL;
  3140. const CStack *fastest = st[i], *other = NULL;
  3141. int bestSpeed = fastest->Speed(turn);
  3142. if(fastest->attackerOwned != curside)
  3143. {
  3144. ret = fastest;
  3145. }
  3146. else
  3147. {
  3148. for(j = i + 1; j < st.size(); j++)
  3149. {
  3150. if(!st[j]) continue;
  3151. if(st[j]->attackerOwned != curside || st[j]->Speed(turn) != bestSpeed)
  3152. break;
  3153. }
  3154. if(j >= st.size())
  3155. {
  3156. ret = fastest;
  3157. }
  3158. else
  3159. {
  3160. other = st[j];
  3161. if(other->Speed(turn) != bestSpeed)
  3162. ret = fastest;
  3163. else
  3164. ret = other;
  3165. }
  3166. }
  3167. assert(ret);
  3168. if(ret == fastest)
  3169. st[i] = NULL;
  3170. else
  3171. st[j] = NULL;
  3172. curside = ret->attackerOwned;
  3173. return ret;
  3174. }
  3175. void BattleInfo::getStackQueue( std::vector<const CStack *> &out, int howMany, int turn /*= 0*/, int lastMoved /*= -1*/ ) const
  3176. {
  3177. //we'll split creatures with remaining movement to 4 parts
  3178. 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
  3179. int toMove = 0; //how many stacks still has move
  3180. const CStack *active = getStack(activeStack);
  3181. //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
  3182. if(!turn && active && active->willMove() && !vstd::contains(active->state, WAITING))
  3183. {
  3184. out.push_back(active);
  3185. if(out.size() == howMany)
  3186. return;
  3187. }
  3188. for(unsigned int i=0; i<stacks.size(); ++i)
  3189. {
  3190. const CStack * const s = stacks[i];
  3191. if(turn <= 0 && !s->willMove() //we are considering current round and stack won't move
  3192. || turn > 0 && !s->canMove(turn) //stack won't be able to move in later rounds
  3193. || turn <= 0 && s == active && out.size() && s == out.front()) //it's active stack already added at the beginning of queue
  3194. {
  3195. continue;
  3196. }
  3197. int p = -1; //in which phase this tack will move?
  3198. if(turn <= 0 && vstd::contains(s->state, WAITING)) //consider waiting state only for ongoing round
  3199. {
  3200. if(vstd::contains(s->state, HAD_MORALE))
  3201. p = 2;
  3202. else
  3203. p = 3;
  3204. }
  3205. else if(s->type->idNumber == 145 || s->type->idNumber == 149) //catapult and turrets are first
  3206. {
  3207. p = 0;
  3208. }
  3209. else
  3210. {
  3211. p = 1;
  3212. }
  3213. phase[p].push_back(s);
  3214. toMove++;
  3215. }
  3216. for(int i = 0; i < 4; i++)
  3217. std::sort(phase[i].begin(), phase[i].end(), CMP_stack(i, turn > 0 ? turn : 0));
  3218. for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
  3219. out.push_back(phase[0][i]);
  3220. if(out.size() == howMany)
  3221. return;
  3222. if(lastMoved == -1)
  3223. {
  3224. if(active)
  3225. {
  3226. if(out.size() && out.front() == active)
  3227. lastMoved = active->attackerOwned;
  3228. else
  3229. lastMoved = active->attackerOwned;
  3230. }
  3231. else
  3232. {
  3233. lastMoved = 0;
  3234. }
  3235. }
  3236. int pi = 1;
  3237. while(out.size() < howMany)
  3238. {
  3239. const CStack *hlp = takeStack(phase[pi], lastMoved, turn);
  3240. if(!hlp)
  3241. {
  3242. pi++;
  3243. if(pi > 3)
  3244. {
  3245. //if(turn != 2)
  3246. getStackQueue(out, howMany, turn + 1, lastMoved);
  3247. return;
  3248. }
  3249. }
  3250. else
  3251. {
  3252. out.push_back(hlp);
  3253. }
  3254. }
  3255. }
  3256. si8 BattleInfo::hasDistancePenalty( int stackID, int destHex )
  3257. {
  3258. const CStack * stack = getStack(stackID);
  3259. int xDst = std::abs(destHex % BFIELD_WIDTH - stack->position % BFIELD_WIDTH),
  3260. yDst = std::abs(destHex / BFIELD_WIDTH - stack->position / BFIELD_WIDTH);
  3261. int distance = std::max(xDst, yDst) + std::min(xDst, yDst) - (std::max(xDst, yDst) + 1)/2;
  3262. //I hope it's approximately correct
  3263. return distance > 10 && !stack->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY);
  3264. }
  3265. si8 BattleInfo::sameSideOfWall(int pos1, int pos2)
  3266. {
  3267. int wallInStackLine = lineToWallHex(pos1/BFIELD_WIDTH);
  3268. int wallInDestLine = lineToWallHex(pos2/BFIELD_WIDTH);
  3269. bool stackLeft = pos1 < wallInStackLine;
  3270. bool destLeft = pos2 < wallInDestLine;
  3271. return stackLeft != destLeft;
  3272. }
  3273. si8 BattleInfo::hasWallPenalty( int stackID, int destHex )
  3274. {
  3275. if (siege == 0)
  3276. {
  3277. return false;
  3278. }
  3279. const CStack * stack = getStack(stackID);
  3280. if (stack->hasBonusOfType(Bonus::NO_WALL_PENALTY));
  3281. {
  3282. return false;
  3283. }
  3284. return !sameSideOfWall(stack->position, destHex);
  3285. }
  3286. si8 BattleInfo::canTeleportTo(int stackID, int destHex, int telportLevel)
  3287. {
  3288. bool ac[BFIELD_SIZE];
  3289. const CStack *s = getStack(stackID, false); //this function is called from healedOrResurrected, so our stack can be dead
  3290. std::set<int> occupyable;
  3291. getAccessibilityMap(ac, s->doubleWide(), s->attackerOwned, false, occupyable, s->hasBonusOfType(Bonus::FLYING), stackID);
  3292. if (siege && telportLevel < 2) //check for wall
  3293. {
  3294. return ac[destHex] && sameSideOfWall(s->position, destHex);
  3295. }
  3296. else
  3297. {
  3298. return ac[destHex];
  3299. }
  3300. }
  3301. void BattleInfo::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3302. {
  3303. CBonusSystemNode::getBonuses(out, selector, root);
  3304. const CStack *dest = dynamic_cast<const CStack*>(root);
  3305. if (!dest)
  3306. return;
  3307. //TODO: make it in clean way
  3308. if(Selector::matchesType(selector, Bonus::MORALE) || Selector::matchesType(selector, Bonus::LUCK))
  3309. {
  3310. BOOST_FOREACH(const CStack *s, stacks)
  3311. {
  3312. if(s->owner == dest->owner)
  3313. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ALLIED_ARMY), this);
  3314. else
  3315. s->getBonuses(out, selector, Selector::effectRange(Bonus::ONLY_ENEMY_ARMY), this);
  3316. }
  3317. }
  3318. }
  3319. int3 CPath::startPos() const
  3320. {
  3321. return nodes[nodes.size()-1].coord;
  3322. }
  3323. void CPath::convert(ui8 mode) //mode=0 -> from 'manifest' to 'object'
  3324. {
  3325. if (mode==0)
  3326. {
  3327. for (unsigned int i=0;i<nodes.size();i++)
  3328. {
  3329. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3330. }
  3331. }
  3332. }
  3333. int3 CPath::endPos() const
  3334. {
  3335. return nodes[0].coord;
  3336. }
  3337. CGPathNode::CGPathNode()
  3338. :coord(-1,-1,-1)
  3339. {
  3340. accessible = 0;
  3341. land = 0;
  3342. moveRemains = 0;
  3343. turns = 255;
  3344. theNodeBefore = NULL;
  3345. }
  3346. bool CPathsInfo::getPath( const int3 &dst, CGPath &out )
  3347. {
  3348. out.nodes.clear();
  3349. const CGPathNode *curnode = &nodes[dst.x][dst.y][dst.z];
  3350. if(!curnode->theNodeBefore || curnode->accessible == CGPathNode::FLYABLE)
  3351. return false;
  3352. //we'll transform number of turns to conform the rule that hero cannot stop on blocked tile
  3353. bool transition01 = false;
  3354. while(curnode)
  3355. {
  3356. CGPathNode cpn = *curnode;
  3357. if(transition01)
  3358. {
  3359. if (curnode->accessible == CGPathNode::ACCESSIBLE)
  3360. {
  3361. transition01 = false;
  3362. }
  3363. else if (curnode->accessible == CGPathNode::FLYABLE)
  3364. {
  3365. cpn.turns = 1;
  3366. }
  3367. }
  3368. if(curnode->turns == 1 && curnode->theNodeBefore->turns == 0)
  3369. {
  3370. transition01 = true;
  3371. }
  3372. curnode = curnode->theNodeBefore;
  3373. out.nodes.push_back(cpn);
  3374. }
  3375. return true;
  3376. }
  3377. CPathsInfo::CPathsInfo( const int3 &Sizes )
  3378. :sizes(Sizes)
  3379. {
  3380. hero = NULL;
  3381. nodes = new CGPathNode**[sizes.x];
  3382. for(int i = 0; i < sizes.x; i++)
  3383. {
  3384. nodes[i] = new CGPathNode*[sizes.y];
  3385. for (int j = 0; j < sizes.y; j++)
  3386. {
  3387. nodes[i][j] = new CGPathNode[sizes.z];
  3388. }
  3389. }
  3390. }
  3391. CPathsInfo::~CPathsInfo()
  3392. {
  3393. for(int i = 0; i < sizes.x; i++)
  3394. {
  3395. for (int j = 0; j < sizes.y; j++)
  3396. {
  3397. delete [] nodes[i][j];
  3398. }
  3399. delete [] nodes[i];
  3400. }
  3401. delete [] nodes;
  3402. }
  3403. int3 CGPath::startPos() const
  3404. {
  3405. return nodes[nodes.size()-1].coord;
  3406. }
  3407. int3 CGPath::endPos() const
  3408. {
  3409. return nodes[0].coord;
  3410. }
  3411. void CGPath::convert( ui8 mode )
  3412. {
  3413. if(mode==0)
  3414. {
  3415. for(unsigned int i=0;i<nodes.size();i++)
  3416. {
  3417. nodes[i].coord = CGHeroInstance::convertPosition(nodes[i].coord,true);
  3418. }
  3419. }
  3420. }
  3421. bool CMP_stack::operator()( const CStack* a, const CStack* b )
  3422. {
  3423. switch(phase)
  3424. {
  3425. case 0: //catapult moves after turrets
  3426. return a->type->idNumber < b->type->idNumber; //catapult is 145 and turrets are 149
  3427. //TODO? turrets order
  3428. case 1: //fastest first, upper slot first
  3429. {
  3430. int as = a->Speed(turn), bs = b->Speed(turn);
  3431. if(as != bs)
  3432. return as > bs;
  3433. else
  3434. return a->slot < b->slot;
  3435. }
  3436. case 2: //fastest last, upper slot first
  3437. //TODO: should be replaced with order of receiving morale!
  3438. case 3: //fastest last, upper slot first
  3439. {
  3440. int as = a->Speed(turn), bs = b->Speed(turn);
  3441. if(as != bs)
  3442. return as < bs;
  3443. else
  3444. return a->slot < b->slot;
  3445. }
  3446. default:
  3447. assert(0);
  3448. return false;
  3449. }
  3450. }
  3451. CMP_stack::CMP_stack( int Phase /*= 1*/, int Turn )
  3452. {
  3453. phase = Phase;
  3454. turn = Turn;
  3455. }
  3456. PlayerState::PlayerState()
  3457. : color(-1), currentSelection(0xffffffff), status(INGAME), daysWithoutCastle(0)
  3458. {
  3459. }
  3460. void PlayerState::getParents(TCNodes &out, const CBonusSystemNode *root /*= NULL*/) const
  3461. {
  3462. /*
  3463. for (std::vector<CGHeroInstance *>::const_iterator it = heroes.begin(); it != heroes.end(); ++it)
  3464. {
  3465. if (*it != root)
  3466. (*it)->getParents(out, root);
  3467. }
  3468. for (std::vector<CGTownInstance *>::const_iterator it = towns.begin(); it != towns.end(); ++it)
  3469. {
  3470. if (*it != root)
  3471. (*it)->getParents(out, root);
  3472. }
  3473. */
  3474. //TODO - dwellings
  3475. }
  3476. void PlayerState::getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root /*= NULL*/) const
  3477. {//temporary
  3478. //CBonusSystemNode::getBonuses(out, selector, root);
  3479. }
  3480. InfoAboutHero::InfoAboutHero()
  3481. {
  3482. details = NULL;
  3483. hclass = NULL;
  3484. portrait = -1;
  3485. }
  3486. InfoAboutHero::InfoAboutHero( const InfoAboutHero & iah )
  3487. {
  3488. assign(iah);
  3489. }
  3490. InfoAboutHero::~InfoAboutHero()
  3491. {
  3492. delete details;
  3493. }
  3494. void InfoAboutHero::initFromHero( const CGHeroInstance *h, bool detailed )
  3495. {
  3496. if(!h) return;
  3497. owner = h->tempOwner;
  3498. hclass = h->type->heroClass;
  3499. name = h->name;
  3500. portrait = h->portrait;
  3501. army = h->getArmy();
  3502. if(detailed)
  3503. {
  3504. //include details about hero
  3505. details = new Details;
  3506. details->luck = h->LuckVal();
  3507. details->morale = h->MoraleVal();
  3508. details->mana = h->mana;
  3509. details->primskills.resize(PRIMARY_SKILLS);
  3510. for (int i = 0; i < PRIMARY_SKILLS ; i++)
  3511. {
  3512. details->primskills[i] = h->getPrimSkillLevel(i);
  3513. }
  3514. }
  3515. else
  3516. {
  3517. //hide info about hero stacks counts using descriptives names ids
  3518. for(TSlots::const_iterator i = army.Slots().begin(); i != army.Slots().end(); ++i)
  3519. {
  3520. army.setStackCount(i->first, i->second.getQuantityID()+1);
  3521. }
  3522. }
  3523. }
  3524. void InfoAboutHero::assign( const InfoAboutHero & iah )
  3525. {
  3526. army = iah.army;
  3527. details = (iah.details ? new Details(*iah.details) : NULL);
  3528. hclass = iah.hclass;
  3529. name = iah.name;
  3530. owner = iah.owner;
  3531. portrait = iah.portrait;
  3532. }
  3533. InfoAboutHero & InfoAboutHero::operator=( const InfoAboutHero & iah )
  3534. {
  3535. assign(iah);
  3536. return *this;
  3537. }
  3538. void CCampaignState::initNewCampaign( const StartInfo &si )
  3539. {
  3540. assert(si.mode == 2);
  3541. campaignName = si.mapname;
  3542. currentMap = si.whichMapInCampaign;
  3543. camp = CCampaignHandler::getCampaign(campaignName, true); //TODO lod???
  3544. for (ui8 i = 0; i < camp->mapPieces.size(); i++)
  3545. mapsRemaining.push_back(i);
  3546. }