CGameHandler.cpp 186 KB

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