CGameHandler.cpp 179 KB

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