CGameHandler.cpp 186 KB

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