CGameHandler.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438
  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. //end battle, remove all info, free memory
  445. giveExp(*battleResult.data);
  446. sendAndApply(battleResult.data);
  447. //if one hero has lost we will erase him
  448. if(battleResult.data->winner!=0 && hero1)
  449. {
  450. RemoveObject ro(hero1->id);
  451. sendAndApply(&ro);
  452. }
  453. if(battleResult.data->winner!=1 && hero2)
  454. {
  455. RemoveObject ro(hero2->id);
  456. sendAndApply(&ro);
  457. }
  458. //give exp
  459. if(battleResult.data->exp[0] && hero1)
  460. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  461. if(battleResult.data->exp[1] && hero2)
  462. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  463. if(battleEndCallback && *battleEndCallback)
  464. {
  465. (*battleEndCallback)(battleResult.data);
  466. delete battleEndCallback;
  467. battleEndCallback = 0;
  468. }
  469. sendAndApply(&resultsApplied);
  470. // Necromancy if applicable.
  471. const CGHeroInstance *winnerHero = battleResult.data->winner != 0 ? hero2 : hero1;
  472. if (winnerHero) {
  473. std::pair<ui32, si32> raisedStack = winnerHero->calculateNecromancy(*battleResult.data);
  474. // Give raised units to winner and show dialog, if any were raised.
  475. if (raisedStack.first != -1) {
  476. int slot = winnerHero->army.getSlotFor(raisedStack.first);
  477. if (slot != -1) {
  478. SetGarrisons sg;
  479. sg.garrs[winnerHero->id] = winnerHero->army;
  480. if (vstd::contains(winnerHero->army.slots, slot)) // Add to existing stack.
  481. sg.garrs[winnerHero->id].slots[slot].second += raisedStack.second;
  482. else // Create a new stack.
  483. sg.garrs[winnerHero->id].slots[slot] = raisedStack;
  484. winnerHero->showNecromancyDialog(raisedStack);
  485. sendAndApply(&sg);
  486. }
  487. }
  488. }
  489. delete battleResult.data;
  490. }
  491. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, const CStack *def)
  492. {
  493. bsa.killedAmount = bsa.damageAmount / def->MaxHealth();
  494. unsigned damageFirst = bsa.damageAmount % def->MaxHealth();
  495. if( def->firstHPleft <= damageFirst )
  496. {
  497. bsa.killedAmount++;
  498. bsa.newHP = def->firstHPleft + def->MaxHealth() - damageFirst;
  499. }
  500. else
  501. {
  502. bsa.newHP = def->firstHPleft - damageFirst;
  503. }
  504. if(def->amount <= bsa.killedAmount) //stack killed
  505. {
  506. bsa.newAmount = 0;
  507. bsa.flags |= 1;
  508. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  509. }
  510. else
  511. {
  512. bsa.newAmount = def->amount - bsa.killedAmount;
  513. }
  514. }
  515. void CGameHandler::prepareAttack(BattleAttack &bat, const CStack *att, const CStack *def, int distance)
  516. {
  517. bat.bsa.clear();
  518. bat.stackAttacking = att->ID;
  519. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  520. #ifdef __GNUC__
  521. BattleStackAttacked *bsa = (BattleStackAttacked *)&*i;
  522. #else
  523. BattleStackAttacked *bsa = &*i;
  524. #endif
  525. bsa->stackAttacked = def->ID;
  526. bsa->attackerID = att->ID;
  527. bsa->damageAmount = BattleInfo::calculateDmg(att, def, gs->battleGetOwner(att->ID), gs->battleGetOwner(def->ID), bat.shot(), distance);//counting dealt damage
  528. if(att->Luck() > 0 && rand()%24 < att->Luck())
  529. {
  530. bsa->damageAmount *= 2;
  531. bat.flags |= 4;
  532. }
  533. prepareAttacked(*bsa, def);
  534. }
  535. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  536. {
  537. srand(time(NULL));
  538. CPack *pack = NULL;
  539. try
  540. {
  541. while(!end2)
  542. {
  543. {
  544. boost::unique_lock<boost::mutex> lock(*c.rmx);
  545. c >> pack; //get the package
  546. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  547. }
  548. int packType = typeList.getTypeID(pack); //get the id of type
  549. CBaseForGHApply *apply = applier->apps[packType]; //and appropriae applier object
  550. if(apply)
  551. {
  552. bool result = apply->applyOnGH(this,&c,pack);
  553. tlog5 << "Message successfully applied (result=" << result << ")!\n";
  554. //send confirmation that we've applied the package
  555. if(pack->type != 6000) //WORKAROUND - not confirm query replies TODO: reconsider
  556. {
  557. PackageApplied applied;
  558. applied.result = result;
  559. applied.packType = packType;
  560. {
  561. boost::unique_lock<boost::mutex> lock(*c.wmx);
  562. c << &applied;
  563. }
  564. }
  565. }
  566. else
  567. {
  568. tlog1 << "Message cannot be applied, cannot find applier (unregistered type)!\n";
  569. }
  570. delete pack;
  571. pack = NULL;
  572. }
  573. }
  574. catch(boost::system::system_error &e) //for boost errors just log, not crash - probably client shut down connection
  575. {
  576. tlog1 << e.what() << std::endl;
  577. end2 = true;
  578. }
  579. HANDLE_EXCEPTION(end2 = true);
  580. handleConEnd:
  581. tlog1 << "Ended handling connection\n";
  582. }
  583. int CGameHandler::moveStack(int stack, int dest)
  584. {
  585. int ret = 0;
  586. CStack *curStack = gs->curB->getStack(stack),
  587. *stackAtEnd = gs->curB->getStackT(dest);
  588. assert(curStack);
  589. assert(dest < BFIELD_SIZE);
  590. //initing necessary tables
  591. bool accessibility[BFIELD_SIZE];
  592. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  593. for(int b=0; b<BFIELD_SIZE; ++b)
  594. {
  595. accessibility[b] = false;
  596. }
  597. for(int g=0; g<accessible.size(); ++g)
  598. {
  599. accessibility[accessible[g]] = true;
  600. }
  601. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  602. if(!stackAtEnd && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !accessibility[dest])
  603. {
  604. if(curStack->attackerOwned)
  605. {
  606. if(accessibility[dest+1])
  607. dest+=1;
  608. }
  609. else
  610. {
  611. if(accessibility[dest-1])
  612. dest-=1;
  613. }
  614. }
  615. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  616. return 0;
  617. bool accessibilityWithOccupyable[BFIELD_SIZE];
  618. std::vector<int> accOc = gs->curB->getAccessibility(curStack->ID, true);
  619. for(int b=0; b<BFIELD_SIZE; ++b)
  620. {
  621. accessibilityWithOccupyable[b] = false;
  622. }
  623. for(int g=0; g<accOc.size(); ++g)
  624. {
  625. accessibilityWithOccupyable[accOc[g]] = true;
  626. }
  627. //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
  628. // return false;
  629. 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);
  630. ret = path.second;
  631. if(curStack->hasFeatureOfType(StackFeature::FLYING))
  632. {
  633. if(path.second <= curStack->Speed() && path.first.size() > 0)
  634. {
  635. //inform clients about move
  636. BattleStackMoved sm;
  637. sm.stack = curStack->ID;
  638. sm.tile = path.first[0];
  639. sm.distance = path.second;
  640. sm.ending = true;
  641. sendAndApply(&sm);
  642. }
  643. }
  644. else //for non-flying creatures
  645. {
  646. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  647. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  648. {
  649. //inform clients about move
  650. BattleStackMoved sm;
  651. sm.stack = curStack->ID;
  652. sm.tile = path.first[v];
  653. sm.distance = path.second;
  654. sm.ending = v==tilesToMove;
  655. sendAndApply(&sm);
  656. }
  657. }
  658. return ret;
  659. }
  660. CGameHandler::CGameHandler(void)
  661. {
  662. QID = 1;
  663. gs = NULL;
  664. IObjectInterface::cb = this;
  665. applier = new CGHApplier;
  666. }
  667. CGameHandler::~CGameHandler(void)
  668. {
  669. delete applier;
  670. applier = NULL;
  671. delete gs;
  672. }
  673. void CGameHandler::init(StartInfo *si, int Seed)
  674. {
  675. Mapa *map = new Mapa(si->mapname);
  676. tlog0 << "Map loaded!" << std::endl;
  677. gs = new CGameState();
  678. tlog0 << "Gamestate created!" << std::endl;
  679. gs->init(si,map,Seed);
  680. tlog0 << "Gamestate initialized!" << std::endl;
  681. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  682. states.addPlayer(i->first);
  683. }
  684. static bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  685. {
  686. return *a < *b;
  687. }
  688. void CGameHandler::newTurn()
  689. {
  690. tlog5 << "Turn " << gs->day+1 << std::endl;
  691. NewTurn n;
  692. n.day = gs->day + 1;
  693. n.resetBuilded = true;
  694. std::map<ui8, si32> hadGold;//starting gold - for buildings like dwarven treasury
  695. srand(time(NULL));
  696. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  697. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  698. {
  699. if(i->first == 255) continue;
  700. else if(i->first > PLAYER_LIMIT) assert(0); //illegal player number!
  701. std::pair<ui8,si32> playerGold(i->first,i->second.resources[6]);
  702. hadGold.insert(playerGold);
  703. tlog1<<i->first<<" & "<<i->second.resources[6]<<"\n";
  704. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  705. {
  706. SetAvailableHeroes sah;
  707. sah.player = i->first;
  708. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  709. if(h)
  710. sah.hid1 = h->subID;
  711. else
  712. sah.hid1 = -1;
  713. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle], pool);
  714. if(h)
  715. sah.hid2 = h->subID;
  716. else
  717. sah.hid2 = -1;
  718. sendAndApply(&sah);
  719. }
  720. if(i->first>=PLAYER_LIMIT) continue;
  721. n.res[i->first] = i->second.resources;
  722. // SetResources r;
  723. // r.player = i->first;
  724. // for(int j=0;j<RESOURCE_QUANTITY;j++)
  725. // r.res[j] = i->second.resources[j];
  726. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  727. {
  728. if(h->visitedTown)
  729. giveSpells(h->visitedTown, h);
  730. NewTurn::Hero hth;
  731. hth.id = h->id;
  732. hth.move = h->maxMovePoints(gs->map->getTile(h->getPosition(false)).tertype != TerrainTile::water);
  733. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  734. hth.mana = std::max(h->mana, h->manaLimit()); //restore all mana
  735. else
  736. hth.mana = std::max(si32(0), std::max(h->mana, std::min(h->mana + h->manaRegain(), h->manaLimit())) );
  737. n.heroes.insert(hth);
  738. if(gs->day) //not first day
  739. {
  740. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  741. {
  742. case 1: //basic
  743. n.res[i->first][6] += 125;
  744. break;
  745. case 2: //advanced
  746. n.res[i->first][6] += 250;
  747. break;
  748. case 3: //expert
  749. n.res[i->first][6] += 500;
  750. break;
  751. }
  752. for(std::list<HeroBonus>::iterator j = h->bonuses.begin(); j != h->bonuses.end(); j++)
  753. if(j->type == HeroBonus::GENERATE_RESOURCE)
  754. n.res[i->first][j->subtype] += j->val;
  755. }
  756. }
  757. //n.res.push_back(r);
  758. }
  759. for(std::vector<CGTownInstance *>::iterator j = gs->map->towns.begin(); j!=gs->map->towns.end(); j++)//handle towns
  760. {
  761. ui8 player = (*j)->tempOwner;
  762. if(gs->getDate(1)==7) //first day of week
  763. {
  764. if ( ((**j).subID == 1) && (gs->getDate(0)) && (player < PLAYER_LIMIT) )//this is rampart and not a first day
  765. {
  766. if (vstd::contains((**j).builtBuildings,22))//we have treasury
  767. {
  768. n.res[player][6] += hadGold[player]/10; //give 10% of starting gold
  769. }
  770. if (vstd::contains((**j).builtBuildings,17))//we have mystic pond
  771. {//TODO: whole week pond should have message "pond produced %d" - need vars to store it
  772. int restype = rand()%4+2;//bonus to random rare resource
  773. restype = (restype==2)?1:restype;
  774. int cnt = rand()%4+1;//with size 1..4
  775. n.res[player][restype] += cnt;
  776. }
  777. }
  778. SetAvailableCreatures sac;
  779. sac.tid = (**j).id;
  780. sac.creatures = (**j).creatures;
  781. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  782. {
  783. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  784. {
  785. sac.creatures[k].first += (**j).creatureGrowth(k);
  786. if(!gs->getDate(0)) //first day of game: use only basic growths
  787. amin(sac.creatures[k].first, VLC->creh->creatures[(*j)->town->basicCreatures[k]].growth);
  788. }
  789. }
  790. n.cres.push_back(sac);
  791. }
  792. if(gs->day && player < PLAYER_LIMIT)//not the first day and town not neutral
  793. {
  794. ////SetResources r;
  795. //r.player = (**j).tempOwner;
  796. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  797. {
  798. if((**j).town->primaryRes == 127) //we'll give wood and ore
  799. {
  800. n.res[player][0] += 1;
  801. n.res[player][2] += 1;
  802. }
  803. else
  804. {
  805. n.res[player][(**j).town->primaryRes] += 1;
  806. }
  807. }
  808. n.res[player][6] += (**j).dailyIncome();
  809. }
  810. }
  811. sendAndApply(&n);
  812. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  813. handleTimeEvents();
  814. //call objects
  815. for(size_t i = 0; i<gs->map->objects.size(); i++)
  816. if(gs->map->objects[i])
  817. gs->map->objects[i]->newTurn();
  818. }
  819. void CGameHandler::run(bool resume)
  820. {
  821. BOOST_FOREACH(CConnection *cc, conns)
  822. {//init conn.
  823. ui8 quantity, pom;
  824. //ui32 seed;
  825. if(!resume)
  826. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  827. (*cc) >> quantity; //how many players will be handled at that client
  828. for(int i=0;i<quantity;i++)
  829. {
  830. (*cc) >> pom; //read player color
  831. {
  832. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  833. connections[pom] = cc;
  834. }
  835. }
  836. }
  837. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  838. {
  839. std::set<int> pom;
  840. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  841. if(j->second == *i)
  842. pom.insert(j->first);
  843. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  844. }
  845. while (!end2)
  846. {
  847. if(!resume)
  848. newTurn();
  849. else
  850. resume = false;
  851. std::map<ui8,PlayerState>::iterator i;
  852. if(!resume)
  853. i = gs->players.begin();
  854. else
  855. i = gs->players.find(gs->currentPlayer);
  856. for(; i != gs->players.end(); i++)
  857. {
  858. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0 || i->first>=PLAYER_LIMIT ) continue; //players has not towns/castle - loser
  859. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  860. gs->currentPlayer = i->first;
  861. {
  862. YourTurn yt;
  863. yt.player = i->first;
  864. boost::unique_lock<boost::mutex> lock(*connections[i->first]->wmx);
  865. *connections[i->first] << &yt;
  866. }
  867. //wait till turn is done
  868. boost::unique_lock<boost::mutex> lock(states.mx);
  869. while(states.players[i->first].makingTurn && !end2)
  870. {
  871. boost::posix_time::time_duration p;
  872. p = boost::posix_time::milliseconds(200);
  873. states.cv.timed_wait(lock,p);
  874. }
  875. }
  876. }
  877. }
  878. namespace CGH
  879. {
  880. using namespace std;
  881. static void readItTo(ifstream & input, vector< vector<int> > & dest) //reads 7 lines, i-th one containing i integers, and puts it to dest
  882. {
  883. for(int j=0; j<7; ++j)
  884. {
  885. std::vector<int> pom;
  886. for(int g=0; g<j+1; ++g)
  887. {
  888. int hlp; input>>hlp;
  889. pom.push_back(hlp);
  890. }
  891. dest.push_back(pom);
  892. }
  893. }
  894. }
  895. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, const CCreatureSet &army1, const CCreatureSet &army2, const CGHeroInstance * hero1, const CGHeroInstance * hero2, bool creatureBank, const CGTownInstance *town)
  896. {
  897. battleResult.set(NULL);
  898. std::vector<CStack*> & stacks = (curB->stacks);
  899. curB->tile = tile;
  900. curB->army1=army1;
  901. curB->army2=army2;
  902. curB->heroes[0] = const_cast<CGHeroInstance*>(hero1);
  903. curB->heroes[1] = const_cast<CGHeroInstance*>(hero2);
  904. curB->round = -2;
  905. curB->activeStack = -1;
  906. if(town)
  907. {
  908. curB->tid = town->id;
  909. curB->siege = town->fortLevel();
  910. }
  911. else
  912. {
  913. curB->tid = -1;
  914. curB->siege = 0;
  915. }
  916. //reading battleStartpos
  917. std::ifstream positions;
  918. positions.open(DATA_DIR "/config/battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  919. if(!positions.is_open())
  920. {
  921. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  922. }
  923. std::string dump;
  924. positions>>dump; positions>>dump;
  925. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight, attackerCreBank, defenderCreBank;
  926. CGH::readItTo(positions, attackerLoose);
  927. positions>>dump;
  928. CGH::readItTo(positions, defenderLoose);
  929. positions>>dump;
  930. positions>>dump;
  931. CGH::readItTo(positions, attackerTight);
  932. positions>>dump;
  933. CGH::readItTo(positions, defenderTight);
  934. positions>>dump;
  935. positions>>dump;
  936. CGH::readItTo(positions, attackerCreBank);
  937. positions>>dump;
  938. CGH::readItTo(positions, defenderCreBank);
  939. positions.close();
  940. //battleStartpos read
  941. int k = 0; //stack serial
  942. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army1.slots.begin(); i!=army1.slots.end(); i++, k++)
  943. {
  944. int pos;
  945. if(creatureBank)
  946. pos = attackerCreBank[army1.slots.size()-1][k];
  947. else if(army1.formation)
  948. pos = attackerTight[army1.slots.size()-1][k];
  949. else
  950. pos = attackerLoose[army1.slots.size()-1][k];
  951. 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);
  952. stacks.push_back(stack);
  953. }
  954. k = 0;
  955. for(std::map<si32,std::pair<ui32,si32> >::const_iterator i = army2.slots.begin(); i!=army2.slots.end(); i++, k++)
  956. {
  957. int pos;
  958. if(creatureBank)
  959. pos = defenderCreBank[army2.slots.size()-1][k];
  960. else if(army2.formation)
  961. pos = defenderTight[army2.slots.size()-1][k];
  962. else
  963. pos = defenderLoose[army2.slots.size()-1][k];
  964. 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);
  965. stacks.push_back(stack);
  966. }
  967. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  968. {
  969. if((stacks[g]->position%17)==1 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && stacks[g]->attackerOwned)
  970. {
  971. stacks[g]->position += 1;
  972. }
  973. else if((stacks[g]->position%17)==15 && stacks[g]->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && !stacks[g]->attackerOwned)
  974. {
  975. stacks[g]->position -= 1;
  976. }
  977. }
  978. //adding war machines
  979. if(hero1)
  980. {
  981. if(hero1->getArt(13)) //ballista
  982. {
  983. CStack * stack = curB->generateNewStack(hero1, 146, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 52);
  984. stacks.push_back(stack);
  985. }
  986. if(hero1->getArt(14)) //ammo cart
  987. {
  988. CStack * stack = curB->generateNewStack(hero1, 148, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 18);
  989. stacks.push_back(stack);
  990. }
  991. if(hero1->getArt(15)) //first aid tent
  992. {
  993. CStack * stack = curB->generateNewStack(hero1, 147, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 154);
  994. stacks.push_back(stack);
  995. }
  996. }
  997. if(hero2)
  998. {
  999. if(hero2->getArt(13)) //ballista
  1000. {
  1001. CStack * stack = curB->generateNewStack(hero2, 146, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 66);
  1002. stacks.push_back(stack);
  1003. }
  1004. if(hero2->getArt(14)) //ammo cart
  1005. {
  1006. CStack * stack = curB->generateNewStack(hero2, 148, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 32);
  1007. stacks.push_back(stack);
  1008. }
  1009. if(hero2->getArt(15)) //first aid tent
  1010. {
  1011. CStack * stack = curB->generateNewStack(hero2, 147, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 168);
  1012. stacks.push_back(stack);
  1013. }
  1014. }
  1015. if(town && hero1 && town->hasFort()) //catapult
  1016. {
  1017. CStack * stack = curB->generateNewStack(hero1, 145, 1, stacks.size(), true, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, 120);
  1018. stacks.push_back(stack);
  1019. }
  1020. //war machines added
  1021. switch(curB->siege) //adding towers
  1022. {
  1023. case 3: //castle
  1024. {//lower tower / upper tower
  1025. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -4);
  1026. stacks.push_back(stack);
  1027. stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -3);
  1028. stacks.push_back(stack);
  1029. }
  1030. case 2: //citadel
  1031. {//main tower
  1032. CStack * stack = curB->generateNewStack(hero2, 149, 1, stacks.size(), false, 255, gs->map->terrain[tile.x][tile.y][tile.z].tertype, -2);
  1033. stacks.push_back(stack);
  1034. }
  1035. }
  1036. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1037. //seting up siege
  1038. if(town && town->hasFort())
  1039. {
  1040. for(int b=0; b<ARRAY_COUNT(curB->si.wallState); ++b)
  1041. {
  1042. curB->si.wallState[b] = 1;
  1043. }
  1044. }
  1045. int terType = gs->battleGetBattlefieldType(tile);
  1046. //randomize obstacles
  1047. if(town == NULL && !creatureBank) //do it only when it's not siege and not creature bank
  1048. {
  1049. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1050. std::vector<int> possibleObstacles;
  1051. for(int i=0; i<BFIELD_SIZE; ++i)
  1052. {
  1053. if(i%17 < 4 || i%17 > 12)
  1054. {
  1055. obAv[i] = false;
  1056. }
  1057. else
  1058. {
  1059. obAv[i] = true;
  1060. }
  1061. }
  1062. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1063. {
  1064. 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
  1065. {
  1066. possibleObstacles.push_back(g->first);
  1067. }
  1068. }
  1069. srand(time(NULL));
  1070. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1071. {
  1072. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1073. while(toBlock>0)
  1074. {
  1075. CObstacleInstance coi;
  1076. coi.uniqueID = curB->obstacles.size();
  1077. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1078. coi.pos = rand()%BFIELD_SIZE;
  1079. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1080. bool badObstacle = false;
  1081. for(int b=0; b<block.size(); ++b)
  1082. {
  1083. if(block[b] < 0 || block[b] >= BFIELD_SIZE || !obAv[block[b]])
  1084. {
  1085. badObstacle = true;
  1086. break;
  1087. }
  1088. }
  1089. if(badObstacle) continue;
  1090. //obstacle can be placed
  1091. curB->obstacles.push_back(coi);
  1092. for(int b=0; b<block.size(); ++b)
  1093. {
  1094. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1095. obAv[block[b]] = false;
  1096. }
  1097. toBlock -= block.size();
  1098. }
  1099. }
  1100. }
  1101. //giving terrain premies for heroes & stacks
  1102. int bonusSubtype = -1;
  1103. switch(terType)
  1104. {
  1105. case 9: //magic plains
  1106. {
  1107. bonusSubtype = 0;
  1108. }
  1109. case 14: //fiery fields
  1110. {
  1111. if(bonusSubtype == -1) bonusSubtype = 1;
  1112. }
  1113. case 15: //rock lands
  1114. {
  1115. if(bonusSubtype == -1) bonusSubtype = 8;
  1116. }
  1117. case 16: //magic clouds
  1118. {
  1119. if(bonusSubtype == -1) bonusSubtype = 2;
  1120. }
  1121. case 17: //lucid pools
  1122. {
  1123. if(bonusSubtype == -1) bonusSubtype = 4;
  1124. }
  1125. { //common part for cases 9, 14, 15, 16, 17
  1126. const CGHeroInstance * cHero = NULL;
  1127. for(int i=0; i<2; ++i)
  1128. {
  1129. if(i == 0) cHero = hero1;
  1130. else cHero = hero2;
  1131. if(cHero == NULL) continue;
  1132. GiveBonus gs;
  1133. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::MAGIC_SCHOOL_SKILL, HeroBonus::OBJECT, 3, -1, "", bonusSubtype);
  1134. gs.hid = cHero->id;
  1135. sendAndApply(&gs);
  1136. }
  1137. break;
  1138. }
  1139. case 18: //holy ground
  1140. {
  1141. for(int g=0; g<stacks.size(); ++g) //+1 morale bonus for good creatures, -1 morale bonus for evil creatures
  1142. {
  1143. if (stacks[g]->creature->isGood())
  1144. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1145. else if (stacks[g]->creature->isEvil())
  1146. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1147. }
  1148. break;
  1149. }
  1150. case 19: //clover field
  1151. {
  1152. for(int g=0; g<stacks.size(); ++g)
  1153. {
  1154. if(stacks[g]->creature->faction == -1) //+2 luck bonus for neutral creatures
  1155. {
  1156. stacks[g]->features.push_back(makeFeature(StackFeature::LUCK_BONUS, StackFeature::WHOLE_BATTLE, 0, 2, StackFeature::OTHER_SOURCE));
  1157. }
  1158. }
  1159. break;
  1160. }
  1161. case 20: //evil fog
  1162. {
  1163. for(int g=0; g<stacks.size(); ++g) //-1 morale bonus for good creatures, +1 morale bonus for evil creatures
  1164. {
  1165. if (stacks[g]->creature->isGood())
  1166. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, -1, StackFeature::OTHER_SOURCE));
  1167. else if (stacks[g]->creature->isEvil())
  1168. stacks[g]->features.push_back(makeFeature(StackFeature::MORALE_BONUS, StackFeature::WHOLE_BATTLE, 0, 1, StackFeature::OTHER_SOURCE));
  1169. }
  1170. break;
  1171. }
  1172. case 22: //cursed ground
  1173. {
  1174. for(int g=0; g<stacks.size(); ++g) //no luck nor morale
  1175. {
  1176. stacks[g]->features.push_back(makeFeature(StackFeature::NO_MORALE, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1177. stacks[g]->features.push_back(makeFeature(StackFeature::NO_LUCK, StackFeature::WHOLE_BATTLE, 0, 0, StackFeature::OTHER_SOURCE));
  1178. }
  1179. const CGHeroInstance * cHero = NULL;
  1180. for(int i=0; i<2; ++i) //blocking spells above level 1
  1181. {
  1182. if(i == 0) cHero = hero1;
  1183. else cHero = hero2;
  1184. if(cHero == NULL) continue;
  1185. GiveBonus gs;
  1186. gs.bonus = HeroBonus(HeroBonus::ONE_BATTLE, HeroBonus::BLOCK_SPELLS_ABOVE_LEVEL, HeroBonus::OBJECT, 1, -1, "", bonusSubtype);
  1187. gs.hid = cHero->id;
  1188. sendAndApply(&gs);
  1189. }
  1190. break;
  1191. }
  1192. }
  1193. //premies given
  1194. //send info about battles
  1195. BattleStart bs;
  1196. bs.info = curB;
  1197. sendAndApply(&bs);
  1198. }
  1199. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1200. {
  1201. //checking winning condition
  1202. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1203. hasStack[0] = hasStack[1] = false;
  1204. for(int b = 0; b<stacks.size(); ++b)
  1205. {
  1206. if(stacks[b]->alive() && !stacks[b]->hasFeatureOfType(StackFeature::SIEGE_WEAPON))
  1207. {
  1208. hasStack[1-stacks[b]->attackerOwned] = true;
  1209. }
  1210. }
  1211. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1212. {
  1213. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1214. br->result = 0;
  1215. br->winner = hasStack[1]; //fleeing side loses
  1216. gs->curB->calculateCasualties(br->casualties);
  1217. battleResult.set(br);
  1218. }
  1219. }
  1220. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1221. {
  1222. if(!vstd::contains(h->artifWorn,17))
  1223. return; //hero hasn't spellbok
  1224. ChangeSpells cs;
  1225. cs.hid = h->id;
  1226. cs.learn = true;
  1227. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  1228. {
  1229. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1230. {
  1231. if(!vstd::contains(h->spells,t->spells[i][j]))
  1232. cs.spells.insert(t->spells[i][j]);
  1233. }
  1234. }
  1235. if(cs.spells.size())
  1236. sendAndApply(&cs);
  1237. }
  1238. void CGameHandler::setBlockVis(int objid, bool bv)
  1239. {
  1240. SetObjectProperty sop(objid,2,bv);
  1241. sendAndApply(&sop);
  1242. }
  1243. bool CGameHandler::removeObject( int objid )
  1244. {
  1245. if(!getObj(objid))
  1246. {
  1247. tlog1 << "Something wrong, that object already has been removed or hasn't existed!\n";
  1248. return false;
  1249. }
  1250. RemoveObject ro;
  1251. ro.id = objid;
  1252. sendAndApply(&ro);
  1253. return true;
  1254. }
  1255. void CGameHandler::setAmount(int objid, ui32 val)
  1256. {
  1257. SetObjectProperty sop(objid,3,val);
  1258. sendAndApply(&sop);
  1259. }
  1260. bool CGameHandler::moveHero( si32 hid, int3 dst, ui8 instant, ui8 asker /*= 255*/ )
  1261. {
  1262. bool blockvis = false;
  1263. const CGHeroInstance *h = getHero(hid);
  1264. 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)
  1265. )
  1266. {
  1267. tlog1 << "Illegal call to move hero!\n";
  1268. return false;
  1269. }
  1270. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1271. int3 hmpos = dst + int3(-1,0,0);
  1272. if(!gs->map->isInTheMap(hmpos))
  1273. {
  1274. tlog1 << "Destination tile os out of the map!\n";
  1275. return false;
  1276. }
  1277. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1278. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1279. //result structure for start - movement failed, no move points used
  1280. TryMoveHero tmh;
  1281. tmh.id = hid;
  1282. tmh.start = h->pos;
  1283. tmh.end = dst;
  1284. tmh.result = TryMoveHero::FAILED;
  1285. tmh.movePoints = h->movement;
  1286. //check if destination tile is available
  1287. //it's a rock or blocked and not visitable tile
  1288. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1289. if((t.tertype == TerrainTile::rock || (t.blocked && !t.visitable))
  1290. && complain("Cannot move hero, destination tile is blocked!")
  1291. || (!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)
  1292. && complain("Cannot move hero, destination tile is on water!")
  1293. || (h->boat && t.tertype != TerrainTile::water && t.blocked)
  1294. && complain("Cannot disembark hero, tile is blocked!")
  1295. || (h->movement < cost && dst != h->pos)
  1296. && complain("Hero don't have any movement points left!")
  1297. || states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1298. && complain("Cannot move hero during the battle"))
  1299. {
  1300. //send info about movement failure
  1301. sendAndApply(&tmh);
  1302. return false;
  1303. }
  1304. //hero enters the boat
  1305. if(!h->boat && t.visitableObjects.size() && t.visitableObjects.front()->ID == 8)
  1306. {
  1307. tmh.result = TryMoveHero::EMBARK;
  1308. tmh.movePoints = 0; //embarking takes all move points
  1309. //TODO: check for bonus that removes that penalty
  1310. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1311. sendAndApply(&tmh);
  1312. return true;
  1313. }
  1314. //hero leaves the boat
  1315. else if(h->boat && t.tertype != TerrainTile::water && !t.blocked)
  1316. {
  1317. tmh.result = TryMoveHero::DISEMBARK;
  1318. tmh.movePoints = 0; //disembarking takes all move points
  1319. //TODO: check for bonus that removes that penalty
  1320. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1321. sendAndApply(&tmh);
  1322. return true;
  1323. }
  1324. //checks for standard movement
  1325. if(!instant)
  1326. {
  1327. if( distance(h->pos,dst) >= 1.5 && complain("Tiles are not neighbouring!")
  1328. || h->movement < cost && h->movement < 100 && complain("Not enough move points!"))
  1329. {
  1330. sendAndApply(&tmh);
  1331. return false;
  1332. }
  1333. //check if there is blocking visitable object
  1334. blockvis = false;
  1335. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1336. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1337. {
  1338. if(obj != h && obj->blockVisit && !(obj->getPassableness() & 1<<h->tempOwner))
  1339. {
  1340. blockvis = true;
  1341. break;
  1342. }
  1343. }
  1344. //we start moving
  1345. if(blockvis)//interaction with blocking object (like resources)
  1346. {
  1347. tmh.result = TryMoveHero::BLOCKING_VISIT;
  1348. sendAndApply(&tmh);
  1349. //failed to move to that tile but we visit object
  1350. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1351. {
  1352. if (obj->blockVisit)
  1353. {
  1354. objectVisited(obj, h);
  1355. }
  1356. }
  1357. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1358. return true;
  1359. }
  1360. else //normal move
  1361. {
  1362. tmh.result = TryMoveHero::SUCCESS;
  1363. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1364. {
  1365. obj->onHeroLeave(h);
  1366. }
  1367. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1368. sendAndApply(&tmh);
  1369. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1370. //call objects if they are visited
  1371. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1372. {
  1373. objectVisited(obj, h);
  1374. }
  1375. }
  1376. tlog5 << "Movement end!\n";
  1377. return true;
  1378. }
  1379. else //instant move - teleportation
  1380. {
  1381. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1382. {
  1383. if(obj->ID==HEROI_TYPE)
  1384. {
  1385. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1386. if(obj->tempOwner==h->tempOwner)
  1387. {
  1388. heroExchange(dh->id, h->id);
  1389. return true;
  1390. }
  1391. //TODO: check for ally
  1392. startBattleI(h, dh);
  1393. return true;
  1394. }
  1395. }
  1396. tmh.result = TryMoveHero::TELEPORTATION;
  1397. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1398. sendAndApply(&tmh);
  1399. return true;
  1400. }
  1401. }
  1402. void CGameHandler::setOwner(int objid, ui8 owner)
  1403. {
  1404. SetObjectProperty sop(objid,1,owner);
  1405. sendAndApply(&sop);
  1406. }
  1407. void CGameHandler::setHoverName(int objid, MetaString* name)
  1408. {
  1409. SetHoverName shn(objid, *name);
  1410. sendAndApply(&shn);
  1411. }
  1412. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1413. {
  1414. sendToAllClients(iw);
  1415. }
  1416. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1417. {
  1418. ask(iw,iw->player,callback);
  1419. }
  1420. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1421. {
  1422. //TODO
  1423. //gsm.lock();
  1424. //int query = QID++;
  1425. //states.addQuery(player,query);
  1426. //sendToAllClients(iw);
  1427. //gsm.unlock();
  1428. //ui32 ret = getQueryResult(iw->player, query);
  1429. //gsm.lock();
  1430. //states.removeQuery(player, query);
  1431. //gsm.unlock();
  1432. return 0;
  1433. }
  1434. int CGameHandler::getCurrentPlayer()
  1435. {
  1436. return gs->currentPlayer;
  1437. }
  1438. void CGameHandler::giveResource(int player, int which, int val)
  1439. {
  1440. if(!val) return; //don't waste time on empty call
  1441. SetResource sr;
  1442. sr.player = player;
  1443. sr.resid = which;
  1444. sr.val = gs->players.find(player)->second.resources[which]+val;
  1445. sendAndApply(&sr);
  1446. }
  1447. void CGameHandler::giveCreatures (int objid, const CGHeroInstance * h, CCreatureSet creatures)
  1448. {
  1449. if (creatures.slots.size() <= 0)
  1450. return;
  1451. CCreatureSet heroArmy = h->army;
  1452. while (creatures.slots.size() > 0)
  1453. {
  1454. int slot = heroArmy.getSlotFor (creatures.slots.begin()->second.first);
  1455. if (slot < 0)
  1456. break;
  1457. heroArmy.slots[slot].first = creatures.slots.begin()->second.first;
  1458. heroArmy.slots[slot].second += creatures.slots.begin()->second.second;
  1459. creatures.slots.erase (creatures.slots.begin());
  1460. }
  1461. if (creatures.slots.size() == 0) //all creatures can be moved to hero army - do that
  1462. {
  1463. SetGarrisons sg;
  1464. sg.garrs[h->id] = heroArmy;
  1465. sendAndApply(&sg);
  1466. }
  1467. else //show garrison window and let player pick creatures
  1468. {
  1469. SetGarrisons sg;
  1470. sg.garrs[objid] = creatures;
  1471. sendAndApply (&sg);
  1472. showGarrisonDialog (objid, h->id, true, 0);
  1473. return;
  1474. }
  1475. }
  1476. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1477. {
  1478. sendToAllClients(comp);
  1479. }
  1480. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1481. {
  1482. HeroVisitCastle vc;
  1483. vc.hid = heroID;
  1484. vc.tid = obj;
  1485. vc.flags |= 1;
  1486. sendAndApply(&vc);
  1487. vistiCastleObjects (getTown(obj), getHero(heroID));
  1488. giveSpells (getTown(obj), getHero(heroID));
  1489. }
  1490. void CGameHandler::vistiCastleObjects (const CGTownInstance *t, const CGHeroInstance *h)
  1491. {
  1492. std::vector<CGTownBuilding*>::const_iterator i;
  1493. for (i = t->bonusingBuildings.begin(); i != t->bonusingBuildings.end(); i++)
  1494. (*i)->onHeroVisit (h);
  1495. }
  1496. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1497. {
  1498. HeroVisitCastle vc;
  1499. vc.hid = heroID;
  1500. vc.tid = obj;
  1501. sendAndApply(&vc);
  1502. }
  1503. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1504. {
  1505. const CGHeroInstance* h = getHero(hid);
  1506. const CArtifact &art = VLC->arth->artifacts[artid];
  1507. SetHeroArtifacts sha;
  1508. sha.hid = hid;
  1509. sha.artifacts = h->artifacts;
  1510. sha.artifWorn = h->artifWorn;
  1511. if(position<0)
  1512. {
  1513. if(position == -2)
  1514. {
  1515. int i;
  1516. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1517. {
  1518. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1519. {
  1520. //we've found a free suitable slot
  1521. sha.artifWorn[art.possibleSlots[i]] = artid;
  1522. break;
  1523. }
  1524. }
  1525. if(i == art.possibleSlots.size() && !art.isBig()) //if haven't find proper slot, use backpack or discard big artifact
  1526. sha.artifacts.push_back(artid);
  1527. }
  1528. else if (!art.isBig()) //should be -1 => put artifact into backpack
  1529. {
  1530. sha.artifacts.push_back(artid);
  1531. }
  1532. }
  1533. else
  1534. {
  1535. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1536. {
  1537. sha.artifWorn[position] = artid;
  1538. }
  1539. else if (!art.isBig())
  1540. {
  1541. sha.artifacts.push_back(artid);
  1542. }
  1543. }
  1544. sendAndApply(&sha);
  1545. }
  1546. 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
  1547. {
  1548. engageIntoBattle(army1->tempOwner);
  1549. engageIntoBattle(army2->tempOwner);
  1550. //block engaged players
  1551. if(army2->tempOwner < PLAYER_LIMIT)
  1552. states.setFlag(army2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1553. boost::thread(boost::bind(&CGameHandler::startBattle, this, army1, army2, tile, hero1, hero2, creatureBank, cb, town));
  1554. }
  1555. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, boost::function<void(BattleResult*)> cb, bool creatureBank )
  1556. {
  1557. startBattleI(army1, army2, tile,
  1558. army1->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army1) : NULL,
  1559. army2->ID == HEROI_TYPE ? static_cast<const CGHeroInstance*>(army2) : NULL,
  1560. creatureBank, cb);
  1561. }
  1562. void CGameHandler::startBattleI( const CArmedInstance *army1, const CArmedInstance *army2, boost::function<void(BattleResult*)> cb, bool creatureBank)
  1563. {
  1564. startBattleI(army1, army2, army2->pos - army2->getVisitableOffset(), cb, creatureBank);
  1565. }
  1566. //void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1567. //{
  1568. // CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1569. // startBattleI(&h->army,&army,tile,h,NULL,cb);
  1570. // //battle(&h->army,army,tile,h,NULL);
  1571. //}
  1572. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1573. {
  1574. ChangeSpells cs;
  1575. cs.hid = hid;
  1576. cs.spells = spells;
  1577. cs.learn = give;
  1578. sendAndApply(&cs);
  1579. }
  1580. int CGameHandler::getSelectedHero()
  1581. {
  1582. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1583. }
  1584. void CGameHandler::setObjProperty( int objid, int prop, si64 val )
  1585. {
  1586. SetObjectProperty sob;
  1587. sob.id = objid;
  1588. sob.what = prop;
  1589. sob.val = val;
  1590. sendAndApply(&sob);
  1591. }
  1592. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1593. {
  1594. SystemMessage sm;
  1595. sm.text = message;
  1596. c << &sm;
  1597. }
  1598. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1599. {
  1600. sendAndApply(bonus);
  1601. }
  1602. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1603. {
  1604. sendAndApply(smp);
  1605. }
  1606. void CGameHandler::setManaPoints( int hid, int val )
  1607. {
  1608. SetMana sm;
  1609. sm.hid = hid;
  1610. sm.val = val;
  1611. sendAndApply(&sm);
  1612. }
  1613. void CGameHandler::giveHero( int id, int player )
  1614. {
  1615. GiveHero gh;
  1616. gh.id = id;
  1617. gh.player = player;
  1618. sendAndApply(&gh);
  1619. }
  1620. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1621. {
  1622. ChangeObjPos cop;
  1623. cop.objid = objid;
  1624. cop.nPos = newPos;
  1625. cop.flags = flags;
  1626. sendAndApply(&cop);
  1627. }
  1628. void CGameHandler::heroExchange(si32 hero1, si32 hero2)
  1629. {
  1630. ui8 player1 = getHero(hero1)->tempOwner;
  1631. ui8 player2 = getHero(hero2)->tempOwner;
  1632. if(player1 == player2)
  1633. {
  1634. OpenWindow hex;
  1635. hex.window = OpenWindow::EXCHANGE_WINDOW;
  1636. hex.id1 = hero1;
  1637. hex.id2 = hero2;
  1638. sendAndApply(&hex);
  1639. }
  1640. }
  1641. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1642. {
  1643. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1644. sel->id = QID;
  1645. callbacks[QID] = callback;
  1646. states.addQuery(player,QID);
  1647. QID++;
  1648. sendAndApply(sel);
  1649. }
  1650. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1651. {
  1652. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1653. sel->id = QID;
  1654. callbacks[QID] = callback;
  1655. states.addQuery(player,QID);
  1656. sendToAllClients(sel);
  1657. QID++;
  1658. }
  1659. void CGameHandler::sendToAllClients( CPackForClient * info )
  1660. {
  1661. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1662. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1663. {
  1664. (*i)->wmx->lock();
  1665. **i << info;
  1666. (*i)->wmx->unlock();
  1667. }
  1668. }
  1669. void CGameHandler::sendAndApply( CPackForClient * info )
  1670. {
  1671. gs->apply(info);
  1672. sendToAllClients(info);
  1673. }
  1674. void CGameHandler::save( const std::string &fname )
  1675. {
  1676. {
  1677. tlog0 << "Ordering clients to serialize...\n";
  1678. SaveGame sg(fname);
  1679. sendToAllClients(&sg);
  1680. }
  1681. {
  1682. tlog0 << "Serializing game info...\n";
  1683. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vlgm1");
  1684. char hlp[8] = "VCMISVG";
  1685. save << hlp << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1686. }
  1687. {
  1688. tlog0 << "Serializing server info...\n";
  1689. CSaveFile save(GVCMIDirs.UserPath + "/Games/" + fname + ".vsgm1");
  1690. save << *this;
  1691. }
  1692. tlog0 << "Game has been successfully saved!\n";
  1693. }
  1694. void CGameHandler::close()
  1695. {
  1696. tlog0 << "We have been requested to close.\n";
  1697. //BOOST_FOREACH(CConnection *cc, conns)
  1698. // if(cc && cc->socket && cc->socket->is_open())
  1699. // cc->socket->close();
  1700. //exit(0);
  1701. }
  1702. bool CGameHandler::arrangeStacks( si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val )
  1703. {
  1704. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1705. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1706. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1707. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1708. if(!isAllowedExchange(id1,id2))
  1709. {
  1710. complain("Cannot exchange stacks between these two objects!\n");
  1711. return false;
  1712. }
  1713. if(what==1) //swap
  1714. {
  1715. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1716. //if one of them is empty, remove entry
  1717. if(!S1.slots[p1].second)
  1718. S1.slots.erase(p1);
  1719. if(!S2.slots[p2].second)
  1720. S2.slots.erase(p2);
  1721. }
  1722. else if(what==2)//merge
  1723. {
  1724. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1725. {
  1726. complain("Cannot merge different creatures stacks!");
  1727. return false;
  1728. }
  1729. S2.slots[p2].second += S1.slots[p1].second;
  1730. S1.slots.erase(p1);
  1731. }
  1732. else if(what==3) //split
  1733. {
  1734. //general conditions checking
  1735. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1736. || (val<1 && complain("no creatures to split")) )
  1737. {
  1738. return false;
  1739. }
  1740. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1741. {
  1742. int total = S1.slots[p1].second + S2.slots[p2].second;
  1743. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1744. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1745. )
  1746. {
  1747. return false;
  1748. }
  1749. S2.slots[p2].second = val;
  1750. S1.slots[p1].second = total - val;
  1751. }
  1752. else //split one stack to the two
  1753. {
  1754. if(S1.slots[p1].second < val)//not enough creatures
  1755. {
  1756. complain("Cannot split that stack, not enough creatures!");
  1757. return false;
  1758. }
  1759. S2.slots[p2].first = S1.slots[p1].first;
  1760. S2.slots[p2].second = val;
  1761. S1.slots[p1].second -= val;
  1762. }
  1763. if(!S1.slots[p1].second) //if we've moved all creatures
  1764. S1.slots.erase(p1);
  1765. }
  1766. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1767. || (s2->needsLastStack() && !S2.slots.size())
  1768. )
  1769. {
  1770. complain("Cannot take the last stack!");
  1771. return false; //leave without applying changes to garrison
  1772. }
  1773. //apply changes
  1774. SetGarrisons sg;
  1775. sg.garrs[id1] = S1;
  1776. if(s1 != s2)
  1777. sg.garrs[id2] = S2;
  1778. sendAndApply(&sg);
  1779. return true;
  1780. }
  1781. int CGameHandler::getPlayerAt( CConnection *c ) const
  1782. {
  1783. std::set<int> all;
  1784. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1785. if(i->second == c)
  1786. all.insert(i->first);
  1787. switch(all.size())
  1788. {
  1789. case 0:
  1790. return 255;
  1791. case 1:
  1792. return *all.begin();
  1793. default:
  1794. {
  1795. //if we have more than one player at this connection, try to pick active one
  1796. if(vstd::contains(all,int(gs->currentPlayer)))
  1797. return gs->currentPlayer;
  1798. else
  1799. return 253; //cannot say which player is it
  1800. }
  1801. }
  1802. }
  1803. bool CGameHandler::disbandCreature( si32 id, ui8 pos )
  1804. {
  1805. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1806. if(!vstd::contains(s1->army.slots,pos))
  1807. {
  1808. complain("Illegal call to disbandCreature - no such stack in army!");
  1809. return false;
  1810. }
  1811. s1->army.slots.erase(pos);
  1812. SetGarrisons sg;
  1813. sg.garrs[id] = s1->army;
  1814. sendAndApply(&sg);
  1815. return true;
  1816. }
  1817. bool CGameHandler::buildStructure( si32 tid, si32 bid )
  1818. {
  1819. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1820. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1821. if(gs->canBuildStructure(t,bid) != 7)
  1822. {
  1823. complain("Cannot raze that building!");
  1824. return false;
  1825. }
  1826. NewStructures ns;
  1827. ns.tid = tid;
  1828. if ( (bid == 18) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[0]+37))) )
  1829. ns.bid.insert(19);//we have upgr. dwelling, upgr. horde will be builded as well
  1830. else if ( (bid == 24) && (vstd::contains(t->builtBuildings,(t->town->hordeLvl[1]+37))) )
  1831. ns.bid.insert(25);
  1832. else if(bid>36) //upg dwelling
  1833. {
  1834. if ( (bid-37 == t->town->hordeLvl[0]) && (vstd::contains(t->builtBuildings,18)) )
  1835. ns.bid.insert(19);//we have horde, will be upgraded as well as dwelling
  1836. if ( (bid-37 == t->town->hordeLvl[1]) && (vstd::contains(t->builtBuildings,24)) )
  1837. ns.bid.insert(25);
  1838. SetAvailableCreatures ssi;
  1839. ssi.tid = tid;
  1840. ssi.creatures = t->creatures;
  1841. ssi.creatures[bid-37].second.push_back(t->town->upgradedCreatures[bid-37]);
  1842. sendAndApply(&ssi);
  1843. }
  1844. else if(bid >= 30) //bas. dwelling
  1845. {
  1846. int crid = t->town->basicCreatures[bid-30];
  1847. SetAvailableCreatures ssi;
  1848. ssi.tid = tid;
  1849. ssi.creatures = t->creatures;
  1850. ssi.creatures[bid-30].first = VLC->creh->creatures[crid].growth;
  1851. ssi.creatures[bid-30].second.push_back(crid);
  1852. sendAndApply(&ssi);
  1853. }
  1854. else if(bid == 11)
  1855. ns.bid.insert(27);
  1856. else if(bid == 12)
  1857. ns.bid.insert(28);
  1858. else if(bid == 13)
  1859. ns.bid.insert(29);
  1860. ns.bid.insert(bid);
  1861. ns.builded = t->builded + 1;
  1862. sendAndApply(&ns);
  1863. //reveal ground for lookout tower
  1864. FoWChange fw;
  1865. fw.player = t->tempOwner;
  1866. fw.mode = 1;
  1867. getTilesInRange(fw.tiles,t->pos,t->getSightRadious(),t->tempOwner,1);
  1868. sendAndApply(&fw);
  1869. SetResources sr;
  1870. sr.player = t->tempOwner;
  1871. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1872. for(int i=0;i<b->resources.size();i++)
  1873. sr.res[i]-=b->resources[i];
  1874. sendAndApply(&sr);
  1875. if(bid<5) //it's mage guild
  1876. {
  1877. if(t->visitingHero)
  1878. giveSpells(t,t->visitingHero);
  1879. if(t->garrisonHero)
  1880. giveSpells(t,t->garrisonHero);
  1881. }
  1882. if(t->visitingHero)
  1883. vistiCastleObjects (t, t->visitingHero);
  1884. if(t->garrisonHero)
  1885. vistiCastleObjects (t, t->garrisonHero);
  1886. return true;
  1887. }
  1888. bool CGameHandler::razeStructure (si32 tid, si32 bid)
  1889. {
  1890. ///incomplete, simply erases target building
  1891. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1892. if (t->builtBuildings.find(bid) == t->builtBuildings.end())
  1893. return false;
  1894. RazeStructures rs;
  1895. rs.tid = tid;
  1896. rs.bid.insert(bid);
  1897. rs.destroyed = t->destroyed + 1;
  1898. sendAndApply(&rs);
  1899. return true;
  1900. }
  1901. void CGameHandler::sendMessageToAll( const std::string &message )
  1902. {
  1903. SystemMessage sm;
  1904. sm.text = message;
  1905. sendToAllClients(&sm);
  1906. }
  1907. bool CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1908. {
  1909. const CGDwelling *dw = static_cast<CGDwelling*>(gs->map->objects[objid]);
  1910. const CArmedInstance *dst = NULL;
  1911. if(dw->ID == TOWNI_TYPE)
  1912. dst = dw;
  1913. else if(dw->ID == 17 || dw->ID == 20) //advmap dwelling
  1914. dst = getHero(gs->getPlayer(dw->tempOwner)->currentSelection); //TODO: check if current hero is really visiting dwelling
  1915. assert(dw && dst);
  1916. //verify
  1917. bool found = false;
  1918. int level = -1;
  1919. typedef std::pair<const int,int> Parka;
  1920. for(level = 0; level < dw->creatures.size(); level++) //iterate through all levels
  1921. {
  1922. const std::pair<ui32, std::vector<ui32> > &cur = dw->creatures[level]; //current level info <amount, list of cr. ids>
  1923. int i = 0;
  1924. for(; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  1925. if(cur.second[i] == crid)
  1926. break;
  1927. if(i < cur.second.size())
  1928. {
  1929. found = true;
  1930. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  1931. break;
  1932. }
  1933. }
  1934. int slot = dst->army.getSlotFor(crid);
  1935. if(!found && complain("Cannot recruit: no such creatures!")
  1936. || cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!")
  1937. || cram<=0 && complain("Cannot recruit: cram <= 0!")
  1938. || slot<0 && complain("Cannot recruit: no available slot!"))
  1939. {
  1940. return false;
  1941. }
  1942. //recruit
  1943. SetResources sr;
  1944. sr.player = dst->tempOwner;
  1945. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1946. sr.res[i] = gs->getPlayer(dst->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1947. SetAvailableCreatures sac;
  1948. sac.tid = objid;
  1949. sac.creatures = dw->creatures;
  1950. sac.creatures[level].first -= cram;
  1951. SetGarrisons sg;
  1952. sg.garrs[dst->id] = dst->army;
  1953. if(sg.garrs[dst->id].slots.find(slot) == sg.garrs[dst->id].slots.end()) //take a free slot
  1954. {
  1955. sg.garrs[dst->id].slots[slot] = std::make_pair(crid,cram);
  1956. }
  1957. else //add creatures to a already existing stack
  1958. {
  1959. sg.garrs[dst->id].slots[slot].second += cram;
  1960. }
  1961. sendAndApply(&sr);
  1962. sendAndApply(&sac);
  1963. sendAndApply(&sg);
  1964. return true;
  1965. }
  1966. bool CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1967. {
  1968. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1969. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1970. int player = obj->tempOwner;
  1971. int crQuantity = obj->army.slots[pos].second;
  1972. //check if upgrade is possible
  1973. if((ui.oldID<0 || !vstd::contains(ui.newID,upgID)) && complain("That upgrade is not possible!"))
  1974. {
  1975. return false;
  1976. }
  1977. //check if player has enough resources
  1978. for(int i=0;i<ui.cost.size();i++)
  1979. {
  1980. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1981. {
  1982. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1983. {
  1984. complain("Cannot upgrade, not enough resources!");
  1985. return false;
  1986. }
  1987. }
  1988. }
  1989. //take resources
  1990. for(int i=0;i<ui.cost.size();i++)
  1991. {
  1992. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1993. {
  1994. SetResource sr;
  1995. sr.player = player;
  1996. sr.resid = j->first;
  1997. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1998. sendAndApply(&sr);
  1999. }
  2000. }
  2001. //upgrade creature
  2002. SetGarrisons sg;
  2003. sg.garrs[objid] = obj->army;
  2004. sg.garrs[objid].slots[pos].first = upgID;
  2005. sendAndApply(&sg);
  2006. return true;
  2007. }
  2008. bool CGameHandler::garrisonSwap( si32 tid )
  2009. {
  2010. CGTownInstance *town = gs->getTown(tid);
  2011. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  2012. {
  2013. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  2014. while(!cso.slots.empty())//while there are unmoved creatures
  2015. {
  2016. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  2017. if(pos<0)
  2018. {
  2019. //try to merge two other stacks to make place
  2020. std::pair<TSlot, TSlot> toMerge;
  2021. if(csn.mergableStacks(toMerge, cso.slots.begin()->first))
  2022. {
  2023. //merge
  2024. csn.slots[toMerge.second].second += csn.slots[toMerge.first].second;
  2025. csn.slots[toMerge.first] = cso.slots.begin()->second;
  2026. }
  2027. else
  2028. {
  2029. complain("Cannot make garrison swap, not enough free slots!");
  2030. return false;
  2031. }
  2032. }
  2033. else if(csn.slots.find(pos) != csn.slots.end()) //add creatures to the existing stack
  2034. {
  2035. csn.slots[pos].second += cso.slots.begin()->second.second;
  2036. }
  2037. else //move stack on the free pos
  2038. {
  2039. csn.slots[pos].first = cso.slots.begin()->second.first;
  2040. csn.slots[pos].second = cso.slots.begin()->second.second;
  2041. }
  2042. cso.slots.erase(cso.slots.begin());
  2043. }
  2044. SetGarrisons sg;
  2045. sg.garrs[town->visitingHero->id] = csn;
  2046. sg.garrs[town->id] = csn;
  2047. sendAndApply(&sg);
  2048. SetHeroesInTown intown;
  2049. intown.tid = tid;
  2050. intown.visiting = -1;
  2051. intown.garrison = town->visitingHero->id;
  2052. sendAndApply(&intown);
  2053. return true;
  2054. }
  2055. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  2056. {
  2057. //check if moving hero out of town will break 8 wandering heroes limit
  2058. if(getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  2059. {
  2060. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  2061. return false;
  2062. }
  2063. SetHeroesInTown intown;
  2064. intown.tid = tid;
  2065. intown.garrison = -1;
  2066. intown.visiting = town->garrisonHero->id;
  2067. sendAndApply(&intown);
  2068. //town will be empty
  2069. SetGarrisons sg;
  2070. sg.garrs[tid] = CCreatureSet();
  2071. sendAndApply(&sg);
  2072. return true;
  2073. }
  2074. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  2075. {
  2076. SetGarrisons sg;
  2077. sg.garrs[town->id] = town->visitingHero->army;
  2078. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  2079. SetHeroesInTown intown;
  2080. intown.tid = tid;
  2081. intown.garrison = town->visitingHero->id;
  2082. intown.visiting = town->garrisonHero->id;
  2083. sendAndApply(&intown);
  2084. sendAndApply(&sg);
  2085. return true;
  2086. }
  2087. else
  2088. {
  2089. complain("Cannot swap garrison hero!");
  2090. return false;
  2091. }
  2092. }
  2093. bool CGameHandler::swapArtifacts(si32 srcHeroID, si32 destHeroID, ui16 srcSlot, ui16 destSlot)
  2094. {
  2095. CGHeroInstance *srcHero = gs->getHero(srcHeroID);
  2096. CGHeroInstance *destHero = gs->getHero(destHeroID);
  2097. // Make sure exchange is even possible between the two heroes.
  2098. if ((distance(srcHero->pos,destHero->pos) > 1.5 )|| (srcHero->tempOwner != destHero->tempOwner))
  2099. return false;
  2100. const CArtifact *srcArtifact = srcHero->getArt(srcSlot);
  2101. const CArtifact *destArtifact = destHero->getArt(destSlot);
  2102. // Check if src/dest slots are appropriate for the artifacts exchanged.
  2103. // Moving to the backpack is always allowed.
  2104. if ((!srcArtifact || destSlot < 19)
  2105. && (((srcArtifact && !vstd::contains(srcArtifact->possibleSlots, destSlot))
  2106. || (destArtifact && srcSlot < 19 && !vstd::contains(destArtifact->possibleSlots, srcSlot)))))
  2107. {
  2108. complain("Cannot swap artifacts!");
  2109. return false;
  2110. }
  2111. if (destSlot >= 19 && srcArtifact->isBig()) {
  2112. complain("Cannot put big artifacts in backpack!");
  2113. return false;
  2114. }
  2115. if (srcSlot == 16 || destSlot == 16) {
  2116. complain("Cannot move catapult!");
  2117. return false;
  2118. }
  2119. // Perform the exchange.
  2120. SetHeroArtifacts sha;
  2121. sha.hid = srcHeroID;
  2122. sha.artifacts = srcHero->artifacts;
  2123. sha.artifWorn = srcHero->artifWorn;
  2124. sha.setArtAtPos(srcSlot, -1);
  2125. if (destSlot < 19 && (destArtifact || srcSlot < 19))
  2126. sha.setArtAtPos(srcSlot, destHero->getArtAtPos(destSlot));
  2127. // Internal hero artifact arrangement.
  2128. if(srcHero == destHero) {
  2129. // Correction for destination from removing source artifact in backpack.
  2130. if (srcSlot >= 19 && destSlot >= 19 && srcSlot < destSlot)
  2131. destSlot--;
  2132. sha.setArtAtPos(destSlot, srcHero->getArtAtPos(srcSlot));
  2133. }
  2134. sendAndApply(&sha);
  2135. if (srcHeroID != destHeroID) {
  2136. // Exchange between two different heroes.
  2137. sha.hid = destHeroID;
  2138. sha.artifacts = destHero->artifacts;
  2139. sha.artifWorn = destHero->artifWorn;
  2140. sha.setArtAtPos(destSlot, srcArtifact ? srcArtifact->id : -1);
  2141. sendAndApply(&sha);
  2142. }
  2143. return true;
  2144. }
  2145. /**
  2146. * Sets a hero artifact slot to contain a specific artifact.
  2147. *
  2148. * @param artID ID of an artifact or -1 for no artifact.
  2149. */
  2150. bool CGameHandler::setArtifact(si32 heroID, ui16 slot, int artID)
  2151. {
  2152. const CGHeroInstance *hero = gs->getHero(heroID);
  2153. if (artID != -1) {
  2154. const CArtifact &artifact = VLC->arth->artifacts[artID];
  2155. if (slot < 19 && !vstd::contains(artifact.possibleSlots, slot)) {
  2156. complain("Artifact does not fit!");
  2157. return false;
  2158. }
  2159. if (slot >= 19 && artifact.isBig()) {
  2160. complain("Cannot put big artifacts in backpack!");
  2161. return false;
  2162. }
  2163. }
  2164. if (slot == 16) {
  2165. complain("Cannot alter catapult slot!");
  2166. return false;
  2167. }
  2168. // Perform the exchange.
  2169. SetHeroArtifacts sha;
  2170. sha.hid = heroID;
  2171. sha.artifacts = hero->artifacts;
  2172. sha.artifWorn = hero->artifWorn;
  2173. sha.setArtAtPos(slot, artID);
  2174. sendAndApply(&sha);
  2175. return true;
  2176. }
  2177. bool CGameHandler::buyArtifact( ui32 hid, si32 aid )
  2178. {
  2179. CGHeroInstance *hero = gs->getHero(hid);
  2180. CGTownInstance *town = hero->visitedTown;
  2181. if(aid==0) //spellbook
  2182. {
  2183. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  2184. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  2185. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  2186. )
  2187. return false;
  2188. giveResource(hero->getOwner(),6,-500);
  2189. giveHeroArtifact(0,hid,17);
  2190. giveSpells(town,hero);
  2191. return true;
  2192. }
  2193. else if(aid < 7 && aid > 3) //war machine
  2194. {
  2195. int price = VLC->arth->artifacts[aid].price;
  2196. if(vstd::contains(hero->artifWorn,ui16(9+aid)) && complain("Hero already has this machine!")
  2197. || !vstd::contains(town->builtBuildings,si32(16)) && complain("No blackismith!")
  2198. || gs->getPlayer(hero->getOwner())->resources[6] < price && complain("Not enough gold!") //no gold
  2199. || town->town->warMachine!= aid && complain("This machine is unavailable here!") ) //TODO: ballista yard in Stronghold
  2200. {
  2201. return false;
  2202. }
  2203. giveResource(hero->getOwner(),6,-price);
  2204. giveHeroArtifact(aid,hid,9+aid);
  2205. return true;
  2206. }
  2207. return false;
  2208. }
  2209. bool CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  2210. {
  2211. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  2212. double yield = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  2213. yield /= gs->resVals[id2];
  2214. SetResource sr;
  2215. sr.player = player;
  2216. sr.resid = id1;
  2217. sr.val = gs->getPlayer(player)->resources[id1] - val;
  2218. sendAndApply(&sr);
  2219. sr.resid = id2;
  2220. sr.val = gs->getPlayer(player)->resources[id2] + (int)yield;
  2221. sendAndApply(&sr);
  2222. return true;
  2223. }
  2224. bool CGameHandler::setFormation( si32 hid, ui8 formation )
  2225. {
  2226. gs->getHero(hid)->army.formation = formation;
  2227. return true;
  2228. }
  2229. bool CGameHandler::hireHero( ui32 tid, ui8 hid )
  2230. {
  2231. CGTownInstance *t = gs->getTown(tid);
  2232. if(!vstd::contains(t->builtBuildings,5) && complain("No tavern!")
  2233. || gs->getPlayer(t->tempOwner)->resources[6]<2500 && complain("Not enough gold for buying hero!")
  2234. || t->visitingHero && complain("There is visiting hero - no place!")
  2235. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  2236. )
  2237. return false;
  2238. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  2239. assert(nh);
  2240. HeroRecruited hr;
  2241. hr.tid = tid;
  2242. hr.hid = nh->subID;
  2243. hr.player = t->tempOwner;
  2244. hr.tile = t->pos - int3(1,0,0);
  2245. sendAndApply(&hr);
  2246. std::map<ui32,CGHeroInstance *> pool = gs->hpool.heroesPool;
  2247. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  2248. for(std::vector<CGHeroInstance *>::iterator j = i->second.availableHeroes.begin(); j != i->second.availableHeroes.end(); j++)
  2249. if(*j)
  2250. pool.erase((**j).subID);
  2251. SetAvailableHeroes sah;
  2252. CGHeroInstance *h1 = gs->hpool.pickHeroFor(false,t->tempOwner,t->town, pool),
  2253. *h2 = gs->getPlayer(t->tempOwner)->availableHeroes[!hid];
  2254. (hid ? sah.hid2 : sah.hid1) = h1 ? h1->subID : -1;
  2255. (hid ? sah.hid1 : sah.hid2) = h2 ? h2->subID : -1;
  2256. sah.player = t->tempOwner;
  2257. sah.flags = hid+1;
  2258. sendAndApply(&sah);
  2259. SetResource sr;
  2260. sr.player = t->tempOwner;
  2261. sr.resid = 6;
  2262. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  2263. sendAndApply(&sr);
  2264. vistiCastleObjects (t, nh);
  2265. giveSpells (t,nh);
  2266. return true;
  2267. }
  2268. bool CGameHandler::queryReply( ui32 qid, ui32 answer )
  2269. {
  2270. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2271. if(vstd::contains(callbacks,qid))
  2272. {
  2273. CFunctionList<void(ui32)> callb = callbacks[qid];
  2274. callbacks.erase(qid);
  2275. if(callb)
  2276. callb(answer);
  2277. }
  2278. else if(vstd::contains(garrisonCallbacks,qid))
  2279. {
  2280. if(garrisonCallbacks[qid])
  2281. garrisonCallbacks[qid]();
  2282. garrisonCallbacks.erase(qid);
  2283. allowedExchanges.erase(qid);
  2284. }
  2285. else
  2286. {
  2287. tlog1 << "Unknown query reply...\n";
  2288. return false;
  2289. }
  2290. return true;
  2291. }
  2292. bool CGameHandler::makeBattleAction( BattleAction &ba )
  2293. {
  2294. tlog1 << "\tMaking action of type " << ba.actionType << std::endl;
  2295. bool ok = true;
  2296. switch(ba.actionType)
  2297. {
  2298. case 2: //walk
  2299. {
  2300. sendAndApply(&StartAction(ba)); //start movement
  2301. moveStack(ba.stackNumber,ba.destinationTile); //move
  2302. sendAndApply(&EndAction());
  2303. break;
  2304. }
  2305. case 3: //defend
  2306. case 8: //wait
  2307. {
  2308. sendAndApply(&StartAction(ba));
  2309. sendAndApply(&EndAction());
  2310. break;
  2311. }
  2312. case 4: //retreat/flee
  2313. {
  2314. if( !gs->battleCanFlee(ba.side ? gs->curB->side2 : gs->curB->side1) )
  2315. break;
  2316. //TODO: remove retreating hero from map and place it in recruitment list
  2317. BattleResult *br = new BattleResult;
  2318. br->result = 1;
  2319. br->winner = !ba.side; //fleeing side loses
  2320. gs->curB->calculateCasualties(br->casualties);
  2321. giveExp(*br);
  2322. battleResult.set(br);
  2323. break;
  2324. }
  2325. case 6: //walk or attack
  2326. {
  2327. sendAndApply(&StartAction(ba)); //start movement and attack
  2328. int startingPos = gs->curB->getStack(ba.stackNumber)->position;
  2329. int distance = moveStack(ba.stackNumber, ba.destinationTile);
  2330. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2331. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  2332. if(curStack->position != ba.destinationTile //we wasn't able to reach destination tile
  2333. && !(curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)
  2334. && ( curStack->position == ba.destinationTile + (curStack->attackerOwned ? +1 : -1 ) )
  2335. ) //nor occupy specified hex
  2336. )
  2337. {
  2338. std::string problem = "We cannot move this stack to its destination " + curStack->creature->namePl;
  2339. tlog3 << problem << std::endl;
  2340. complain(problem);
  2341. ok = false;
  2342. sendAndApply(&EndAction());
  2343. break;
  2344. }
  2345. if(curStack->ID == stackAtEnd->ID) //we should just move, it will be handled by following check
  2346. {
  2347. stackAtEnd = NULL;
  2348. }
  2349. if(!stackAtEnd)
  2350. {
  2351. std::ostringstream problem;
  2352. problem << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  2353. std::string probl = problem.str();
  2354. tlog3 << probl << std::endl;
  2355. complain(probl);
  2356. ok = false;
  2357. sendAndApply(&EndAction());
  2358. break;
  2359. }
  2360. ui16 curpos = curStack->position,
  2361. enemypos = stackAtEnd->position;
  2362. if( !(
  2363. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  2364. || (curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //back <=> front
  2365. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  2366. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) //front <=> back
  2367. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2368. || (stackAtEnd->hasFeatureOfType(StackFeature::DOUBLE_WIDE) && curStack->hasFeatureOfType(StackFeature::DOUBLE_WIDE)//back <=> back
  2369. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  2370. )
  2371. )
  2372. {
  2373. tlog3 << "Attack cannot be performed!";
  2374. sendAndApply(&EndAction());
  2375. ok = false;
  2376. }
  2377. //attack
  2378. BattleAttack bat;
  2379. prepareAttack(bat, curStack, stackAtEnd, distance);
  2380. sendAndApply(&bat);
  2381. //counterattack
  2382. if(!curStack->hasFeatureOfType(StackFeature::BLOCKS_RETALIATION)
  2383. && stackAtEnd->alive()
  2384. && ( stackAtEnd->counterAttacks > 0 || stackAtEnd->hasFeatureOfType(StackFeature::UNLIMITED_RETALIATIONS) )
  2385. && !stackAtEnd->hasFeatureOfType(StackFeature::SIEGE_WEAPON)
  2386. && !stackAtEnd->hasFeatureOfType(StackFeature::HYPNOTIZED))
  2387. {
  2388. prepareAttack(bat, stackAtEnd, curStack, 0);
  2389. bat.flags |= 2;
  2390. sendAndApply(&bat);
  2391. }
  2392. //second attack
  2393. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0
  2394. && !curStack->hasFeatureOfType(StackFeature::SHOOTER)
  2395. && curStack->alive()
  2396. && stackAtEnd->alive() )
  2397. {
  2398. bat.flags = 0;
  2399. prepareAttack(bat, curStack, stackAtEnd, 0);
  2400. sendAndApply(&bat);
  2401. }
  2402. //return
  2403. if(curStack->hasFeatureOfType(StackFeature::RETURN_AFTER_STRIKE) && startingPos != curStack->position)
  2404. {
  2405. moveStack(ba.stackNumber, startingPos);
  2406. }
  2407. sendAndApply(&EndAction());
  2408. break;
  2409. }
  2410. case 7: //shoot
  2411. {
  2412. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  2413. *destStack= gs->curB->getStackT(ba.destinationTile);
  2414. if( !gs->battleCanShoot(ba.stackNumber, ba.destinationTile) )
  2415. break;
  2416. sendAndApply(&StartAction(ba)); //start shooting
  2417. BattleAttack bat;
  2418. prepareAttack(bat, curStack, destStack, 0);
  2419. bat.flags |= 1;
  2420. sendAndApply(&bat);
  2421. if(curStack->valOfFeatures(StackFeature::ADDITIONAL_ATTACK) > 0 //if unit shots twice let's make another shot
  2422. && curStack->alive()
  2423. && destStack->alive()
  2424. && curStack->shots
  2425. )
  2426. {
  2427. prepareAttack(bat, curStack, destStack, 0);
  2428. sendAndApply(&bat);
  2429. }
  2430. sendAndApply(&EndAction());
  2431. break;
  2432. }
  2433. case 9: //catapult
  2434. {
  2435. sendAndApply(&StartAction(ba));
  2436. const CGHeroInstance * attackingHero = gs->curB->heroes[ba.side];
  2437. CHeroHandler::SBallisticsLevelInfo sbi = VLC->heroh->ballistics[attackingHero->getSecSkillLevel(20)]; //artillery
  2438. int attackedPart = gs->curB->hexToWallPart(ba.destinationTile);
  2439. if(attackedPart == -1)
  2440. {
  2441. complain("catapult tried to attack non-catapultable hex!");
  2442. break;
  2443. }
  2444. for(int g=0; g<sbi.shots; ++g)
  2445. {
  2446. if(gs->curB->si.wallState[attackedPart] == 3) //it's not destroyed
  2447. continue;
  2448. CatapultAttack ca; //package for clients
  2449. std::pair< std::pair< ui8, si16 >, ui8> attack;
  2450. attack.first.first = attackedPart;
  2451. attack.first.second = ba.destinationTile;
  2452. attack.second = 0;
  2453. int chanceForHit = 0;
  2454. int dmgChance[3] = {sbi.noDmg, sbi.oneDmg, sbi.twoDmg}; //dmgChance[i] - chance for doing i dmg when hit is successful
  2455. switch(attackedPart)
  2456. {
  2457. case 0: //keep
  2458. chanceForHit = sbi.keep;
  2459. break;
  2460. case 1: //bottom tower
  2461. case 6: //upper tower
  2462. chanceForHit = sbi.tower;
  2463. break;
  2464. case 2: //bottom wall
  2465. case 3: //below gate
  2466. case 4: //over gate
  2467. case 5: //upper wall
  2468. chanceForHit = sbi.wall;
  2469. break;
  2470. case 7: //gate
  2471. chanceForHit = sbi.gate;
  2472. break;
  2473. }
  2474. if(rand()%100 <= chanceForHit) //hit is successful
  2475. {
  2476. int dmgRand = rand()%100;
  2477. //accumulating dmgChance
  2478. dmgChance[1] += dmgChance[0];
  2479. dmgChance[2] += dmgChance[1];
  2480. //calculating dealt damage
  2481. for(int v = 0; v < ARRAY_COUNT(dmgChance); ++v)
  2482. {
  2483. if(dmgRand <= dmgChance[v])
  2484. {
  2485. attack.second = v;
  2486. break;
  2487. }
  2488. }
  2489. if(attack.second > 0 && (attackedPart == 0 || attackedPart == 1 || attackedPart == 6))
  2490. {
  2491. int posRemove = -1;
  2492. switch(attackedPart)
  2493. {
  2494. case 0: //keep
  2495. posRemove = -2;
  2496. break;
  2497. case 1: //bottom tower
  2498. posRemove = -3;
  2499. break;
  2500. case 6: //upper tower
  2501. posRemove = -4;
  2502. break;
  2503. }
  2504. BattleStacksRemoved bsr;
  2505. for(int g=0; g<gs->curB->stacks.size(); ++g)
  2506. {
  2507. if(gs->curB->stacks[g]->position == posRemove)
  2508. {
  2509. bsr.stackIDs.insert( gs->curB->stacks[g]->ID );
  2510. break;
  2511. }
  2512. }
  2513. sendAndApply(&bsr);
  2514. }
  2515. }
  2516. ca.attacker = ba.stackNumber;
  2517. ca.attackedParts.insert(attack);
  2518. sendAndApply(&ca);
  2519. }
  2520. sendAndApply(&EndAction());
  2521. break;
  2522. }
  2523. }
  2524. battleMadeAction.setn(true);
  2525. return ok;
  2526. }
  2527. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  2528. {
  2529. bool cheated=true;
  2530. sendAndApply(&PlayerMessage(player,message));
  2531. if(message == "vcmiistari") //give all spells and 999 mana
  2532. {
  2533. SetMana sm;
  2534. ChangeSpells cs;
  2535. SetHeroArtifacts sha;
  2536. CGHeroInstance *h = gs->getHero(gs->getPlayer(player)->currentSelection);
  2537. if(!h && complain("Cannot realize cheat, no hero selected!")) return;
  2538. sm.hid = cs.hid = h->id;
  2539. //give all spells
  2540. cs.learn = 1;
  2541. for(int i=0;i<VLC->spellh->spells.size();i++)
  2542. {
  2543. if(!VLC->spellh->spells[i].creatureAbility)
  2544. cs.spells.insert(i);
  2545. }
  2546. //give mana
  2547. sm.val = 999;
  2548. if(!h->getArt(17)) //hero doesn't have spellbook
  2549. {
  2550. //give spellbook
  2551. sha.hid = h->id;
  2552. sha.artifacts = h->artifacts;
  2553. sha.artifWorn = h->artifWorn;
  2554. sha.artifWorn[17] = 0;
  2555. sendAndApply(&sha);
  2556. }
  2557. sendAndApply(&cs);
  2558. sendAndApply(&sm);
  2559. }
  2560. else if(message == "vcmiainur") //gives 5 archangels into each slot
  2561. {
  2562. SetGarrisons sg;
  2563. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2564. if(!hero) return;
  2565. sg.garrs[hero->id] = hero->army;
  2566. for(int i=0;i<7;i++)
  2567. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2568. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  2569. sendAndApply(&sg);
  2570. }
  2571. else if(message == "vcmiangband") //gives 10 black knight into each slot
  2572. {
  2573. SetGarrisons sg;
  2574. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2575. if(!hero) return;
  2576. sg.garrs[hero->id] = hero->army;
  2577. for(int i=0;i<7;i++)
  2578. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  2579. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  2580. sendAndApply(&sg);
  2581. }
  2582. else if(message == "vcminoldor") //all war machines
  2583. {
  2584. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2585. if(!hero) return;
  2586. SetHeroArtifacts sha;
  2587. sha.hid = hero->id;
  2588. sha.artifacts = hero->artifacts;
  2589. sha.artifWorn = hero->artifWorn;
  2590. sha.artifWorn[13] = 4;
  2591. sha.artifWorn[14] = 5;
  2592. sha.artifWorn[15] = 6;
  2593. sendAndApply(&sha);
  2594. }
  2595. else if(message == "vcminahar") //1000000 movement points
  2596. {
  2597. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2598. if(!hero) return;
  2599. SetMovePoints smp;
  2600. smp.hid = hero->id;
  2601. smp.val = 1000000;
  2602. sendAndApply(&smp);
  2603. }
  2604. else if(message == "vcmiformenos") //give resources
  2605. {
  2606. SetResources sr;
  2607. sr.player = player;
  2608. sr.res = gs->getPlayer(player)->resources;
  2609. for(int i=0;i<7;i++)
  2610. sr.res[i] += 100;
  2611. sr.res[6] += 19900;
  2612. sendAndApply(&sr);
  2613. }
  2614. else if(message == "vcmieagles") //reveal FoW
  2615. {
  2616. FoWChange fc;
  2617. fc.mode = 1;
  2618. fc.player = player;
  2619. for(int i=0;i<gs->map->width;i++)
  2620. for(int j=0;j<gs->map->height;j++)
  2621. for(int k=0;k<gs->map->twoLevel+1;k++)
  2622. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  2623. fc.tiles.insert(int3(i,j,k));
  2624. sendAndApply(&fc);
  2625. }
  2626. else if(message == "vcmiglorfindel")
  2627. {
  2628. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  2629. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  2630. }
  2631. else
  2632. cheated = false;
  2633. if(cheated)
  2634. {
  2635. sendAndApply(&SystemMessage("CHEATER!!!"));
  2636. }
  2637. }
  2638. static ui32 calculateHealedHP(const CGHeroInstance * caster, const CSpell * spell, const CStack * stack)
  2639. {
  2640. switch(spell->id)
  2641. {
  2642. case 37: //cure
  2643. {
  2644. int healedHealth = caster->getPrimSkillLevel(2) * 5 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2645. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft);
  2646. break;
  2647. }
  2648. case 38: //resurrection
  2649. {
  2650. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2651. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2652. break;
  2653. }
  2654. case 39: //animate dead
  2655. {
  2656. int healedHealth = caster->getPrimSkillLevel(2) * 50 + spell->powers[caster->getSpellSchoolLevel(spell)];
  2657. return std::min<ui32>(healedHealth, stack->MaxHealth() - stack->firstHPleft + stack->baseAmount * stack->MaxHealth());
  2658. break;
  2659. }
  2660. }
  2661. //we shouldn't be here
  2662. tlog1 << "calculateHealedHP called for non-healing spell: " << spell->name << std::endl;
  2663. return 0;
  2664. }
  2665. static std::vector<ui32> calculateResistedStacks(const CSpell * sp, const CGHeroInstance * caster, const CGHeroInstance * hero2, const std::set<CStack*> affectedCreatures)
  2666. {
  2667. std::vector<ui32> ret;
  2668. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2669. {
  2670. if ((*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2671. || ((*it)->valOfFeatures(StackFeature::LEVEL_SPELL_IMMUNITY) >= sp->level))
  2672. {
  2673. ret.push_back((*it)->ID);
  2674. continue;
  2675. }
  2676. //non-negative spells on friendly stacks should always succeed, unless immune
  2677. if(sp->positiveness >= 0 && (*it)->owner == caster->tempOwner)
  2678. continue;
  2679. const CGHeroInstance * bonusHero; //hero we should take bonuses from
  2680. if((*it)->owner == caster->tempOwner)
  2681. bonusHero = caster;
  2682. else
  2683. bonusHero = hero2;
  2684. int prob = (*it)->valOfFeatures(StackFeature::MAGIC_RESISTANCE); //probability of resistance in %
  2685. if(bonusHero)
  2686. {
  2687. //bonusHero's resistance support (secondary skils and artifacts)
  2688. prob += bonusHero->valOfBonuses(HeroBonus::MAGIC_RESISTANCE);
  2689. switch(bonusHero->getSecSkillLevel(26)) //resistance
  2690. {
  2691. case 1: //basic
  2692. prob += 5;
  2693. break;
  2694. case 2: //advanced
  2695. prob += 10;
  2696. break;
  2697. case 3: //expert
  2698. prob += 20;
  2699. break;
  2700. }
  2701. }
  2702. if(prob > 100) prob = 100;
  2703. if(rand()%100 < prob) //immunity from resistance
  2704. ret.push_back((*it)->ID);
  2705. }
  2706. if(sp->id == 60) //hypnotize
  2707. {
  2708. for(std::set<CStack*>::const_iterator it = affectedCreatures.begin(); it != affectedCreatures.end(); ++it)
  2709. {
  2710. if( (*it)->hasFeatureOfType(StackFeature::SPELL_IMMUNITY, sp->id) //100% sure spell immunity
  2711. || ( (*it)->amount - 1 ) * (*it)->MaxHealth() + (*it)->firstHPleft
  2712. >
  2713. caster->getPrimSkillLevel(2) * 25 + sp->powers[caster->getSpellSchoolLevel(sp)]
  2714. )
  2715. {
  2716. ret.push_back((*it)->ID);
  2717. }
  2718. }
  2719. }
  2720. return ret;
  2721. }
  2722. bool CGameHandler::makeCustomAction( BattleAction &ba )
  2723. {
  2724. switch(ba.actionType)
  2725. {
  2726. case 1: //hero casts spell
  2727. {
  2728. const CGHeroInstance *h = gs->curB->heroes[ba.side];
  2729. const CGHeroInstance *secondHero = gs->curB->heroes[!ba.side];
  2730. if(!h)
  2731. {
  2732. tlog2 << "Wrong caster!\n";
  2733. return false;
  2734. }
  2735. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2736. {
  2737. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2738. return false;
  2739. }
  2740. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2741. ui8 skill = h->getSpellSchoolLevel(s); //skill level
  2742. if( !(h->canCastThisSpell(s)) //hero cannot cast this spell at all
  2743. || (h->mana < gs->curB->getSpellCost(s, h)) //not enough mana
  2744. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2745. || (gs->curB->castSpells[ba.side]) //spell has been cast
  2746. || (secondHero->hasBonusOfType(HeroBonus::SPELL_IMMUNITY, s->id)) //non - casting hero provides immunity for this spell
  2747. || (gs->battleMaxSpellLevel() < s->level) //non - casting hero stops caster from casting this spell
  2748. )
  2749. {
  2750. tlog2 << "Spell cannot be cast!\n";
  2751. return false;
  2752. }
  2753. sendAndApply(&StartAction(ba)); //start spell casting
  2754. SpellCast sc;
  2755. sc.side = ba.side;
  2756. sc.id = ba.additionalInfo;
  2757. sc.skill = skill;
  2758. sc.tile = ba.destinationTile;
  2759. sc.dmgToDisplay = 0;
  2760. //calculating affected creatures for all spells
  2761. std::set<CStack*> attackedCres = gs->curB->getAttackedCreatures(s, h, ba.destinationTile);
  2762. for(std::set<CStack*>::const_iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2763. {
  2764. sc.affectedCres.insert((*it)->ID);
  2765. }
  2766. //checking if creatures resist
  2767. sc.resisted = calculateResistedStacks(s, h, secondHero, attackedCres);
  2768. //calculating dmg to display
  2769. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2770. {
  2771. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2772. continue;
  2773. sc.dmgToDisplay += gs->curB->calculateSpellDmg(s, h, *it);
  2774. }
  2775. sendAndApply(&sc);
  2776. //applying effects
  2777. switch(ba.additionalInfo) //spell id
  2778. {
  2779. case 15: //magic arrow
  2780. case 16: //ice bolt
  2781. case 17: //lightning bolt
  2782. case 18: //implosion
  2783. case 20: //frost ring
  2784. case 21: //fireball
  2785. case 22: //inferno
  2786. case 23: //meteor shower
  2787. case 24: //death ripple
  2788. case 25: //destroy undead
  2789. case 26: //armageddon
  2790. {
  2791. StacksInjured si;
  2792. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2793. {
  2794. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2795. continue;
  2796. BattleStackAttacked bsa;
  2797. bsa.flags |= 2;
  2798. bsa.effect = VLC->spellh->spells[ba.additionalInfo].mainEffectAnim;
  2799. bsa.damageAmount = gs->curB->calculateSpellDmg(s, h, *it);
  2800. bsa.stackAttacked = (*it)->ID;
  2801. bsa.attackerID = -1;
  2802. prepareAttacked(bsa,*it);
  2803. si.stacks.insert(bsa);
  2804. }
  2805. if(!si.stacks.empty())
  2806. sendAndApply(&si);
  2807. break;
  2808. }
  2809. case 27: //shield
  2810. case 28: //air shield
  2811. case 30: //protection from air
  2812. case 31: //protection from fire
  2813. case 32: //protection from water
  2814. case 33: //protection from earth
  2815. case 34: //anti-magic
  2816. case 41: //bless
  2817. case 42: //curse
  2818. case 43: //bloodlust
  2819. case 44: //precision
  2820. case 45: //weakness
  2821. case 46: //stone skin
  2822. case 47: //disrupting ray
  2823. case 48: //prayer
  2824. case 49: //mirth
  2825. case 50: //sorrow
  2826. case 51: //fortune
  2827. case 52: //misfortune
  2828. case 53: //haste
  2829. case 54: //slow
  2830. case 55: //slayer
  2831. case 56: //frenzy
  2832. case 58: //counterstrike
  2833. case 59: //berserk
  2834. case 60: //hypnotize
  2835. case 61: //forgetfulness
  2836. case 62: //blind
  2837. {
  2838. SetStackEffect sse;
  2839. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2840. {
  2841. if(vstd::contains(sc.resisted, (*it)->ID)) //this creature resisted the spell
  2842. continue;
  2843. sse.stacks.insert((*it)->ID);
  2844. }
  2845. sse.effect.id = ba.additionalInfo;
  2846. sse.effect.level = h->getSpellSchoolLevel(s);
  2847. sse.effect.turnsRemain = BattleInfo::calculateSpellDuration(s, h);
  2848. if(!sse.stacks.empty())
  2849. sendAndApply(&sse);
  2850. break;
  2851. }
  2852. case 37: //cure
  2853. case 38: //resurrection
  2854. case 39: //animate dead
  2855. {
  2856. StacksHealedOrResurrected shr;
  2857. for(std::set<CStack*>::iterator it = attackedCres.begin(); it != attackedCres.end(); ++it)
  2858. {
  2859. if(vstd::contains(sc.resisted, (*it)->ID) //this creature resisted the spell
  2860. || (s->id == 39 && !(*it)->hasFeatureOfType(StackFeature::UNDEAD)) //we try to cast animate dead on living stack
  2861. )
  2862. continue;
  2863. StacksHealedOrResurrected::HealInfo hi;
  2864. hi.stackID = (*it)->ID;
  2865. hi.healedHP = calculateHealedHP(h, s, *it);
  2866. shr.healedStacks.push_back(hi);
  2867. }
  2868. if(!shr.healedStacks.empty())
  2869. sendAndApply(&shr);
  2870. break;
  2871. }
  2872. case 64: //remove obstacle
  2873. {
  2874. ObstaclesRemoved obr;
  2875. for(int g=0; g<gs->curB->obstacles.size(); ++g)
  2876. {
  2877. std::vector<int> blockedHexes = VLC->heroh->obstacles[gs->curB->obstacles[g].ID].getBlocked(gs->curB->obstacles[g].pos);
  2878. if(vstd::contains(blockedHexes, ba.destinationTile)) //this obstacle covers given hex
  2879. {
  2880. obr.obstacles.insert(gs->curB->obstacles[g].uniqueID);
  2881. }
  2882. }
  2883. if(!obr.obstacles.empty())
  2884. sendAndApply(&obr);
  2885. break;
  2886. }
  2887. }
  2888. sendAndApply(&EndAction());
  2889. if( !gs->curB->getStack(gs->curB->activeStack, false)->alive() )
  2890. {
  2891. battleMadeAction.setn(true);
  2892. }
  2893. checkForBattleEnd(gs->curB->stacks);
  2894. if(battleResult.get())
  2895. {
  2896. endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  2897. }
  2898. return true;
  2899. }
  2900. }
  2901. return false;
  2902. }
  2903. void CGameHandler::handleTimeEvents()
  2904. {
  2905. gs->map->events.sort(evntCmp);
  2906. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2907. {
  2908. CMapEvent *ev = gs->map->events.front();
  2909. for(int player = 0; player < PLAYER_LIMIT; player++)
  2910. {
  2911. PlayerState *pinfo = gs->getPlayer(player);
  2912. if( pinfo //player exists
  2913. && (ev->players & 1<<player) //event is enabled to this player
  2914. && ((ev->computerAffected && !pinfo->human)
  2915. || (ev->humanAffected && pinfo->human)
  2916. )
  2917. )
  2918. {
  2919. //give resources
  2920. SetResources sr;
  2921. sr.player = player;
  2922. sr.res = pinfo->resources;
  2923. //prepare dialog
  2924. InfoWindow iw;
  2925. iw.player = player;
  2926. iw.text << ev->message;
  2927. for (int i=0; i<ev->resources.size(); i++)
  2928. {
  2929. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2930. {
  2931. // If removing too much resources, adjust the
  2932. // amount so the total doesn't become negative.
  2933. if (sr.res[i] + ev->resources[i] < 0)
  2934. ev->resources[i] = -sr.res[i];
  2935. if(ev->resources[i]) //if non-zero res change
  2936. {
  2937. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2938. sr.res[i] += ev->resources[i];
  2939. }
  2940. }
  2941. }
  2942. if (iw.components.size())
  2943. {
  2944. sendAndApply(&sr); //update player resources if changed
  2945. }
  2946. sendAndApply(&iw); //show dialog
  2947. }
  2948. } //PLAYERS LOOP
  2949. if(ev->nextOccurence)
  2950. {
  2951. ev->firstOccurence += ev->nextOccurence;
  2952. gs->map->events.sort(evntCmp);
  2953. }
  2954. else
  2955. {
  2956. delete ev;
  2957. gs->map->events.pop_front();
  2958. }
  2959. }
  2960. }
  2961. bool CGameHandler::complain( const std::string &problem )
  2962. {
  2963. sendMessageToAll("Server encountered a problem: " + problem);
  2964. tlog1 << problem << std::endl;
  2965. return true;
  2966. }
  2967. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  2968. {
  2969. //TODO: write
  2970. return 0;
  2971. }
  2972. void CGameHandler::showGarrisonDialog( int upobj, int hid, bool removableUnits, const boost::function<void()> &cb )
  2973. {
  2974. ui8 player = getOwner(hid);
  2975. GarrisonDialog gd;
  2976. gd.hid = hid;
  2977. gd.objid = upobj;
  2978. {
  2979. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2980. gd.id = QID;
  2981. garrisonCallbacks[QID] = cb;
  2982. allowedExchanges[QID] = std::pair<si32,si32>(upobj,hid);
  2983. states.addQuery(player,QID);
  2984. QID++;
  2985. gd.removableUnits = removableUnits;
  2986. sendAndApply(&gd);
  2987. }
  2988. }
  2989. bool CGameHandler::isAllowedExchange( int id1, int id2 )
  2990. {
  2991. if(id1 == id2)
  2992. return true;
  2993. {
  2994. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  2995. for(std::map<ui32, std::pair<si32,si32> >::const_iterator i = allowedExchanges.begin(); i!=allowedExchanges.end(); i++)
  2996. if(id1 == i->second.first && id2 == i->second.second || id2 == i->second.first && id1 == i->second.second)
  2997. return true;
  2998. }
  2999. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  3000. if(o1->ID == TOWNI_TYPE)
  3001. {
  3002. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  3003. if(t->visitingHero == o2 || t->garrisonHero == o2)
  3004. return true;
  3005. }
  3006. if(o2->ID == TOWNI_TYPE)
  3007. {
  3008. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  3009. if(t->visitingHero == o1 || t->garrisonHero == o1)
  3010. return true;
  3011. }
  3012. if(o1->ID == HEROI_TYPE && o2->ID == HEROI_TYPE
  3013. && distance(o1->pos, o2->pos) < 2) //hero stands on the same tile or on the neighbouring tiles
  3014. {
  3015. //TODO: it's workaround, we should check if first hero visited second and player hasn't closed exchange window
  3016. //(to block moving stacks for free [without visiting] beteen heroes)
  3017. return true;
  3018. }
  3019. return false;
  3020. }
  3021. void CGameHandler::objectVisited( const CGObjectInstance * obj, const CGHeroInstance * h )
  3022. {
  3023. obj->onHeroVisit(h);
  3024. }
  3025. bool CGameHandler::buildBoat( ui32 objid )
  3026. {
  3027. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  3028. int boatType = 1;
  3029. if(obj->state())
  3030. {
  3031. complain("Cannot build boat in this shipyard!");
  3032. return false;
  3033. }
  3034. else if(obj->o->ID == TOWNI_TYPE
  3035. && !vstd::contains((static_cast<const CGTownInstance*>(obj))->builtBuildings,6))
  3036. {
  3037. complain("Cannot build boat in the town - no shipyard!");
  3038. return false;
  3039. }
  3040. //TODO use "real" cost via obj->getBoatCost
  3041. if(getResource(obj->o->tempOwner, 6) < 1000 || getResource(obj->o->tempOwner, 0) < 10)
  3042. {
  3043. complain("Not enough resources to build a boat!");
  3044. return false;
  3045. }
  3046. int3 tile = obj->bestLocation();
  3047. if(!gs->map->isInTheMap(tile))
  3048. {
  3049. complain("Cannot find appropriate tile for a boat!");
  3050. return false;
  3051. }
  3052. //take boat cost
  3053. SetResources sr;
  3054. sr.player = obj->o->tempOwner;
  3055. sr.res = gs->getPlayer(obj->o->tempOwner)->resources;
  3056. sr.res[0] -= 10;
  3057. sr.res[6] -= 1000;
  3058. sendAndApply(&sr);
  3059. //create boat
  3060. NewObject no;
  3061. no.ID = 8;
  3062. if (obj->o->ID == TOWNI_TYPE)
  3063. { //check what kind of creatures are avaliable in town
  3064. if (VLC->creh->creatures[(static_cast<const CGTownInstance*>(obj))->creatures[0].second[0]].isGood())
  3065. boatType = 1;
  3066. else if (VLC->creh->creatures[(static_cast<const CGTownInstance*>(obj))->creatures[0].second[0]].isEvil())
  3067. boatType = 0;
  3068. else //neutral
  3069. boatType = 2;
  3070. }
  3071. no.subID = boatType;
  3072. no.pos = tile + int3(1,0,0);
  3073. sendAndApply(&no);
  3074. return true;
  3075. }
  3076. void CGameHandler::engageIntoBattle( ui8 player )
  3077. {
  3078. if(vstd::contains(states.players, player))
  3079. states.setFlag(player,&PlayerStatus::engagedIntoBattle,true);
  3080. //notify interfaces
  3081. PlayerBlocked pb;
  3082. pb.player = player;
  3083. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  3084. sendAndApply(&pb);
  3085. }