CGameHandler.cpp 154 KB

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