CGameHandler.cpp 172 KB

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