CGameHandler.cpp 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953
  1. #include "../hch/CCampaignHandler.h"
  2. #include "../StartInfo.h"
  3. #include "../hch/CArtHandler.h"
  4. #include "../hch/CBuildingHandler.h"
  5. #include "../hch/CDefObjInfoHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CGeneralTextHandler.h"
  10. #include "../hch/CTownHandler.h"
  11. #include "../hch/CCreatureHandler.h"
  12. #include "../lib/CGameState.h"
  13. #include "../lib/CondSh.h"
  14. #include "../lib/NetPacks.h"
  15. #include "../lib/VCMI_Lib.h"
  16. #include "../lib/map.h"
  17. #include "../lib/VCMIDirs.h"
  18. #include "CGameHandler.h"
  19. #include <boost/bind.hpp>
  20. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  21. #include <boost/foreach.hpp>
  22. #include <boost/thread.hpp>
  23. #include <boost/thread/shared_mutex.hpp>
  24. #include <boost/assign/list_of.hpp>
  25. #include <fstream>
  26. #include <boost/system/system_error.hpp>
  27. /*
  28. * CGameHandler.cpp, part of VCMI engine
  29. *
  30. * Authors: listed in file AUTHORS in main folder
  31. *
  32. * License: GNU General Public License v2.0 or later
  33. * Full text of license available in license.txt file, in main folder
  34. *
  35. */
  36. #undef DLL_EXPORT
  37. #define DLL_EXPORT
  38. #include "../lib/RegisterTypes.cpp"
  39. #ifndef _MSC_VER
  40. #include <boost/thread/xtime.hpp>
  41. #endif
  42. extern bool end2;
  43. #ifdef min
  44. #undef min
  45. #endif
  46. #ifdef max
  47. #undef max
  48. #endif
  49. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  50. #define NEW_ROUND BattleNextRound bnr;\
  51. bnr.round = gs->curB->round + 1;\
  52. sendAndApply(&bnr);
  53. CondSh<bool> battleMadeAction;
  54. CondSh<BattleResult *> battleResult(NULL);
  55. class CBaseForGHApply
  56. {
  57. public:
  58. virtual bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  59. };
  60. template <typename T> class CApplyOnGH : public CBaseForGHApply
  61. {
  62. public:
  63. bool applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  64. {
  65. T *ptr = static_cast<T*>(pack);
  66. ptr->c = c;
  67. return ptr->applyGh(gh);
  68. }
  69. };
  70. class CGHApplier
  71. {
  72. public:
  73. std::map<ui16,CBaseForGHApply*> apps;
  74. CGHApplier()
  75. {
  76. registerTypes3(*this);
  77. }
  78. template<typename T> void registerType(const T * t=NULL)
  79. {
  80. ui16 ID = typeList.registerType(t);
  81. apps[ID] = new CApplyOnGH<T>;
  82. }
  83. } *applier = NULL;
  84. CMP_stack cmpst ;
  85. static inline double distance(int3 a, int3 b)
  86. {
  87. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  88. }
  89. static void giveExp(BattleResult &r)
  90. {
  91. r.exp[0] = 0;
  92. r.exp[1] = 0;
  93. for(std::map<ui32,si32>::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  94. {
  95. r.exp[r.winner] += VLC->creh->creatures[i->first]->valOfBonuses(Bonus::STACK_HEALTH) * i->second;
  96. }
  97. }
  98. PlayerStatus PlayerStatuses::operator[](ui8 player)
  99. {
  100. boost::unique_lock<boost::mutex> l(mx);
  101. if(players.find(player) != players.end())
  102. {
  103. return players[player];
  104. }
  105. else
  106. {
  107. throw std::string("No such player!");
  108. }
  109. }
  110. void PlayerStatuses::addPlayer(ui8 player)
  111. {
  112. boost::unique_lock<boost::mutex> l(mx);
  113. players[player];
  114. }
  115. bool PlayerStatuses::hasQueries(ui8 player)
  116. {
  117. boost::unique_lock<boost::mutex> l(mx);
  118. if(players.find(player) != players.end())
  119. {
  120. return players[player].queries.size();
  121. }
  122. else
  123. {
  124. throw std::string("No such player!");
  125. }
  126. }
  127. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  128. {
  129. boost::unique_lock<boost::mutex> l(mx);
  130. if(players.find(player) != players.end())
  131. {
  132. return players[player].*flag;
  133. }
  134. else
  135. {
  136. throw std::string("No such player!");
  137. }
  138. }
  139. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  140. {
  141. boost::unique_lock<boost::mutex> l(mx);
  142. if(players.find(player) != players.end())
  143. {
  144. players[player].*flag = val;
  145. }
  146. else
  147. {
  148. throw std::string("No such player!");
  149. }
  150. cv.notify_all();
  151. }
  152. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  153. {
  154. boost::unique_lock<boost::mutex> l(mx);
  155. if(players.find(player) != players.end())
  156. {
  157. players[player].queries.insert(id);
  158. }
  159. else
  160. {
  161. throw std::string("No such player!");
  162. }
  163. cv.notify_all();
  164. }
  165. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  166. {
  167. boost::unique_lock<boost::mutex> l(mx);
  168. if(players.find(player) != players.end())
  169. {
  170. players[player].queries.erase(id);
  171. }
  172. else
  173. {
  174. throw std::string("No such player!");
  175. }
  176. cv.notify_all();
  177. }
  178. template <typename T>
  179. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  180. {
  181. fun(args[which]);
  182. }
  183. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  184. {
  185. SetSecSkill sss;
  186. sss.id = ID;
  187. sss.which = which;
  188. sss.val = val;
  189. sss.abs = abs;
  190. sendAndApply(&sss);
  191. if(which == 7) //Wisdom
  192. {
  193. const CGHeroInstance *h = getHero(ID);
  194. if(h && h->visitedTown)
  195. giveSpells(h->visitedTown, h);
  196. }
  197. }
  198. void CGameHandler::changePrimSkill(int ID, int which, si64 val, bool abs)
  199. {
  200. SetPrimSkill sps;
  201. sps.id = ID;
  202. sps.which = which;
  203. sps.abs = abs;
  204. sps.val = val;
  205. sendAndApply(&sps);
  206. if(which==4) //only for exp - hero may level up
  207. {
  208. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  209. while (hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  210. {
  211. //give prim skill
  212. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  213. int r = rand()%100, pom=0, x=0;
  214. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  215. for(;x<PRIMARY_SKILLS;x++)
  216. {
  217. pom += hero->type->heroClass->primChance[x].*g;
  218. if(r<pom)
  219. break;
  220. }
  221. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  222. SetPrimSkill sps;
  223. sps.id = ID;
  224. sps.which = x;
  225. sps.abs = false;
  226. sps.val = 1;
  227. sendAndApply(&sps);
  228. HeroLevelUp hlu;
  229. hlu.heroid = ID;
  230. hlu.primskill = x;
  231. hlu.level = hero->level+1;
  232. //picking sec. skills for choice
  233. std::set<int> basicAndAdv, expert, none;
  234. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  235. for(unsigned i=0;i<hero->secSkills.size();i++)
  236. {
  237. if(hero->secSkills[i].second < 3)
  238. basicAndAdv.insert(hero->secSkills[i].first);
  239. else
  240. expert.insert(hero->secSkills[i].first);
  241. none.erase(hero->secSkills[i].first);
  242. }
  243. //first offered skill
  244. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  245. {
  246. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  247. none.erase(hlu.skills.back());
  248. }
  249. else if(basicAndAdv.size())
  250. {
  251. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  252. hlu.skills.push_back(s);
  253. basicAndAdv.erase(s);
  254. }
  255. //second offered skill
  256. if(basicAndAdv.size())
  257. {
  258. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  259. }
  260. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  261. {
  262. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  263. }
  264. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  265. {
  266. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  267. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  268. }
  269. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  270. {
  271. sendAndApply(&hlu);
  272. changeSecSkill(ID,hlu.skills.back(),1,false);
  273. }
  274. else //apply and send info
  275. {
  276. sendAndApply(&hlu);
  277. }
  278. }
  279. }
  280. }
  281. static CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  282. {
  283. if(color == 254)
  284. color = 255;
  285. CCreatureSet ret(set);
  286. for(int i=0; i<bat->stacks.size();i++)
  287. {
  288. CStack *st = bat->stacks[i];
  289. if(vstd::contains(st->state, SUMMONED)) //don't take into account sumoned stacks
  290. continue;
  291. if(st->owner==color && !set.slotEmpty(st->slot) && st->count < set.getAmount(st->slot))
  292. {
  293. if(st->alive())
  294. ret.setStackCount(st->slot, st->count);
  295. else
  296. ret.eraseStack(st->slot);
  297. }
  298. }
  299. return ret;
  300. }
  301. void CGameHandler::startBattle(const CArmedInstance *army1, const CArmedInstance * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town)
  302. {
  303. battleEndCallback = new boost::function<void(BattleResult*)>(cb);
  304. bEndArmy1 = army1;
  305. bEndArmy2 = army2;
  306. {
  307. BattleInfo *curB = new BattleInfo;
  308. curB->side1 = army1->tempOwner;
  309. curB->side2 = army2->tempOwner;
  310. if(curB->side2 == 254)
  311. curB->side2 = 255;
  312. setupBattle(curB, tile, army1, army2, hero1, hero2, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  313. }
  314. NEW_ROUND;
  315. //TODO: pre-tactic stuff, call scripts etc.
  316. //tactic round
  317. {
  318. NEW_ROUND;
  319. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  320. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  321. {
  322. //TODO: tactic round (round -1)
  323. }
  324. }
  325. //spells opening battle
  326. if (hero1 && hero1->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  327. {
  328. BonusList bl;
  329. hero1->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  330. BOOST_FOREACH (Bonus b, bl)
  331. {
  332. handleSpellCasting(b.subtype, 3, -1, 0, hero1->tempOwner, NULL, hero2, b.val);
  333. }
  334. }
  335. if (hero2 && hero2->hasBonusOfType(Bonus::OPENING_BATTLE_SPELL))
  336. {
  337. BonusList bl;
  338. hero2->getBonuses(bl, Selector::type(Bonus::OPENING_BATTLE_SPELL));
  339. BOOST_FOREACH (Bonus b, bl)
  340. {
  341. handleSpellCasting(b.subtype, 3, -1, 1, hero2->tempOwner, NULL, hero1, b.val);
  342. }
  343. }
  344. //main loop
  345. while(!battleResult.get()) //till the end of the battle ;]
  346. {
  347. NEW_ROUND;
  348. std::vector<CStack*> & stacks = (gs->curB->stacks);
  349. const BattleInfo & curB = *gs->curB;
  350. //stack loop
  351. const CStack *next;
  352. while(!battleResult.get() && (next = curB.getNextStack()) && next->willMove())
  353. {
  354. //check for bad morale => freeze
  355. int nextStackMorale = next->MoraleVal();
  356. if( nextStackMorale < 0 &&
  357. !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses)
  358. )
  359. {
  360. if( rand()%24 < -2 * nextStackMorale)
  361. {
  362. //unit loses its turn - empty freeze action
  363. BattleAction ba;
  364. ba.actionType = 11;
  365. ba.additionalInfo = 1;
  366. ba.side = !next->attackerOwned;
  367. ba.stackNumber = next->ID;
  368. sendAndApply(&StartAction(ba));
  369. sendAndApply(&EndAction());
  370. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  371. continue;
  372. }
  373. }
  374. if(next->hasBonusOfType(Bonus::ATTACKS_NEAREST_CREATURE)) //while in berserk
  375. {
  376. std::pair<const CStack *, int> attackInfo = curB.getNearestStack(next, boost::logic::indeterminate);
  377. if(attackInfo.first != NULL)
  378. {
  379. BattleAction attack;
  380. attack.actionType = 6;
  381. attack.side = !next->attackerOwned;
  382. attack.stackNumber = next->ID;
  383. attack.additionalInfo = attackInfo.first->position;
  384. attack.destinationTile = attackInfo.second;
  385. makeBattleAction(attack);
  386. checkForBattleEnd(stacks);
  387. }
  388. continue;
  389. }
  390. const CGHeroInstance * curOwner = gs->battleGetOwner(next->ID);
  391. if( (next->position < 0 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //arrow turret, hero has no ballistics
  392. || (next->type->idNumber == 146 && (!curOwner || curOwner->getSecSkillLevel(20) == 0))) //ballista, hero has no artillery
  393. {
  394. BattleAction attack;
  395. attack.actionType = 7;
  396. attack.side = !next->attackerOwned;
  397. attack.stackNumber = next->ID;
  398. for(int g=0; g<gs->curB->stacks.size(); ++g)
  399. {
  400. if(gs->curB->stacks[g]->owner != next->owner && gs->curB->stacks[g]->alive())
  401. {
  402. attack.destinationTile = gs->curB->stacks[g]->position;
  403. break;
  404. }
  405. }
  406. makeBattleAction(attack);
  407. checkForBattleEnd(stacks);
  408. continue;
  409. }
  410. if(next->type->idNumber == 145 && (!curOwner || curOwner->getSecSkillLevel(10) == 0)) //catapult, hero has no ballistics
  411. {
  412. BattleAction attack;
  413. static const int wallHexes[] = {50, 183, 182, 130, 62, 29, 12, 95};
  414. attack.destinationTile = wallHexes[ rand()%ARRAY_COUNT(wallHexes) ];
  415. attack.actionType = 9;
  416. attack.additionalInfo = 0;
  417. attack.side = !next->attackerOwned;
  418. attack.stackNumber = next->ID;
  419. makeBattleAction(attack);
  420. continue;
  421. }
  422. if(next->type->idNumber == 147 && (!curOwner || curOwner->getSecSkillLevel(27) == 0)) //first aid tent, hero has no first aid
  423. {
  424. BattleAction heal;
  425. std::vector< const CStack * > possibleStacks;
  426. for (int v=0; v<gs->curB->stacks.size(); ++v)
  427. {
  428. const CStack * cstack = gs->curB->stacks[v];
  429. if (cstack->owner == next->owner && cstack->firstHPleft < cstack->MaxHealth() && cstack->alive()) //it's friendly and not fully healthy
  430. {
  431. possibleStacks.push_back(cstack);
  432. }
  433. }
  434. if(possibleStacks.size() == 0)
  435. {
  436. //nothing to heal
  437. BattleAction doNothing;
  438. doNothing.actionType = 0;
  439. doNothing.additionalInfo = 0;
  440. doNothing.destinationTile = -1;
  441. doNothing.side = !next->attackerOwned;
  442. doNothing.stackNumber = next->ID;
  443. sendAndApply(&StartAction(doNothing));
  444. sendAndApply(&EndAction());
  445. continue;
  446. }
  447. else
  448. {
  449. //heal random creature
  450. const CStack * toBeHealed = possibleStacks[ rand()%possibleStacks.size() ];
  451. heal.actionType = 12;
  452. heal.additionalInfo = 0;
  453. heal.destinationTile = toBeHealed->position;
  454. heal.side = !next->attackerOwned;
  455. heal.stackNumber = next->ID;
  456. makeBattleAction(heal);
  457. }
  458. continue;
  459. }
  460. askInterfaceForMove:
  461. //ask interface and wait for answer
  462. if(!battleResult.get())
  463. {
  464. BattleSetActiveStack sas;
  465. sas.stack = next->ID;
  466. sendAndApply(&sas);
  467. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  468. while(next->alive() && (!battleMadeAction.data && !battleResult.get())) //active stack hasn't made its action and battle is still going
  469. battleMadeAction.cond.wait(lock);
  470. battleMadeAction.data = false;
  471. }
  472. else
  473. {
  474. break;
  475. }
  476. //we're after action, all results applied
  477. checkForBattleEnd(stacks); //check if this action ended the battle
  478. //check for good morale
  479. nextStackMorale = next->MoraleVal();
  480. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  481. && !vstd::contains(next->state,DEFENDING)
  482. && !vstd::contains(next->state,WAITING)
  483. && next->alive()
  484. && nextStackMorale > 0
  485. && !(NBonus::hasOfType(hero1, Bonus::BLOCK_MORALE) || NBonus::hasOfType(hero2, Bonus::BLOCK_MORALE)) //checking if heroes have (or don't have) morale blocking bonuses
  486. )
  487. if(rand()%24 < nextStackMorale) //this stack hasn't got morale this turn
  488. goto askInterfaceForMove; //move this stack once more
  489. }
  490. }
  491. endBattle(tile, hero1, hero2);
  492. }
  493. void CGameHandler::endBattle(int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2)
  494. {
  495. BattleResultsApplied resultsApplied;
  496. resultsApplied.player1 = bEndArmy1->tempOwner;
  497. resultsApplied.player2 = bEndArmy2->tempOwner;
  498. //unblock engaged players
  499. if(bEndArmy1->tempOwner<PLAYER_LIMIT)
  500. states.setFlag(bEndArmy1->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  501. if(bEndArmy2 && bEndArmy2->tempOwner<PLAYER_LIMIT)
  502. states.setFlag(bEndArmy2->tempOwner, &PlayerStatus::engagedIntoBattle, false);
  503. //casualties among heroes armies
  504. SetGarrisons sg;
  505. sg.garrs[bEndArmy1->id] = takeCasualties(bEndArmy1->tempOwner, *bEndArmy1, gs->curB);
  506. sg.garrs[bEndArmy2->id] = takeCasualties(bEndArmy2->tempOwner, *bEndArmy2, gs->curB);
  507. sendAndApply(&sg);
  508. ui8 sides[2];
  509. sides[0] = gs->curB->side1;
  510. sides[1] = gs->curB->side2;
  511. ui8 loser = sides[!battleResult.data->winner];
  512. //end battle, remove all info, free memory
  513. giveExp(*battleResult.data);
  514. sendAndApply(battleResult.data);
  515. //if one hero has lost we will erase him
  516. if(battleResult.data->winner!=0 && hero1)
  517. {
  518. RemoveObject ro(hero1->id);
  519. sendAndApply(&ro);
  520. }
  521. if(battleResult.data->winner!=1 && hero2)
  522. {
  523. RemoveObject ro(hero2->id);
  524. sendAndApply(&ro);
  525. }
  526. //give exp
  527. if(battleResult.data->exp[0] && hero1)
  528. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  529. if(battleResult.data->exp[1] && hero2)
  530. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  531. if(battleEndCallback && *battleEndCallback)
  532. {
  533. (*battleEndCallback)(battleResult.data);
  534. delete battleEndCallback;
  535. battleEndCallback = 0;
  536. }
  537. sendAndApply(&resultsApplied);
  538. // Necromancy if applicable.
  539. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  540. const CGHeroInstance *loserHero = battleResult.data->winner != 0 ? hero1 : hero2;
  541. if (winnerHero)
  542. {
  543. CStackInstance raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  544. // Give raised units to winner and show dialog, if any were raised.
  545. if (raisedStack.type)
  546. {
  547. int slot = winnerHero->getSlotFor(raisedStack.type->idNumber);
  548. if (slot != -1)
  549. {
  550. SetGarrisons sg;
  551. sg.garrs[winnerHero->id] = winnerHero->getArmy();
  552. sg.garrs[winnerHero->id].addToSlot(slot, raisedStack);
  553. // if (vstd::contains(winnerHero->slots, slot)) // Add to existing stack.
  554. // sg.garrs[winnerHero->id].slots[slot].count += raisedStack.count;
  555. // else // Create a new stack.
  556. // sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  557. winnerHero->showNecromancyDialog(raisedStack);
  558. sendAndApply(&sg);
  559. }
  560. }
  561. }
  562. if(visitObjectAfterVictory && winnerHero == hero1)
  563. {
  564. visitObjectOnTile(*getTile(winnerHero->getPosition()), winnerHero);
  565. }
  566. visitObjectAfterVictory = false;
  567. winLoseHandle(1<<sides[0] | 1<<sides[1]); //handle victory/loss of engaged players
  568. int result = battleResult.get()->result;
  569. if(result == 1 || result == 2) //loser has escaped or surrendered
  570. {
  571. SetAvailableHeroes sah;
  572. sah.player = loser;
  573. sah.hid[0] = loserHero->subID;
  574. if(result == 1) //retreat
  575. {
  576. sah.army[0] = new CCreatureSet();
  577. sah.army[0]->addToSlot(0, VLC->creh->nameToID[loserHero->type->refTypeStack[0]],1);
  578. }
  579. if(const CGHeroInstance *another = getPlayerState(loser)->availableHeroes[1])
  580. sah.hid[1] = another->subID;
  581. else
  582. sah.hid[1] = -1;
  583. sendAndApply(&sah);
  584. }
  585. delete battleResult.data;
  586. }
  587. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  588. {
  589. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  590. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  591. if( def->firstHPleft <= damageFirst )
  592. {
  593. bsa.killedAmount++;
  594. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  595. }
  596. else
  597. {
  598. bsa.newHP = def->firstHPleft - damageFirst;
  599. }
  600. if(def->count <= bsa.killedAmount) //stack killed
  601. {
  602. bsa.newAmount = 0;
  603. bsa.flags |= 1;
  604. bsa.killedAmount = def->count; //we cannot kill more creatures than we have
  605. }
  606. else
  607. {
  608. bsa.newAmount = def->count - bsa.killedAmount;
  609. }
  610. }
  611. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  612. {
  613. bat.bsa.clear();
  614. bat.stackAttacking = att->ID;
  615. bat.bsa.push_back(BattleStackAttacked());
  616. BattleStackAttacked *bsa = &bat.bsa.back();
  617. bsa->stackAttacked = def->ID;
  618. bsa->attackerID = att->ID;
  619. int attackerLuck = att->LuckVal();
  620. const CGHeroInstance * h0 = gs->curB->heroes[0],
  621. * h1 = gs->curB->heroes[1];
  622. bool noLuck = false;
  623. if(h0 && NBonus::hasOfType(h0, Bonus::BLOCK_LUCK) ||
  624. h1 && NBonus::hasOfType(h1, Bonus::BLOCK_LUCK))
  625. {
  626. noLuck = true;
  627. }
  628. if(!noLuck && attackerLuck > 0 && rand()%24 < attackerLuck) //TODO?: negative luck option?
  629. {
  630. bsa->damageAmount *= 2;
  631. bat.flags |= 4;
  632. }
  633. bsa->damageAmount = gs->curB->calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance, bat.lucky());//counting dealt damage
  634. int dmg = bsa->damageAmount;
  635. prepareAttacked(*bsa, def);
  636. //life drain handling
  637. if (att->hasBonusOfType(Bonus::LIFE_DRAIN))
  638. {
  639. StacksHealedOrResurrected shi;
  640. shi.lifeDrain = true;
  641. shi.drainedFrom = def->ID;
  642. StacksHealedOrResurrected::HealInfo hi;
  643. hi.stackID = att->ID;
  644. hi.healedHP = std::min<int>(dmg, att->MaxHealth() - att->firstHPleft + att->MaxHealth() * (att->baseAmount - att->count) );
  645. hi.lowLevelResurrection = false;
  646. shi.healedStacks.push_back(hi);
  647. if (hi.healedHP > 0)
  648. {
  649. bsa->healedStacks.push_back(shi);
  650. }
  651. }
  652. else
  653. {
  654. }
  655. //fire shield handling
  656. if ( !bat.shot() && def->hasBonusOfType(Bonus::FIRE_SHIELD) && !bsa->killed() )
  657. {
  658. bat.bsa.push_back(BattleStackAttacked());
  659. BattleStackAttacked *bsa = &bat.bsa.back();
  660. bsa->stackAttacked = att->ID;
  661. bsa->attackerID = def->ID;
  662. bsa->flags |= 2;
  663. bsa->effect = 11;
  664. bsa->damageAmount = (dmg * def->valOfBonuses(Bonus::FIRE_SHIELD)) / 100;
  665. prepareAttacked(*bsa, att);
  666. }
  667. }
  668. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  669. {
  670. srand(time(NULL));
  671. CPack *pack = NULL;
  672. try
  673. {
  674. while(1)//server should never shut connection first //was: while(!end2)
  675. {
  676. {
  677. boost::unique_lock<boost::mutex> lock(*c.rmx);
  678. c >> pack; //get the package
  679. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  680. }
  681. int packType = typeList.getTypeID(pack); //get the id of type
  682. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  683. if(apply)
  684. {
  685. bool result = apply->applyOnGH(this,&c,pack);
  686. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  687. //send confirmation that we've applied the package
  688. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  689. {
  690. PackageApplied applied;
  691. applied.result = result;
  692. applied.packType = packType;
  693. {
  694. boost::unique_lock<boost::mutex> lock(*c.wmx);
  695. c << &applied;
  696. }
  697. }
  698. }
  699. else
  700. {
  701. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  702. }
  703. delete pack;
  704. pack = NULL;
  705. }
  706. }
  707. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  708. {
  709. assert(!c.connected); //make sure that connection has been marked as broken
  710. tlog1 << e.what() << std::endl;
  711. end2 = true;
  712. }
  713. HANDLE_EXCEPTION(end2 = true);
  714. tlog1 << "Ended handling connection\n";
  715. }
  716. int CGameHandler::moveStack(int stack, int dest)
  717. {
  718. int ret = 0;
  719. CStack *curStack = gs->curB->getStack(stack),
  720. *stackAtEnd = gs->curB->getStackT(dest);
  721. assert(curStack);
  722. assert(dest < BFIELD_SIZE);
  723. //initing necessary tables
  724. bool accessibility[BFIELD_SIZE];
  725. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  726. for(int b=0; b<BFIELD_SIZE; ++b)
  727. {
  728. accessibility[b] = false;
  729. }
  730. for(int g=0; g<accessible.size(); ++g)
  731. {
  732. accessibility[accessible[g]] = true;
  733. }
  734. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  735. if(!stackAtEnd && curStack->doubleWide() && !accessibility[dest])
  736. {
  737. if(curStack->attackerOwned)
  738. {
  739. if(accessibility[dest+1])
  740. dest+=1;
  741. }
  742. else
  743. {
  744. if(accessibility[dest-1])
  745. dest-=1;
  746. }
  747. }
  748. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  749. return 0;
  750. bool accessibilityWithOccupyable[BFIELD_SIZE];
  751. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  752. for(int b=0; b<BFIELD_SIZE; ++b)
  753. {
  754. accessibilityWithOccupyable[b] = false;
  755. }
  756. for(int g=0; g<accOc.size(); ++g)
  757. {
  758. accessibilityWithOccupyable[accOc[g]] = true;
  759. }
  760. //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex
  761. // return false;
  762. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibilityWithOccupyable, curStack->hasBonusOfType(Bonus::FLYING), curStack->doubleWide(), curStack->attackerOwned);
  763. ret = path.second;
  764. if(curStack->hasBonusOfType(Bonus::FLYING))
  765. {
  766. if(path.second <= curStack->Speed() && path.first.size() > 0)
  767. {
  768. //inform clients about move
  769. BattleStackMoved sm;
  770. sm.stack = curStack->ID;
  771. sm.tile = path.first[0];
  772. sm.distance = path.second;
  773. sm.ending = true;
  774. sm.teleporting = false;
  775. sendAndApply(&sm);
  776. }
  777. }
  778. else //for non-flying creatures
  779. {
  780. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  781. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  782. {
  783. //inform clients about move
  784. BattleStackMoved sm;
  785. sm.stack = curStack->ID;
  786. sm.tile = path.first[v];
  787. sm.distance = path.second;
  788. sm.ending = v==tilesToMove;
  789. sm.teleporting = false;
  790. sendAndApply(&sm);
  791. }
  792. }
  793. return ret;
  794. }
  795. CGameHandler::CGameHandler(void)
  796. {
  797. QID = 1;
  798. gs = NULL;
  799. IObjectInterface::cb = this;
  800. applier = new CGHApplier;
  801. visitObjectAfterVictory = false;
  802. }
  803. CGameHandler::~CGameHandler(void)
  804. {
  805. delete applier;
  806. applier = NULL;
  807. delete gs;
  808. }
  809. void CGameHandler::init(StartInfo *si, int Seed)
  810. {
  811. gs = new CGameState();
  812. tlog0 << "Gamestate created!" << std::endl;
  813. gs->init(si, 0, Seed);
  814. tlog0 << "Gamestate initialized!" << std::endl;
  815. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  816. states.addPlayer(i->first);
  817. }
  818. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  819. {
  820. return *a < *b;
  821. }
  822. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false)
  823. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  824. if (forced || town->creatures[CREATURES_PER_TOWN].second.empty())//we need to change creature
  825. {
  826. SetAvailableCreatures ssi;
  827. ssi.tid = town->id;
  828. ssi.creatures = town->creatures;
  829. ssi.creatures[CREATURES_PER_TOWN].second.clear();//remove old one
  830. const std::vector<CGDwelling *> &dwellings = gs->getPlayer(town->tempOwner)->dwellings;
  831. if (dwellings.empty())//no dwellings - just remove
  832. {
  833. sendAndApply(&ssi);
  834. return;
  835. }
  836. ui32 dwellpos = rand()%dwellings.size();//take random dwelling
  837. ui32 creapos = rand()%dwellings[dwellpos]->creatures.size();//for multi-creature dwellings like Golem Factory
  838. ui32 creature = dwellings[dwellpos]->creatures[creapos].second[0];
  839. ssi.creatures[CREATURES_PER_TOWN].first = VLC->creh->creatures[creature]->growth;
  840. ssi.creatures[CREATURES_PER_TOWN].second.push_back(creature);
  841. sendAndApply(&ssi);
  842. }
  843. }
  844. void CGameHandler::newTurn()
  845. {
  846. tlog5 << "Turn " << gs->day+1 << std::endl;
  847. NewTurn n;
  848. n.day = gs->day + 1;
  849. n.resetBuilded = true;
  850. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  851. srand(time(NULL));
  852. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  853. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  854. {
  855. if(i->first == 255)
  856. continue;
  857. else if(i->first >= PLAYER_LIMIT)
  858. assert(0); //illegal player number!
  859. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  860. hadGold.insert(playerGold);
  861. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  862. {
  863. SetAvailableHeroes sah;
  864. sah.player = i->first;
  865. //pick heroes and their armies
  866. CHeroClass *banned = NULL;
  867. for (int j = 0; j < AVAILABLE_HEROES_PER_PLAYER; j++)
  868. {
  869. if(CGHeroInstance *h = gs->hpool.pickHeroFor(j == 0, i->first, getNativeTown(i->first), pool, banned)) //first hero - native if possible, second hero -> any other class
  870. {
  871. sah.hid[j] = h->subID;
  872. h->initArmy(sah.army[j] = new CCreatureSet());
  873. banned = h->type->heroClass;
  874. }
  875. else
  876. sah.hid[j] = -1;
  877. }
  878. sendAndApply(&sah);
  879. }
  880. n.res[i->first] = i->second.resources;
  881. // SetResources r;
  882. // r.player = i->first;
  883. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  884. // r.res[j] = i->second.resources[j];
  885. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  886. {
  887. if(h->visitedTown)
  888. giveSpells(h->visitedTown, h);
  889. NewTurn::Hero hth;
  890. hth.id = h->id;
  891. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  892. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  893. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  894. else
  895. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  896. n.heroes.insert(hth);
  897. if(gs->day) //not first day
  898. {
  899. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  900. {
  901. case 1: //basic
  902. n.res[i->first][6] += 125;
  903. break;
  904. case 2: //advanced
  905. n.res[i->first][6] += 250;
  906. break;
  907. case 3: //expert
  908. n.res[i->first][6] += 500;
  909. break;
  910. }
  911. for (int k = 0; k < RESOURCE_QUANTITY; k++)
  912. {
  913. n.res[i->first][k] += h->valOfBonuses(Bonus::GENERATE_RESOURCE, k);
  914. }
  915. //TODO player bonuses
  916. }
  917. }
  918. //n.res.push_back(r);
  919. }
  920. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  921. {
  922. ui8 player = (*j)->tempOwner;
  923. if(gs->getDate(1)==7) //first day of week
  924. {
  925. if ((*j)->subID == 5 && vstd::contains((*j)->builtBuildings, 22))
  926. setPortalDwelling(*j, true);//set creatures for Portal of Summoning
  927. if ((**j).subID == 1 && gs->getDate(0) && player < PLAYER_LIMIT && vstd::contains((**j).builtBuildings, 22))//dwarven treasury
  928. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  929. SetAvailableCreatures sac;
  930. sac.tid = (**j).id;
  931. sac.creatures = (**j).creatures;
  932. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  933. {
  934. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  935. {
  936. sac.creatures[k].first += (**j).creatureGrowth(k);
  937. if(!gs->getDate(0)) //first day of game: use only basic growths
  938. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]]->growth);
  939. }
  940. }
  941. n.cres.push_back(sac);
  942. }
  943. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  944. {
  945. ////SetResources r;
  946. //r.player = (**j).tempOwner;
  947. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  948. {
  949. if((**j).town->primaryRes == 127) //we'll give wood and ore
  950. {
  951. n.res[player][0] += 1;
  952. n.res[player][2] += 1;
  953. }
  954. else
  955. {
  956. n.res[player][(**j).town->primaryRes] += 1;
  957. }
  958. }
  959. n.res[player][6] += (**j).dailyIncome();
  960. }
  961. if ((**j).subID == 2 && vstd::contains((**j).builtBuildings, 26)) // Skyship, probably easier to handle same as Veil of darkness
  962. { //do it every new day after veils apply
  963. FoWChange fw;
  964. fw.mode = 1;
  965. fw.player = player;
  966. getAllTiles(fw.tiles, player, -1, 0);
  967. sendAndApply (&fw);
  968. }
  969. if ((**j).hasBonusOfType (Bonus::DARKNESS))
  970. {
  971. (**j).hideTiles((**j).getOwner(), (**j).getBonus(Selector::type(Bonus::DARKNESS))->val);
  972. }
  973. //unhiding what shouldn't be hidden? //that's handled in netpacks client
  974. }
  975. if(getDate(2) == 1)
  976. {
  977. SetAvailableArtifacts saa;
  978. saa.id = -1;
  979. pickAllowedArtsSet(saa.arts);
  980. sendAndApply(&saa);
  981. }
  982. sendAndApply(&n);
  983. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  984. handleTimeEvents();
  985. //call objects
  986. for(size_t i = 0; i<gs->map->objects.size(); i++)
  987. if(gs->map->objects[i])
  988. gs->map->objects[i]->newTurn();
  989. winLoseHandle(0xff);
  990. //warn players without town
  991. if(gs->day)
  992. {
  993. for (std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  994. {
  995. if(i->second.status || i->second.towns.size() || i->second.color >= PLAYER_LIMIT)
  996. continue;
  997. InfoWindow iw;
  998. iw.player = i->first;
  999. iw.components.push_back(Component(Component::FLAG,i->first,0,0));
  1000. if(!i->second.daysWithoutCastle)
  1001. {
  1002. iw.text.addTxt(MetaString::GENERAL_TXT,6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1003. iw.text.addReplacement(MetaString::COLOR, i->first);
  1004. }
  1005. else if(i->second.daysWithoutCastle == 6)
  1006. {
  1007. iw.text.addTxt(MetaString::ARRAY_TXT,129); //%s, this is your last day to capture a town or you will be banished from this land.
  1008. iw.text.addReplacement(MetaString::COLOR, i->first);
  1009. }
  1010. else
  1011. {
  1012. iw.text.addTxt(MetaString::ARRAY_TXT,128); //%s, you only have %d days left to capture a town or you will be banished from this land.
  1013. iw.text.addReplacement(MetaString::COLOR, i->first);
  1014. iw.text.addReplacement(7 - i->second.daysWithoutCastle);
  1015. }
  1016. sendAndApply(&iw);
  1017. }
  1018. }
  1019. }
  1020. void CGameHandler::run(bool resume, const StartInfo *si /*= NULL*/)
  1021. {
  1022. using namespace boost::posix_time;
  1023. BOOST_FOREACH(CConnection *cc, conns)
  1024. {//init conn.
  1025. ui8 quantity, pom;
  1026. //ui32 seed;
  1027. if(!resume)
  1028. (*cc) << si << gs->map->checksum << gs->seed; // gs->scenarioOps
  1029. (*cc) >> quantity; //how many players will be handled at that client
  1030. for(int i=0;i<quantity;i++)
  1031. {
  1032. (*cc) >> pom; //read player color
  1033. {
  1034. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1035. connections[pom] = cc;
  1036. }
  1037. }
  1038. }
  1039. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1040. {
  1041. std::set<int> pom;
  1042. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1043. if(j->second == *i)
  1044. pom.insert(j->first);
  1045. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1046. }
  1047. while (!end2)
  1048. {
  1049. if(!resume)
  1050. newTurn();
  1051. std::map<ui8,PlayerState>::iterator i;
  1052. if(!resume)
  1053. i = gs->players.begin();
  1054. else
  1055. i = gs->players.find(gs->currentPlayer);
  1056. resume = false;
  1057. for(; i != gs->players.end(); i++)
  1058. {
  1059. if(i->second.towns.size()==0 && i->second.heroes.size()==0
  1060. || i->second.color<0
  1061. || i->first>=PLAYER_LIMIT
  1062. || i->second.status)
  1063. {
  1064. continue;
  1065. }
  1066. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1067. {
  1068. YourTurn yt;
  1069. yt.player = i->first;
  1070. sendAndApply(&yt);
  1071. }
  1072. //wait till turn is done
  1073. boost::unique_lock<boost::mutex> lock(states.mx);
  1074. while(states.players[i->first].makingTurn && !end2)
  1075. {
  1076. static time_duration p = milliseconds(200);
  1077. states.cv.timed_wait(lock,p);
  1078. }
  1079. }
  1080. }
  1081. while(conns.size() && (*conns.begin())->isOpen())
  1082. boost::this_thread::sleep(boost::posix_time::milliseconds(5)); //give time client to close socket
  1083. }
  1084. namespace CGH
  1085. {
  1086. using namespace std;
  1087. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  1088. {
  1089. for(int j=0; j<7; ++j)
  1090. {
  1091. std::vector<int> pom;
  1092. for(int g=0; g<j+1; ++g)
  1093. {
  1094. int hlp; input>>hlp;
  1095. pom.push_back(hlp);
  1096. }
  1097. dest.push_back(pom);
  1098. }
  1099. }
  1100. }
  1101. void CGameHandler::setupBattle(BattleInfo * curB, int3 tile, const CArmedInstance *army1, const CArmedInstance *army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  1102. {
  1103. battleResult.set(NULL);
  1104. std::vector<CStack*> & stacks = (curB->stacks);
  1105. curB->tile = tile;
  1106. curB->belligerents[0] = const_cast<CArmedInstance*>(army1);
  1107. curB->belligerents[1] = const_cast<CArmedInstance*>(army2);
  1108. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  1109. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  1110. curB->round = -2;
  1111. curB->activeStack = -1;
  1112. if(town)
  1113. {
  1114. curB->tid = town->id;
  1115. curB->siege = town->fortLevel();
  1116. }
  1117. else
  1118. {
  1119. curB->tid = -1;
  1120. curB->siege = 0;
  1121. }
  1122. //reading battleStartpos
  1123. std::ifstream positions;
  1124. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1125. if(!positions.is_open())
  1126. {
  1127. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1128. }
  1129. std::string dump;
  1130. positions>>dump; positions>>dump;
  1131. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  1132. CGH::readItTo(positions, attackerLoose);
  1133. positions>>dump;
  1134. CGH::readItTo(positions, defenderLoose);
  1135. positions>>dump;
  1136. positions>>dump;
  1137. CGH::readItTo(positions, attackerTight);
  1138. positions>>dump;
  1139. CGH::readItTo(positions, defenderTight);
  1140. positions>>dump;
  1141. positions>>dump;
  1142. CGH::readItTo(positions, attackerCreBank);
  1143. positions>>dump;
  1144. CGH::readItTo(positions, defenderCreBank);
  1145. positions.close();
  1146. //battleStartpos read
  1147. int k = 0; //stack serial
  1148. for(TSlots::const_iterator i = army1->Slots().begin(); i!=army1->Slots().end(); i++, k++)
  1149. {
  1150. int pos;
  1151. if(creatureBank)
  1152. pos = attackerCreBank[army1->stacksCount()-1][k];
  1153. else if(army1->formation)
  1154. pos = attackerTight[army1->stacksCount()-1][k];
  1155. else
  1156. pos = attackerLoose[army1->stacksCount()-1][k];
  1157. CStack * stack = curB->generateNewStack(i->second, stacks.size(), true, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1158. stacks.push_back(stack);
  1159. }
  1160. k = 0;
  1161. for(TSlots::const_iterator i = army2->Slots().begin(); i!=army2->Slots().end(); i++, k++)
  1162. {
  1163. int pos;
  1164. if(creatureBank)
  1165. pos = defenderCreBank[army2->stacksCount()-1][k];
  1166. else if(army2->formation)
  1167. pos = defenderTight[army2->stacksCount()-1][k];
  1168. else
  1169. pos = defenderLoose[army2->stacksCount()-1][k];
  1170. CStack * stack = curB->generateNewStack(i->second, stacks.size(), false, i->first, gs->map->terrain[tile.x][tile.y][tile.z].tertype, pos);
  1171. stacks.push_back(stack);
  1172. }
  1173. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1174. {
  1175. if((stacks[g]->position%17)==1 && stacks[g]->doubleWide() && stacks[g]->attackerOwned)
  1176. {
  1177. stacks[g]->position += 1;
  1178. }
  1179. else if((stacks[g]->position%17)==15 && stacks[g]->doubleWide() && !stacks[g]->attackerOwned)
  1180. {
  1181. stacks[g]->position -= 1;
  1182. }
  1183. }
  1184. //adding war machines
  1185. if(hero1)
  1186. {
  1187. if(hero1->getArt(13)) //ballista
  1188. {
  1189. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  1190. stacks.push_back(stack);
  1191. }
  1192. if(hero1->getArt(14)) //ammo cart
  1193. {
  1194. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  1195. stacks.push_back(stack);
  1196. }
  1197. if(hero1->getArt(15)) //first aid tent
  1198. {
  1199. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  1200. stacks.push_back(stack);
  1201. }
  1202. }
  1203. if(hero2)
  1204. {
  1205. if(hero2->getArt(13)) //ballista
  1206. {
  1207. CStack * stack = curB->generateNewStack(CStackInstance(146, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1208. stacks.push_back(stack);
  1209. }
  1210. if(hero2->getArt(14)) //ammo cart
  1211. {
  1212. CStack * stack = curB->generateNewStack(CStackInstance(148, 1, hero1), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1213. stacks.push_back(stack);
  1214. }
  1215. if(hero2->getArt(15)) //first aid tent
  1216. {
  1217. CStack * stack = curB->generateNewStack(CStackInstance(147, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1218. stacks.push_back(stack);
  1219. }
  1220. }
  1221. if(town && hero1 && town->hasFort()) //catapult
  1222. {
  1223. CStack * stack = curB->generateNewStack(CStackInstance(145, 1, hero1), stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1224. stacks.push_back(stack);
  1225. }
  1226. //war machines added
  1227. switch(curB->siege) //adding towers
  1228. {
  1229. case 3: //castle
  1230. {//lower tower / upper tower
  1231. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1232. stacks.push_back(stack);
  1233. stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1234. stacks.push_back(stack);
  1235. }
  1236. case 2: //citadel
  1237. {//main tower
  1238. CStack * stack = curB->generateNewStack(CStackInstance(149, 1, hero2), stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1239. stacks.push_back(stack);
  1240. }
  1241. }
  1242. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1243. //seting up siege
  1244. if(town && town->hasFort())
  1245. {
  1246. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1247. {
  1248. curB->si.wallState[b] = 1;
  1249. }
  1250. }
  1251. int terType = gs->battleGetBattlefieldType(tile);
  1252. //randomize obstacles
  1253. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1254. {
  1255. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1256. std::vector<int> possibleObstacles;
  1257. for(int i=0; i<BFIELD_SIZE; ++i)
  1258. {
  1259. if(i%17 < 4 || i%17 > 12)
  1260. {
  1261. obAv[i] = false;
  1262. }
  1263. else
  1264. {
  1265. obAv[i] = true;
  1266. }
  1267. }
  1268. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1269. {
  1270. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  1271. {
  1272. possibleObstacles.push_back(g->first);
  1273. }
  1274. }
  1275. srand(time(NULL));
  1276. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1277. {
  1278. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1279. while(toBlock>0)
  1280. {
  1281. CObstacleInstance coi;
  1282. coi.uniqueID = curB->obstacles.size();
  1283. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1284. coi.pos = rand()%BFIELD_SIZE;
  1285. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1286. bool badObstacle = false;
  1287. for(int b=0; b<block.size(); ++b)
  1288. {
  1289. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1290. {
  1291. badObstacle = true;
  1292. break;
  1293. }
  1294. }
  1295. if(badObstacle) continue;
  1296. //obstacle can be placed
  1297. curB->obstacles.push_back(coi);
  1298. for(int b=0; b<block.size(); ++b)
  1299. {
  1300. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1301. obAv[block[b]] = false;
  1302. }
  1303. toBlock -= block.size();
  1304. }
  1305. }
  1306. }
  1307. //giving building bonuses, if siege and we have harrisoned hero
  1308. if (town)
  1309. {
  1310. if (hero2)
  1311. {
  1312. for (int i=0; i<4; i++)
  1313. {
  1314. int val = town->defenceBonus(i);
  1315. if (val)
  1316. {
  1317. GiveBonus gs;
  1318. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::PRIMARY_SKILL, Bonus::OBJECT, val, -1, "", i);
  1319. gs.id = hero2->id;
  1320. sendAndApply(&gs);
  1321. }
  1322. }
  1323. }
  1324. else//if we don't have hero - apply separately, if hero present - will be taken from hero bonuses
  1325. {
  1326. if(town->subID == 0 && vstd::contains(town->builtBuildings,22)) //castle, brotherhood of sword built
  1327. for(int g=0; g<stacks.size(); ++g)
  1328. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1329. else if(vstd::contains(town->builtBuildings,5)) //tavern is built
  1330. for(int g=0; g<stacks.size(); ++g)
  1331. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TOWN_STRUCTURE));
  1332. if(town->subID == 1 && vstd::contains(town->builtBuildings,21)) //rampart, fountain of fortune is present
  1333. for(int g=0; g<stacks.size(); ++g)
  1334. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TOWN_STRUCTURE));
  1335. }
  1336. }
  1337. //giving terrain premies for heroes & stacks
  1338. int bonusSubtype = -1;
  1339. switch(terType)
  1340. {
  1341. case 9: //magic plains
  1342. {
  1343. bonusSubtype = 0;
  1344. }
  1345. case 14: //fiery fields
  1346. {
  1347. if(bonusSubtype == -1) bonusSubtype = 1;
  1348. }
  1349. case 15: //rock lands
  1350. {
  1351. if(bonusSubtype == -1) bonusSubtype = 8;
  1352. }
  1353. case 16: //magic clouds
  1354. {
  1355. if(bonusSubtype == -1) bonusSubtype = 2;
  1356. }
  1357. case 17: //lucid pools
  1358. {
  1359. if(bonusSubtype == -1) bonusSubtype = 4;
  1360. }
  1361. { //common part for cases 9, 14, 15, 16, 17
  1362. const CGHeroInstance * cHero = NULL;
  1363. for(int i=0; i<2; ++i)
  1364. {
  1365. if(i == 0) cHero = hero1;
  1366. else cHero = hero2;
  1367. if(cHero == NULL) continue;
  1368. GiveBonus gs;
  1369. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::MAGIC_SCHOOL_SKILL, Bonus::OBJECT, 3, -1, "", bonusSubtype);
  1370. gs.id = cHero->id;
  1371. sendAndApply(&gs);
  1372. }
  1373. break;
  1374. }
  1375. case 18: //holy ground
  1376. {
  1377. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1378. {
  1379. if (stacks[g]->type->isGood())
  1380. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1381. else if (stacks[g]->type->isEvil())
  1382. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1383. }
  1384. break;
  1385. }
  1386. case 19: //clover field
  1387. {
  1388. for(int g=0; g<stacks.size(); ++g)
  1389. {
  1390. if(stacks[g]->type->faction == -1) //+2 luck bonus for neutral creatures
  1391. {
  1392. stacks[g]->bonuses.push_back(makeFeature(Bonus::LUCK, Bonus::ONE_BATTLE, 0, 2, Bonus::TERRAIN_OVERLAY));
  1393. }
  1394. }
  1395. break;
  1396. }
  1397. case 20: //evil fog
  1398. {
  1399. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1400. {
  1401. if (stacks[g]->type->isGood())
  1402. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, -1, Bonus::TERRAIN_OVERLAY));
  1403. else if (stacks[g]->type->isEvil())
  1404. stacks[g]->bonuses.push_back(makeFeature(Bonus::MORALE, Bonus::ONE_BATTLE, 0, 1, Bonus::TERRAIN_OVERLAY));
  1405. }
  1406. break;
  1407. }
  1408. case 22: //cursed ground
  1409. {
  1410. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1411. {
  1412. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_MORALE, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1413. stacks[g]->bonuses.push_back(makeFeature(Bonus::NO_LUCK, Bonus::ONE_BATTLE, 0, 0, Bonus::TERRAIN_OVERLAY));
  1414. }
  1415. const CGHeroInstance * cHero = NULL;
  1416. for(int i=0; i<2; ++i) //blocking spells above level 1
  1417. {
  1418. if(i == 0) cHero = hero1;
  1419. else cHero = hero2;
  1420. if(cHero == NULL) continue;
  1421. GiveBonus gs;
  1422. gs.bonus = Bonus(Bonus::ONE_BATTLE, Bonus::BLOCK_SPELLS_ABOVE_LEVEL, Bonus::OBJECT, 1, -1, "", bonusSubtype);
  1423. gs.id = cHero->id;
  1424. sendAndApply(&gs);
  1425. }
  1426. break;
  1427. }
  1428. }
  1429. //premies given
  1430. //send info about battles
  1431. BattleStart bs;
  1432. bs.info = curB;
  1433. sendAndApply(&bs);
  1434. }
  1435. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1436. {
  1437. //checking winning condition
  1438. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1439. hasStack[0] = hasStack[1] = false;
  1440. for(int b = 0; b<stacks.size(); ++b)
  1441. {
  1442. if(stacks[b]->alive() && !stacks[b]->hasBonusOfType(Bonus::SIEGE_WEAPON))
  1443. {
  1444. hasStack[1-stacks[b]->attackerOwned] = true;
  1445. }
  1446. }
  1447. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1448. {
  1449. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1450. br->result = 0;
  1451. br->winner = hasStack[1]; //fleeing side loses
  1452. gs->curB->calculateCasualties(br->casualties);
  1453. battleResult.set(br);
  1454. }
  1455. }
  1456. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1457. {
  1458. if(!vstd::contains(h->artifWorn,17))
  1459. return; //hero hasn't spellbok
  1460. ChangeSpells cs;
  1461. cs.hid = h->id;
  1462. cs.learn = true;
  1463. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1464. {
  1465. if (t->subID == 8 && vstd::contains(t->builtBuildings, 26)) //Aurora Borealis
  1466. {
  1467. std::vector<ui16> spells;
  1468. getAllowedSpells(spells, i);
  1469. for (int j = 0; j < spells.size(); ++j)
  1470. cs.spells.insert(spells[j]);
  1471. }
  1472. else
  1473. {
  1474. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1475. {
  1476. if(!vstd::contains(h->spells,t->spells[i][j]))
  1477. cs.spells.insert(t->spells[i][j]);
  1478. }
  1479. }
  1480. }
  1481. if(cs.spells.size())
  1482. sendAndApply(&cs);
  1483. }
  1484. void CGameHandler::setBlockVis(int objid, bool bv)
  1485. {
  1486. SetObjectProperty sop(objid,2,bv);
  1487. sendAndApply(&sop);
  1488. }
  1489. bool CGameHandler::removeObject( int objid )
  1490. {
  1491. if(!getObj(objid))
  1492. {
  1493. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1494. return false;
  1495. }
  1496. RemoveObject ro;
  1497. ro.id = objid;
  1498. sendAndApply(&ro);
  1499. winLoseHandle(255); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1500. return true;
  1501. }
  1502. void CGameHandler::setAmount(int objid, ui32 val)
  1503. {
  1504. SetObjectProperty sop(objid,3,val);
  1505. sendAndApply(&sop);
  1506. }
  1507. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1508. {
  1509. bool blockvis = false;
  1510. const CGHeroInstance *h = getHero(hid);
  1511. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1512. )
  1513. {
  1514. tlog1 << "Illegal call to move hero!\n";
  1515. return false;
  1516. }
  1517. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1518. int3 hmpos = dst + int3(-1,0,0);
  1519. if(!gs->map->isInTheMap(hmpos))
  1520. {
  1521. tlog1 << "Destination tile is outside the map!\n";
  1522. return false;
  1523. }
  1524. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1525. int cost = gs->getMovementCost(h, h->getPosition(false), CGHeroInstance::convertPosition(dst,false),h->movement);
  1526. int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1527. //result structure for start - movement failed, no move points used
  1528. TryMoveHero tmh;
  1529. tmh.id = hid;
  1530. tmh.start = h->pos;
  1531. tmh.end = dst;
  1532. tmh.result = TryMoveHero::FAILED;
  1533. tmh.movePoints = h->movement;
  1534. //check if destination tile is available
  1535. //it's a rock or blocked and not visitable tile
  1536. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1537. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable && !h->hasBonusOfType(Bonus::FLYING_MOVEMENT) ))
  1538. && complain("Cannot move hero, destination tile is blocked!")
  1539. || (!h->boat && !h->canWalkOnSea() && t.tertype == TerrainTile::water && (t.visitableObjects.size() != 1 || (t.visitableObjects.front()->ID != 8 && t.visitableObjects.front()->ID != HEROI_TYPE))) //hero is not on boat/water walking and dst water tile doesn't contain boat/hero (objs visitable from land)
  1540. && complain("Cannot move hero, destination tile is on water!")
  1541. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1542. && complain("Cannot disembark hero, tile is blocked!")
  1543. || (h->movement < cost && dst != h->pos && !instant)
  1544. && complain("Hero doesn't have any movement points left!")
  1545. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1546. && complain("Cannot move hero during the battle"))
  1547. {
  1548. //send info about movement failure
  1549. sendAndApply(&tmh);
  1550. return false;
  1551. }
  1552. //hero enters the boat
  1553. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1554. {
  1555. tmh.result = TryMoveHero::EMBARK;
  1556. tmh.movePoints = 0; //embarking takes all move points
  1557. //TODO: check for bonus that removes that penalty
  1558. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1559. sendAndApply(&tmh);
  1560. return true;
  1561. }
  1562. //hero leaves the boat
  1563. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1564. {
  1565. tmh.result = TryMoveHero::DISEMBARK;
  1566. tmh.movePoints = 0; //disembarking takes all move points
  1567. //TODO: check for bonus that removes that penalty
  1568. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1569. sendAndApply(&tmh);
  1570. tryAttackingGuard(guardPos, h);
  1571. return true;
  1572. }
  1573. //checks for standard movement
  1574. if(!instant)
  1575. {
  1576. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighboring!")
  1577. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1578. {
  1579. sendAndApply(&tmh);
  1580. return false;
  1581. }
  1582. //check if there is blocking visitable object
  1583. blockvis = false;
  1584. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1585. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1586. {
  1587. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1588. {
  1589. blockvis = true;
  1590. break;
  1591. }
  1592. }
  1593. //we start moving
  1594. if(blockvis)//interaction with blocking object (like resources)
  1595. {
  1596. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1597. sendAndApply(&tmh);
  1598. //failed to move to that tile but we visit object
  1599. if(t.visitableObjects.size())
  1600. objectVisited(t.visitableObjects.back(), h);
  1601. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1602. // {
  1603. // if (obj->blockVisit)
  1604. // {
  1605. // objectVisited(obj, h);
  1606. // }
  1607. // }
  1608. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1609. return true;
  1610. }
  1611. else //normal move
  1612. {
  1613. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1614. {
  1615. obj->onHeroLeave(h);
  1616. }
  1617. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1618. tmh.result = TryMoveHero::SUCCESS;
  1619. tmh.attackedFrom = guardPos;
  1620. sendAndApply(&tmh);
  1621. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1622. // If a creature guards the tile, block visit.
  1623. const bool fightingGuard = tryAttackingGuard(guardPos, h);
  1624. if(!fightingGuard && t.visitableObjects.size()) //call objects if they are visited
  1625. {
  1626. visitObjectOnTile(t, h);
  1627. }
  1628. // BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1629. // {
  1630. // objectVisited(obj, h);
  1631. // }
  1632. tlog5 << "Movement end!\n";
  1633. return true;
  1634. }
  1635. }
  1636. else //instant move - teleportation
  1637. {
  1638. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1639. {
  1640. if(obj->ID==HEROI_TYPE)
  1641. {
  1642. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1643. if(obj->tempOwner==h->tempOwner)
  1644. {
  1645. heroExchange(dh->id, h->id);
  1646. return true;
  1647. }
  1648. //TODO: check for ally
  1649. startBattleI(h, dh);
  1650. return true;
  1651. }
  1652. }
  1653. tmh.result = TryMoveHero::TELEPORTATION;
  1654. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1655. sendAndApply(&tmh);
  1656. return true;
  1657. }
  1658. }
  1659. bool CGameHandler::teleportHero(si32 hid, si32 dstid, ui8 source, ui8 asker/* = 255*/)
  1660. {
  1661. const CGHeroInstance *h = getHero(hid);
  1662. const CGTownInstance *t = getTown(dstid);
  1663. if ( !h || !t || h->getOwner() != gs->currentPlayer )
  1664. tlog1<<"Invalid call to teleportHero!";
  1665. const CGTownInstance *from = h->visitedTown;
  1666. if((h->getOwner() != t->getOwner())
  1667. && complain("Cannot teleport hero to another player")
  1668. || (!from || from->subID!=3 || !vstd::contains(from->builtBuildings, 22))
  1669. && complain("Hero must be in town with Castle gate for teleporting")
  1670. || (t->subID!=3 || !vstd::contains(t->builtBuildings, 22))
  1671. && complain("Cannot teleport hero to town without Castle gate in it"))
  1672. return false;
  1673. int3 pos = t->visitablePos();
  1674. pos += h->getVisitableOffset();
  1675. stopHeroVisitCastle(from->id, hid);
  1676. moveHero(hid,pos,1);
  1677. heroVisitCastle(dstid, hid);
  1678. return true;
  1679. }
  1680. void CGameHandler::setOwner(int objid, ui8 owner)
  1681. {
  1682. ui8 oldOwner = getOwner(objid);
  1683. SetObjectProperty sop(objid,1,owner);
  1684. sendAndApply(&sop);
  1685. winLoseHandle(1<<owner | 1<<oldOwner);
  1686. if(owner < PLAYER_LIMIT && getTown(objid)) //town captured
  1687. {
  1688. const CGTownInstance * town = getTown(objid);
  1689. if (town->subID == 5 && vstd::contains(town->builtBuildings, 22))
  1690. setPortalDwelling(town);
  1691. if (!gs->getPlayer(owner)->towns.size())//player lost last town
  1692. {
  1693. InfoWindow iw;
  1694. iw.player = oldOwner;
  1695. iw.text.addTxt(MetaString::GENERAL_TXT, 6); //%s, you have lost your last town. If you do not conquer another town in the next week, you will be eliminated.
  1696. sendAndApply(&iw);
  1697. }
  1698. }
  1699. const CGObjectInstance * obj = getObj(objid);
  1700. if ((obj->ID == 17 || obj->ID == 20 ) && gs->getPlayer(owner)->dwellings.size()==1 )//first dwelling captured
  1701. BOOST_FOREACH(const CGTownInstance *t, gs->getPlayer(owner)->towns)
  1702. if (t->subID == 5 && vstd::contains(t->builtBuildings, 22))
  1703. setPortalDwelling(t);//set initial creatures for all portals of summoning
  1704. }
  1705. void CGameHandler::setHoverName(int objid, MetaString* name)
  1706. {
  1707. SetHoverName shn(objid, *name);
  1708. sendAndApply(&shn);
  1709. }
  1710. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1711. {
  1712. sendToAllClients(iw);
  1713. }
  1714. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1715. {
  1716. ask(iw,iw->player,callback);
  1717. }
  1718. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1719. {
  1720. //TODO
  1721. //gsm.lock();
  1722. //int query = QID++;
  1723. //states.addQuery(player,query);
  1724. //sendToAllClients(iw);
  1725. //gsm.unlock();
  1726. //ui32 ret = getQueryResult(iw->player, query);
  1727. //gsm.lock();
  1728. //states.removeQuery(player, query);
  1729. //gsm.unlock();
  1730. return 0;
  1731. }
  1732. int CGameHandler::getCurrentPlayer()
  1733. {
  1734. return gs->currentPlayer;
  1735. }
  1736. void CGameHandler::giveResource(int player, int which, int val)
  1737. {
  1738. if(!val) return; //don't waste time on empty call
  1739. SetResource sr;
  1740. sr.player = player;
  1741. sr.resid = which;
  1742. sr.val = gs->players.find(player)->second.resources[which]+val;
  1743. sendAndApply(&sr);
  1744. }
  1745. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1746. {
  1747. if (creatures.stacksCount() <= 0)
  1748. return;
  1749. CCreatureSet heroArmy = h->getArmy();
  1750. while (creatures.stacksCount())
  1751. {
  1752. int slot = heroArmy.getSlotFor(creatures.Slots().begin()->second.type->idNumber);
  1753. if (slot < 0)
  1754. break;
  1755. heroArmy.addToSlot(slot, creatures.slots.begin()->second);
  1756. creatures.slots.erase (creatures.slots.begin());
  1757. }
  1758. if (creatures.stacksCount() == 0) //all creatures can be moved to hero army - do that
  1759. {
  1760. SetGarrisons sg;
  1761. sg.garrs[h->id] = heroArmy;
  1762. sendAndApply(&sg);
  1763. }
  1764. else //show garrison window and let player pick creatures
  1765. {
  1766. SetGarrisons sg;
  1767. sg.garrs[objid] = creatures;
  1768. sendAndApply (&sg);
  1769. showGarrisonDialog (objid, h->id, true, 0);
  1770. return;
  1771. }
  1772. }
  1773. void CGameHandler::takeCreatures (int objid, TSlots creatures) //probably we could use ArmedInstance as well
  1774. {
  1775. if (creatures.size() <= 0)
  1776. return;
  1777. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  1778. CCreatureSet newArmy = obj->getArmy();
  1779. while (creatures.size())
  1780. {
  1781. int slot = newArmy.getSlotFor(creatures.begin()->second.type->idNumber);
  1782. if (slot < 0)
  1783. break;
  1784. newArmy.slots[slot].count -= creatures.begin()->second.count;
  1785. if (newArmy.getStack(slot).count < 1)
  1786. newArmy.eraseStack(slot);
  1787. creatures.erase (creatures.begin());
  1788. }
  1789. SetGarrisons sg;
  1790. sg.garrs[objid] = newArmy;
  1791. sendAndApply(&sg);
  1792. }
  1793. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1794. {
  1795. sendToAllClients(comp);
  1796. }
  1797. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1798. {
  1799. HeroVisitCastle vc;
  1800. vc.hid = heroID;
  1801. vc.tid = obj;
  1802. vc.flags |= 1;
  1803. sendAndApply(&vc);
  1804. const CGHeroInstance *h = getHero(heroID);
  1805. vistiCastleObjects (getTown(obj), h);
  1806. giveSpells (getTown(obj), getHero(heroID));
  1807. if(gs->map->victoryCondition.condition == transportItem)
  1808. checkLossVictory(h->tempOwner); //transported artifact?
  1809. }
  1810. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1811. {
  1812. std::vector<CGTownBuilding*>::const_iterator i;
  1813. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1814. (*i)->onHeroVisit (h);
  1815. }
  1816. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1817. {
  1818. HeroVisitCastle vc;
  1819. vc.hid = heroID;
  1820. vc.tid = obj;
  1821. sendAndApply(&vc);
  1822. }
  1823. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1824. {
  1825. const CGHeroInstance* h = getHero(hid);
  1826. const CArtifact &art = *VLC->arth->artifacts[artid];
  1827. SetHeroArtifacts sha;
  1828. sha.hid = hid;
  1829. sha.artifacts = h->artifacts;
  1830. sha.artifWorn = h->artifWorn;
  1831. if(position<0)
  1832. {
  1833. if(position == -2)
  1834. {
  1835. int i;
  1836. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1837. {
  1838. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1839. {
  1840. //we've found a free suitable slot
  1841. VLC->arth->equipArtifact(sha.artifWorn, art.possibleSlots[i], artid);
  1842. break;
  1843. }
  1844. }
  1845. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  1846. sha.artifacts.push_back(artid);
  1847. }
  1848. else if (!art.isBig()) //should be -1 => put artifact into backpack
  1849. {
  1850. sha.artifacts.push_back(artid);
  1851. }
  1852. }
  1853. else
  1854. {
  1855. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1856. {
  1857. VLC->arth->equipArtifact(sha.artifWorn, position, artid);
  1858. }
  1859. else if (!art.isBig())
  1860. {
  1861. sha.artifacts.push_back(artid);
  1862. }
  1863. }
  1864. sendAndApply(&sha);
  1865. }
  1866. bool CGameHandler::removeArtifact(int artid, int hid)
  1867. {
  1868. const CGHeroInstance* h = getHero(hid);
  1869. SetHeroArtifacts sha;
  1870. sha.hid = hid;
  1871. sha.artifacts = h->artifacts;
  1872. sha.artifWorn = h->artifWorn;
  1873. std::vector<ui32>::iterator it;
  1874. if ((it = std::find(sha.artifacts.begin(), sha.artifacts.end(), artid)) != sha.artifacts.end()) //it is in backpack
  1875. sha.artifacts.erase(it);
  1876. else //worn
  1877. {
  1878. std::map<ui16,ui32>::iterator itr;
  1879. for (itr = sha.artifWorn.begin(); itr != sha.artifWorn.end(); ++itr)
  1880. {
  1881. if (itr->second == artid)
  1882. {
  1883. VLC->arth->unequipArtifact(sha.artifWorn, itr->first);
  1884. break;
  1885. }
  1886. }
  1887. if(itr == sha.artifWorn.end())
  1888. {
  1889. tlog2 << "Cannot find artifact to remove!\n";
  1890. return false;
  1891. }
  1892. }
  1893. sendAndApply(&sha);
  1894. return true;
  1895. }
  1896. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank, boost::function<void(BattleResult*)> cb, const CGTownInstance *town) //use hero=NULL for no hero
  1897. {
  1898. engageIntoBattle(army1->tempOwner);
  1899. engageIntoBattle(army2->tempOwner);
  1900. //block engaged players
  1901. if(army2->tempOwner < PLAYER_LIMIT)
  1902. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1903. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1904. }
  1905. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1906. {
  1907. startBattleI(army1, army2, tile,
  1908. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1909. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1910. creatureBank, cb);
  1911. }
  1912. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1913. {
  1914. startBattleI(army1, army2, army2->visitablePos(), cb, creatureBank);
  1915. }
  1916. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1917. //{
  1918. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1919. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1920. // //battle(&h->army,army,tile,h,NULL);
  1921. //}
  1922. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1923. {
  1924. ChangeSpells cs;
  1925. cs.hid = hid;
  1926. cs.spells = spells;
  1927. cs.learn = give;
  1928. sendAndApply(&cs);
  1929. }
  1930. int CGameHandler::getSelectedHero()
  1931. {
  1932. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1933. }
  1934. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1935. {
  1936. SetObjectProperty sob;
  1937. sob.id = objid;
  1938. sob.what = prop;
  1939. sob.val = val;
  1940. sendAndApply(&sob);
  1941. }
  1942. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1943. {
  1944. SystemMessage sm;
  1945. sm.text = message;
  1946. c << &sm;
  1947. }
  1948. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1949. {
  1950. sendAndApply(bonus);
  1951. }
  1952. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1953. {
  1954. sendAndApply(smp);
  1955. }
  1956. void CGameHandler::setManaPoints( int hid, int val )
  1957. {
  1958. SetMana sm;
  1959. sm.hid = hid;
  1960. sm.val = val;
  1961. sendAndApply(&sm);
  1962. }
  1963. void CGameHandler::giveHero( int id, int player )
  1964. {
  1965. GiveHero gh;
  1966. gh.id = id;
  1967. gh.player = player;
  1968. sendAndApply(&gh);
  1969. }
  1970. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1971. {
  1972. ChangeObjPos cop;
  1973. cop.objid = objid;
  1974. cop.nPos = newPos;
  1975. cop.flags = flags;
  1976. sendAndApply(&cop);
  1977. }
  1978. void CGameHandler::useScholarSkill(si32 fromHero, si32 toHero)
  1979. {
  1980. const CGHeroInstance * h1 = getHero(fromHero);
  1981. const CGHeroInstance * h2 = getHero(toHero);
  1982. if ( h1->getSecSkillLevel(18) < h2->getSecSkillLevel(18) )
  1983. {
  1984. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  1985. std::swap(fromHero, toHero);
  1986. }
  1987. int ScholarLevel = h1->getSecSkillLevel(18);//heroes can trade up to this level
  1988. if (!ScholarLevel || !vstd::contains(h1->artifWorn,17) || !vstd::contains(h2->artifWorn,17) )
  1989. return;//no scholar skill or no spellbook
  1990. int h1Lvl = std::min(ScholarLevel+1, h1->getSecSkillLevel(7)+2),
  1991. h2Lvl = std::min(ScholarLevel+1, h2->getSecSkillLevel(7)+2);//heroes can receive this levels
  1992. ChangeSpells cs1;
  1993. cs1.learn = true;
  1994. cs1.hid = toHero;//giving spells to first hero
  1995. for(std::set<ui32>::const_iterator it=h1->spells.begin(); it!=h1->spells.end();it++)
  1996. if ( h2Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h2->spells, *it))//hero can learn it and don't have it yet
  1997. cs1.spells.insert(*it);//spell to learn
  1998. ChangeSpells cs2;
  1999. cs2.learn = true;
  2000. cs2.hid = fromHero;
  2001. for(std::set<ui32>::const_iterator it=h2->spells.begin(); it!=h2->spells.end();it++)
  2002. if ( h1Lvl >= VLC->spellh->spells[*it].level && !vstd::contains(h1->spells, *it))
  2003. cs2.spells.insert(*it);
  2004. if (cs1.spells.size() || cs2.spells.size())//create a message
  2005. {
  2006. InfoWindow iw;
  2007. iw.player = h1->tempOwner;
  2008. iw.components.push_back(Component(Component::SEC_SKILL, 18, ScholarLevel, 0));
  2009. iw.text.addTxt(MetaString::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2010. iw.text.addReplacement(h1->name);
  2011. if (cs2.spells.size())//if found new spell - apply
  2012. {
  2013. iw.text.addTxt(MetaString::GENERAL_TXT, 140);//learns
  2014. int size = cs2.spells.size();
  2015. for(std::set<ui32>::const_iterator it=cs2.spells.begin(); it!=cs2.spells.end();it++)
  2016. {
  2017. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  2018. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  2019. switch (size--)
  2020. {
  2021. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2022. case 1: break;
  2023. default: iw.text << ", ";
  2024. }
  2025. }
  2026. iw.text.addTxt(MetaString::GENERAL_TXT, 142);//from %s
  2027. iw.text.addReplacement(h2->name);
  2028. sendAndApply(&cs2);
  2029. }
  2030. if (cs1.spells.size() && cs2.spells.size() )
  2031. {
  2032. iw.text.addTxt(MetaString::GENERAL_TXT, 141);//and
  2033. }
  2034. if (cs1.spells.size())
  2035. {
  2036. iw.text.addTxt(MetaString::GENERAL_TXT, 147);//teaches
  2037. int size = cs1.spells.size();
  2038. for(std::set<ui32>::const_iterator it=cs1.spells.begin(); it!=cs1.spells.end();it++)
  2039. {
  2040. iw.components.push_back(Component(Component::SPELL, (*it), 1, 0));
  2041. iw.text.addTxt(MetaString::SPELL_NAME, (*it));
  2042. switch (size--)
  2043. {
  2044. case 2: iw.text.addTxt(MetaString::GENERAL_TXT, 141);
  2045. case 1: break;
  2046. default: iw.text << ", ";
  2047. } }
  2048. iw.text.addTxt(MetaString::GENERAL_TXT, 148);//from %s
  2049. iw.text.addReplacement(h2->name);
  2050. sendAndApply(&cs1);
  2051. }
  2052. sendAndApply(&iw);
  2053. }
  2054. }
  2055. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  2056. {
  2057. ui8 player1 = getHero(hero1)->tempOwner;
  2058. ui8 player2 = getHero(hero2)->tempOwner;
  2059. if(player1 == player2)//TODO: allies
  2060. {
  2061. OpenWindow hex;
  2062. hex.window = OpenWindow::EXCHANGE_WINDOW;
  2063. hex.id1 = hero1;
  2064. hex.id2 = hero2;
  2065. sendAndApply(&hex);
  2066. useScholarSkill(hero1,hero2);
  2067. }
  2068. }
  2069. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  2070. {
  2071. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2072. sel->id = QID;
  2073. callbacks[QID] = callback;
  2074. states.addQuery(player,QID);
  2075. QID++;
  2076. sendAndApply(sel);
  2077. }
  2078. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  2079. {
  2080. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2081. sel->id = QID;
  2082. callbacks[QID] = callback;
  2083. states.addQuery(player,QID);
  2084. sendToAllClients(sel);
  2085. QID++;
  2086. }
  2087. void CGameHandler::sendToAllClients( CPackForClient * info )
  2088. {
  2089. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  2090. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  2091. {
  2092. (*i)->wmx->lock();
  2093. **i << info;
  2094. (*i)->wmx->unlock();
  2095. }
  2096. }
  2097. void CGameHandler::sendAndApply( CPackForClient * info )
  2098. {
  2099. gs->apply(info);
  2100. sendToAllClients(info);
  2101. }
  2102. void CGameHandler::sendAndApply( SetGarrisons * info )
  2103. {
  2104. sendAndApply((CPackForClient*)info);
  2105. if(gs->map->victoryCondition.condition == gatherTroop)
  2106. for(std::map<ui32,CCreatureSet>::const_iterator i = info->garrs.begin(); i != info->garrs.end(); i++)
  2107. checkLossVictory(getObj(i->first)->tempOwner);
  2108. }
  2109. void CGameHandler::sendAndApply( SetResource * info )
  2110. {
  2111. sendAndApply((CPackForClient*)info);
  2112. if(gs->map->victoryCondition.condition == gatherResource)
  2113. checkLossVictory(info->player);
  2114. }
  2115. void CGameHandler::sendAndApply( SetResources * info )
  2116. {
  2117. sendAndApply((CPackForClient*)info);
  2118. if(gs->map->victoryCondition.condition == gatherResource)
  2119. checkLossVictory(info->player);
  2120. }
  2121. void CGameHandler::sendAndApply( NewStructures * info )
  2122. {
  2123. sendAndApply((CPackForClient*)info);
  2124. if(gs->map->victoryCondition.condition == buildCity)
  2125. checkLossVictory(getTown(info->tid)->tempOwner);
  2126. }
  2127. void CGameHandler::save( const std::string &fname )
  2128. {
  2129. {
  2130. tlog0 << "Ordering clients to serialize...\n";
  2131. SaveGame sg(fname);
  2132. sendToAllClients(&sg);
  2133. }
  2134. {
  2135. tlog0 << "Serializing game info...\n";
  2136. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  2137. char hlp[8] = "VCMISVG";
  2138. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps << *VLC << gs;
  2139. }
  2140. {
  2141. tlog0 << "Serializing server info...\n";
  2142. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  2143. save << *this;
  2144. }
  2145. tlog0 << "Game has been successfully saved!\n";
  2146. }
  2147. void CGameHandler::close()
  2148. {
  2149. tlog0 << "We have been requested to close.\n";
  2150. //BOOST_FOREACH(CConnection *cc, conns)
  2151. // if(cc && cc->socket && cc->socket->is_open())
  2152. // cc->socket->close();
  2153. //exit(0);
  2154. }
  2155. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  2156. {
  2157. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  2158. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  2159. CCreatureSet temp1 = s1->getArmy(), temp2 = s2->getArmy(),
  2160. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  2161. if(!isAllowedExchange(id1,id2))
  2162. {
  2163. complain("Cannot exchange stacks between these two objects!\n");
  2164. return false;
  2165. }
  2166. if(what==1) //swap
  2167. {
  2168. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  2169. //if one of them is empty, remove entry
  2170. if(!S1.slots[p1].count)
  2171. S1.slots.erase(p1);
  2172. if(!S2.slots[p2].count)
  2173. S2.slots.erase(p2);
  2174. }
  2175. else if(what==2)//merge
  2176. {
  2177. if(S1.slots[p1].type != S2.slots[p2].type) //not same creature
  2178. {
  2179. complain("Cannot merge different creatures stacks!");
  2180. return false;
  2181. }
  2182. S2.slots[p2].count += S1.slots[p1].count;
  2183. S1.slots.erase(p1);
  2184. }
  2185. else if(what==3) //split
  2186. {
  2187. //general conditions checking
  2188. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  2189. || (val<1 && complain("no creatures to split")) )
  2190. {
  2191. return false;
  2192. }
  2193. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  2194. {
  2195. int total = S1.slots[p1].count + S2.slots[p2].count;
  2196. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  2197. || (S2.slots[p2].type != S1.slots[p1].type && complain("Cannot rebalance different creatures stacks!"))
  2198. )
  2199. {
  2200. return false;
  2201. }
  2202. S2.slots[p2].count = val;
  2203. S1.slots[p1].count = total - val;
  2204. }
  2205. else //split one stack to the two
  2206. {
  2207. if(S1.slots[p1].count < val)//not enough creatures
  2208. {
  2209. complain("Cannot split that stack, not enough creatures!");
  2210. return false;
  2211. }
  2212. S2.slots[p2].type = S1.slots[p1].type;
  2213. S2.slots[p2].count = val;
  2214. S1.slots[p1].count -= val;
  2215. }
  2216. if(!S1.slots[p1].count) //if we've moved all creatures
  2217. S1.slots.erase(p1);
  2218. }
  2219. if((s1->needsLastStack() && !S1.stacksCount()) //it's not allowed to take last stack from hero army!
  2220. || (s2->needsLastStack() && !S2.stacksCount())
  2221. )
  2222. {
  2223. complain("Cannot take the last stack!");
  2224. return false; //leave without applying changes to garrison
  2225. }
  2226. //apply changes
  2227. SetGarrisons sg;
  2228. sg.garrs[id1] = S1;
  2229. if(s1 != s2)
  2230. sg.garrs[id2] = S2;
  2231. sendAndApply(&sg);
  2232. return true;
  2233. }
  2234. int CGameHandler::getPlayerAt( CConnection *c ) const
  2235. {
  2236. std::set<int> all;
  2237. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  2238. if(i->second == c)
  2239. all.insert(i->first);
  2240. switch(all.size())
  2241. {
  2242. case 0:
  2243. return 255;
  2244. case 1:
  2245. return *all.begin();
  2246. default:
  2247. {
  2248. //if we have more than one player at this connection, try to pick active one
  2249. if(vstd::contains(all,int(gs->currentPlayer)))
  2250. return gs->currentPlayer;
  2251. else
  2252. return 253; //cannot say which player is it
  2253. }
  2254. }
  2255. }
  2256. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  2257. {
  2258. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  2259. if(!vstd::contains(s1->slots,pos))
  2260. {
  2261. complain("Illegal call to disbandCreature - no such stack in army!");
  2262. return false;
  2263. }
  2264. s1->slots.erase(pos);
  2265. SetGarrisons sg;
  2266. sg.garrs[id] = s1->getArmy();
  2267. sendAndApply(&sg);
  2268. return true;
  2269. }
  2270. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  2271. {
  2272. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2273. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  2274. if(gs->canBuildStructure(t,bid) != 7)
  2275. {
  2276. complain("Cannot build that building!");
  2277. return false;
  2278. }
  2279. if(bid == 26) //grail
  2280. {
  2281. if(!t->visitingHero || !t->visitingHero->hasArt(2))
  2282. {
  2283. complain("Cannot build grail - hero doesn't have it");
  2284. return false;
  2285. }
  2286. removeArtifact(2, t->visitingHero->id);
  2287. }
  2288. NewStructures ns;
  2289. ns.tid = tid;
  2290. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  2291. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  2292. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  2293. ns.bid.insert(25);
  2294. else if(bid>36) //upg dwelling
  2295. {
  2296. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  2297. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  2298. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  2299. ns.bid.insert(25);
  2300. SetAvailableCreatures ssi;
  2301. ssi.tid = tid;
  2302. ssi.creatures = t->creatures;
  2303. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  2304. sendAndApply(&ssi);
  2305. }
  2306. else if(bid >= 30) //bas. dwelling
  2307. {
  2308. int crid = t->town->basicCreatures[bid-30];
  2309. SetAvailableCreatures ssi;
  2310. ssi.tid = tid;
  2311. ssi.creatures = t->creatures;
  2312. ssi.creatures[bid-30].first = VLC->creh->creatures[crid]->growth;
  2313. ssi.creatures[bid-30].second.push_back(crid);
  2314. sendAndApply(&ssi);
  2315. }
  2316. else if(bid == 11)
  2317. ns.bid.insert(27);
  2318. else if(bid == 12)
  2319. ns.bid.insert(28);
  2320. else if(bid == 13)
  2321. ns.bid.insert(29);
  2322. else if (t->subID == 4 && bid == 17) //veil of darkness
  2323. {
  2324. GiveBonus gb(GiveBonus::TOWN);
  2325. gb.bonus.type = Bonus::DARKNESS;
  2326. gb.bonus.val = 20;
  2327. gb.id = t->id;
  2328. gb.bonus.duration = Bonus::PERMANENT;
  2329. gb.bonus.source = Bonus::TOWN_STRUCTURE;
  2330. gb.bonus.id = 17;
  2331. sendAndApply(&gb);
  2332. }
  2333. else if ( t->subID == 5 && bid == 22 )
  2334. {
  2335. setPortalDwelling(t);
  2336. }
  2337. ns.bid.insert(bid);
  2338. ns.builded = t->builded + 1;
  2339. sendAndApply(&ns);
  2340. //reveal ground for lookout tower
  2341. FoWChange fw;
  2342. fw.player = t->tempOwner;
  2343. fw.mode = 1;
  2344. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  2345. sendAndApply(&fw);
  2346. SetResources sr;
  2347. sr.player = t->tempOwner;
  2348. sr.res = gs->getPlayer(t->tempOwner)->resources;
  2349. for(int i=0;i<b->resources.size();i++)
  2350. sr.res[i]-=b->resources[i];
  2351. sendAndApply(&sr);
  2352. if(bid<5) //it's mage guild
  2353. {
  2354. if(t->visitingHero)
  2355. giveSpells(t,t->visitingHero);
  2356. if(t->garrisonHero)
  2357. giveSpells(t,t->garrisonHero);
  2358. }
  2359. if(t->visitingHero)
  2360. vistiCastleObjects (t, t->visitingHero);
  2361. if(t->garrisonHero)
  2362. vistiCastleObjects (t, t->garrisonHero);
  2363. checkLossVictory(t->tempOwner);
  2364. return true;
  2365. }
  2366. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  2367. {
  2368. ///incomplete, simply erases target building
  2369. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  2370. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  2371. return false;
  2372. RazeStructures rs;
  2373. rs.tid = tid;
  2374. rs.bid.insert(bid);
  2375. rs.destroyed = t->destroyed + 1;
  2376. sendAndApply(&rs);
  2377. //TODO: Remove dwellers
  2378. if (t->subID == 4 && bid == 17) //Veil of Darkness
  2379. {
  2380. RemoveBonus rb(RemoveBonus::TOWN);
  2381. rb.whoID = t->id;
  2382. rb.source = Bonus::TOWN_STRUCTURE;
  2383. rb.id = 17;
  2384. sendAndApply(&rb);
  2385. }
  2386. return true;
  2387. }
  2388. void CGameHandler::sendMessageToAll( const std::string &message )
  2389. {
  2390. SystemMessage sm;
  2391. sm.text = message;
  2392. sendToAllClients(&sm);
  2393. }
  2394. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram, si32 fromLvl )
  2395. {
  2396. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  2397. const CArmedInstance *dst = NULL;
  2398. const CCreature *c = VLC->creh->creatures[crid];
  2399. bool warMachine = c->hasBonusOfType(Bonus::SIEGE_WEAPON);
  2400. //TODO: test for owning
  2401. if(dw->ID == TOWNI_TYPE)
  2402. dst = dw;
  2403. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  2404. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  2405. else if(dw->ID == 106)
  2406. dst = dynamic_cast<const CGHeroInstance *>(getTile(dw->visitablePos())->visitableObjects.back());
  2407. assert(dw && dst);
  2408. //verify
  2409. bool found = false;
  2410. int level = 0;
  2411. typedef std::pair<const int,int> Parka;
  2412. for(; level < dw->creatures.size(); level++) //iterate through all levels
  2413. {
  2414. if ( (fromLvl != -1) && ( level !=fromLvl ) )
  2415. continue;
  2416. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  2417. int i = 0;
  2418. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  2419. if(cur.second[i] == crid)
  2420. break;
  2421. if(i < cur.second.size())
  2422. {
  2423. found = true;
  2424. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  2425. break;
  2426. }
  2427. }
  2428. int slot = dst->getSlotFor(crid);
  2429. if(!found && complain("Cannot recruit: no such creatures!")
  2430. || cram > VLC->creh->creatures[crid]->maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  2431. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  2432. || slot<0 && !warMachine && complain("Cannot recruit: no available slot!"))
  2433. {
  2434. return false;
  2435. }
  2436. //recruit
  2437. SetResources sr;
  2438. sr.player = dst->tempOwner;
  2439. for(int i=0;i<RESOURCE_QUANTITY;i++)
  2440. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (c->cost[i] * cram);
  2441. SetAvailableCreatures sac;
  2442. sac.tid = objid;
  2443. sac.creatures = dw->creatures;
  2444. sac.creatures[level].first -= cram;
  2445. sendAndApply(&sr);
  2446. sendAndApply(&sac);
  2447. if(warMachine)
  2448. {
  2449. switch(crid)
  2450. {
  2451. case 146:
  2452. giveHeroArtifact(4, dst->id, 13);
  2453. break;
  2454. case 147:
  2455. giveHeroArtifact(6, dst->id, 15);
  2456. break;
  2457. case 148:
  2458. giveHeroArtifact(5, dst->id, 14);
  2459. break;
  2460. default:
  2461. complain("This war machine cannot be recruited!");
  2462. return false;
  2463. }
  2464. }
  2465. else
  2466. {
  2467. SetGarrisons sg;
  2468. sg.garrs[dst->id] = dst->getArmy();
  2469. sg.garrs[dst->id] .addToSlot(slot, crid, cram);
  2470. sendAndApply(&sg);
  2471. }
  2472. return true;
  2473. }
  2474. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  2475. {
  2476. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  2477. UpgradeInfo ui = gs->getUpgradeInfo(obj->getStack(pos));
  2478. int player = obj->tempOwner;
  2479. int crQuantity = obj->slots[pos].count;
  2480. //check if upgrade is possible
  2481. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  2482. {
  2483. return false;
  2484. }
  2485. //check if player has enough resources
  2486. for(int i=0;i<ui.cost.size();i++)
  2487. {
  2488. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2489. {
  2490. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  2491. {
  2492. complain("Cannot upgrade, not enough resources!");
  2493. return false;
  2494. }
  2495. }
  2496. }
  2497. //take resources
  2498. for(int i=0;i<ui.cost.size();i++)
  2499. {
  2500. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  2501. {
  2502. SetResource sr;
  2503. sr.player = player;
  2504. sr.resid = j->first;
  2505. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  2506. sendAndApply(&sr);
  2507. }
  2508. }
  2509. //upgrade creature
  2510. SetGarrisons sg;
  2511. sg.garrs[objid] = obj->getArmy();
  2512. sg.garrs[objid].slots[pos].setType(upgID);
  2513. sendAndApply(&sg);
  2514. return true;
  2515. }
  2516. bool CGameHandler::garrisonSwap( si32 tid )
  2517. {
  2518. CGTownInstance *town = gs->getTown(tid);
  2519. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2520. {
  2521. CCreatureSet csn = town->visitingHero->getArmy(), cso = town->getArmy();
  2522. while(!cso.slots.empty())//while there are unmoved creatures
  2523. {
  2524. int pos = csn.getSlotFor(cso.slots.begin()->second.type->idNumber);
  2525. if(pos<0)
  2526. {
  2527. //try to merge two other stacks to make place
  2528. std::pair<TSlot, TSlot> toMerge;
  2529. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2530. {
  2531. //merge
  2532. csn.slots[toMerge.second].count += csn.slots[toMerge.first].count;
  2533. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2534. }
  2535. else
  2536. {
  2537. complain("Cannot make garrison swap, not enough free slots!");
  2538. return false;
  2539. }
  2540. }
  2541. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2542. {
  2543. csn.slots[pos].count += cso.slots.begin()->second.count;
  2544. }
  2545. else //move stack on the free pos
  2546. {
  2547. csn.slots[pos].type = cso.slots.begin()->second.type;
  2548. csn.slots[pos].count = cso.slots.begin()->second.count;
  2549. }
  2550. cso.slots.erase(cso.slots.begin());
  2551. }
  2552. SetGarrisons sg;
  2553. sg.garrs[town->visitingHero->id] = csn;
  2554. sg.garrs[town->id] = csn;
  2555. sendAndApply(&sg);
  2556. SetHeroesInTown intown;
  2557. intown.tid = tid;
  2558. intown.visiting = -1;
  2559. intown.garrison = town->visitingHero->id;
  2560. sendAndApply(&intown);
  2561. return true;
  2562. }
  2563. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2564. {
  2565. //check if moving hero out of town will break 8 wandering heroes limit
  2566. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2567. {
  2568. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2569. return false;
  2570. }
  2571. SetHeroesInTown intown;
  2572. intown.tid = tid;
  2573. intown.garrison = -1;
  2574. intown.visiting = town->garrisonHero->id;
  2575. sendAndApply(&intown);
  2576. //town will be empty
  2577. SetGarrisons sg;
  2578. sg.garrs[tid] = CCreatureSet();
  2579. sendAndApply(&sg);
  2580. return true;
  2581. }
  2582. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2583. {
  2584. SetGarrisons sg;
  2585. sg.garrs[town->id] = town->visitingHero->getArmy();;
  2586. sg.garrs[town->garrisonHero->id] = town->garrisonHero->getArmy();
  2587. SetHeroesInTown intown;
  2588. intown.tid = tid;
  2589. intown.garrison = town->visitingHero->id;
  2590. intown.visiting = town->garrisonHero->id;
  2591. sendAndApply(&intown);
  2592. sendAndApply(&sg);
  2593. return true;
  2594. }
  2595. else
  2596. {
  2597. complain("Cannot swap garrison hero!");
  2598. return false;
  2599. }
  2600. }
  2601. // With the amount of changes done to the function, it's more like transferArtifacts.
  2602. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2603. {
  2604. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2605. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2606. // Make sure exchange is even possible between the two heroes.
  2607. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2608. return false;
  2609. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2610. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2611. if (srcArtifact == NULL)
  2612. {
  2613. complain("No artifact to swap!");
  2614. return false;
  2615. }
  2616. SetHeroArtifacts sha;
  2617. sha.hid = srcHeroID;
  2618. sha.artifacts = srcHero->artifacts;
  2619. sha.artifWorn = srcHero->artifWorn;
  2620. // Combinational artifacts needs to be removed first so they don't get denied movement because of their own locks.
  2621. if (srcHeroID == destHeroID && srcSlot < 19 && destSlot < 19)
  2622. {
  2623. sha.setArtAtPos(srcSlot, -1);
  2624. if (!vstd::contains(sha.artifWorn, destSlot))
  2625. destArtifact = NULL;
  2626. }
  2627. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2628. // Moving to the backpack is always allowed.
  2629. if ((!srcArtifact || destSlot < 19)
  2630. && (srcArtifact && !srcArtifact->fitsAt(srcHeroID == destHeroID ? sha.artifWorn : destHero->artifWorn, destSlot)))
  2631. {
  2632. complain("Cannot swap artifacts!");
  2633. return false;
  2634. }
  2635. if ((srcArtifact && srcArtifact->id == 145) || (destArtifact && destArtifact->id == 145))
  2636. {
  2637. complain("Cannot move artifact locks.");
  2638. return false;
  2639. }
  2640. if (destSlot >= 19 && srcArtifact->isBig())
  2641. {
  2642. complain("Cannot put big artifacts in backpack!");
  2643. return false;
  2644. }
  2645. if (srcSlot == 16 || destSlot == 16)
  2646. {
  2647. complain("Cannot move catapult!");
  2648. return false;
  2649. }
  2650. // If dest does not fit in src, put it in dest's backpack instead.
  2651. if (srcHeroID == destHeroID) // To avoid stumbling on own locks, remove artifact first.
  2652. sha.setArtAtPos(destSlot, -1);
  2653. const bool destFits = !destArtifact || srcSlot >= 19 || destSlot >= 19 || destArtifact->fitsAt(sha.artifWorn, srcSlot);
  2654. if (srcHeroID == destHeroID && destArtifact)
  2655. sha.setArtAtPos(destSlot, destArtifact->id);
  2656. sha.setArtAtPos(srcSlot, -1);
  2657. if (destSlot < 19 && (destArtifact || srcSlot < 19) && destFits)
  2658. sha.setArtAtPos(srcSlot, destArtifact ? destArtifact->id : -1);
  2659. // Internal hero artifact arrangement.
  2660. if(srcHero == destHero)
  2661. {
  2662. // Correction for destination from removing source artifact in backpack.
  2663. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2664. destSlot--;
  2665. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2666. }
  2667. sendAndApply(&sha);
  2668. if (srcHeroID != destHeroID)
  2669. {
  2670. // Exchange between two different heroes.
  2671. sha.hid = destHeroID;
  2672. sha.artifacts = destHero->artifacts;
  2673. sha.artifWorn = destHero->artifWorn;
  2674. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2675. if (!destFits)
  2676. sha.setArtAtPos(sha.artifacts.size() + 19, destHero->getArtAtPos(destSlot));
  2677. sendAndApply(&sha);
  2678. }
  2679. return true;
  2680. }
  2681. /**
  2682. * Assembles or disassembles a combination artifact.
  2683. * @param heroID ID of hero holding the artifact(s).
  2684. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  2685. * @param assemble True for assembly operation, false for disassembly.
  2686. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  2687. * artifact to assemble to. Otherwise it's not used.
  2688. */
  2689. bool CGameHandler::assembleArtifacts (si32 heroID, ui16 artifactSlot, bool assemble, ui32 assembleTo)
  2690. {
  2691. if (artifactSlot < 0 || artifactSlot > 18) {
  2692. complain("Illegal artifact slot.");
  2693. return false;
  2694. }
  2695. CGHeroInstance *hero = gs->getHero(heroID);
  2696. const CArtifact *destArtifact = hero->getArt(artifactSlot);
  2697. SetHeroArtifacts sha;
  2698. sha.hid = heroID;
  2699. sha.artifacts = hero->artifacts;
  2700. sha.artifWorn = hero->artifWorn;
  2701. if (assemble) {
  2702. if (VLC->arth->artifacts.size() < assembleTo) {
  2703. complain("Illegal artifact to assemble to.");
  2704. return false;
  2705. }
  2706. if (!destArtifact->canBeAssembledTo(hero->artifWorn, assembleTo)) {
  2707. complain("Artifact cannot be assembled.");
  2708. return false;
  2709. }
  2710. const CArtifact &artifact = *VLC->arth->artifacts[assembleTo];
  2711. if (artifact.constituents == NULL) {
  2712. complain("Not a combinational artifact.");
  2713. return false;
  2714. }
  2715. // Perform assembly.
  2716. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2717. const bool destSpecific = vstd::contains(artifact.possibleSlots, artifactSlot); // Prefer the chosen slot as the location for the assembled artifact.
  2718. BOOST_FOREACH(ui32 constituentID, *artifact.constituents) {
  2719. if (destSpecific && constituentID == destArtifact->id) {
  2720. sha.artifWorn[artifactSlot] = assembleTo;
  2721. destConsumed = true;
  2722. continue;
  2723. }
  2724. bool found = false;
  2725. for (std::map<ui16, ui32>::iterator it = sha.artifWorn.begin(); it != sha.artifWorn.end(); ++it) {
  2726. if (it->second == constituentID) { // Found possible constituent to substitute.
  2727. if (destSpecific && !destConsumed && it->second == destArtifact->id) {
  2728. // Find the specified destination for assembled artifact.
  2729. if (it->first == artifactSlot) {
  2730. it->second = assembleTo;
  2731. destConsumed = true;
  2732. found = true;
  2733. break;
  2734. }
  2735. } else {
  2736. // Either put the assembled artifact in a fitting spot, or put a lock.
  2737. if (!destSpecific && !destConsumed && vstd::contains(artifact.possibleSlots, it->first)) {
  2738. it->second = assembleTo;
  2739. destConsumed = true;
  2740. } else {
  2741. it->second = 145;
  2742. }
  2743. found = true;
  2744. break;
  2745. }
  2746. }
  2747. }
  2748. if (!found) {
  2749. complain("Constituent missing.");
  2750. return false;
  2751. }
  2752. }
  2753. } else {
  2754. // Perform disassembly.
  2755. bool destConsumed = false; // Determines which constituent that will be counted for together with the artifact.
  2756. BOOST_FOREACH(ui32 constituentID, *destArtifact->constituents) {
  2757. const CArtifact &constituent = *VLC->arth->artifacts[constituentID];
  2758. if (!destConsumed && vstd::contains(constituent.possibleSlots, artifactSlot)) {
  2759. sha.artifWorn[artifactSlot] = constituentID;
  2760. destConsumed = true;
  2761. } else {
  2762. BOOST_REVERSE_FOREACH(ui16 slotID, constituent.possibleSlots) {
  2763. if (vstd::contains(sha.artifWorn, slotID) && sha.artifWorn[slotID] == 145) {
  2764. sha.artifWorn[slotID] = constituentID;
  2765. break;
  2766. }
  2767. }
  2768. }
  2769. }
  2770. }
  2771. sendAndApply(&sha);
  2772. return true;
  2773. }
  2774. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2775. {
  2776. CGHeroInstance *hero = gs->getHero(hid);
  2777. CGTownInstance *town = const_cast<CGTownInstance*>(hero->visitedTown);
  2778. if(aid==0) //spellbook
  2779. {
  2780. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2781. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2782. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2783. )
  2784. return false;
  2785. giveResource(hero->getOwner(),6,-500);
  2786. giveHeroArtifact(0,hid,17);
  2787. giveSpells(town,hero);
  2788. return true;
  2789. }
  2790. else if(aid < 7 && aid > 3) //war machine
  2791. {
  2792. int price = VLC->arth->artifacts[aid]->price;
  2793. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2794. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2795. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2796. || (!(town->subID == 6 && vstd::contains(town->builtBuildings,si32(22) ) )
  2797. && town->town->warMachine!= aid ) && complain("This machine is unavailable here!") )
  2798. {
  2799. return false;
  2800. }
  2801. giveResource(hero->getOwner(),6,-price);
  2802. giveHeroArtifact(aid,hid,9+aid);
  2803. return true;
  2804. }
  2805. return false;
  2806. }
  2807. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, int rid, int aid)
  2808. {
  2809. if(!vstd::contains(m->availableItemsIds(RESOURCE_ARTIFACT), aid))
  2810. COMPLAIN_RET("That artifact is unavailable!");
  2811. int b1, b2;
  2812. m->getOffer(rid, aid, b1, b2, RESOURCE_ARTIFACT);
  2813. if(getResource(h->tempOwner, rid) < b1)
  2814. COMPLAIN_RET("You can't afford to buy this artifact!");
  2815. SetResource sr;
  2816. sr.player = h->tempOwner;
  2817. sr.resid = rid;
  2818. sr.val = getResource(h->tempOwner, rid) - b1;
  2819. sendAndApply(&sr);
  2820. SetAvailableArtifacts saa;
  2821. if(m->o->ID == TOWNI_TYPE)
  2822. {
  2823. saa.id = -1;
  2824. saa.arts = CGTownInstance::merchantArtifacts;
  2825. }
  2826. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m->o)) //black market
  2827. {
  2828. saa.id = bm->id;
  2829. saa.arts = bm->artifacts;
  2830. }
  2831. else
  2832. COMPLAIN_RET("Wrong marktet...");
  2833. bool found = false;
  2834. BOOST_FOREACH(const CArtifact *&art, saa.arts)
  2835. {
  2836. if(art && art->id == aid)
  2837. {
  2838. art = NULL;
  2839. found = true;
  2840. break;
  2841. }
  2842. }
  2843. if(!found)
  2844. COMPLAIN_RET("Cannot find selected artifact on the list");
  2845. sendAndApply(&saa);
  2846. giveHeroArtifact(aid, h->id, -2);
  2847. }
  2848. bool CGameHandler::buySecSkill( const IMarket *m, const CGHeroInstance *h, int skill)
  2849. {
  2850. if (!h)
  2851. COMPLAIN_RET("You need hero to buy a skill!");
  2852. if (h->getSecSkillLevel(skill))
  2853. COMPLAIN_RET("Hero already know this skill");
  2854. if (h->secSkills.size() >= SKILL_PER_HERO)//can't learn more skills
  2855. COMPLAIN_RET("Hero can't learn any more skills");
  2856. if (h->type->heroClass->proSec[skill]==0)//can't learn this skill (like necromancy for most of non-necros)
  2857. COMPLAIN_RET("The hero can't learn this skill!");
  2858. if(!vstd::contains(m->availableItemsIds(RESOURCE_SKILL), skill))
  2859. COMPLAIN_RET("That skill is unavailable!");
  2860. if(getResource(h->tempOwner, 6) < 2000)//TODO: remove hardcoded resource\summ?
  2861. COMPLAIN_RET("You can't afford to buy this skill");
  2862. SetResource sr;
  2863. sr.player = h->tempOwner;
  2864. sr.resid = 6;
  2865. sr.val = getResource(h->tempOwner, 6) - 2000;
  2866. sendAndApply(&sr);
  2867. changeSecSkill(h->id, skill, 1, true);
  2868. }
  2869. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, ui8 player, ui32 id1, ui32 id2)
  2870. {
  2871. int r1 = gs->getPlayer(player)->resources[id1],
  2872. r2 = gs->getPlayer(player)->resources[id2];
  2873. amin(val, r1); //can't trade more resources than have
  2874. int b1, b2; //base quantities for trade
  2875. market->getOffer(id1, id2, b1, b2, RESOURCE_RESOURCE);
  2876. int units = val / b1; //how many base quantities we trade
  2877. if(val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2878. {
  2879. //TODO: complain?
  2880. assert(0);
  2881. }
  2882. SetResource sr;
  2883. sr.player = player;
  2884. sr.resid = id1;
  2885. sr.val = r1 - b1 * units;
  2886. sendAndApply(&sr);
  2887. sr.resid = id2;
  2888. sr.val = r2 + b2 * units;
  2889. sendAndApply(&sr);
  2890. return true;
  2891. }
  2892. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, ui32 slot, ui32 resourceID)
  2893. {
  2894. if(!vstd::contains(hero->Slots(), slot))
  2895. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  2896. const CStackInstance &s = hero->getStack(slot);
  2897. if(s.count < count //can't sell more creatures than have
  2898. || hero->Slots().size() == 1 && hero->needsLastStack() && s.count == count) //can't sell last stack
  2899. {
  2900. COMPLAIN_RET("Not enough creatures in army!");
  2901. }
  2902. int b1, b2; //base quantities for trade
  2903. market->getOffer(s.type->idNumber, resourceID, b1, b2, CREATURE_RESOURCE);
  2904. int units = count / b1; //how many base quantities we trade
  2905. if(count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  2906. {
  2907. //TODO: complain?
  2908. assert(0);
  2909. }
  2910. SetGarrisons sg;
  2911. sg.garrs[hero->id] = hero->getArmy();
  2912. if(s.count > count)
  2913. sg.garrs[hero->id].setStackCount(slot, s.count - count);
  2914. else
  2915. sg.garrs[hero->id].eraseStack(slot);
  2916. sendAndApply(&sg);
  2917. SetResource sr;
  2918. sr.player = hero->tempOwner;
  2919. sr.resid = resourceID;
  2920. sr.val = getResource(hero->tempOwner, resourceID) + b2 * units;
  2921. sendAndApply(&sr);
  2922. return true;
  2923. }
  2924. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, ui32 slot)
  2925. {
  2926. const CArmedInstance *army = NULL;
  2927. if (hero)
  2928. army = hero;
  2929. else
  2930. {
  2931. army = dynamic_cast<const CGTownInstance *>(market->o);
  2932. }
  2933. if (!army)
  2934. COMPLAIN_RET("Incorrect call to transform in undead!");
  2935. tlog1<<"test2\n";
  2936. if(!vstd::contains(army->Slots(), slot))
  2937. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  2938. tlog1<<"test3\n";
  2939. const CStackInstance &s = army->getStack(slot);
  2940. int resCreature;//resulting creature - bone dragons or skeletons
  2941. if (s.hasBonusOfType(Bonus::KING1))
  2942. resCreature = 68;
  2943. else
  2944. resCreature = 56;
  2945. tlog1<<"test4\n";
  2946. SetGarrisons sg;
  2947. sg.garrs[army->id] = army->getArmy();
  2948. sg.garrs[army->id].setCreature(slot, resCreature, s.count);
  2949. sendAndApply(&sg);
  2950. return true;
  2951. }
  2952. bool CGameHandler::sendResources(ui32 val, ui8 player, ui32 r1, ui32 r2)
  2953. {
  2954. const PlayerState *p2 = gs->getPlayer(r2, false);
  2955. if(!p2 || p2->status != PlayerState::INGAME)
  2956. {
  2957. complain("Dest player must be in game!");
  2958. return false;
  2959. }
  2960. si32 curRes1 = gs->getPlayer(player)->resources[r1], curRes2 = gs->getPlayer(r2)->resources[r1];
  2961. val = std::min(si32(val),curRes1);
  2962. SetResource sr;
  2963. sr.player = player;
  2964. sr.resid = r1;
  2965. sr.val = curRes1 - val;
  2966. sendAndApply(&sr);
  2967. sr.player = r2;
  2968. sr.val = curRes2 + val;
  2969. sendAndApply(&sr);
  2970. return true;
  2971. }
  2972. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2973. {
  2974. gs->getHero(hid)-> formation = formation;
  2975. return true;
  2976. }
  2977. bool CGameHandler::hireHero(const CGObjectInstance *obj, ui8 hid, ui8 player)
  2978. {
  2979. const PlayerState *p = gs->getPlayer(player);
  2980. const CGTownInstance *t = gs->getTown(obj->id);
  2981. //common prconditions
  2982. if( p->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2983. || getHeroCount(player, false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!"))
  2984. return false;
  2985. if(t) //tavern in town
  2986. {
  2987. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2988. || t->visitingHero && complain("There is visiting hero - no place!"))
  2989. return false;
  2990. }
  2991. else if(obj->ID == 95) //Tavern on adv map
  2992. {
  2993. if(getTile(obj->visitablePos())->visitableObjects.back() != obj && complain("Tavern entry must be unoccupied!"))
  2994. return false;
  2995. }
  2996. CGHeroInstance *nh = p->availableHeroes[hid];
  2997. assert(nh);
  2998. HeroRecruited hr;
  2999. hr.tid = obj->id;
  3000. hr.hid = nh->subID;
  3001. hr.player = player;
  3002. hr.tile = obj->visitablePos() + nh->getVisitableOffset();
  3003. sendAndApply(&hr);
  3004. std::map<ui32,CGHeroInstance *> pool = gs->unusedHeroesFromPool();
  3005. const CGHeroInstance *theOtherHero = p->availableHeroes[!hid];
  3006. const CGHeroInstance *newHero = gs->hpool.pickHeroFor(false, player, getNativeTown(player), pool, theOtherHero->type->heroClass);
  3007. SetAvailableHeroes sah;
  3008. sah.player = player;
  3009. if(newHero)
  3010. {
  3011. sah.hid[hid] = newHero->subID;
  3012. sah.army[hid] = new CCreatureSet();
  3013. sah.army[hid]->addToSlot(0, VLC->creh->nameToID[newHero->type->refTypeStack[0]],1);
  3014. }
  3015. else
  3016. sah.hid[hid] = -1;
  3017. sah.hid[!hid] = theOtherHero ? theOtherHero->subID : -1;
  3018. sendAndApply(&sah);
  3019. SetResource sr;
  3020. sr.player = player;
  3021. sr.resid = 6;
  3022. sr.val = p->resources[6] - 2500;
  3023. sendAndApply(&sr);
  3024. if(t)
  3025. {
  3026. vistiCastleObjects (t, nh);
  3027. giveSpells (t,nh);
  3028. }
  3029. return true;
  3030. }
  3031. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  3032. {
  3033. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3034. if(vstd::contains(callbacks,qid))
  3035. {
  3036. CFunctionList<void(ui32)> callb = callbacks[qid];
  3037. callbacks.erase(qid);
  3038. if(callb)
  3039. callb(answer);
  3040. }
  3041. else if(vstd::contains(garrisonCallbacks,qid))
  3042. {
  3043. if(garrisonCallbacks[qid])
  3044. garrisonCallbacks[qid]();
  3045. garrisonCallbacks.erase(qid);
  3046. allowedExchanges.erase(qid);
  3047. }
  3048. else
  3049. {
  3050. tlog1 << "Unknown query reply...\n";
  3051. return false;
  3052. }
  3053. return true;
  3054. }
  3055. bool CGameHandler::makeBattleAction( BattleAction &ba )
  3056. {
  3057. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  3058. bool ok = true;
  3059. switch(ba.actionType)
  3060. {
  3061. case 2: //walk
  3062. {
  3063. sendAndApply(&StartAction(ba)); //start movement
  3064. moveStack(ba.stackNumber,ba.destinationTile); //move
  3065. sendAndApply(&EndAction());
  3066. break;
  3067. }
  3068. case 3: //defend
  3069. case 8: //wait
  3070. {
  3071. sendAndApply(&StartAction(ba));
  3072. sendAndApply(&EndAction());
  3073. break;
  3074. }
  3075. case 4: //retreat/flee
  3076. {
  3077. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  3078. break;
  3079. //TODO: remove retreating hero from map and place it in recruitment list
  3080. BattleResult *br = new BattleResult;
  3081. br->result = 1;
  3082. br->winner = !ba.side; //fleeing side loses
  3083. gs->curB->calculateCasualties(br->casualties);
  3084. giveExp(*br);
  3085. battleResult.set(br);
  3086. break;
  3087. }
  3088. case 6: //walk or attack
  3089. {
  3090. sendAndApply(&StartAction(ba)); //start movement and attack
  3091. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  3092. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  3093. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  3094. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  3095. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  3096. && !(curStack->doubleWide()
  3097. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  3098. ) //nor occupy specified hex
  3099. )
  3100. {
  3101. std::string problem = "We cannot move this stack to its destination " + curStack->type->namePl;
  3102. tlog3 << problem << std::endl;
  3103. complain(problem);
  3104. ok = false;
  3105. sendAndApply(&EndAction());
  3106. break;
  3107. }
  3108. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  3109. {
  3110. stackAtEnd = NULL;
  3111. }
  3112. if(!stackAtEnd)
  3113. {
  3114. std::ostringstream problem;
  3115. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  3116. std::string probl = problem.str();
  3117. tlog3 << probl << std::endl;
  3118. complain(probl);
  3119. ok = false;
  3120. sendAndApply(&EndAction());
  3121. break;
  3122. }
  3123. ui16 curpos = curStack->position,
  3124. enemypos = stackAtEnd->position;
  3125. if( !(
  3126. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  3127. || (curStack->doubleWide() //back <=> front
  3128. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  3129. || (stackAtEnd->doubleWide() //front <=> back
  3130. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  3131. || (stackAtEnd->doubleWide() && curStack->doubleWide()//back <=> back
  3132. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  3133. )
  3134. )
  3135. {
  3136. tlog3 << "Attack cannot be performed!";
  3137. sendAndApply(&EndAction());
  3138. ok = false;
  3139. }
  3140. //attack
  3141. BattleAttack bat;
  3142. prepareAttack(bat, curStack, stackAtEnd, distance);
  3143. sendAndApply(&bat);
  3144. handleAfterAttackCasting(bat);
  3145. //counterattack
  3146. if(!curStack->hasBonusOfType(Bonus::BLOCKS_RETALIATION)
  3147. && stackAtEnd->alive()
  3148. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasBonusOfType(Bonus::UNLIMITED_RETALIATIONS) )
  3149. && !stackAtEnd->hasBonusOfType(Bonus::SIEGE_WEAPON)
  3150. && !stackAtEnd->hasBonusOfType(Bonus::HYPNOTIZED))
  3151. {
  3152. prepareAttack(bat, stackAtEnd, curStack, 0);
  3153. bat.flags |= 2;
  3154. sendAndApply(&bat);
  3155. handleAfterAttackCasting(bat);
  3156. }
  3157. //second attack
  3158. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0
  3159. && !curStack->hasBonusOfType(Bonus::SHOOTER)
  3160. && curStack->alive()
  3161. && stackAtEnd->alive() )
  3162. {
  3163. bat.flags = 0;
  3164. prepareAttack(bat, curStack, stackAtEnd, 0);
  3165. sendAndApply(&bat);
  3166. handleAfterAttackCasting(bat);
  3167. }
  3168. //return
  3169. if(curStack->hasBonusOfType(Bonus::RETURN_AFTER_STRIKE) && startingPos != curStack->position && curStack->alive())
  3170. {
  3171. moveStack(ba.stackNumber, startingPos);
  3172. //NOTE: curStack->ID == ba.stackNumber (rev 1431)
  3173. }
  3174. sendAndApply(&EndAction());
  3175. break;
  3176. }
  3177. case 7: //shoot
  3178. {
  3179. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  3180. *destStack= gs->curB->getStackT(ba.destinationTile);
  3181. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  3182. break;
  3183. sendAndApply(&StartAction(ba)); //start shooting
  3184. BattleAttack bat;
  3185. bat.flags |= 1;
  3186. prepareAttack(bat, curStack, destStack, 0);
  3187. sendAndApply(&bat);
  3188. if(curStack->valOfBonuses(Bonus::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  3189. && curStack->alive()
  3190. && destStack->alive()
  3191. && curStack->shots
  3192. )
  3193. {
  3194. prepareAttack(bat, curStack, destStack, 0);
  3195. sendAndApply(&bat);
  3196. handleAfterAttackCasting(bat);
  3197. }
  3198. sendAndApply(&EndAction());
  3199. break;
  3200. }
  3201. case 9: //catapult
  3202. {
  3203. sendAndApply(&StartAction(ba));
  3204. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  3205. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(10)]; //ballistics
  3206. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  3207. if(attackedPart == -1)
  3208. {
  3209. complain("catapult tried to attack non-catapultable hex!");
  3210. break;
  3211. }
  3212. int wallInitHP = gs->curB->si.wallState[attackedPart];
  3213. int dmgAlreadyDealt = 0; //in successive iterations damage is dealt but not yet substracted from wall's HPs
  3214. for(int g=0; g<sbi.shots; ++g)
  3215. {
  3216. if(wallInitHP + dmgAlreadyDealt == 3) //it's not destroyed
  3217. continue;
  3218. CatapultAttack ca; //package for clients
  3219. std::pair< std::pair< ui8, si16 >, ui8> attack; //<< attackedPart , destination tile >, damageDealt >
  3220. attack.first.first = attackedPart;
  3221. attack.first.second = ba.destinationTile;
  3222. attack.second = 0;
  3223. int chanceForHit = 0;
  3224. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  3225. switch(attackedPart)
  3226. {
  3227. case 0: //keep
  3228. chanceForHit = sbi.keep;
  3229. break;
  3230. case 1: //bottom tower
  3231. case 6: //upper tower
  3232. chanceForHit = sbi.tower;
  3233. break;
  3234. case 2: //bottom wall
  3235. case 3: //below gate
  3236. case 4: //over gate
  3237. case 5: //upper wall
  3238. chanceForHit = sbi.wall;
  3239. break;
  3240. case 7: //gate
  3241. chanceForHit = sbi.gate;
  3242. break;
  3243. }
  3244. if(rand()%100 <= chanceForHit) //hit is successful
  3245. {
  3246. int dmgRand = rand()%100;
  3247. //accumulating dmgChance
  3248. dmgChance[1] += dmgChance[0];
  3249. dmgChance[2] += dmgChance[1];
  3250. //calculating dealt damage
  3251. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  3252. {
  3253. if(dmgRand <= dmgChance[v])
  3254. {
  3255. attack.second = std::min(3 - dmgAlreadyDealt - wallInitHP, v);
  3256. dmgAlreadyDealt += attack.second;
  3257. break;
  3258. }
  3259. }
  3260. //removing creatures in turrets / keep if one is destroyed
  3261. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  3262. {
  3263. int posRemove = -1;
  3264. switch(attackedPart)
  3265. {
  3266. case 0: //keep
  3267. posRemove = -2;
  3268. break;
  3269. case 1: //bottom tower
  3270. posRemove = -3;
  3271. break;
  3272. case 6: //upper tower
  3273. posRemove = -4;
  3274. break;
  3275. }
  3276. BattleStacksRemoved bsr;
  3277. for(int g=0; g<gs->curB->stacks.size(); ++g)
  3278. {
  3279. if(gs->curB->stacks[g]->position == posRemove)
  3280. {
  3281. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  3282. break;
  3283. }
  3284. }
  3285. sendAndApply(&bsr);
  3286. }
  3287. }
  3288. ca.attacker = ba.stackNumber;
  3289. ca.attackedParts.insert(attack);
  3290. sendAndApply(&ca);
  3291. }
  3292. sendAndApply(&EndAction());
  3293. break;
  3294. }
  3295. case 12: //healing
  3296. {
  3297. sendAndApply(&StartAction(ba));
  3298. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  3299. CStack *healer = gs->curB->getStack(ba.stackNumber),
  3300. *destStack = gs->curB->getStackT(ba.destinationTile);
  3301. if(healer == NULL || destStack == NULL || !healer->hasBonusOfType(Bonus::HEALER))
  3302. {
  3303. complain("There is either no healer, no destination, or healer cannot heal :P");
  3304. }
  3305. int maxHealable = destStack->MaxHealth() - destStack->firstHPleft;
  3306. int maxiumHeal = std::max(10, attackingHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 27));
  3307. int healed = std::min(maxHealable, maxiumHeal);
  3308. if(healed == 0)
  3309. {
  3310. //nothing to heal.. should we complain?
  3311. }
  3312. else
  3313. {
  3314. StacksHealedOrResurrected shr;
  3315. shr.lifeDrain = false;
  3316. StacksHealedOrResurrected::HealInfo hi;
  3317. hi.healedHP = healed;
  3318. hi.lowLevelResurrection = 0;
  3319. hi.stackID = destStack->ID;
  3320. shr.healedStacks.push_back(hi);
  3321. sendAndApply(&shr);
  3322. }
  3323. sendAndApply(&EndAction());
  3324. break;
  3325. }
  3326. }
  3327. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  3328. battleMadeAction.setn(true);
  3329. return ok;
  3330. }
  3331. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  3332. {
  3333. bool cheated=true;
  3334. sendAndApply(&PlayerMessage(player,message));
  3335. if(message == "vcmiistari") //give all spells and 999 mana
  3336. {
  3337. SetMana sm;
  3338. ChangeSpells cs;
  3339. SetHeroArtifacts sha;
  3340. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  3341. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  3342. sm.hid = cs.hid = h->id;
  3343. //give all spells
  3344. cs.learn = 1;
  3345. for(int i=0;i<VLC->spellh->spells.size();i++)
  3346. {
  3347. if(!VLC->spellh->spells[i].creatureAbility)
  3348. cs.spells.insert(i);
  3349. }
  3350. //give mana
  3351. sm.val = 999;
  3352. if(!h->getArt(17)) //hero doesn't have spellbook
  3353. {
  3354. //give spellbook
  3355. sha.hid = h->id;
  3356. sha.artifacts = h->artifacts;
  3357. sha.artifWorn = h->artifWorn;
  3358. VLC->arth->equipArtifact(sha.artifWorn, 17, 0);
  3359. sendAndApply(&sha);
  3360. }
  3361. sendAndApply(&cs);
  3362. sendAndApply(&sm);
  3363. }
  3364. else if(message == "vcmiainur") //gives 5 archangels into each slot
  3365. {
  3366. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3367. if(!hero) return;
  3368. SetGarrisons sg;
  3369. CCreatureSet &newArmy = sg.garrs[hero->id];
  3370. newArmy = hero->getArmy();
  3371. for(int i=0; i<ARMY_SIZE; i++)
  3372. if(newArmy.slotEmpty(i))
  3373. newArmy.addToSlot(i, CStackInstance(13,5));
  3374. sendAndApply(&sg);
  3375. }
  3376. else if(message == "vcmiangband") //gives 10 black knight into each slot
  3377. {
  3378. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3379. if(!hero) return;
  3380. SetGarrisons sg;
  3381. CCreatureSet &newArmy = sg.garrs[hero->id];
  3382. newArmy = hero->getArmy();
  3383. for(int i=0; i<ARMY_SIZE; i++)
  3384. if(newArmy.slotEmpty(i))
  3385. newArmy.addToSlot(i, CStackInstance(66,10));
  3386. sendAndApply(&sg);
  3387. }
  3388. else if(message == "vcminoldor") //all war machines
  3389. {
  3390. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3391. if(!hero) return;
  3392. SetHeroArtifacts sha;
  3393. sha.hid = hero->id;
  3394. sha.artifacts = hero->artifacts;
  3395. sha.artifWorn = hero->artifWorn;
  3396. VLC->arth->equipArtifact(sha.artifWorn, 13, 4);
  3397. VLC->arth->equipArtifact(sha.artifWorn, 14, 5);
  3398. VLC->arth->equipArtifact(sha.artifWorn, 15, 6);
  3399. sendAndApply(&sha);
  3400. }
  3401. else if(message == "vcminahar") //1000000 movement points
  3402. {
  3403. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3404. if(!hero) return;
  3405. SetMovePoints smp;
  3406. smp.hid = hero->id;
  3407. smp.val = 1000000;
  3408. sendAndApply(&smp);
  3409. }
  3410. else if(message == "vcmiformenos") //give resources
  3411. {
  3412. SetResources sr;
  3413. sr.player = player;
  3414. sr.res = gs->getPlayer(player)->resources;
  3415. for(int i=0;i<7;i++)
  3416. sr.res[i] += 100;
  3417. sr.res[6] += 19900;
  3418. sendAndApply(&sr);
  3419. }
  3420. else if(message == "vcmieagles") //reveal FoW
  3421. {
  3422. FoWChange fc;
  3423. fc.mode = 1;
  3424. fc.player = player;
  3425. for(int i=0;i<gs->map->width;i++)
  3426. for(int j=0;j<gs->map->height;j++)
  3427. for(int k=0;k<gs->map->twoLevel+1;k++)
  3428. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  3429. fc.tiles.insert(int3(i,j,k));
  3430. sendAndApply(&fc);
  3431. }
  3432. else if(message == "vcmiglorfindel")
  3433. {
  3434. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  3435. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  3436. }
  3437. else
  3438. cheated = false;
  3439. if(cheated)
  3440. {
  3441. sendAndApply(&SystemMessage(VLC->generaltexth->allTexts[260]));
  3442. }
  3443. }
  3444. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  3445. {
  3446. switch(spell->id)
  3447. {
  3448. case 37: //cure
  3449. {
  3450. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3451. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  3452. break;
  3453. }
  3454. case 38: //resurrection
  3455. {
  3456. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3457. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  3458. break;
  3459. }
  3460. case 39: //animate dead
  3461. {
  3462. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  3463. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  3464. break;
  3465. }
  3466. }
  3467. //we shouldn't be here
  3468. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  3469. return 0;
  3470. }
  3471. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  3472. {
  3473. std::vector<ui32> ret;
  3474. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3475. {
  3476. if (NBonus::hasOfType(caster, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES) ||
  3477. NBonus::hasOfType(hero2, Bonus::NEGATE_ALL_NATURAL_IMMUNITIES))
  3478. {
  3479. //don't use natural immunities when one of heroes has this bonus
  3480. BonusList bl = (*it)->getBonuses(Selector::type(Bonus::SPELL_IMMUNITY)),
  3481. b2 = (*it)->getBonuses(Selector::type(Bonus::LEVEL_SPELL_IMMUNITY));
  3482. bl.insert(bl.end(), b2.begin(), b2.end());
  3483. BOOST_FOREACH(Bonus bb, bl)
  3484. {
  3485. if( (bb.type == Bonus::SPELL_IMMUNITY && bb.subtype == sp->id || //100% sure spell immunity
  3486. bb.type == Bonus::LEVEL_SPELL_IMMUNITY && bb.val >= sp->level) //some creature abilities have level 0
  3487. && bb.source != Bonus::CREATURE_ABILITY)
  3488. {
  3489. ret.push_back((*it)->ID);
  3490. continue;
  3491. }
  3492. }
  3493. }
  3494. else
  3495. {
  3496. if ((*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3497. || ( (*it)->hasBonusOfType(Bonus::LEVEL_SPELL_IMMUNITY) &&
  3498. (*it)->valOfBonuses(Bonus::LEVEL_SPELL_IMMUNITY) >= sp->level) ) //some creature abilities have level 0
  3499. {
  3500. ret.push_back((*it)->ID);
  3501. continue;
  3502. }
  3503. }
  3504. //non-negative spells on friendly stacks should always succeed, unless immune
  3505. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  3506. continue;
  3507. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  3508. if(caster && (*it)->owner == caster->tempOwner)
  3509. bonusHero = caster;
  3510. else
  3511. bonusHero = hero2;
  3512. int prob = (*it)->valOfBonuses(Bonus::MAGIC_RESISTANCE); //probability of resistance in %
  3513. if(bonusHero)
  3514. {
  3515. //bonusHero's resistance support (secondary skils and artifacts)
  3516. prob += bonusHero->valOfBonuses(Bonus::MAGIC_RESISTANCE);
  3517. //resistance skill
  3518. prob += bonusHero->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 26) / 100.0f;
  3519. }
  3520. if(prob > 100) prob = 100;
  3521. if(rand()%100 < prob) //immunity from resistance
  3522. ret.push_back((*it)->ID);
  3523. }
  3524. if(sp->id == 60) //hypnotize
  3525. {
  3526. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  3527. {
  3528. if( (*it)->hasBonusOfType(Bonus::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  3529. || ( (*it)->count - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  3530. >
  3531. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  3532. )
  3533. {
  3534. ret.push_back((*it)->ID);
  3535. }
  3536. }
  3537. }
  3538. return ret;
  3539. }
  3540. void CGameHandler::handleSpellCasting( int spellID, int spellLvl, int destination, ui8 casterSide, ui8 casterColor,
  3541. const CGHeroInstance * caster, const CGHeroInstance * secHero, int usedSpellPower )
  3542. {
  3543. CSpell *spell = &VLC->spellh->spells[spellID];
  3544. BattleSpellCast sc;
  3545. sc.side = casterSide;
  3546. sc.id = spellID;
  3547. sc.skill = spellLvl;
  3548. sc.tile = destination;
  3549. sc.dmgToDisplay = 0;
  3550. sc.castedByHero = (bool)caster;
  3551. //calculating affected creatures for all spells
  3552. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(spell, spellLvl, casterColor, destination);
  3553. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3554. {
  3555. sc.affectedCres.insert((*it)->ID);
  3556. }
  3557. //checking if creatures resist
  3558. sc.resisted = calculateResistedStacks(spell, caster, secHero, attackedCres);
  3559. //calculating dmg to display
  3560. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3561. {
  3562. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3563. continue;
  3564. sc.dmgToDisplay += gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3565. }
  3566. sendAndApply(&sc);
  3567. //applying effects
  3568. switch(spellID)
  3569. {
  3570. case 15: //magic arrow
  3571. case 16: //ice bolt
  3572. case 17: //lightning bolt
  3573. case 18: //implosion
  3574. case 20: //frost ring
  3575. case 21: //fireball
  3576. case 22: //inferno
  3577. case 23: //meteor shower
  3578. case 24: //death ripple
  3579. case 25: //destroy undead
  3580. case 26: //armageddon
  3581. case 77: //Thunderbolt (thunderbirds)
  3582. {
  3583. StacksInjured si;
  3584. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3585. {
  3586. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3587. continue;
  3588. BattleStackAttacked bsa;
  3589. bsa.flags |= 2;
  3590. bsa.effect = spell->mainEffectAnim;
  3591. bsa.damageAmount = gs->curB->calculateSpellDmg(spell, caster, *it, spellLvl, usedSpellPower);
  3592. bsa.stackAttacked = (*it)->ID;
  3593. bsa.attackerID = -1;
  3594. prepareAttacked(bsa,*it);
  3595. si.stacks.push_back(bsa);
  3596. }
  3597. if(!si.stacks.empty())
  3598. sendAndApply(&si);
  3599. break;
  3600. }
  3601. case 27: //shield
  3602. case 28: //air shield
  3603. case 29: //fire shield
  3604. case 30: //protection from air
  3605. case 31: //protection from fire
  3606. case 32: //protection from water
  3607. case 33: //protection from earth
  3608. case 34: //anti-magic
  3609. case 41: //bless
  3610. case 42: //curse
  3611. case 43: //bloodlust
  3612. case 44: //precision
  3613. case 45: //weakness
  3614. case 46: //stone skin
  3615. case 47: //disrupting ray
  3616. case 48: //prayer
  3617. case 49: //mirth
  3618. case 50: //sorrow
  3619. case 51: //fortune
  3620. case 52: //misfortune
  3621. case 53: //haste
  3622. case 54: //slow
  3623. case 55: //slayer
  3624. case 56: //frenzy
  3625. case 58: //counterstrike
  3626. case 59: //berserk
  3627. case 60: //hypnotize
  3628. case 61: //forgetfulness
  3629. case 62: //blind
  3630. {
  3631. SetStackEffect sse;
  3632. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3633. {
  3634. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  3635. continue;
  3636. sse.stacks.push_back((*it)->ID);
  3637. }
  3638. sse.effect.id = spellID;
  3639. sse.effect.level = spellLvl;
  3640. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(spell, caster, usedSpellPower);
  3641. if(!sse.stacks.empty())
  3642. sendAndApply(&sse);
  3643. break;
  3644. }
  3645. case 63: //teleport
  3646. {
  3647. BattleStackMoved bsm;
  3648. bsm.distance = -1;
  3649. bsm.stack = gs->curB->activeStack;
  3650. bsm.ending = true;
  3651. bsm.tile = destination;
  3652. bsm.teleporting = true;
  3653. sendAndApply(&bsm);
  3654. break;
  3655. }
  3656. case 37: //cure
  3657. case 38: //resurrection
  3658. case 39: //animate dead
  3659. {
  3660. StacksHealedOrResurrected shr;
  3661. shr.lifeDrain = false;
  3662. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  3663. {
  3664. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  3665. || (spellID == 39 && !(*it)->hasBonusOfType(Bonus::UNDEAD)) //we try to cast animate dead on living stack
  3666. )
  3667. continue;
  3668. StacksHealedOrResurrected::HealInfo hi;
  3669. hi.stackID = (*it)->ID;
  3670. hi.healedHP = calculateHealedHP(caster, spell, *it);
  3671. hi.lowLevelResurrection = spellLvl <= 1;
  3672. shr.healedStacks.push_back(hi);
  3673. }
  3674. if(!shr.healedStacks.empty())
  3675. sendAndApply(&shr);
  3676. break;
  3677. }
  3678. case 64: //remove obstacle
  3679. {
  3680. ObstaclesRemoved obr;
  3681. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  3682. {
  3683. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  3684. if(vstd::contains(blockedHexes, destination)) //this obstacle covers given hex
  3685. {
  3686. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  3687. }
  3688. }
  3689. if(!obr.obstacles.empty())
  3690. sendAndApply(&obr);
  3691. break;
  3692. }
  3693. }
  3694. }
  3695. bool CGameHandler::makeCustomAction( BattleAction &ba )
  3696. {
  3697. switch(ba.actionType)
  3698. {
  3699. case 1: //hero casts spell
  3700. {
  3701. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  3702. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  3703. if(!h)
  3704. {
  3705. tlog2 << "Wrong caster!\n";
  3706. return false;
  3707. }
  3708. if(ba.additionalInfo >= VLC->spellh->spells.size())
  3709. {
  3710. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  3711. return false;
  3712. }
  3713. const CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  3714. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  3715. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  3716. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  3717. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  3718. || (gs->curB->castSpells[ba.side]) //spell has been cast
  3719. || (NBonus::hasOfType(secondHero, Bonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  3720. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  3721. )
  3722. {
  3723. tlog2 << "Spell cannot be cast!\n";
  3724. return false;
  3725. }
  3726. sendAndApply(&StartAction(ba)); //start spell casting
  3727. handleSpellCasting(ba.additionalInfo, skill, ba.destinationTile, ba.side, h->tempOwner, h, secondHero, h->getPrimSkillLevel(2));
  3728. sendAndApply(&EndAction());
  3729. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  3730. {
  3731. battleMadeAction.setn(true);
  3732. }
  3733. checkForBattleEnd(gs->curB->stacks);
  3734. if(battleResult.get())
  3735. {
  3736. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  3737. }
  3738. return true;
  3739. }
  3740. }
  3741. return false;
  3742. }
  3743. void CGameHandler::handleTimeEvents()
  3744. {
  3745. gs->map->events.sort(evntCmp);
  3746. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  3747. {
  3748. CMapEvent *ev = gs->map->events.front();
  3749. for(int player = 0; player < PLAYER_LIMIT; player++)
  3750. {
  3751. PlayerState *pinfo = gs->getPlayer(player);
  3752. if( pinfo //player exists
  3753. && (ev->players & 1<<player) //event is enabled to this player
  3754. && ((ev->computerAffected && !pinfo->human)
  3755. || (ev->humanAffected && pinfo->human)
  3756. )
  3757. )
  3758. {
  3759. //give resources
  3760. SetResources sr;
  3761. sr.player = player;
  3762. sr.res = pinfo->resources;
  3763. //prepare dialog
  3764. InfoWindow iw;
  3765. iw.player = player;
  3766. iw.text << ev->message;
  3767. for (int i=0; i<ev->resources.size(); i++)
  3768. {
  3769. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  3770. {
  3771. // If removing too much resources, adjust the
  3772. // amount so the total doesn't become negative.
  3773. if (sr.res[i] + ev->resources[i] < 0)
  3774. ev->resources[i] = -sr.res[i];
  3775. if(ev->resources[i]) //if non-zero res change
  3776. {
  3777. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  3778. sr.res[i] += ev->resources[i];
  3779. }
  3780. }
  3781. }
  3782. if (iw.components.size())
  3783. {
  3784. sendAndApply(&sr); //update player resources if changed
  3785. }
  3786. sendAndApply(&iw); //show dialog
  3787. }
  3788. } //PLAYERS LOOP
  3789. if(ev->nextOccurence)
  3790. {
  3791. ev->firstOccurence += ev->nextOccurence;
  3792. gs->map->events.sort(evntCmp);
  3793. }
  3794. else
  3795. {
  3796. delete ev;
  3797. gs->map->events.pop_front();
  3798. }
  3799. }
  3800. }
  3801. bool CGameHandler::complain( const std::string &problem )
  3802. {
  3803. sendMessageToAll("Server encountered a problem: " + problem);
  3804. tlog1 << problem << std::endl;
  3805. return true;
  3806. }
  3807. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  3808. {
  3809. //TODO: write
  3810. return 0;
  3811. }
  3812. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  3813. {
  3814. ui8 player = getOwner(hid);
  3815. GarrisonDialog gd;
  3816. gd.hid = hid;
  3817. gd.objid = upobj;
  3818. {
  3819. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3820. gd.id = QID;
  3821. garrisonCallbacks[QID] = cb;
  3822. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  3823. states.addQuery(player,QID);
  3824. QID++;
  3825. gd.removableUnits = removableUnits;
  3826. sendAndApply(&gd);
  3827. }
  3828. }
  3829. void CGameHandler::showThievesGuildWindow(int requestingObjId)
  3830. {
  3831. OpenWindow ow;
  3832. ow.window = OpenWindow::THIEVES_GUILD;
  3833. ow.id1 = requestingObjId;
  3834. sendAndApply(&ow);
  3835. }
  3836. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  3837. {
  3838. if(id1 == id2)
  3839. return true;
  3840. {
  3841. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3842. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  3843. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  3844. return true;
  3845. }
  3846. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3847. if(o1->ID == TOWNI_TYPE)
  3848. {
  3849. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3850. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3851. return true;
  3852. }
  3853. if(o2->ID == TOWNI_TYPE)
  3854. {
  3855. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3856. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3857. return true;
  3858. }
  3859. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3860. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3861. {
  3862. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3863. //(to block moving stacks for free [without visiting] beteen heroes)
  3864. return true;
  3865. }
  3866. return false;
  3867. }
  3868. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3869. {
  3870. obj->onHeroVisit(h);
  3871. }
  3872. bool CGameHandler::buildBoat( ui32 objid )
  3873. {
  3874. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3875. int boatType = 1;
  3876. if(obj->state())
  3877. {
  3878. complain("Cannot build boat in this shipyard!");
  3879. return false;
  3880. }
  3881. else if(obj->o->ID == TOWNI_TYPE
  3882. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3883. {
  3884. complain("Cannot build boat in the town - no shipyard!");
  3885. return false;
  3886. }
  3887. //TODO use "real" cost via obj->getBoatCost
  3888. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3889. {
  3890. complain("Not enough resources to build a boat!");
  3891. return false;
  3892. }
  3893. int3 tile = obj->bestLocation();
  3894. if(!gs->map->isInTheMap(tile))
  3895. {
  3896. complain("Cannot find appropriate tile for a boat!");
  3897. return false;
  3898. }
  3899. //take boat cost
  3900. SetResources sr;
  3901. sr.player = obj->o->tempOwner;
  3902. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3903. sr.res[0] -= 10;
  3904. sr.res[6] -= 1000;
  3905. sendAndApply(&sr);
  3906. //create boat
  3907. NewObject no;
  3908. no.ID = 8;
  3909. no.subID = obj->getBoatType();
  3910. no.pos = tile + int3(1,0,0);
  3911. sendAndApply(&no);
  3912. return true;
  3913. }
  3914. void CGameHandler::engageIntoBattle( ui8 player )
  3915. {
  3916. if(vstd::contains(states.players, player))
  3917. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3918. //notify interfaces
  3919. PlayerBlocked pb;
  3920. pb.player = player;
  3921. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3922. sendAndApply(&pb);
  3923. }
  3924. void CGameHandler::winLoseHandle(ui8 players )
  3925. {
  3926. for(size_t i = 0; i < PLAYER_LIMIT; i++)
  3927. {
  3928. if(players & 1<<i && gs->getPlayer(i))
  3929. {
  3930. checkLossVictory(i);
  3931. }
  3932. }
  3933. }
  3934. void CGameHandler::checkLossVictory( ui8 player )
  3935. {
  3936. const PlayerState *p = gs->getPlayer(player);
  3937. if(p->status) //player already won / lost
  3938. return;
  3939. int loss = gs->lossCheck(player);
  3940. int vic = gs->victoryCheck(player);
  3941. if(!loss && !vic)
  3942. return;
  3943. InfoWindow iw;
  3944. getLossVicMessage(player, vic ? vic : loss , vic, iw);
  3945. sendAndApply(&iw);
  3946. PlayerEndsGame peg;
  3947. peg.player = player;
  3948. peg.victory = vic;
  3949. sendAndApply(&peg);
  3950. if(vic > 0) //one player won -> all enemies lost //TODO: allies
  3951. {
  3952. iw.text.localStrings.front().second++; //message about losing because enemy won first is just after victory message
  3953. for (std::map<ui8,PlayerState>::const_iterator i = gs->players.begin(); i!=gs->players.end(); i++)
  3954. {
  3955. if(i->first < PLAYER_LIMIT && i->first != player)
  3956. {
  3957. iw.player = i->first;
  3958. sendAndApply(&iw);
  3959. peg.player = i->first;
  3960. peg.victory = false;
  3961. sendAndApply(&peg);
  3962. }
  3963. }
  3964. }
  3965. else //player lost -> all his objects become unflagged (neutral)
  3966. {
  3967. std::vector<CGHeroInstance*> hlp = p->heroes;
  3968. for (std::vector<CGHeroInstance*>::const_iterator i = hlp.begin(); i != hlp.end(); i++) //eliminate heroes
  3969. removeObject((*i)->id);
  3970. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  3971. {
  3972. if(*i && (*i)->tempOwner == player)
  3973. setOwner((**i).id,NEUTRAL_PLAYER);
  3974. }
  3975. //eliminating one player may cause victory of another:
  3976. winLoseHandle(ALL_PLAYERS & ~(1<<player));
  3977. }
  3978. if(vic)
  3979. end2 = true;
  3980. }
  3981. void CGameHandler::getLossVicMessage( ui8 player, ui8 standard, bool victory, InfoWindow &out ) const
  3982. {
  3983. const PlayerState *p = gs->getPlayer(player);
  3984. // if(!p->human)
  3985. // return; //AI doesn't need text info of loss
  3986. out.player = player;
  3987. if(victory)
  3988. {
  3989. if(standard < 0) //not std loss
  3990. {
  3991. switch(gs->map->victoryCondition.condition)
  3992. {
  3993. case artifact:
  3994. out.text.addTxt(MetaString::GENERAL_TXT, 280); //Congratulations! You have found the %s, and can claim victory!
  3995. out.text.addReplacement(MetaString::ART_NAMES,gs->map->victoryCondition.ID); //artifact name
  3996. break;
  3997. case gatherTroop:
  3998. out.text.addTxt(MetaString::GENERAL_TXT, 276); //Congratulations! You have over %d %s in your armies. Your enemies have no choice but to bow down before your power!
  3999. out.text.addReplacement(gs->map->victoryCondition.count);
  4000. out.text.addReplacement(MetaString::CRE_PL_NAMES, gs->map->victoryCondition.ID);
  4001. break;
  4002. case gatherResource:
  4003. out.text.addTxt(MetaString::GENERAL_TXT, 278); //Congratulations! You have collected over %d %s in your treasury. Victory is yours!
  4004. out.text.addReplacement(gs->map->victoryCondition.count);
  4005. out.text.addReplacement(MetaString::RES_NAMES, gs->map->victoryCondition.ID);
  4006. break;
  4007. case buildCity:
  4008. out.text.addTxt(MetaString::GENERAL_TXT, 282); //Congratulations! You have successfully upgraded your town, and can claim victory!
  4009. break;
  4010. case buildGrail:
  4011. out.text.addTxt(MetaString::GENERAL_TXT, 284); //Congratulations! You have constructed a permanent home for the Grail, and can claim victory!
  4012. break;
  4013. case beatHero:
  4014. {
  4015. out.text.addTxt(MetaString::GENERAL_TXT, 252); //Congratulations! You have completed your quest to defeat the enemy hero %s. Victory is yours!
  4016. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->victoryCondition.obj);
  4017. assert(h);
  4018. out.text.addReplacement(h->name);
  4019. }
  4020. break;
  4021. case captureCity:
  4022. {
  4023. out.text.addTxt(MetaString::GENERAL_TXT, 249); //Congratulations! You captured %s, and are victorious!
  4024. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->victoryCondition.obj);
  4025. assert(t);
  4026. out.text.addReplacement(t->name);
  4027. }
  4028. break;
  4029. case beatMonster:
  4030. out.text.addTxt(MetaString::GENERAL_TXT, 286); //Congratulations! You have completed your quest to kill the fearsome beast, and can claim victory!
  4031. break;
  4032. case takeDwellings:
  4033. out.text.addTxt(MetaString::GENERAL_TXT, 288); //Congratulations! Your flag flies on the dwelling of every creature. Victory is yours!
  4034. break;
  4035. case takeMines:
  4036. out.text.addTxt(MetaString::GENERAL_TXT, 290); //Congratulations! Your flag flies on every mine. Victory is yours!
  4037. break;
  4038. case transportItem:
  4039. out.text.addTxt(MetaString::GENERAL_TXT, 292); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  4040. break;
  4041. }
  4042. }
  4043. else
  4044. {
  4045. out.text.addTxt(MetaString::GENERAL_TXT, 659); //Congratulations! You have reached your destination, precious cargo intact, and can claim victory!
  4046. }
  4047. }
  4048. else
  4049. {
  4050. if(standard < 0) //not std loss
  4051. {
  4052. switch(gs->map->lossCondition.typeOfLossCon)
  4053. {
  4054. case lossCastle:
  4055. {
  4056. out.text.addTxt(MetaString::GENERAL_TXT, 251); //The town of %s has fallen - all is lost!
  4057. const CGTownInstance *t = dynamic_cast<const CGTownInstance*>(gs->map->lossCondition.obj);
  4058. assert(t);
  4059. out.text.addReplacement(t->name);
  4060. }
  4061. break;
  4062. case lossHero:
  4063. {
  4064. out.text.addTxt(MetaString::GENERAL_TXT, 253); //The hero, %s, has suffered defeat - your quest is over!
  4065. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(gs->map->lossCondition.obj);
  4066. assert(h);
  4067. out.text.addReplacement(h->name);
  4068. }
  4069. break;
  4070. case timeExpires:
  4071. out.text.addTxt(MetaString::GENERAL_TXT, 254); //Alas, time has run out on your quest. All is lost.
  4072. break;
  4073. }
  4074. }
  4075. else if(standard == 2)
  4076. {
  4077. out.text.addTxt(MetaString::GENERAL_TXT, 7);//%s, your heroes abandon you, and you are banished from this land.
  4078. out.text.addReplacement(MetaString::COLOR, player);
  4079. out.components.push_back(Component(Component::FLAG,player,0,0));
  4080. }
  4081. else //lost all towns and heroes
  4082. {
  4083. out.text.addTxt(MetaString::GENERAL_TXT, 660); //All your forces have been defeated, and you are banished from this land!
  4084. }
  4085. }
  4086. }
  4087. bool CGameHandler::dig( const CGHeroInstance *h )
  4088. {
  4089. for (std::vector<CGObjectInstance*>::const_iterator i = gs->map->objects.begin(); i != gs->map->objects.end(); i++) //unflag objs
  4090. {
  4091. if(*i && (*i)->ID == 124 && (*i)->pos == h->getPosition())
  4092. {
  4093. complain("Cannot dig - there is already a hole under the hero!");
  4094. return false;
  4095. }
  4096. }
  4097. NewObject no;
  4098. no.ID = 124;
  4099. no.pos = h->getPosition();
  4100. no.subID = getTile(no.pos)->tertype;
  4101. if(no.subID >= 8) //no digging on water / rock
  4102. {
  4103. complain("Cannot dig - wrong terrain type!");
  4104. return false;
  4105. }
  4106. sendAndApply(&no);
  4107. SetMovePoints smp;
  4108. smp.hid = h->id;
  4109. smp.val = 0;
  4110. sendAndApply(&smp);
  4111. InfoWindow iw;
  4112. iw.player = h->tempOwner;
  4113. if(gs->map->grailPos == h->getPosition())
  4114. {
  4115. iw.text.addTxt(MetaString::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4116. iw.text.addTxt(MetaString::ART_NAMES, 2);
  4117. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4118. giveHeroArtifact(2, h->id, -1); //give grail
  4119. sendAndApply(&iw);
  4120. iw.text.clear();
  4121. iw.text.addTxt(MetaString::ART_DESCR, 2);
  4122. sendAndApply(&iw);
  4123. }
  4124. else
  4125. {
  4126. iw.text.addTxt(MetaString::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  4127. iw.soundID = soundBase::Dig;
  4128. sendAndApply(&iw);
  4129. }
  4130. return true;
  4131. }
  4132. void CGameHandler::handleAfterAttackCasting( const BattleAttack & bat )
  4133. {
  4134. const CStack * attacker = gs->curB->getStack(bat.stackAttacking);
  4135. if( attacker->hasBonusOfType(Bonus::SPELL_AFTER_ATTACK) )
  4136. {
  4137. BOOST_FOREACH(const Bonus & sf, attacker->getBonuses(Selector::type(Bonus::SPELL_AFTER_ATTACK)))
  4138. {
  4139. if (sf.type == Bonus::SPELL_AFTER_ATTACK)
  4140. {
  4141. const CStack * oneOfAttacked = NULL;
  4142. for(int g=0; g<bat.bsa.size(); ++g)
  4143. {
  4144. if (bat.bsa[g].newAmount > 0)
  4145. {
  4146. oneOfAttacked = gs->curB->getStack(bat.bsa[g].stackAttacked);
  4147. break;
  4148. }
  4149. }
  4150. if(oneOfAttacked == NULL) //all attacked creatures have been killed
  4151. return;
  4152. int spellID = sf.subtype;
  4153. int spellLevel = sf.val;
  4154. int chance = sf.additionalInfo % 1000;
  4155. int meleeRanged = sf.additionalInfo / 1000;
  4156. int destination = oneOfAttacked->position;
  4157. //check if spell should be casted (probability handling)
  4158. if( rand()%100 >= chance )
  4159. continue;
  4160. //casting
  4161. handleSpellCasting(spellID, spellLevel, destination, !attacker->attackerOwned, attacker->owner, NULL, NULL, attacker->count);
  4162. }
  4163. }
  4164. }
  4165. }
  4166. bool CGameHandler::castSpell(const CGHeroInstance *h, int spellID, const int3 &pos)
  4167. {
  4168. const CSpell *s = &VLC->spellh->spells[spellID];
  4169. int cost = h->getSpellCost(s);
  4170. int schoolLevel = h->getSpellSchoolLevel(s);
  4171. if(!h->canCastThisSpell(s))
  4172. COMPLAIN_RET("Hero cannot cast this spell!");
  4173. if(h->mana < cost)
  4174. COMPLAIN_RET("Hero doesn't have enough spell points to cast this spell!");
  4175. if(s->combatSpell)
  4176. COMPLAIN_RET("This function can be used only for adventure map spells!");
  4177. AdvmapSpellCast asc;
  4178. asc.caster = h;
  4179. asc.spellID = spellID;
  4180. sendAndApply(&asc);
  4181. using namespace Spells;
  4182. switch(spellID)
  4183. {
  4184. case SUMMON_BOAT: //Summon Boat
  4185. {
  4186. //check if spell works at all
  4187. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  4188. {
  4189. InfoWindow iw;
  4190. iw.player = h->tempOwner;
  4191. iw.text.addTxt(MetaString::GENERAL_TXT, 336); //%s tried to summon a boat, but failed.
  4192. iw.text.addReplacement(h->name);
  4193. sendAndApply(&iw);
  4194. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  4195. }
  4196. //try to find unoccupied boat to summon
  4197. const CGBoat *nearest = NULL;
  4198. double dist = 0;
  4199. int3 summonPos = h->bestLocation();
  4200. if(summonPos.x < 0)
  4201. COMPLAIN_RET("There is no water tile available!");
  4202. BOOST_FOREACH(const CGObjectInstance *obj, gs->map->objects)
  4203. {
  4204. if(obj && obj->ID == 8)
  4205. {
  4206. const CGBoat *b = static_cast<const CGBoat*>(obj);
  4207. if(b->hero) continue; //we're looking for unoccupied boat
  4208. double nDist = distance(b->pos, h->getPosition());
  4209. if(!nearest || nDist < dist) //it's first boat or closer than previous
  4210. {
  4211. nearest = b;
  4212. dist = nDist;
  4213. }
  4214. }
  4215. }
  4216. if(nearest) //we found boat to summon
  4217. {
  4218. ChangeObjPos cop;
  4219. cop.objid = nearest->id;
  4220. cop.nPos = summonPos + int3(1,0,0);;
  4221. cop.flags = 1;
  4222. sendAndApply(&cop);
  4223. }
  4224. else if(schoolLevel < 2) //none or basic level -> cannot create boat :(
  4225. {
  4226. InfoWindow iw;
  4227. iw.player = h->tempOwner;
  4228. iw.text.addTxt(MetaString::GENERAL_TXT, 335); //There are no boats to summon.
  4229. sendAndApply(&iw);
  4230. }
  4231. else //create boat
  4232. {
  4233. NewObject no;
  4234. no.ID = 8;
  4235. no.subID = h->getBoatType();
  4236. no.pos = summonPos + int3(1,0,0);;
  4237. sendAndApply(&no);
  4238. }
  4239. break;
  4240. }
  4241. case SCUTTLE_BOAT: //Scuttle Boat
  4242. {
  4243. //check if spell works at all
  4244. if(rand() % 100 >= s->powers[schoolLevel]) //power is % chance of success
  4245. {
  4246. InfoWindow iw;
  4247. iw.player = h->tempOwner;
  4248. iw.text.addTxt(MetaString::GENERAL_TXT, 337); //%s tried to scuttle the boat, but failed
  4249. iw.text.addReplacement(h->name);
  4250. sendAndApply(&iw);
  4251. return true; //TODO? or should it be false? request was correct and realized, but spell failed...
  4252. }
  4253. if(!gs->map->isInTheMap(pos))
  4254. COMPLAIN_RET("Invalid dst tile for scuttle!");
  4255. //TODO: test range, visibility
  4256. const TerrainTile *t = &gs->map->getTile(pos);
  4257. if(!t->visitableObjects.size() || t->visitableObjects.back()->ID != 8)
  4258. COMPLAIN_RET("There is no boat to scuttle!");
  4259. RemoveObject ro;
  4260. ro.id = t->visitableObjects.back()->id;
  4261. sendAndApply(&ro);
  4262. break;
  4263. }
  4264. case DIMENSION_DOOR: //Dimension Door
  4265. {
  4266. const TerrainTile *dest = getTile(pos);
  4267. const TerrainTile *curr = getTile(h->getSightCenter());
  4268. if(!dest)
  4269. COMPLAIN_RET("Destination tile doesn't exist!");
  4270. if(!h->movement)
  4271. COMPLAIN_RET("Hero needs movement points to cast Dimension Door!");
  4272. if(h->getBonusesCount(Bonus::CASTED_SPELL, Spells::DIMENSION_DOOR) >= s->powers[schoolLevel]) //limit casts per turn
  4273. {
  4274. InfoWindow iw;
  4275. iw.player = h->tempOwner;
  4276. iw.text.addTxt(MetaString::GENERAL_TXT, 338); //%s is not skilled enough to cast this spell again today.
  4277. iw.text.addReplacement(h->name);
  4278. sendAndApply(&iw);
  4279. break;
  4280. }
  4281. GiveBonus gb;
  4282. gb.id = h->id;
  4283. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::NONE, Bonus::CASTED_SPELL, 0, Spells::DIMENSION_DOOR);
  4284. sendAndApply(&gb);
  4285. if(!dest->isClear(curr)) //wrong dest tile
  4286. {
  4287. InfoWindow iw;
  4288. iw.player = h->tempOwner;
  4289. iw.text.addTxt(MetaString::GENERAL_TXT, 70); //Dimension Door failed!
  4290. sendAndApply(&iw);
  4291. break;
  4292. }
  4293. //we need obtain guard pos before moving hero, otherwise we get nothing, because tile will be "unguarded" by hero
  4294. int3 guardPos = gs->guardingCreaturePosition(pos);
  4295. TryMoveHero tmh;
  4296. tmh.id = h->id;
  4297. tmh.movePoints = std::max<int>(0, h->movement - 300);
  4298. tmh.result = TryMoveHero::TELEPORTATION;
  4299. tmh.start = h->pos;
  4300. tmh.end = pos + h->getVisitableOffset();
  4301. getTilesInRange(tmh.fowRevealed, pos, h->getSightRadious(), h->tempOwner,1);
  4302. sendAndApply(&tmh);
  4303. tryAttackingGuard(guardPos, h);
  4304. }
  4305. break;
  4306. case FLY: //Fly
  4307. {
  4308. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  4309. GiveBonus gb;
  4310. gb.id = h->id;
  4311. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::FLYING_MOVEMENT, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  4312. sendAndApply(&gb);
  4313. }
  4314. break;
  4315. case WATER_WALK: //Water Walk
  4316. {
  4317. int subtype = schoolLevel >= 2 ? 1 : 2; //adv or expert
  4318. GiveBonus gb;
  4319. gb.id = h->id;
  4320. gb.bonus = Bonus(Bonus::ONE_DAY, Bonus::WATER_WALKING, Bonus::CASTED_SPELL, 0, Spells::FLY, subtype);
  4321. sendAndApply(&gb);
  4322. }
  4323. break;
  4324. case VISIONS: //Visions
  4325. case VIEW_EARTH: //View Earth
  4326. case DISGUISE: //Disguise
  4327. case VIEW_AIR: //View Air
  4328. case TOWN_PORTAL: //Town Portal
  4329. default:
  4330. COMPLAIN_RET("This spell is not implemented yet!");
  4331. }
  4332. SetMana sm;
  4333. sm.hid = h->id;
  4334. sm.val = h->mana - cost;
  4335. sendAndApply(&sm);
  4336. return true;
  4337. }
  4338. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4339. {
  4340. //to prevent self-visiting heroes on space press
  4341. if(t.visitableObjects.back() != h)
  4342. objectVisited(t.visitableObjects.back(), h);
  4343. else if(t.visitableObjects.size() > 1)
  4344. objectVisited(*(t.visitableObjects.end()-2),h);
  4345. }
  4346. bool CGameHandler::tryAttackingGuard(const int3 &guardPos, const CGHeroInstance * h)
  4347. {
  4348. if(!gs->map->isInTheMap(guardPos))
  4349. return false;
  4350. const TerrainTile &guardTile = gs->map->terrain[guardPos.x][guardPos.y][guardPos.z];
  4351. objectVisited(guardTile.visitableObjects.back(), h);
  4352. visitObjectAfterVictory = true;
  4353. return true;
  4354. }
  4355. bool CGameHandler::sacrificeCreatures(const IMarket *market, const CGHeroInstance *hero, TSlot slot, ui32 count)
  4356. {
  4357. int oldCount = hero->getAmount(slot);
  4358. int newCount = oldCount - count;
  4359. if(oldCount < count)
  4360. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4361. else if(oldCount == count && hero->Slots().size() == 1 && hero->needsLastStack())
  4362. COMPLAIN_RET("Cannot sacrifice last creature!");
  4363. int crid = hero->getStack(slot).type->idNumber;
  4364. SetGarrisons sg;
  4365. sg.garrs[hero->id] = hero->getArmy();
  4366. if(newCount)
  4367. sg.garrs[hero->id].setStackCount(slot, newCount);
  4368. else
  4369. sg.garrs[hero->id].eraseStack(slot);
  4370. sendAndApply(&sg);
  4371. int dump, exp;
  4372. market->getOffer(crid, 0, dump, exp, CREATURE_EXP);
  4373. exp *= count;
  4374. changePrimSkill (hero->id, 4, exp);
  4375. return true;
  4376. }
  4377. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, ui32 artID)
  4378. {
  4379. if(!removeArtifact(artID, hero->id))
  4380. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  4381. int dmp, expToGive;
  4382. m->getOffer(artID, 0, dmp, expToGive, ARTIFACT_EXP);
  4383. changePrimSkill(hero->id, 4, expToGive);
  4384. return true;
  4385. }