CGameHandler.cpp 126 KB

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