CGameHandler.cpp 151 KB

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