CGameState.cpp 128 KB

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