CGameHandler.cpp 172 KB

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