CGameHandler.cpp 149 KB

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