CGameHandler.cpp 135 KB

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