CGameHandler.cpp 85 KB

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