CGameState.cpp 130 KB

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