CGameHandler.cpp 91 KB

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