CGameHandler.cpp 154 KB

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