2
0

CGameHandler.cpp 146 KB

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