CGameHandler.cpp 137 KB

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