CGameHandler.cpp 154 KB

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