CGameHandler.cpp 112 KB

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