2
0

CGameHandler.cpp 190 KB

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