CGameHandler.cpp 171 KB

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