CGameHandler.cpp 154 KB

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