CGameHandler.cpp 169 KB

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