CGameHandler.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CGeneralTextHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CTownHandler.h"
  10. #include "../CGameState.h"
  11. #include "../lib/CondSh.h"
  12. #include "../lib/Connection.h"
  13. #include "../lib/NetPacks.h"
  14. #include "../lib/VCMI_Lib.h"
  15. #include "../map.h"
  16. #include "CGameHandler.h"
  17. #include <boost/bind.hpp>
  18. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  19. #include <boost/foreach.hpp>
  20. #include <boost/thread.hpp>
  21. #include <boost/thread/shared_mutex.hpp>
  22. #include <fstream>
  23. #ifndef _MSC_VER
  24. #include <boost/thread/xtime.hpp>
  25. #endif
  26. extern bool end2;
  27. #include "../lib/BattleAction.h"
  28. #ifdef min
  29. #undef min
  30. #endif
  31. #ifdef max
  32. #undef max
  33. #endif
  34. #define NEW_ROUND BattleNextRound bnr;\
  35. bnr.round = gs->curB->round + 1;\
  36. sendAndApply(&bnr);
  37. boost::mutex gsm;
  38. ui32 CGameHandler::QID = 1;
  39. CondSh<bool> battleMadeAction;
  40. CondSh<BattleResult *> battleResult(NULL);
  41. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  42. class CMP_stack
  43. {
  44. public:
  45. inline bool operator ()(const CStack* a, const CStack* b)
  46. {
  47. return (a->speed())>(b->speed());
  48. }
  49. } cmpst ;
  50. double distance(int3 a, int3 b)
  51. {
  52. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  53. }
  54. int getSchoolLevel(const CGHeroInstance *h, const CSpell *s)
  55. {
  56. ui8 ret = 0;
  57. if(s->fire)
  58. ret = std::max(ret,h->getSecSkillLevel(14));
  59. if(s->air)
  60. ret = std::max(ret,h->getSecSkillLevel(15));
  61. if(s->water)
  62. ret = std::max(ret,h->getSecSkillLevel(16));
  63. if(s->earth)
  64. ret = std::max(ret,h->getSecSkillLevel(17));
  65. return ret;
  66. }
  67. void giveExp(BattleResult &r)
  68. {
  69. r.exp[0] = 0;
  70. r.exp[1] = 0;
  71. for(std::set<std::pair<ui32,si32> >::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  72. {
  73. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  74. }
  75. }
  76. //bool CGameState::checkFunc(int obid, std::string name)
  77. //{
  78. // if (objscr.find(obid)!=objscr.end())
  79. // {
  80. // if(objscr[obid].find(name)!=objscr[obid].end())
  81. // {
  82. // return true;
  83. // }
  84. // }
  85. // return false;
  86. //}
  87. PlayerStatus PlayerStatuses::operator[](ui8 player)
  88. {
  89. boost::unique_lock<boost::mutex> l(mx);
  90. if(players.find(player) != players.end())
  91. {
  92. return players[player];
  93. }
  94. else
  95. {
  96. throw std::string("No such player!");
  97. }
  98. }
  99. void PlayerStatuses::addPlayer(ui8 player)
  100. {
  101. boost::unique_lock<boost::mutex> l(mx);
  102. players[player];
  103. }
  104. bool PlayerStatuses::hasQueries(ui8 player)
  105. {
  106. boost::unique_lock<boost::mutex> l(mx);
  107. if(players.find(player) != players.end())
  108. {
  109. return players[player].queries.size();
  110. }
  111. else
  112. {
  113. throw std::string("No such player!");
  114. }
  115. }
  116. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  117. {
  118. boost::unique_lock<boost::mutex> l(mx);
  119. if(players.find(player) != players.end())
  120. {
  121. return players[player].*flag;
  122. }
  123. else
  124. {
  125. throw std::string("No such player!");
  126. }
  127. }
  128. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  129. {
  130. boost::unique_lock<boost::mutex> l(mx);
  131. if(players.find(player) != players.end())
  132. {
  133. players[player].*flag = val;
  134. }
  135. else
  136. {
  137. throw std::string("No such player!");
  138. }
  139. cv.notify_all();
  140. }
  141. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  142. {
  143. boost::unique_lock<boost::mutex> l(mx);
  144. if(players.find(player) != players.end())
  145. {
  146. players[player].queries.insert(id);
  147. }
  148. else
  149. {
  150. throw std::string("No such player!");
  151. }
  152. cv.notify_all();
  153. }
  154. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  155. {
  156. boost::unique_lock<boost::mutex> l(mx);
  157. if(players.find(player) != players.end())
  158. {
  159. players[player].queries.erase(id);
  160. }
  161. else
  162. {
  163. throw std::string("No such player!");
  164. }
  165. cv.notify_all();
  166. }
  167. //void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  168. //{
  169. // std::vector<int> tempv = script->yourObjects();
  170. // for (unsigned i=0;i<tempv.size();i++)
  171. // {
  172. // (*mapa)[tempv[i]]=script;
  173. // }
  174. // cppscripts.insert(script);
  175. //}
  176. template <typename T>
  177. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  178. {
  179. fun(args[which]);
  180. }
  181. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  182. {
  183. SetSecSkill sss;
  184. sss.id = ID;
  185. sss.which = which;
  186. sss.val = val;
  187. sss.abs = abs;
  188. sendAndApply(&sss);
  189. }
  190. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  191. {
  192. SetPrimSkill sps;
  193. sps.id = ID;
  194. sps.which = which;
  195. sps.abs = abs;
  196. sps.val = val;
  197. sendAndApply(&sps);
  198. if(which==4) //only for exp - hero may level up
  199. {
  200. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  201. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  202. {
  203. //give prim skill
  204. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  205. int r = rand()%100, pom=0, x=0;
  206. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  207. for(;x<PRIMARY_SKILLS;x++)
  208. {
  209. pom += hero->type->heroClass->primChance[x].*g;
  210. if(r<pom)
  211. break;
  212. }
  213. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  214. SetPrimSkill sps;
  215. sps.id = ID;
  216. sps.which = x;
  217. sps.abs = false;
  218. sps.val = 1;
  219. sendAndApply(&sps);
  220. HeroLevelUp hlu;
  221. hlu.heroid = ID;
  222. hlu.primskill = x;
  223. hlu.level = hero->level+1;
  224. //picking sec. skills for choice
  225. std::set<int> basicAndAdv, expert, none;
  226. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  227. for(unsigned i=0;i<hero->secSkills.size();i++)
  228. {
  229. if(hero->secSkills[i].second < 3)
  230. basicAndAdv.insert(hero->secSkills[i].first);
  231. else
  232. expert.insert(hero->secSkills[i].first);
  233. none.erase(hero->secSkills[i].first);
  234. }
  235. //first offered skill
  236. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  237. {
  238. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  239. none.erase(hlu.skills.back());
  240. }
  241. else if(basicAndAdv.size())
  242. {
  243. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  244. hlu.skills.push_back(s);
  245. basicAndAdv.erase(s);
  246. }
  247. //second offered skill
  248. if(basicAndAdv.size())
  249. {
  250. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  251. }
  252. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  253. {
  254. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  255. }
  256. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  257. {
  258. 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));
  259. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  260. }
  261. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  262. {
  263. changeSecSkill(ID,hlu.skills.back(),1,false);
  264. sendAndApply(&hlu);
  265. }
  266. else //apply and send info
  267. {
  268. sendAndApply(&hlu);
  269. }
  270. }
  271. }
  272. }
  273. CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  274. {
  275. CCreatureSet ret(set);
  276. for(int i=0; i<bat->stacks.size();i++)
  277. {
  278. CStack *st = bat->stacks[i];
  279. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  280. {
  281. if(st->alive())
  282. ret.slots[st->slot].second = st->amount;
  283. else
  284. ret.slots.erase(st->slot);
  285. }
  286. }
  287. return ret;
  288. }
  289. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  290. {
  291. BattleInfo *curB = new BattleInfo;
  292. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  293. NEW_ROUND;
  294. //TODO: pre-tactic stuff, call scripts etc.
  295. //tactic round
  296. {
  297. NEW_ROUND;
  298. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  299. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  300. {
  301. //TODO: tactic round (round -1)
  302. }
  303. }
  304. //main loop
  305. while(!battleResult.get()) //till the end of the battle ;]
  306. {
  307. NEW_ROUND;
  308. std::vector<CStack*> & stacks = (gs->curB->stacks);
  309. const BattleInfo & curB = *gs->curB;
  310. //stack loop
  311. CStack *next;
  312. while(!battleResult.get() && (next=gs->curB->getNextStack()))
  313. {
  314. next->state -= WAITING; //if stack was waiting it'll now make move, so it won't be "waiting" anymore
  315. //check for bad morale => freeze
  316. if(next->Morale() < 0)
  317. {
  318. if( rand()%24 < (-next->Morale())*2 )
  319. {
  320. //unit loses its turn - empty freeze action
  321. BattleAction ba;
  322. ba.actionType = 11;
  323. ba.additionalInfo = 1;
  324. ba.side = !next->attackerOwned;
  325. ba.stackNumber = next->ID;
  326. sendAndApply(&StartAction(ba));
  327. sendDataToClients(ui16(3008));
  328. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  329. continue;
  330. }
  331. }
  332. askInterfaceForMove:
  333. //ask interface and wait for answer
  334. {
  335. BattleSetActiveStack sas;
  336. sas.stack = next->ID;
  337. sendAndApply(&sas);
  338. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  339. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  340. battleMadeAction.cond.wait(lock);
  341. battleMadeAction.data = false;
  342. }
  343. //we're after action, all results applied
  344. checkForBattleEnd(stacks); //check if this action ended the battle
  345. //check for good morale
  346. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  347. && !vstd::contains(next->state,DEFENDING)
  348. && !vstd::contains(next->state,WAITING)
  349. && next->alive()
  350. && next->Morale() > 0
  351. )
  352. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  353. goto askInterfaceForMove; //move this stack once more
  354. }
  355. }
  356. //unblock engaged players
  357. if(hero1->tempOwner<PLAYER_LIMIT)
  358. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  359. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  360. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  361. //casualties among heroes armies
  362. SetGarrisons sg;
  363. if(hero1)
  364. sg.garrs[hero1->id] = takeCasualties(hero1->tempOwner,hero1->army,gs->curB);
  365. if(hero2)
  366. sg.garrs[hero2->id] = takeCasualties(hero2->tempOwner,hero2->army,gs->curB);
  367. sendAndApply(&sg);
  368. //end battle, remove all info, free memory
  369. giveExp(*battleResult.data);
  370. sendAndApply(battleResult.data);
  371. if(cb)
  372. cb(battleResult.data);
  373. //if one hero has lost we will erase him
  374. if(battleResult.data->winner!=0 && hero1)
  375. {
  376. RemoveObject ro(hero1->id);
  377. sendAndApply(&ro);
  378. }
  379. if(battleResult.data->winner!=1 && hero2)
  380. {
  381. RemoveObject ro(hero2->id);
  382. sendAndApply(&ro);
  383. }
  384. //give exp
  385. if(battleResult.data->exp[0] && hero1)
  386. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  387. if(battleResult.data->exp[1] && hero2)
  388. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  389. delete battleResult.data;
  390. }
  391. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, CStack *def)
  392. {
  393. bsa.killedAmount = bsa.damageAmount / def->creature->hitPoints;
  394. unsigned damageFirst = bsa.damageAmount % def->creature->hitPoints;
  395. if( def->firstHPleft <= damageFirst )
  396. {
  397. bsa.killedAmount++;
  398. bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  399. }
  400. else
  401. {
  402. bsa.newHP = def->firstHPleft - damageFirst;
  403. }
  404. if(def->amount <= bsa.killedAmount) //stack killed
  405. {
  406. bsa.newAmount = 0;
  407. bsa.flags |= 1;
  408. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  409. }
  410. else
  411. {
  412. bsa.newAmount = def->amount - bsa.killedAmount;
  413. }
  414. }
  415. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  416. {
  417. bat.stackAttacking = att->ID;
  418. bat.bsa.stackAttacked = def->ID;
  419. bat.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
  420. if(att->Luck() > 0 && rand()%24 < att->Luck())
  421. {
  422. bat.bsa.damageAmount *= 2;
  423. bat.bsa.flags |= 4;
  424. }
  425. prepareAttacked(bat.bsa,def);
  426. }
  427. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  428. {
  429. try
  430. {
  431. ui16 pom;
  432. while(!end2)
  433. {
  434. c >> pom;
  435. bool blockvis = false;
  436. switch(pom)
  437. {
  438. case 98:
  439. {
  440. std::string fname;
  441. Mapa * mapa;
  442. c >> fname;
  443. {
  444. sendMessageTo(c,"Serializing game info...");
  445. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vlgm1");
  446. char hlp[8] = "VCMISVG";
  447. save << hlp << version << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  448. }
  449. {
  450. sendMessageTo(c,"Serializing server info...");
  451. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vsgm1");
  452. save << *this;
  453. }
  454. sendMessageTo(c,"Game has been succesfully saved!");
  455. break;
  456. }
  457. case 99: //end!
  458. {
  459. tlog0 << "We have been requested to close.\n";
  460. exit(0);
  461. }
  462. case 100: //my interface ended its turn
  463. {
  464. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  465. break;
  466. }
  467. case 500: //dismiss hero
  468. {
  469. si32 id;
  470. c >> id;
  471. RemoveObject rh(id);
  472. sendAndApply(&rh);
  473. break;
  474. }
  475. case 501://interface wants to move hero
  476. {
  477. int3 start, end;
  478. si32 id;
  479. c >> id >> start >> end;
  480. tlog5 << "Interface wants to move hero "<<id << " from "<<start << " to " << end << std::endl;
  481. int3 hmpos = end + int3(-1,0,0);
  482. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  483. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  484. int cost = gs->getMovementCost(h,start,end,h->movement);
  485. TryMoveHero tmh;
  486. tmh.id = id;
  487. tmh.start = start;
  488. tmh.end = end;
  489. tmh.result = 0;
  490. tmh.movePoints = h->movement;
  491. if((h->getOwner() != gs->currentPlayer) //not turn of that hero
  492. || (distance(start,end)>=1.5) //tiles are not neighouring
  493. || (h->movement < cost && h->movement < 100) //lack of movement points
  494. || (t.tertype == rock) //rock
  495. || (!h->canWalkOnSea() && t.tertype == water)
  496. || (t.blocked && !t.visitable) //tile is blocked andnot visitable
  497. )
  498. goto fail;
  499. //check if there is blocking visitable object
  500. blockvis = false;
  501. tmh.movePoints = h->movement = std::max(si32(0),h->movement-cost); //take move points
  502. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  503. {
  504. if(obj->blockVisit)
  505. {
  506. blockvis = true;
  507. break;
  508. }
  509. }
  510. //we start moving
  511. if(blockvis)//interaction with blocking object (like resources)
  512. {
  513. sendAndApply(&tmh); //failed to move to that tile but we visit object
  514. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  515. {
  516. if (obj->blockVisit)
  517. {
  518. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  519. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  520. //if(obj->state) //hard-coded function
  521. obj->onHeroVisit(h);
  522. }
  523. }
  524. tlog5 << "Blocing visit at " << hmpos << std::endl;
  525. break;
  526. }
  527. else //normal move
  528. {
  529. tmh.result = 1;
  530. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x-1][start.y][start.z].visitableObjects)
  531. {
  532. //TODO: allow to handle this in script-languages
  533. //if(obj->state) //hard-coded function
  534. obj->onHeroLeave(h);
  535. }
  536. tmh.fowRevealed = gs->tilesToReveal(h->getPosition(false),h->getSightDistance(),h->tempOwner);
  537. sendAndApply(&tmh);
  538. tlog5 << "Moved to " <<tmh.end<<std::endl;
  539. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  540. {
  541. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  542. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  543. //if(obj->state) //hard-coded function
  544. obj->onHeroVisit(h);
  545. }
  546. }
  547. tlog5 << "Movement end!\n";
  548. break;
  549. fail:
  550. tlog2 << "Movement failed to " << tmh.end << std::endl;
  551. sendAndApply(&tmh);
  552. break;
  553. }
  554. case 502: //swap creatures in garrison
  555. {
  556. ui8 what, p1, p2; si32 id1, id2;
  557. c >> what >> id1 >> p1 >> id2 >> p2;
  558. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  559. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  560. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  561. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  562. if(what==1) //swap
  563. {
  564. std::swap(S1.slots[p1],S2.slots[p2]);
  565. if(!S1.slots[p1].second)
  566. S1.slots.erase(p1);
  567. if(!S2.slots[p2].second)
  568. S2.slots.erase(p2);
  569. }
  570. else if(what==2)//merge
  571. {
  572. if(S1.slots[p1].first != S2.slots[p2].first) break; //not same creature
  573. S2.slots[p2].second += S1.slots[p1].second;
  574. S1.slots.erase(p1);
  575. }
  576. else if(what==3) //split
  577. {
  578. si32 val;
  579. c >> val;
  580. if( vstd::contains(S2.slots,p2) //dest. slot not free
  581. || !vstd::contains(S1.slots,p1) //no creatures to split
  582. || S1.slots[p1].second < val //not enough creatures
  583. || val<1 //val must be positive
  584. )
  585. break;
  586. S2.slots[p2].first = S1.slots[p1].first;
  587. S2.slots[p2].second = val;
  588. S1.slots[p1].second -= val;
  589. if(!S1.slots[p1].second) //if we've moved all creatures
  590. S1.slots.erase(p1);
  591. }
  592. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  593. || (s2->needsLastStack() && !S2.slots.size())
  594. )
  595. {
  596. break; //leave without applying changes to garrison
  597. }
  598. SetGarrisons sg;
  599. sg.garrs[id1] = S1;
  600. if(s1 != s2)
  601. sg.garrs[id2] = S2;
  602. sendAndApply(&sg);
  603. break;
  604. }
  605. case 503: //disband creature
  606. {
  607. si32 id;
  608. ui8 pos;
  609. c >> id >> pos;
  610. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  611. s1->army.slots.erase(pos);
  612. SetGarrisons sg;
  613. sg.garrs[id] = s1->army;
  614. sendAndApply(&sg);
  615. break;
  616. }
  617. case 504: //build structure
  618. {
  619. si32 tid, bid;
  620. c >> tid >> bid;
  621. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  622. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  623. if(gs->canBuildStructure(t,bid) != 7)
  624. {
  625. sendMessageTo(c,"Cannot build that building!");
  626. break;
  627. }
  628. NewStructures ns;
  629. ns.tid = tid;
  630. if(bid>36) //upg dwelling
  631. {
  632. if(t->getHordeLevel(0) == (bid-37))
  633. ns.bid.insert(19);
  634. else if(t->getHordeLevel(1) == (bid-37))
  635. ns.bid.insert(25);
  636. }
  637. else if(bid >= 30) //bas. dwelling
  638. {
  639. SetAvailableCreatures ssi;
  640. ssi.tid = tid;
  641. ssi.creatures = t->strInfo.creatures;
  642. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  643. sendAndApply(&ssi);
  644. }
  645. ns.bid.insert(bid);
  646. ns.builded = t->builded + 1;
  647. sendAndApply(&ns);
  648. SetResources sr;
  649. sr.player = t->tempOwner;
  650. sr.res = gs->players[t->tempOwner].resources;
  651. for(int i=0;i<7;i++)
  652. sr.res[i]-=b->resources[i];
  653. sendAndApply(&sr);
  654. if(bid<5) //it's mage guild
  655. {
  656. if(t->visitingHero)
  657. giveSpells(t,t->visitingHero);
  658. if(t->garrisonHero)
  659. giveSpells(t,t->garrisonHero);
  660. }
  661. break;
  662. }
  663. case 506: //recruit creature
  664. {
  665. si32 objid, ser=-1; //ser - used dwelling level
  666. ui32 crid, cram; //recruited creature id and amount
  667. c >> objid >> crid >> cram;
  668. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  669. //verify
  670. bool found = false;
  671. typedef std::pair<const int,int> Parka;
  672. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  673. {
  674. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  675. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  676. {
  677. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  678. ser = av->first;
  679. break;
  680. }
  681. }
  682. int slot = t->army.getSlotFor(crid);
  683. if(!found || //no such creature
  684. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  685. cram<=0 ||
  686. slot<0 )
  687. break;
  688. //recruit
  689. SetResources sr;
  690. sr.player = t->tempOwner;
  691. for(int i=0;i<RESOURCE_QUANTITY;i++)
  692. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  693. SetAvailableCreatures sac;
  694. sac.tid = objid;
  695. sac.creatures = t->strInfo.creatures;
  696. sac.creatures[ser] -= cram;
  697. SetGarrisons sg;
  698. sg.garrs[objid] = t->army;
  699. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  700. {
  701. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  702. }
  703. else //add creatures to a already existing stack
  704. {
  705. sg.garrs[objid].slots[slot].second += cram;
  706. }
  707. sendAndApply(&sr);
  708. sendAndApply(&sac);
  709. sendAndApply(&sg);
  710. break;
  711. }
  712. case 507://upgrade creature
  713. {
  714. ui32 objid, upgID;
  715. ui8 pos;
  716. c >> objid >> pos >> upgID;
  717. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  718. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  719. int player = obj->tempOwner;
  720. int crQuantity = obj->army.slots[pos].second;
  721. //check if upgrade is possible
  722. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  723. break;
  724. //check if player has enough resources
  725. for(int i=0;i<ui.cost.size();i++)
  726. {
  727. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  728. {
  729. if(gs->players[player].resources[j->first] < j->second*crQuantity)
  730. goto upgend;
  731. }
  732. }
  733. //take resources
  734. for(int i=0;i<ui.cost.size();i++)
  735. {
  736. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  737. {
  738. SetResource sr;
  739. sr.player = player;
  740. sr.resid = j->first;
  741. sr.val = gs->players[player].resources[j->first] - j->second*crQuantity;
  742. sendAndApply(&sr);
  743. }
  744. }
  745. {
  746. //upgrade creature
  747. SetGarrisons sg;
  748. sg.garrs[objid] = obj->army;
  749. sg.garrs[objid].slots[pos].first = upgID;
  750. sendAndApply(&sg);
  751. }
  752. upgend:
  753. break;
  754. }
  755. case 508: //garrison swap
  756. {
  757. si32 tid;
  758. c >> tid;
  759. CGTownInstance *town = gs->getTown(tid);
  760. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  761. {
  762. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  763. while(!cso.slots.empty())//while there are unmoved creatures
  764. {
  765. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  766. if(pos<0)
  767. goto handleConEnd;
  768. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  769. {
  770. csn.slots[pos].second += cso.slots.begin()->second.second;
  771. }
  772. else //move stack on the free pos
  773. {
  774. csn.slots[pos].first = cso.slots.begin()->second.first;
  775. csn.slots[pos].second = cso.slots.begin()->second.second;
  776. }
  777. cso.slots.erase(cso.slots.begin());
  778. }
  779. SetGarrisons sg;
  780. sg.garrs[town->visitingHero->id] = csn;
  781. sg.garrs[town->id] = csn;
  782. sendAndApply(&sg);
  783. SetHeroesInTown intown;
  784. intown.tid = tid;
  785. intown.visiting = -1;
  786. intown.garrison = town->visitingHero->id;
  787. sendAndApply(&intown);
  788. }
  789. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  790. {
  791. SetHeroesInTown intown;
  792. intown.tid = tid;
  793. intown.garrison = -1;
  794. intown.visiting = town->garrisonHero->id;
  795. sendAndApply(&intown);
  796. //town will be empty
  797. SetGarrisons sg;
  798. sg.garrs[tid] = CCreatureSet();
  799. sendAndApply(&sg);
  800. }
  801. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  802. {
  803. SetGarrisons sg;
  804. sg.garrs[town->id] = town->visitingHero->army;
  805. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  806. //sg.garrs[town->visitingHero->id] = town->visitingHero->army;
  807. SetHeroesInTown intown;
  808. intown.tid = tid;
  809. intown.garrison = town->visitingHero->id;
  810. intown.visiting = town->garrisonHero->id;
  811. sendAndApply(&intown);
  812. sendAndApply(&sg);
  813. }
  814. else
  815. {
  816. tlog3 << "Warning, wrong garrison swap command for " << tid << std::endl;
  817. }
  818. break;
  819. }
  820. case 509: //swap artifacts
  821. {
  822. si32 hid1, hid2;
  823. ui16 slot1, slot2;
  824. c >> hid1 >> slot1 >> hid2 >> slot2;
  825. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  826. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  827. break;
  828. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  829. h2->setArtAtPos(slot2,a1);
  830. h1->setArtAtPos(slot1,a2);
  831. SetHeroArtifacts sha;
  832. sha.hid = hid1;
  833. sha.artifacts = h1->artifacts;
  834. sha.artifWorn = h1->artifWorn;
  835. sendAndApply(&sha);
  836. if(hid1 != hid2)
  837. {
  838. sha.hid = hid2;
  839. sha.artifacts = h2->artifacts;
  840. sha.artifWorn = h2->artifWorn;
  841. sendAndApply(&sha);
  842. }
  843. break;
  844. }
  845. case 510: //buy artifact
  846. {
  847. ui32 hid;
  848. si32 aid, bid;
  849. c >> hid >> aid;
  850. CGHeroInstance *hero = gs->getHero(hid);
  851. CGTownInstance *town = hero->visitedTown;
  852. if(aid==0) //spellbok
  853. {
  854. if(!vstd::contains(town->builtBuildings,si32(0)))
  855. break;
  856. SetResource sr;
  857. sr.player = hero->tempOwner;
  858. sr.resid = 6;
  859. sr.val = gs->players[hero->tempOwner].resources[6] - 500;
  860. sendAndApply(&sr);
  861. SetHeroArtifacts sha;
  862. sha.hid = hid;
  863. sha.artifacts = hero->artifacts;
  864. sha.artifWorn = hero->artifWorn;
  865. sha.artifWorn[17] = 0;
  866. sendAndApply(&sha);
  867. giveSpells(town,hero);
  868. }
  869. else if(aid < 7 && aid > 3) //war machine
  870. {
  871. int price = VLC->arth->artifacts[aid].price;
  872. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  873. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  874. || gs->players[hero->tempOwner].resources[6] < price //no gold
  875. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  876. {
  877. break;
  878. }
  879. SetResource sr;
  880. sr.player = hero->tempOwner;
  881. sr.resid = 6;
  882. sr.val = gs->players[hero->tempOwner].resources[6] - price;
  883. sendAndApply(&sr);
  884. SetHeroArtifacts sha;
  885. sha.hid = hid;
  886. sha.artifacts = hero->artifacts;
  887. sha.artifWorn = hero->artifWorn;
  888. sha.artifWorn[9+aid] = aid;
  889. sendAndApply(&sha);
  890. }
  891. break;
  892. }
  893. case 511: //trade at marketplace
  894. {
  895. ui8 player;
  896. ui32 mode, id1, id2, val;
  897. c >> player >> mode >> id1 >> id2 >> val;
  898. val = std::min(si32(val),gs->players[player].resources[id1]);
  899. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  900. uzysk /= gs->resVals[id2];
  901. SetResource sr;
  902. sr.player = player;
  903. sr.resid = id1;
  904. sr.val = gs->players[player].resources[id1] - val;
  905. sendAndApply(&sr);
  906. sr.resid = id2;
  907. sr.val = gs->players[player].resources[id2] + (int)uzysk;
  908. sendAndApply(&sr);
  909. break;
  910. }
  911. case 512:
  912. {
  913. si32 hid;
  914. ui8 formation;
  915. c >> hid >> formation;
  916. gs->getHero(hid)->army.formation = formation;
  917. break;
  918. }
  919. case 513:
  920. {
  921. std::string message;
  922. c >> message;
  923. bool cheated=true;
  924. sendDataToClients(ui16(513));
  925. sendDataToClients(ui8(*players.begin()));
  926. sendDataToClients(message);
  927. if(message == "vcmiistari") //give all spells and 999 mana
  928. {
  929. SetMana sm;
  930. ChangeSpells cs;
  931. cs.learn = 1;
  932. for(int i=0;i<VLC->spellh->spells.size();i++)
  933. {
  934. if(!VLC->spellh->spells[i].creatureAbility)
  935. cs.spells.insert(i);
  936. }
  937. sm.hid = cs.hid = gs->players[*players.begin()].currentSelection;
  938. sm.val = 999;
  939. if(gs->getHero(cs.hid))
  940. {
  941. sendAndApply(&cs);
  942. sendAndApply(&sm);
  943. }
  944. }
  945. else if(message == "vcmiainur") //gives 5 archangels into each slot
  946. {
  947. SetGarrisons sg;
  948. CGHeroInstance *hero = gs->getHero(gs->players[*players.begin()].currentSelection);
  949. if(!hero) break;
  950. sg.garrs[hero->id] = hero->army;
  951. for(int i=0;i<7;i++)
  952. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  953. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  954. sendAndApply(&sg);
  955. }
  956. else if(message == "vcmiangband") //gives 10 black knightinto each slot
  957. {
  958. SetGarrisons sg;
  959. CGHeroInstance *hero = gs->getHero(gs->players[*players.begin()].currentSelection);
  960. if(!hero) break;
  961. sg.garrs[hero->id] = hero->army;
  962. for(int i=0;i<7;i++)
  963. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  964. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  965. sendAndApply(&sg);
  966. }
  967. else if(message == "vcminoldor") //all war machines
  968. {
  969. CGHeroInstance *hero = gs->getHero(gs->players[*players.begin()].currentSelection);
  970. if(!hero) break;
  971. SetHeroArtifacts sha;
  972. sha.hid = hero->id;
  973. sha.artifacts = hero->artifacts;
  974. sha.artifWorn = hero->artifWorn;
  975. sha.artifWorn[13] = 4;
  976. sha.artifWorn[14] = 5;
  977. sha.artifWorn[15] = 6;
  978. sendAndApply(&sha);
  979. }
  980. else if(message == "vcminahar") //1000000 movement points
  981. {
  982. CGHeroInstance *hero = gs->getHero(gs->players[*players.begin()].currentSelection);
  983. if(!hero) break;
  984. SetMovePoints smp;
  985. smp.hid = hero->id;
  986. smp.val = 1000000;
  987. sendAndApply(&smp);
  988. }
  989. else if(message == "vcmiformenos") //give resources
  990. {
  991. SetResources sr;
  992. sr.player = *players.begin();
  993. sr.res = gs->players[sr.player].resources;
  994. for(int i=0;i<7;i++)
  995. sr.res[i] += 100;
  996. sr.res[6] += 19900;
  997. sendAndApply(&sr);
  998. }
  999. else if(message == "vcmieagles") //reveal FoW
  1000. {
  1001. FoWChange fc;
  1002. fc.player = *players.begin();
  1003. for(int i=0;i<gs->map->width;i++)
  1004. for(int j=0;j<gs->map->height;j++)
  1005. for(int k=0;k<gs->map->twoLevel+1;k++)
  1006. if(!gs->players[fc.player].fogOfWarMap[i][j][k])
  1007. fc.tiles.insert(int3(i,j,k));
  1008. sendAndApply(&fc);
  1009. }
  1010. else if(message == "vcmiglorfindel")
  1011. {
  1012. CGHeroInstance *hero = gs->getHero(gs->players[*players.begin()].currentSelection);
  1013. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  1014. }
  1015. else
  1016. cheated = false;
  1017. if(cheated)
  1018. {
  1019. message = "CHEATER!!!";
  1020. sendDataToClients(ui16(513));
  1021. sendDataToClients(ui8(*players.begin()));
  1022. sendDataToClients(message);
  1023. }
  1024. break;
  1025. }
  1026. case 514:
  1027. {
  1028. SetSelection ss;
  1029. c >> ss;
  1030. sendAndApply(&ss);
  1031. break;
  1032. }
  1033. case 515:
  1034. {
  1035. ui32 tid;
  1036. ui8 hid;
  1037. c >> tid >> hid;
  1038. CGTownInstance *t = gs->getTown(tid);
  1039. if(!vstd::contains(players,t->tempOwner) //not our town
  1040. || !vstd::contains(t->builtBuildings,5) //no tavern in the town
  1041. || gs->players[t->tempOwner].resources[6]<2500 //not enough gold
  1042. || t->visitingHero //there is visiting hero - no place
  1043. || gs->players[t->tempOwner].heroes.size()>7 //8 hero limit
  1044. )
  1045. break;
  1046. CGHeroInstance *nh = gs->players[t->tempOwner].availableHeroes[hid];
  1047. HeroRecruited hr;
  1048. hr.tid = tid;
  1049. hr.hid = nh->subID;
  1050. hr.player = t->tempOwner;
  1051. hr.tile = t->pos - int3(1,0,0);
  1052. sendAndApply(&hr);
  1053. SetAvailableHeroes sah;
  1054. (hid ? sah.hid2 : sah.hid1) = gs->hpool.pickHeroFor(false,t->tempOwner,t->town)->subID;
  1055. (hid ? sah.hid1 : sah.hid2) = gs->players[t->tempOwner].availableHeroes[!hid]->subID;
  1056. sah.player = t->tempOwner;
  1057. sah.flags = hid+1;
  1058. sendAndApply(&sah);
  1059. SetResource sr;
  1060. sr.player = t->tempOwner;
  1061. sr.resid = 6;
  1062. sr.val = gs->players[t->tempOwner].resources[6] - 2500;
  1063. sendAndApply(&sr);
  1064. break;
  1065. }
  1066. case 2001:
  1067. {
  1068. ui32 qid, answer;
  1069. c >> qid >> answer;
  1070. gsm.lock();
  1071. CFunctionList<void(ui32)> callb = callbacks[qid];
  1072. callbacks.erase(qid);
  1073. gsm.unlock();
  1074. callb(answer);
  1075. break;
  1076. }
  1077. case 3002:
  1078. {
  1079. BattleAction ba;
  1080. c >> ba;
  1081. switch(ba.actionType)
  1082. {
  1083. case 2: //walk
  1084. {
  1085. sendAndApply(&StartAction(ba)); //start movement
  1086. moveStack(ba.stackNumber,ba.destinationTile); //move
  1087. sendDataToClients(ui16(3008)); //end movement
  1088. break;
  1089. }
  1090. case 3: //defend
  1091. case 8: //wait
  1092. {
  1093. sendAndApply(&StartAction(ba));
  1094. sendDataToClients(ui16(3008));
  1095. break;
  1096. }
  1097. case 4: //retreat/flee
  1098. {
  1099. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  1100. //TODO: calculate casualties
  1101. //TODO: remove retreating hero from map and place it in recruitment list
  1102. BattleResult *br = new BattleResult;
  1103. br->result = 1;
  1104. br->winner = !ba.side; //fleeing side loses
  1105. gs->curB->calculateCasualties(br->casualties);
  1106. giveExp(*br);
  1107. battleResult.set(br);
  1108. break;
  1109. }
  1110. case 6: //walk or attack
  1111. {
  1112. sendAndApply(&StartAction(ba)); //start movement and attack
  1113. moveStack(ba.stackNumber,ba.destinationTile);
  1114. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1115. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  1116. if(curStack->position != ba.destinationTile) //we wasn't able to reach destination tile
  1117. {
  1118. tlog3<<"We cannot move this stack to its destination "<<curStack->creature->namePl<<std::endl;
  1119. }
  1120. if(!stackAtEnd)
  1121. {
  1122. tlog3 << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  1123. break;
  1124. }
  1125. ui16 curpos = curStack->position,
  1126. enemypos = stackAtEnd->position;
  1127. if( !(
  1128. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  1129. || (curStack->creature->isDoubleWide() //back <=> front
  1130. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  1131. || (stackAtEnd->creature->isDoubleWide() //front <=> back
  1132. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1133. || (stackAtEnd->creature->isDoubleWide() && curStack->creature->isDoubleWide()//back <=> back
  1134. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1135. )
  1136. )
  1137. {
  1138. tlog3 << "Attack cannot be performed!";
  1139. sendDataToClients(ui16(3008)); //end movement and attack
  1140. break;
  1141. }
  1142. //attack
  1143. BattleAttack bat;
  1144. prepareAttack(bat,curStack,stackAtEnd);
  1145. sendAndApply(&bat);
  1146. //counterattack
  1147. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  1148. && stackAtEnd->alive()
  1149. && stackAtEnd->counterAttacks
  1150. && !vstd::contains(stackAtEnd->abilities, SIEGE_WEAPON)) //TODO: support for multiple retaliatons per turn
  1151. {
  1152. prepareAttack(bat,stackAtEnd,curStack);
  1153. bat.flags |= 2;
  1154. sendAndApply(&bat);
  1155. }
  1156. //second attack
  1157. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  1158. && curStack->alive()
  1159. && stackAtEnd->alive() )
  1160. {
  1161. bat.flags = 0;
  1162. prepareAttack(bat,curStack,stackAtEnd);
  1163. sendAndApply(&bat);
  1164. }
  1165. sendDataToClients(ui16(3008)); //end movement and attack
  1166. break;
  1167. }
  1168. case 7: //shoot
  1169. {
  1170. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1171. *destStack= gs->curB->getStackT(ba.destinationTile);
  1172. if(!curStack //our stack exists
  1173. || !destStack //there is a stack at destination tile
  1174. || !curStack->shots //stack has shots
  1175. || gs->curB->isStackBlocked(curStack->ID) //we are not blocked
  1176. || !vstd::contains(curStack->abilities,SHOOTER) //our stack is shooting unit
  1177. )
  1178. break;
  1179. for(int g=0; g<curStack->effects.size(); ++g)
  1180. {
  1181. if(61 == curStack->effects[g].id) //forgetfulness
  1182. break;
  1183. }
  1184. sendAndApply(&StartAction(ba)); //start shooting
  1185. BattleAttack bat;
  1186. prepareAttack(bat,curStack,destStack);
  1187. bat.flags |= 1;
  1188. sendAndApply(&bat);
  1189. if(vstd::contains(curStack->abilities,TWICE_ATTACK) //if unit shots twice let's make another shot
  1190. && curStack->alive()
  1191. && destStack->alive()
  1192. && curStack->shots
  1193. )
  1194. {
  1195. prepareAttack(bat,curStack,destStack);
  1196. sendAndApply(&bat);
  1197. }
  1198. sendDataToClients(ui16(3008)); //end shooting
  1199. break;
  1200. }
  1201. }
  1202. battleMadeAction.setn(true);
  1203. break;
  1204. }
  1205. case 3003: //custom action (probably spell)
  1206. {
  1207. BattleAction ba;
  1208. c >> ba;
  1209. switch(ba.actionType)
  1210. {
  1211. case 1: //hero casts spell
  1212. {
  1213. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  1214. if(!h)
  1215. {
  1216. tlog2 << "Wrong caster!\n";
  1217. goto customactionend;
  1218. }
  1219. if(ba.additionalInfo >= VLC->spellh->spells.size())
  1220. {
  1221. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  1222. goto customactionend;
  1223. }
  1224. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  1225. ui8 skill = 0; //skill level
  1226. if(s->fire)
  1227. skill = std::max(skill,h->getSecSkillLevel(14));
  1228. if(s->air)
  1229. skill = std::max(skill,h->getSecSkillLevel(15));
  1230. if(s->water)
  1231. skill = std::max(skill,h->getSecSkillLevel(16));
  1232. if(s->earth)
  1233. skill = std::max(skill,h->getSecSkillLevel(17));
  1234. //TODO: skill level may be different on special terrain
  1235. if( !(vstd::contains(h->spells,ba.additionalInfo)) //hero doesn't know this spell
  1236. || (h->mana < s->costs[skill]) //not enough mana
  1237. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  1238. || (gs->curB->castedSpells[ba.side])
  1239. )
  1240. {
  1241. tlog2 << "Spell cannot be casted!\n";
  1242. goto customactionend;
  1243. }
  1244. sendAndApply(&StartAction(ba)); //start spell casting
  1245. //TODO: check resistances
  1246. #define SPELL_CAST_TEMPLATE_1(NUMBER, DURATION) SetStackEffect sse; \
  1247. if(getSchoolLevel(h,s) < 3) /*not expert */ \
  1248. { \
  1249. sse.stack = gs->curB->getStackT(ba.destinationTile)->ID; \
  1250. sse.effect.id = (NUMBER); \
  1251. sse.effect.level = getSchoolLevel(h,s); \
  1252. sse.effect.turnsRemain = (DURATION); /*! - any duration */ \
  1253. sendAndApply(&sse); \
  1254. } \
  1255. else \
  1256. { \
  1257. for(int it=0; it<gs->curB->stacks.size(); ++it) \
  1258. { \
  1259. /*if it's non negative spell and our unit or non positive spell and hostile unit */ \
  1260. if((VLC->spellh->spells[ba.additionalInfo].positiveness >= 0 && gs->curB->stacks[it]->owner == h->tempOwner) \
  1261. ||(VLC->spellh->spells[ba.additionalInfo].positiveness <= 0 && gs->curB->stacks[it]->owner != h->tempOwner ) \
  1262. ) \
  1263. { \
  1264. sse.stack = gs->curB->stacks[it]->ID; \
  1265. sse.effect.id = (NUMBER); \
  1266. sse.effect.level = getSchoolLevel(h,s); \
  1267. sse.effect.turnsRemain = (DURATION); \
  1268. sendAndApply(&sse); \
  1269. } \
  1270. } \
  1271. }
  1272. SpellCasted sc;
  1273. sc.side = ba.side;
  1274. sc.id = ba.additionalInfo;
  1275. sc.skill = skill;
  1276. sc.tile = ba.destinationTile;
  1277. sendAndApply(&sc);
  1278. switch(ba.additionalInfo) //spell id
  1279. {
  1280. case 15: //magic arrow
  1281. {
  1282. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  1283. if(!attacked) break;
  1284. BattleStackAttacked bsa;
  1285. bsa.flags |= 2;
  1286. bsa.effect = 64;
  1287. bsa.damageAmount = h->getPrimSkillLevel(2) * 10 + s->powers[getSchoolLevel(h,s)];
  1288. bsa.stackAttacked = attacked->ID;
  1289. prepareAttacked(bsa,attacked);
  1290. sendAndApply(&bsa);
  1291. break;
  1292. }
  1293. case 16: //ice bolt
  1294. {
  1295. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  1296. if(!attacked) break;
  1297. BattleStackAttacked bsa;
  1298. bsa.flags |= 2;
  1299. bsa.effect = 46;
  1300. bsa.damageAmount = h->getPrimSkillLevel(2) * 20 + s->powers[getSchoolLevel(h,s)];
  1301. bsa.stackAttacked = attacked->ID;
  1302. prepareAttacked(bsa,attacked);
  1303. sendAndApply(&bsa);
  1304. break;
  1305. }
  1306. case 17: //lightning bolt
  1307. {
  1308. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  1309. if(!attacked) break;
  1310. BattleStackAttacked bsa;
  1311. bsa.flags |= 2;
  1312. bsa.effect = 38;
  1313. bsa.damageAmount = h->getPrimSkillLevel(2) * 25 + s->powers[getSchoolLevel(h,s)];
  1314. bsa.stackAttacked = attacked->ID;
  1315. prepareAttacked(bsa,attacked);
  1316. sendAndApply(&bsa);
  1317. break;
  1318. }
  1319. case 18: //implosion
  1320. {
  1321. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  1322. if(!attacked) break;
  1323. BattleStackAttacked bsa;
  1324. bsa.flags |= 2;
  1325. bsa.effect = 10;
  1326. bsa.damageAmount = h->getPrimSkillLevel(2) * 75 + s->powers[getSchoolLevel(h,s)];
  1327. bsa.stackAttacked = attacked->ID;
  1328. prepareAttacked(bsa,attacked);
  1329. sendAndApply(&bsa);
  1330. break;
  1331. }
  1332. case 27: //shield
  1333. {
  1334. SPELL_CAST_TEMPLATE_1(27, h->getPrimSkillLevel(2))
  1335. break;
  1336. }
  1337. case 28: //air shield
  1338. {
  1339. SPELL_CAST_TEMPLATE_1(28, h->getPrimSkillLevel(2))
  1340. break;
  1341. }
  1342. case 41: //bless
  1343. {
  1344. SPELL_CAST_TEMPLATE_1(41, h->getPrimSkillLevel(2))
  1345. break;
  1346. }
  1347. case 42: //curse
  1348. {
  1349. SPELL_CAST_TEMPLATE_1(42, h->getPrimSkillLevel(2))
  1350. break;
  1351. }
  1352. case 43: //bloodlust
  1353. {
  1354. SPELL_CAST_TEMPLATE_1(43, h->getPrimSkillLevel(2))
  1355. break;
  1356. }
  1357. case 45: //weakness
  1358. {
  1359. SPELL_CAST_TEMPLATE_1(45, h->getPrimSkillLevel(2))
  1360. break;
  1361. }
  1362. case 46: //stone skin
  1363. {
  1364. SPELL_CAST_TEMPLATE_1(46, h->getPrimSkillLevel(2))
  1365. break;
  1366. }
  1367. case 48: //prayer
  1368. {
  1369. SPELL_CAST_TEMPLATE_1(48, h->getPrimSkillLevel(2))
  1370. break;
  1371. }
  1372. case 49: //mirth
  1373. {
  1374. SPELL_CAST_TEMPLATE_1(49, h->getPrimSkillLevel(2))
  1375. break;
  1376. }
  1377. case 50: //sorrow
  1378. {
  1379. SPELL_CAST_TEMPLATE_1(50, h->getPrimSkillLevel(2))
  1380. break;
  1381. }
  1382. case 51: //fortune
  1383. {
  1384. SPELL_CAST_TEMPLATE_1(51, h->getPrimSkillLevel(2))
  1385. break;
  1386. }
  1387. case 52: //misfortune
  1388. {
  1389. SPELL_CAST_TEMPLATE_1(52, h->getPrimSkillLevel(2))
  1390. break;
  1391. }
  1392. case 53: //haste
  1393. {
  1394. SPELL_CAST_TEMPLATE_1(53, h->getPrimSkillLevel(2))
  1395. break;
  1396. }
  1397. case 54: //slow
  1398. {
  1399. SPELL_CAST_TEMPLATE_1(54, h->getPrimSkillLevel(2))
  1400. break;
  1401. }
  1402. case 56: //frenzy
  1403. {
  1404. SPELL_CAST_TEMPLATE_1(56, 1)
  1405. break;
  1406. }
  1407. case 61: //forgetfulness
  1408. {
  1409. SPELL_CAST_TEMPLATE_1(61, h->getPrimSkillLevel(2))
  1410. break;
  1411. }
  1412. }
  1413. //TODO: spells to support possibly soon (list by Zamolxis):
  1414. /*- Magic Arrow
  1415. - Haste
  1416. - Bless
  1417. - Bloodlust
  1418. - Curse
  1419. - Dispel
  1420. - Shield
  1421. - Slow
  1422. - Stone Skin
  1423. - Lightning Bolt
  1424. - Ice Bolt
  1425. - Precision
  1426. - Blind
  1427. - Fire Wall
  1428. - Weakness
  1429. - Death Ripple */
  1430. sendDataToClients(ui16(3008)); //end casting
  1431. break;
  1432. }
  1433. }
  1434. customactionend:
  1435. break;
  1436. }
  1437. default:
  1438. throw std::string("Not supported client message!");
  1439. }
  1440. }
  1441. }
  1442. HANDLE_EXCEPTION(end2 = true);
  1443. handleConEnd:
  1444. tlog1 << "Ended handling connection\n";
  1445. #undef SPELL_CAST_TEMPLATE_1
  1446. }
  1447. void CGameHandler::moveStack(int stack, int dest)
  1448. {
  1449. CStack *curStack = gs->curB->getStack(stack),
  1450. *stackAtEnd = gs->curB->getStackT(dest);
  1451. //initing necessary tables
  1452. bool accessibility[BFIELD_SIZE];
  1453. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  1454. for(int b=0; b<BFIELD_SIZE; ++b)
  1455. {
  1456. accessibility[b] = false;
  1457. }
  1458. for(int g=0; g<accessible.size(); ++g)
  1459. {
  1460. accessibility[accessible[g]] = true;
  1461. }
  1462. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  1463. if(!stackAtEnd && curStack->creature->isDoubleWide() && !accessibility[dest])
  1464. {
  1465. if(curStack->attackerOwned)
  1466. {
  1467. if(accessibility[dest+1])
  1468. dest+=1;
  1469. }
  1470. else
  1471. {
  1472. if(accessibility[dest-1])
  1473. dest-=1;
  1474. }
  1475. }
  1476. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  1477. return;
  1478. //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
  1479. // return false;
  1480. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  1481. int tilesToMove = std::max((int)(path.size() - curStack->speed()), 0);
  1482. for(int v=path.size()-1; v>=tilesToMove; --v)
  1483. {
  1484. //inform clients about move
  1485. BattleStackMoved sm;
  1486. sm.stack = curStack->ID;
  1487. sm.tile = path[v];
  1488. sendAndApply(&sm);
  1489. }
  1490. }
  1491. CGameHandler::CGameHandler(void)
  1492. {
  1493. gs = NULL;
  1494. IObjectInterface::cb = this;
  1495. }
  1496. CGameHandler::~CGameHandler(void)
  1497. {
  1498. delete gs;
  1499. }
  1500. void CGameHandler::init(StartInfo *si, int Seed)
  1501. {
  1502. Mapa *map = new Mapa(si->mapname);
  1503. tlog0 << "Map loaded!" << std::endl;
  1504. gs = new CGameState();
  1505. tlog0 << "Gamestate created!" << std::endl;
  1506. gs->init(si,map,Seed);
  1507. tlog0 << "Gamestate initialized!" << std::endl;
  1508. /****************************LUA OBJECT SCRIPTS************************************************/
  1509. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  1510. //for (int i=0; i<lf->size(); i++)
  1511. //{
  1512. // try
  1513. // {
  1514. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  1515. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  1516. // CLuaCallback::registerFuncs(objs->is);
  1517. // //objs
  1518. // for (int j=0; j<temp->size(); j++)
  1519. // {
  1520. // int obid ; //obj ID
  1521. // int dspos = (*temp)[j].find_first_of('_');
  1522. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  1523. // std::string fname = (*temp)[j].substr(0,dspos);
  1524. // if (skrypty->find(obid)==skrypty->end())
  1525. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  1526. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  1527. // }
  1528. // delete temp;
  1529. // }HANDLE_EXCEPTION
  1530. //}
  1531. //delete lf;
  1532. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1533. states.addPlayer(i->first);
  1534. }
  1535. void CGameHandler::newTurn()
  1536. {
  1537. tlog5 << "Turn " << gs->day+1 << std::endl;
  1538. NewTurn n;
  1539. n.day = gs->day + 1;
  1540. n.resetBuilded = true;
  1541. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  1542. {
  1543. if(i->first == 255) continue;
  1544. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  1545. {
  1546. SetAvailableHeroes sah;
  1547. sah.player = i->first;
  1548. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle]);
  1549. if(h)
  1550. sah.hid1 = h->subID;
  1551. else
  1552. sah.hid1 = -1;
  1553. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle],sah.hid1);
  1554. if(h)
  1555. sah.hid2 = h->subID;
  1556. else
  1557. sah.hid2 = -1;
  1558. sendAndApply(&sah);
  1559. }
  1560. if(i->first>=PLAYER_LIMIT) continue;
  1561. SetResources r;
  1562. r.player = i->first;
  1563. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1564. r.res[j] = i->second.resources[j];
  1565. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  1566. {
  1567. NewTurn::Hero hth;
  1568. hth.id = h->id;
  1569. hth.move = h->maxMovePoints(true); //TODO: check if hero is really on the land
  1570. hth.mana = std::max(h->mana,std::min(h->mana+1+h->getSecSkillLevel(8), h->manaLimit())); //hero regains 1 mana point + mysticism lvel
  1571. n.heroes.insert(hth);
  1572. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  1573. {
  1574. case 1: //basic
  1575. r.res[6] += 125;
  1576. break;
  1577. case 2: //advanced
  1578. r.res[6] += 250;
  1579. break;
  1580. case 3: //expert
  1581. r.res[6] += 500;
  1582. break;
  1583. }
  1584. }
  1585. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  1586. {
  1587. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  1588. {
  1589. if((**j).town->primaryRes == 127) //we'll give wood and ore
  1590. {
  1591. r.res[0] += 1;
  1592. r.res[2] += 1;
  1593. }
  1594. else
  1595. {
  1596. r.res[(**j).town->primaryRes] += 1;
  1597. }
  1598. }
  1599. if(gs->getDate(1)==7) //first day of week
  1600. {
  1601. SetAvailableCreatures sac;
  1602. sac.tid = (**j).id;
  1603. sac.creatures = (**j).strInfo.creatures;
  1604. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  1605. {
  1606. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  1607. sac.creatures[k] += (**j).creatureGrowth(k);
  1608. }
  1609. n.cres.push_back(sac);
  1610. }
  1611. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  1612. r.res[6] += (**j).dailyIncome();
  1613. }
  1614. n.res.push_back(r);
  1615. }
  1616. sendAndApply(&n);
  1617. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  1618. for(size_t i = 0; i<gs->map->objects.size(); i++)
  1619. if(gs->map->objects[i])
  1620. gs->map->objects[i]->newTurn();
  1621. }
  1622. void CGameHandler::run(bool resume)
  1623. {
  1624. BOOST_FOREACH(CConnection *cc, conns)
  1625. {//init conn.
  1626. ui8 quantity, pom;
  1627. //ui32 seed;
  1628. if(!resume)
  1629. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  1630. (*cc) >> quantity; //how many players will be handled at that client
  1631. for(int i=0;i<quantity;i++)
  1632. {
  1633. (*cc) >> pom; //read player color
  1634. gsm.lock();
  1635. connections[pom] = cc;
  1636. gsm.unlock();
  1637. }
  1638. }
  1639. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1640. {
  1641. std::set<int> pom;
  1642. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1643. if(j->second == *i)
  1644. pom.insert(j->first);
  1645. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1646. }
  1647. /****************************SCRIPTS************************************************/
  1648. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  1649. /****************************C++ OBJECT SCRIPTS************************************************/
  1650. //std::map<int,CCPPObjectScript*> scripts;
  1651. //CScriptCallback * csc = new CScriptCallback();
  1652. //csc->gh = this;
  1653. //handleCPPObjS(&scripts,new CVisitableOPH(csc));
  1654. //handleCPPObjS(&scripts,new CVisitableOPW(csc));
  1655. //handleCPPObjS(&scripts,new CPickable(csc));
  1656. //handleCPPObjS(&scripts,new CMines(csc));
  1657. //handleCPPObjS(&scripts,new CTownScript(csc));
  1658. //handleCPPObjS(&scripts,new CHeroScript(csc));
  1659. //handleCPPObjS(&scripts,new CMonsterS(csc));
  1660. //handleCPPObjS(&scripts,new CCreatureGen(csc));
  1661. //handleCPPObjS(&scripts,new CTeleports(csc));
  1662. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  1663. //std::string temps("newObject");
  1664. //for (unsigned i=0; i<gs->map->objects.size(); i++)
  1665. //{
  1666. //c++ scripts
  1667. //if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  1668. //{
  1669. // gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  1670. // gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  1671. //}
  1672. //else
  1673. //{
  1674. // gs->map->objects[i]->state = NULL;
  1675. //}
  1676. //// lua scripts
  1677. //if(checkFunc(map->objects[i]->ID,temps))
  1678. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  1679. //}
  1680. while (!end2)
  1681. {
  1682. if(!resume)
  1683. newTurn();
  1684. else
  1685. resume = false;
  1686. std::map<ui8,PlayerState>::iterator i;
  1687. if(!resume)
  1688. i = gs->players.begin();
  1689. else
  1690. i = gs->players.find(gs->currentPlayer);
  1691. for(; i != gs->players.end(); i++)
  1692. {
  1693. 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
  1694. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1695. gs->currentPlayer = i->first;
  1696. *connections[i->first] << ui16(100) << i->first;
  1697. //wait till turn is done
  1698. boost::unique_lock<boost::mutex> lock(states.mx);
  1699. while(states.players[i->first].makingTurn && !end2)
  1700. {
  1701. boost::posix_time::time_duration p;
  1702. p = boost::posix_time::milliseconds(200);
  1703. #ifdef _MSC_VER
  1704. states.cv.timed_wait(lock,p);
  1705. #else
  1706. boost::xtime time={0,0};
  1707. time.nsec = static_cast<boost::xtime::xtime_nsec_t>(p.total_nanoseconds());
  1708. states.cv.timed_wait(lock,time);
  1709. #endif
  1710. }
  1711. }
  1712. }
  1713. }
  1714. namespace CGH
  1715. {
  1716. using namespace std;
  1717. void readItTo(ifstream & input, vector< vector<int> > & dest)
  1718. {
  1719. for(int j=0; j<7; ++j)
  1720. {
  1721. std::vector<int> pom;
  1722. for(int g=0; g<j+1; ++g)
  1723. {
  1724. int hlp; input>>hlp;
  1725. pom.push_back(hlp);
  1726. }
  1727. dest.push_back(pom);
  1728. }
  1729. }
  1730. }
  1731. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  1732. {
  1733. battleResult.set(NULL);
  1734. std::vector<CStack*> & stacks = (curB->stacks);
  1735. curB->tile = tile;
  1736. curB->siege = 0; //TODO: add sieges
  1737. curB->army1=army1;
  1738. curB->army2=army2;
  1739. curB->hero1=(hero1)?(hero1->id):(-1);
  1740. curB->hero2=(hero2)?(hero2->id):(-1);
  1741. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  1742. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  1743. curB->round = -2;
  1744. curB->activeStack = -1;
  1745. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  1746. {
  1747. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  1748. //base luck/morale calculations
  1749. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  1750. if(hero1)
  1751. {
  1752. stacks.back()->morale = hero1->getCurrentMorale(i->first,false);
  1753. stacks.back()->luck = hero1->getCurrentLuck(i->first,false);
  1754. }
  1755. else
  1756. {
  1757. stacks.back()->morale = 0;
  1758. stacks.back()->luck = 0;
  1759. }
  1760. stacks[stacks.size()-1]->ID = stacks.size()-1;
  1761. }
  1762. //initialization of positions
  1763. std::ifstream positions;
  1764. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1765. if(!positions.is_open())
  1766. {
  1767. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1768. }
  1769. std::string dump;
  1770. positions>>dump; positions>>dump;
  1771. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  1772. CGH::readItTo(positions, attackerLoose);
  1773. positions>>dump;
  1774. CGH::readItTo(positions, defenderLoose);
  1775. positions>>dump;
  1776. positions>>dump;
  1777. CGH::readItTo(positions, attackerTight);
  1778. positions>>dump;
  1779. CGH::readItTo(positions, defenderTight);
  1780. positions.close();
  1781. if(army1.formation)
  1782. for(int b=0; b<army1.slots.size(); ++b) //tight
  1783. {
  1784. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  1785. }
  1786. else
  1787. for(int b=0; b<army1.slots.size(); ++b) //loose
  1788. {
  1789. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  1790. }
  1791. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  1792. {
  1793. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  1794. //base luck/morale calculations
  1795. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  1796. if(hero2)
  1797. {
  1798. stacks.back()->morale = hero2->getCurrentMorale(i->first,false);
  1799. stacks.back()->luck = hero2->getCurrentLuck(i->first,false);
  1800. }
  1801. else
  1802. {
  1803. stacks.back()->morale = 0;
  1804. stacks.back()->luck = 0;
  1805. }
  1806. }
  1807. if(army2.formation)
  1808. for(int b=0; b<army2.slots.size(); ++b) //tight
  1809. {
  1810. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  1811. }
  1812. else
  1813. for(int b=0; b<army2.slots.size(); ++b) //loose
  1814. {
  1815. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  1816. }
  1817. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1818. {
  1819. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  1820. {
  1821. stacks[g]->position += 1;
  1822. }
  1823. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  1824. {
  1825. stacks[g]->position -= 1;
  1826. }
  1827. }
  1828. //adding war machines
  1829. if(hero1)
  1830. {
  1831. if(hero1->getArt(13)) //ballista
  1832. {
  1833. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero1->tempOwner, stacks.size(), true, 255));
  1834. stacks[stacks.size()-1]->position = 52;
  1835. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  1836. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  1837. }
  1838. if(hero1->getArt(14)) //ammo cart
  1839. {
  1840. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero1->tempOwner, stacks.size(), true, 255));
  1841. stacks[stacks.size()-1]->position = 18;
  1842. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  1843. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  1844. }
  1845. if(hero1->getArt(15)) //first aid tent
  1846. {
  1847. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero1->tempOwner, stacks.size(), true, 255));
  1848. stacks[stacks.size()-1]->position = 154;
  1849. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  1850. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  1851. }
  1852. }
  1853. if(hero2)
  1854. {
  1855. if(hero2->getArt(13)) //ballista
  1856. {
  1857. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero2->tempOwner, stacks.size(), false, 255));
  1858. stacks[stacks.size()-1]->position = 66;
  1859. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  1860. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  1861. }
  1862. if(hero2->getArt(14)) //ammo cart
  1863. {
  1864. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero2->tempOwner, stacks.size(), false, 255));
  1865. stacks[stacks.size()-1]->position = 32;
  1866. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  1867. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  1868. }
  1869. if(hero2->getArt(15)) //first aid tent
  1870. {
  1871. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero2->tempOwner, stacks.size(), false, 255));
  1872. stacks[stacks.size()-1]->position = 168;
  1873. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  1874. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  1875. }
  1876. }
  1877. //war machiens added
  1878. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1879. //randomize obstacles
  1880. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  1881. std::vector<int> possibleObstacles;
  1882. for(int i=0; i<BFIELD_SIZE; ++i)
  1883. {
  1884. if(i%17 < 4 || i%17 > 12)
  1885. {
  1886. obAv[i] = false;
  1887. }
  1888. else
  1889. {
  1890. obAv[i] = true;
  1891. }
  1892. }
  1893. int terType = gs->battleGetBattlefieldType(tile);
  1894. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  1895. {
  1896. if(g->second.allowedTerrains[terType] == '1')
  1897. {
  1898. possibleObstacles.push_back(g->first);
  1899. }
  1900. }
  1901. srand(time(NULL));
  1902. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  1903. {
  1904. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  1905. while(toBlock>0)
  1906. {
  1907. CObstacleInstance coi;
  1908. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  1909. coi.pos = rand()%BFIELD_SIZE;
  1910. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  1911. bool badObstacle = false;
  1912. for(int b=0; b<block.size(); ++b)
  1913. {
  1914. if(!obAv[block[b]])
  1915. {
  1916. badObstacle = true;
  1917. break;
  1918. }
  1919. }
  1920. if(badObstacle) continue;
  1921. //obstacle can be placed
  1922. curB->obstacles.push_back(coi);
  1923. for(int b=0; b<block.size(); ++b)
  1924. {
  1925. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  1926. obAv[block[b]] = false;
  1927. }
  1928. toBlock -= block.size();
  1929. }
  1930. }
  1931. //block engaged players
  1932. if(hero1->tempOwner<PLAYER_LIMIT)
  1933. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1934. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  1935. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1936. //send info about battles
  1937. BattleStart bs;
  1938. bs.info = curB;
  1939. sendAndApply(&bs);
  1940. }
  1941. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1942. {
  1943. //checking winning condition
  1944. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1945. hasStack[0] = hasStack[1] = false;
  1946. for(int b = 0; b<stacks.size(); ++b)
  1947. {
  1948. if(stacks[b]->alive())
  1949. {
  1950. hasStack[1-stacks[b]->attackerOwned] = true;
  1951. }
  1952. }
  1953. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1954. {
  1955. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1956. br->result = 0;
  1957. br->winner = hasStack[1]; //fleeing side loses
  1958. gs->curB->calculateCasualties(br->casualties);
  1959. battleResult.set(br);
  1960. }
  1961. }
  1962. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1963. {
  1964. if(!vstd::contains(h->artifWorn,17))
  1965. return; //hero hasn't spellbok
  1966. ChangeSpells cs;
  1967. cs.hid = h->id;
  1968. cs.learn = true;
  1969. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+4);i++)
  1970. {
  1971. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1972. {
  1973. if(!vstd::contains(h->spells,t->spells[i][j]))
  1974. cs.spells.insert(t->spells[i][j]);
  1975. }
  1976. }
  1977. if(cs.spells.size())
  1978. sendAndApply(&cs);
  1979. }
  1980. void CGameHandler::setBlockVis(int objid, bool bv)
  1981. {
  1982. SetObjectProperty sop(objid,2,bv);
  1983. sendAndApply(&sop);
  1984. }
  1985. void CGameHandler::removeObject(int objid)
  1986. {
  1987. RemoveObject ro;
  1988. ro.id = objid;
  1989. sendAndApply(&ro);
  1990. }
  1991. void CGameHandler::setAmount(int objid, ui32 val)
  1992. {
  1993. SetObjectProperty sop(objid,3,val);
  1994. sendAndApply(&sop);
  1995. }
  1996. void CGameHandler::moveHero(int hid, int3 pos, bool instant)
  1997. {
  1998. if(!instant)
  1999. {
  2000. tlog1 << "Not supported call to CGameHandler::moveHero\n";
  2001. return;
  2002. }
  2003. CGHeroInstance *h = const_cast<CGHeroInstance *>(getHero(hid));
  2004. //check if destination tile is free
  2005. BOOST_FOREACH(CGObjectInstance* obj, gs->map->terrain[pos.x-1][pos.y][pos.z].blockingObjects)
  2006. {
  2007. if(obj->ID==HEROI_TYPE)
  2008. {
  2009. if(obj->tempOwner==h->tempOwner)
  2010. return;//TODO: exchange
  2011. //TODO: check for ally
  2012. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  2013. startBattleI(&h->army,&dh->army,pos,h,dh,0);
  2014. return;
  2015. }
  2016. }
  2017. TryMoveHero tmh;
  2018. tmh.start = h->pos;
  2019. tmh.end = pos;
  2020. tmh.id = hid;
  2021. tmh.movePoints = h->movement;
  2022. tmh.result = instant+1;
  2023. tmh.fowRevealed = gs->tilesToReveal(CGHeroInstance::convertPosition(pos,false),h->getSightDistance(),h->tempOwner);
  2024. sendAndApply(&tmh);
  2025. }
  2026. void CGameHandler::setOwner(int objid, ui8 owner)
  2027. {
  2028. SetObjectProperty sop(objid,1,owner);
  2029. sendAndApply(&sop);
  2030. }
  2031. void CGameHandler::setHoverName(int objid, MetaString* name)
  2032. {
  2033. SetHoverName shn(objid, *name);
  2034. sendAndApply(&shn);
  2035. }
  2036. void CGameHandler::showInfoDialog(InfoWindow *iw)
  2037. {
  2038. sendToAllClients(iw);
  2039. }
  2040. void CGameHandler::showYesNoDialog( YesNoDialog *iw, const CFunctionList<void(ui32)> &callback )
  2041. {
  2042. ask(iw,iw->player,callback);
  2043. }
  2044. void CGameHandler::showSelectionDialog(SelectionDialog *iw, const CFunctionList<void(ui32)> &callback)
  2045. {
  2046. ask(iw,iw->player,callback);
  2047. }
  2048. int CGameHandler::getCurrentPlayer()
  2049. {
  2050. return gs->currentPlayer;
  2051. }
  2052. void CGameHandler::giveResource(int player, int which, int val)
  2053. {
  2054. SetResource sr;
  2055. sr.player = player;
  2056. sr.resid = which;
  2057. sr.val = (gs->players.find(player)->second.resources[which]+val);
  2058. sendAndApply(&sr);
  2059. }
  2060. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  2061. {
  2062. sendToAllClients(comp);
  2063. }
  2064. void CGameHandler::heroVisitCastle(int obj, int heroID)
  2065. {
  2066. HeroVisitCastle vc;
  2067. vc.hid = heroID;
  2068. vc.tid = obj;
  2069. vc.flags |= 1;
  2070. sendAndApply(&vc);
  2071. giveSpells(getTown(obj),getHero(heroID));
  2072. }
  2073. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  2074. {
  2075. HeroVisitCastle vc;
  2076. vc.hid = heroID;
  2077. vc.tid = obj;
  2078. sendAndApply(&vc);
  2079. }
  2080. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  2081. {
  2082. const CGHeroInstance* h = getHero(hid);
  2083. SetHeroArtifacts sha;
  2084. sha.hid = hid;
  2085. sha.artifacts = h->artifacts;
  2086. sha.artifWorn = h->artifWorn;
  2087. if(position<0)
  2088. {
  2089. if(position == -2)
  2090. {
  2091. int i;
  2092. for(i=0; i<VLC->arth->artifacts[artid].possibleSlots.size(); i++) //try to put artifact into first avaialble slot
  2093. {
  2094. if( !vstd::contains(sha.artifWorn,VLC->arth->artifacts[artid].possibleSlots[i]) )
  2095. {
  2096. sha.artifWorn[VLC->arth->artifacts[artid].possibleSlots[i]] = artid;
  2097. break;
  2098. }
  2099. }
  2100. if(i==VLC->arth->artifacts[artid].possibleSlots.size()) //if haven't find proper slot, use backpack
  2101. sha.artifacts.push_back(artid);
  2102. }
  2103. else //should be -1 => putartifact into backpack
  2104. {
  2105. sha.artifacts.push_back(artid);
  2106. }
  2107. }
  2108. else
  2109. {
  2110. if(!vstd::contains(sha.artifWorn,ui16(position)))
  2111. sha.artifWorn[position] = artid;
  2112. else
  2113. sha.artifacts.push_back(artid);
  2114. }
  2115. sendAndApply(&sha);
  2116. }
  2117. void CGameHandler::startBattleI(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb) //use hero=NULL for no hero
  2118. {
  2119. boost::thread(boost::bind(&CGameHandler::startBattle,this,*(CCreatureSet *)army1,*(CCreatureSet *)army2,tile,(CGHeroInstance *)hero1,(CGHeroInstance *)hero2,cb));
  2120. }
  2121. void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  2122. {
  2123. CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  2124. startBattleI(&h->army,&army,tile,h,NULL,cb);
  2125. //battle(&h->army,army,tile,h,NULL);
  2126. }
  2127. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  2128. {
  2129. ChangeSpells cs;
  2130. cs.hid = hid;
  2131. cs.spells = spells;
  2132. cs.learn = give;
  2133. sendAndApply(&cs);
  2134. }
  2135. int CGameHandler::getSelectedHero()
  2136. {
  2137. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  2138. }
  2139. void CGameHandler::setObjProperty( int objid, int prop, int val )
  2140. {
  2141. SetObjectProperty sob;
  2142. sob.id = objid;
  2143. sob.what = prop;
  2144. sob.val = val;
  2145. sendAndApply(&sob);
  2146. }
  2147. void CGameHandler::sendMessageTo( CConnection &c, std::string message )
  2148. {
  2149. c << ui16(95) << message;
  2150. }
  2151. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  2152. {
  2153. sendAndApply(bonus);
  2154. }
  2155. void CGameHandler::setMovePoints( SetMovePoints * smp )
  2156. {
  2157. sendAndApply(smp);
  2158. }
  2159. void CGameHandler::setManaPoints( int hid, int val )
  2160. {
  2161. SetMana sm;
  2162. sm.hid = hid;
  2163. sm.val = val;
  2164. sendAndApply(&sm);
  2165. }
  2166. void CGameHandler::giveHero( int id, int player )
  2167. {
  2168. GiveHero gh;
  2169. gh.id = id;
  2170. gh.player = player;
  2171. sendAndApply(&gh);
  2172. }
  2173. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  2174. {
  2175. ChangeObjPos cop;
  2176. cop.objid = objid;
  2177. cop.nPos = newPos;
  2178. cop.flags = flags;
  2179. sendAndApply(&cop);
  2180. }
  2181. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  2182. {
  2183. gsm.lock();
  2184. sel->id = QID;
  2185. callbacks[QID] = callback;
  2186. states.addQuery(player,QID);
  2187. QID++;
  2188. sendAndApply(sel);
  2189. gsm.unlock();
  2190. }
  2191. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  2192. {
  2193. gsm.lock();
  2194. sel->id = QID;
  2195. callbacks[QID] = callback;
  2196. states.addQuery(player,QID);
  2197. sendToAllClients(sel);
  2198. QID++;
  2199. gsm.unlock();
  2200. }