CGameState.cpp 106 KB

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