CGameHandler.cpp 141 KB

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