CGameHandler.cpp 186 KB

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