CGameState.cpp 118 KB

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