CGameHandler.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. #include <boost/foreach.hpp>
  2. #include <boost/thread.hpp>
  3. #include <boost/thread/shared_mutex.hpp>
  4. #include <boost/bind.hpp>
  5. #include "CGameHandler.h"
  6. #include "CScriptCallback.h"
  7. #include "../CLua.h"
  8. #include "../CGameState.h"
  9. #include "../StartInfo.h"
  10. #include "../map.h"
  11. #include "../lib/NetPacks.h"
  12. #include "../lib/Connection.h"
  13. #include "../hch/CArtHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CTownHandler.h"
  16. #include "../hch/CBuildingHandler.h"
  17. #include "../hch/CHeroHandler.h"
  18. #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types
  19. #include "../lib/VCMI_Lib.h"
  20. #include "../lib/CondSh.h"
  21. #include <fstream>
  22. #ifndef _MSC_VER
  23. #include <boost/thread/xtime.hpp>
  24. #endif
  25. extern bool end2;
  26. #include "../lib/BattleAction.h"
  27. #ifdef min
  28. #undef min
  29. #endif
  30. #ifdef max
  31. #undef max
  32. #endif
  33. #define NEW_ROUND BattleNextRound bnr;\
  34. bnr.round = gs->curB->round + 1;\
  35. sendAndApply(&bnr);
  36. boost::mutex gsm;
  37. ui32 CGameHandler::QID = 1;
  38. CondSh<bool> battleMadeAction;
  39. CondSh<BattleResult *> battleResult(NULL);
  40. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  41. class CMP_stack
  42. {
  43. public:
  44. bool operator ()(const CStack* a, const CStack* b)
  45. {
  46. return (a->creature->speed)>(b->creature->speed);
  47. }
  48. } cmpst ;
  49. double distance(int3 a, int3 b)
  50. {
  51. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  52. }
  53. //bool CGameState::checkFunc(int obid, std::string name)
  54. //{
  55. // if (objscr.find(obid)!=objscr.end())
  56. // {
  57. // if(objscr[obid].find(name)!=objscr[obid].end())
  58. // {
  59. // return true;
  60. // }
  61. // }
  62. // return false;
  63. //}
  64. PlayerStatus PlayerStatuses::operator[](ui8 player)
  65. {
  66. boost::unique_lock<boost::mutex> l(mx);
  67. if(players.find(player) != players.end())
  68. {
  69. return players[player];
  70. }
  71. else
  72. {
  73. throw std::string("No such player!");
  74. }
  75. }
  76. void PlayerStatuses::addPlayer(ui8 player)
  77. {
  78. boost::unique_lock<boost::mutex> l(mx);
  79. players[player];
  80. }
  81. bool PlayerStatuses::hasQueries(ui8 player)
  82. {
  83. boost::unique_lock<boost::mutex> l(mx);
  84. if(players.find(player) != players.end())
  85. {
  86. return players[player].queries.size();
  87. }
  88. else
  89. {
  90. throw std::string("No such player!");
  91. }
  92. }
  93. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  94. {
  95. boost::unique_lock<boost::mutex> l(mx);
  96. if(players.find(player) != players.end())
  97. {
  98. return players[player].*flag;
  99. }
  100. else
  101. {
  102. throw std::string("No such player!");
  103. }
  104. }
  105. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  106. {
  107. boost::unique_lock<boost::mutex> l(mx);
  108. if(players.find(player) != players.end())
  109. {
  110. players[player].*flag = val;
  111. }
  112. else
  113. {
  114. throw std::string("No such player!");
  115. }
  116. cv.notify_all();
  117. }
  118. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  119. {
  120. boost::unique_lock<boost::mutex> l(mx);
  121. if(players.find(player) != players.end())
  122. {
  123. players[player].queries.insert(id);
  124. }
  125. else
  126. {
  127. throw std::string("No such player!");
  128. }
  129. cv.notify_all();
  130. }
  131. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  132. {
  133. boost::unique_lock<boost::mutex> l(mx);
  134. if(players.find(player) != players.end())
  135. {
  136. players[player].queries.erase(id);
  137. }
  138. else
  139. {
  140. throw std::string("No such player!");
  141. }
  142. cv.notify_all();
  143. }
  144. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  145. {
  146. std::vector<int> tempv = script->yourObjects();
  147. for (unsigned i=0;i<tempv.size();i++)
  148. {
  149. (*mapa)[tempv[i]]=script;
  150. }
  151. cppscripts.insert(script);
  152. }
  153. template <typename T>
  154. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  155. {
  156. fun(args[which]);
  157. }
  158. void CGameHandler::changeSecSkill(int ID, ui16 which, int val, bool abs)
  159. {
  160. SetSecSkill sps;
  161. sps.id = ID;
  162. sps.which = which;
  163. sps.abs = abs;
  164. sps.val = val;
  165. sendAndApply(&sps);
  166. }
  167. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  168. {
  169. SetPrimSkill sps;
  170. sps.id = ID;
  171. sps.which = which;
  172. sps.abs = abs;
  173. sps.val = val;
  174. sendAndApply(&sps);
  175. if(which==4) //only for exp - hero may level up
  176. {
  177. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  178. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  179. {
  180. //give prim skill
  181. std::cout << hero->name <<" got level "<<hero->level<<std::endl;
  182. int r = rand()%100, pom=0, x=0;
  183. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  184. for(;x<PRIMARY_SKILLS;x++)
  185. {
  186. pom += hero->type->heroClass->primChance[x].*g;
  187. if(r<pom)
  188. break;
  189. }
  190. std::cout << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  191. SetPrimSkill sps;
  192. sps.id = ID;
  193. sps.which = x;
  194. sps.abs = false;
  195. sps.val = 1;
  196. sendAndApply(&sps);
  197. HeroLevelUp hlu;
  198. hlu.heroid = ID;
  199. hlu.primskill = x;
  200. hlu.level = hero->level+1;
  201. //picking sec. skills for choice
  202. std::set<int> basicAndAdv, expert, none;
  203. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  204. for(unsigned i=0;i<hero->secSkills.size();i++)
  205. {
  206. if(hero->secSkills[i].second < 2)
  207. basicAndAdv.insert(hero->secSkills[i].first);
  208. else
  209. expert.insert(hero->secSkills[i].first);
  210. none.erase(hero->secSkills[i].first);
  211. }
  212. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  213. {
  214. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  215. }
  216. else
  217. {
  218. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  219. hlu.skills.push_back(s);
  220. basicAndAdv.erase(s);
  221. }
  222. if(basicAndAdv.size())
  223. {
  224. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  225. }
  226. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  227. {
  228. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  229. }
  230. 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));
  231. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  232. }
  233. }
  234. }
  235. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  236. {
  237. BattleInfo *curB = new BattleInfo;
  238. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  239. NEW_ROUND;
  240. //TODO: pre-tactic stuff, call scripts etc.
  241. //tactic round
  242. {
  243. NEW_ROUND;
  244. if( (hero1 && hero1->getSecSkillLevel(19)>=0) ||
  245. ( hero2 && hero2->getSecSkillLevel(19)>=0) )//someone has tactics
  246. {
  247. //TODO: tactic round (round -1)
  248. }
  249. }
  250. //main loop
  251. while(!battleResult.get()) //till the end of the battle ;]
  252. {
  253. NEW_ROUND;
  254. std::vector<CStack*> & stacks = (gs->curB->stacks);
  255. const BattleInfo & curB = *gs->curB;
  256. //stack loop
  257. for(unsigned i=0;i<stacks.size() && !battleResult.get();i++)
  258. {
  259. if(!stacks[i]->alive()) continue;//indicates imposiibility of making action for this dead unit
  260. BattleSetActiveStack sas;
  261. sas.stack = stacks[i]->ID;
  262. sendAndApply(&sas);
  263. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  264. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  265. battleMadeAction.cond.wait(lock);
  266. battleMadeAction.data = false;
  267. checkForBattleEnd(stacks); //check if this action ended the battle
  268. }
  269. }
  270. //unblock engaged players
  271. if(hero1->tempOwner<PLAYER_LIMIT)
  272. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  273. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  274. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  275. //end battle, remove all info, free memory
  276. sendAndApply(battleResult.data);
  277. if(cb)
  278. cb(battleResult.data);
  279. delete battleResult.data;
  280. //for(int i=0;i<stacks.size();i++)
  281. // delete stacks[i];
  282. //delete curB;
  283. //curB = NULL;
  284. }
  285. void prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  286. {
  287. bat.stackAttacking = att->ID;
  288. bat.bsa.stackAttacked = def->ID;
  289. bat.bsa.damageAmount = BattleInfo::calculateDmg(att, def);//counting dealt damage
  290. //applying damages
  291. bat.bsa.killedAmount = bat.bsa.damageAmount / def->creature->hitPoints;
  292. unsigned damageFirst = bat.bsa.damageAmount % def->creature->hitPoints;
  293. if( def->firstHPleft <= damageFirst )
  294. {
  295. bat.bsa.killedAmount++;
  296. bat.bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  297. }
  298. else
  299. {
  300. bat.bsa.newHP = def->firstHPleft - damageFirst;
  301. }
  302. if(def->amount <= bat.bsa.killedAmount) //stack killed
  303. {
  304. bat.bsa.newAmount = 0;
  305. bat.bsa.flags |= 1;
  306. bat.bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  307. }
  308. else
  309. {
  310. bat.bsa.newAmount = def->amount - bat.bsa.killedAmount;
  311. }
  312. }
  313. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  314. {
  315. try
  316. {
  317. ui16 pom;
  318. while(!end2)
  319. {
  320. c >> pom;
  321. bool blockvis = false;
  322. switch(pom)
  323. {
  324. case 99: //end!
  325. {
  326. log0 << "We have been requested to close.\n";
  327. exit(0);
  328. }
  329. case 100: //my interface ended its turn
  330. {
  331. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  332. break;
  333. }
  334. case 500:
  335. {
  336. si32 id;
  337. c >> id;
  338. RemoveObject rh(id);
  339. sendAndApply(&rh);
  340. break;
  341. }
  342. case 501://interface wants to move hero
  343. {
  344. int3 start, end;
  345. si32 id;
  346. c >> id >> start >> end;
  347. int3 hmpos = end + int3(-1,0,0);
  348. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  349. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  350. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  351. TryMoveHero tmh;
  352. tmh.id = id;
  353. tmh.start = start;
  354. tmh.end = end;
  355. tmh.result = 0;
  356. tmh.movePoints = h->movement;
  357. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  358. (distance(start,end)>=1.5) || //tiles are not neighouring
  359. (h->movement < cost) || //lack of movement points
  360. (t.tertype == rock) || //rock
  361. (!h->canWalkOnSea() && t.tertype == water) ||
  362. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  363. goto fail;
  364. //check if there is blocking visitable object
  365. blockvis = false;
  366. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  367. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  368. {
  369. if(obj->blockVisit)
  370. {
  371. blockvis = true;
  372. break;
  373. }
  374. }
  375. //we start moving
  376. if(blockvis)//interaction with blocking object (like resources)
  377. {
  378. sendAndApply(&tmh); //failed to move to that tile but we visit object
  379. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  380. {
  381. if (obj->blockVisit)
  382. {
  383. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  384. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  385. if(obj->state) //hard-coded function
  386. obj->state->onHeroVisit(obj->id,h->id);
  387. }
  388. }
  389. break;
  390. }
  391. else //normal move
  392. {
  393. tmh.result = 1;
  394. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x-1][start.y][start.z].visitableObjects)
  395. {
  396. //TODO: allow to handle this in script-languages
  397. if(obj->state) //hard-coded function
  398. obj->state->onHeroLeave(obj->id,h->id);
  399. }
  400. //reveal fog of war
  401. int heroSight = h->getSightDistance();
  402. int xbeg = start.x - heroSight - 2;
  403. if(xbeg < 0)
  404. xbeg = 0;
  405. int xend = start.x + heroSight + 2;
  406. if(xend >= gs->map->width)
  407. xend = gs->map->width;
  408. int ybeg = start.y - heroSight - 2;
  409. if(ybeg < 0)
  410. ybeg = 0;
  411. int yend = start.y + heroSight + 2;
  412. if(yend >= gs->map->height)
  413. yend = gs->map->height;
  414. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  415. {
  416. for(int yd=ybeg; yd<yend; ++yd)
  417. {
  418. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  419. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  420. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  421. {
  422. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  423. {
  424. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  425. }
  426. }
  427. }
  428. }
  429. sendAndApply(&tmh);
  430. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  431. {
  432. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  433. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  434. if(obj->state) //hard-coded function
  435. obj->state->onHeroVisit(obj->id,h->id);
  436. }
  437. }
  438. break;
  439. fail:
  440. sendAndApply(&tmh);
  441. break;
  442. }
  443. case 502: //swap creatures in garrison
  444. {
  445. ui8 what, p1, p2; si32 id1, id2;
  446. c >> what >> id1 >> p1 >> id2 >> p2;
  447. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  448. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  449. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  450. if(what==1) //swap
  451. {
  452. int pom = S2->slots[p2].first;
  453. S2->slots[p2].first = S1->slots[p1].first;
  454. S1->slots[p1].first = pom;
  455. int pom2 = S2->slots[p2].second;
  456. S2->slots[p2].second = S1->slots[p1].second;
  457. S1->slots[p1].second = pom2;
  458. if(!S1->slots[p1].second)
  459. S1->slots.erase(p1);
  460. if(!S2->slots[p2].second)
  461. S2->slots.erase(p2);
  462. }
  463. else if(what==2)//merge
  464. {
  465. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  466. S2->slots[p2].second += S1->slots[p1].second;
  467. S1->slots[p1].first = NULL;
  468. S1->slots[p1].second = 0;
  469. S1->slots.erase(p1);
  470. }
  471. else if(what==3) //split
  472. {
  473. si32 val;
  474. c >> val;
  475. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  476. S2->slots[p2].first = S1->slots[p1].first;
  477. S2->slots[p2].second = val;
  478. S1->slots[p1].second -= val;
  479. if(!S1->slots[p1].second) //if we've moved all creatures
  480. S1->slots.erase(p1);
  481. }
  482. if((s1->ID==34 && !S1->slots.size()) //it's not allowed to take last stack from hero army!
  483. || (s2->ID==34 && !S2->slots.size()))
  484. {
  485. break;
  486. }
  487. SetGarrisons sg;
  488. sg.garrs[id1] = *S1;
  489. if(s1 != s2)
  490. sg.garrs[id2] = *S2;
  491. sendAndApply(&sg);
  492. break;
  493. }
  494. case 503:
  495. {
  496. si32 id;
  497. ui8 pos;
  498. c >> id >> pos;
  499. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  500. s1->army.slots.erase(pos);
  501. SetGarrisons sg;
  502. sg.garrs[id] = s1->army;
  503. sendAndApply(&sg);
  504. break;
  505. }
  506. case 504:
  507. {
  508. si32 tid, bid;
  509. c >> tid >> bid;
  510. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  511. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  512. for(int i=0;i<RESOURCE_QUANTITY;i++)
  513. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  514. break; //no res
  515. //TODO: check requirements
  516. //TODO: check if building isn't forbidden
  517. NewStructures ns;
  518. ns.tid = tid;
  519. if(bid>36) //upg dwelling
  520. {
  521. if(t->getHordeLevel(0) == (bid-37))
  522. ns.bid.insert(19);
  523. else if(t->getHordeLevel(1) == (bid-37))
  524. ns.bid.insert(25);
  525. }
  526. else if(bid >= 30) //bas. dwelling
  527. {
  528. SetAvailableCreatures ssi;
  529. ssi.tid = tid;
  530. ssi.creatures = t->strInfo.creatures;
  531. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  532. sendAndApply(&ssi);
  533. }
  534. ns.bid.insert(bid);
  535. ns.builded = t->builded + 1;
  536. sendAndApply(&ns);
  537. SetResources sr;
  538. sr.player = t->tempOwner;
  539. sr.res = gs->players[t->tempOwner].resources;
  540. for(int i=0;i<7;i++)
  541. sr.res[i]-=b->resources[i];
  542. sendAndApply(&sr);
  543. if(bid<5) //it's mage guild
  544. {
  545. if(t->visitingHero)
  546. giveSpells(t,t->visitingHero);
  547. if(t->garrisonHero)
  548. giveSpells(t,t->garrisonHero);
  549. }
  550. break;
  551. }
  552. case 506: //recruit creature
  553. {
  554. si32 objid, ser=-1; //ser - used dwelling level
  555. ui32 crid, cram; //recruited creature id and amount
  556. c >> objid >> crid >> cram;
  557. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  558. //verify
  559. bool found = false;
  560. typedef std::pair<const int,int> Parka;
  561. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  562. {
  563. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  564. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  565. {
  566. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  567. ser = av->first;
  568. break;
  569. }
  570. }
  571. int slot = t->army.getSlotFor(crid);
  572. if(!found || //no such creature
  573. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  574. cram<=0 ||
  575. slot<0 )
  576. break;
  577. //recruit
  578. SetResources sr;
  579. sr.player = t->tempOwner;
  580. for(int i=0;i<RESOURCE_QUANTITY;i++)
  581. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  582. SetAvailableCreatures sac;
  583. sac.tid = objid;
  584. sac.creatures = t->strInfo.creatures;
  585. sac.creatures[ser] -= cram;
  586. SetGarrisons sg;
  587. sg.garrs[objid] = t->army;
  588. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  589. {
  590. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  591. }
  592. else //add creatures to a already existing stack
  593. {
  594. sg.garrs[objid].slots[slot].second += cram;
  595. }
  596. sendAndApply(&sr);
  597. sendAndApply(&sac);
  598. sendAndApply(&sg);
  599. break;
  600. }
  601. case 507://upgrade creature
  602. {
  603. ui32 objid, upgID;
  604. ui8 pos;
  605. c >> objid >> pos >> upgID;
  606. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  607. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  608. int player = obj->tempOwner;
  609. int crQuantity = obj->army.slots[pos].second;
  610. //check if upgrade is possible
  611. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  612. break;
  613. //check if player has enough resources
  614. for(int i=0;i<ui.cost.size();i++)
  615. {
  616. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  617. {
  618. if(gs->players[player].resources[j->first] < j->second*crQuantity)
  619. goto upgend;
  620. }
  621. }
  622. //take resources
  623. for(int i=0;i<ui.cost.size();i++)
  624. {
  625. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  626. {
  627. SetResource sr;
  628. sr.player = player;
  629. sr.resid = j->first;
  630. sr.val = gs->players[player].resources[j->first] - j->second*crQuantity;
  631. sendAndApply(&sr);
  632. }
  633. }
  634. {
  635. //upgrade creature
  636. SetGarrisons sg;
  637. sg.garrs[objid] = obj->army;
  638. sg.garrs[objid].slots[pos].first = upgID;
  639. sendAndApply(&sg);
  640. }
  641. upgend:
  642. break;
  643. }
  644. case 508: //garrison swap
  645. {
  646. si32 tid;
  647. c >> tid;
  648. CGTownInstance *town = gs->getTown(tid);
  649. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  650. {
  651. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  652. while(!cso.slots.empty())//while there are unmoved creatures
  653. {
  654. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  655. if(pos<0)
  656. goto handleConEnd;
  657. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  658. {
  659. csn.slots[pos].second += cso.slots.begin()->second.second;
  660. }
  661. else //move stack on the free pos
  662. {
  663. csn.slots[pos].first = cso.slots.begin()->second.first;
  664. csn.slots[pos].second = cso.slots.begin()->second.second;
  665. }
  666. cso.slots.erase(cso.slots.begin());
  667. }
  668. SetGarrisons sg;
  669. sg.garrs[town->visitingHero->id] = csn;
  670. sg.garrs[town->id] = csn;
  671. sendAndApply(&sg);
  672. SetHeroesInTown intown;
  673. intown.tid = tid;
  674. intown.visiting = -1;
  675. intown.garrison = town->visitingHero->id;
  676. sendAndApply(&intown);
  677. }
  678. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  679. {
  680. SetHeroesInTown intown;
  681. intown.tid = tid;
  682. intown.garrison = -1;
  683. intown.visiting = town->garrisonHero->id;
  684. sendAndApply(&intown);
  685. //town will be empty
  686. SetGarrisons sg;
  687. sg.garrs[tid] = CCreatureSet();
  688. sendAndApply(&sg);
  689. }
  690. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  691. {
  692. SetGarrisons sg;
  693. sg.garrs[town->id] = town->visitingHero->army;
  694. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  695. //sg.garrs[town->visitingHero->id] = town->visitingHero->army;
  696. SetHeroesInTown intown;
  697. intown.tid = tid;
  698. intown.garrison = town->visitingHero->id;
  699. intown.visiting = town->garrisonHero->id;
  700. sendAndApply(&intown);
  701. sendAndApply(&sg);
  702. }
  703. else
  704. {
  705. std::cout << "Warning, wrong garrison swap command for " << tid << std::endl;
  706. }
  707. break;
  708. }
  709. case 509: //swap artifacts
  710. {
  711. si32 hid1, hid2;
  712. ui16 slot1, slot2;
  713. c >> hid1 >> slot1 >> hid2 >> slot2;
  714. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  715. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  716. break;
  717. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  718. h2->setArtAtPos(slot2,a1);
  719. h1->setArtAtPos(slot1,a2);
  720. SetHeroArtifacts sha;
  721. sha.hid = hid1;
  722. sha.artifacts = h1->artifacts;
  723. sha.artifWorn = h1->artifWorn;
  724. sendAndApply(&sha);
  725. if(hid1 != hid2)
  726. {
  727. sha.hid = hid2;
  728. sha.artifacts = h2->artifacts;
  729. sha.artifWorn = h2->artifWorn;
  730. sendAndApply(&sha);
  731. }
  732. break;
  733. }
  734. case 510: //buy artifact
  735. {
  736. ui32 hid;
  737. si32 aid, bid;
  738. c >> hid >> aid;
  739. CGHeroInstance *hero = gs->getHero(hid);
  740. CGTownInstance *town = hero->visitedTown;
  741. if(aid==0) //spellbok
  742. {
  743. if(!vstd::contains(town->builtBuildings,si32(0)))
  744. break;
  745. SetResource sr;
  746. sr.player = hero->tempOwner;
  747. sr.resid = 6;
  748. sr.val = gs->players[hero->tempOwner].resources[6] - 500;
  749. sendAndApply(&sr);
  750. SetHeroArtifacts sha;
  751. sha.hid = hid;
  752. sha.artifacts = hero->artifacts;
  753. sha.artifWorn = hero->artifWorn;
  754. sha.artifWorn[17] = 0;
  755. sendAndApply(&sha);
  756. giveSpells(town,hero);
  757. }
  758. else if(aid < 7 && aid > 3) //war machine
  759. {
  760. int price = VLC->arth->artifacts[aid].price;
  761. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  762. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  763. || gs->players[hero->tempOwner].resources[6] < price //no gold
  764. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  765. {
  766. break;
  767. }
  768. SetResource sr;
  769. sr.player = hero->tempOwner;
  770. sr.resid = 6;
  771. sr.val = gs->players[hero->tempOwner].resources[6] - price;
  772. sendAndApply(&sr);
  773. SetHeroArtifacts sha;
  774. sha.hid = hid;
  775. sha.artifacts = hero->artifacts;
  776. sha.artifWorn = hero->artifWorn;
  777. sha.artifWorn[9+aid] = aid;
  778. sendAndApply(&sha);
  779. }
  780. break;
  781. }
  782. case 511: //trade at marketplace
  783. {
  784. ui8 player;
  785. ui32 mode, id1, id2, val;
  786. c >> player >> mode >> id1 >> id2 >> val;
  787. val = std::min(si32(val),gs->players[player].resources[id1]);
  788. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  789. uzysk /= gs->resVals[id2];
  790. SetResource sr;
  791. sr.player = player;
  792. sr.resid = id1;
  793. sr.val = gs->players[player].resources[id1] - val;
  794. sendAndApply(&sr);
  795. sr.resid = id2;
  796. sr.val = gs->players[player].resources[id2] + (int)uzysk;
  797. sendAndApply(&sr);
  798. break;
  799. }
  800. case 2001:
  801. {
  802. ui32 qid, answer;
  803. c >> qid >> answer;
  804. gsm.lock();
  805. CFunctionList<void(ui32)> callb = callbacks[qid];
  806. callbacks.erase(qid);
  807. gsm.unlock();
  808. callb(answer);
  809. break;
  810. }
  811. case 3002:
  812. {
  813. BattleAction ba;
  814. c >> ba;
  815. switch(ba.actionType)
  816. {
  817. case 2: //walk
  818. {
  819. moveStack(ba.stackNumber,ba.destinationTile);
  820. break;
  821. }
  822. case 3: //defend
  823. {
  824. break;
  825. }
  826. case 4: //retreat/flee
  827. {
  828. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  829. //TODO: calculate casualties
  830. //TODO: remove retreating hero from map and place it in recrutation list
  831. BattleResult *br = new BattleResult;
  832. br->result = 1;
  833. br->winner = !ba.side; //fleeing side loses
  834. gs->curB->calculateCasualties(br->casualties);
  835. battleResult.set(br);
  836. break;
  837. }
  838. case 6: //walk or attack
  839. {
  840. moveStack(ba.stackNumber,ba.destinationTile);
  841. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  842. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  843. if((curStack->position != ba.destinationTile) || //we wasn't able to reach destination tile
  844. (BattleInfo::mutualPosition(ba.destinationTile,ba.additionalInfo)<0) ) //destination tile is not neighbouring with enemy stack
  845. return;
  846. BattleAttack bat;
  847. prepareAttack(bat,curStack,stackAtEnd);
  848. sendAndApply(&bat);
  849. //counterattack
  850. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  851. && stackAtEnd->alive()
  852. && !stackAtEnd->counterAttacks ) //TODO: support for multiple retaliatons per turn
  853. {
  854. prepareAttack(bat,stackAtEnd,curStack);
  855. bat.flags |= 2;
  856. sendAndApply(&bat);
  857. }
  858. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  859. && curStack->alive())
  860. {
  861. bat.flags = 0;
  862. prepareAttack(bat,curStack,stackAtEnd);
  863. sendAndApply(&bat);
  864. }
  865. break;
  866. }
  867. case 7: //shoot
  868. {
  869. //TODO: check arrows count
  870. //TODO: check if stack isn't blocked by enemy
  871. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  872. *destStack= gs->curB->getStackT(ba.destinationTile);
  873. BattleAttack bat;
  874. prepareAttack(bat,curStack,destStack);
  875. bat.flags |= 1;
  876. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  877. && curStack->alive())
  878. {
  879. prepareAttack(bat,curStack,destStack);
  880. sendAndApply(&bat);
  881. }
  882. sendAndApply(&bat);
  883. break;
  884. }
  885. }
  886. battleMadeAction.setn(true);
  887. //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy
  888. break;
  889. }
  890. default:
  891. #ifndef __GNUC__
  892. throw std::exception("Not supported client message!");
  893. #else
  894. throw std::exception();
  895. #endif
  896. break;
  897. }
  898. }
  899. }
  900. catch (const std::exception& e)
  901. {
  902. log1 << e.what() << std::endl;
  903. end2 = true;
  904. }
  905. catch (const std::exception * e)
  906. {
  907. log1 << e->what()<< std::endl;
  908. end2 = true;
  909. delete e;
  910. }
  911. catch(...)
  912. {
  913. end2 = true;
  914. }
  915. handleConEnd:
  916. ;
  917. }
  918. void CGameHandler::moveStack(int stack, int dest)
  919. {
  920. CStack *curStack = gs->curB->getStack(stack),
  921. *stackAtEnd = gs->curB->getStackT(dest);
  922. //initing necessary tables
  923. bool accessibility[187];
  924. if(curStack->creature->isDoubleWide())
  925. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned,curStack->ID);
  926. else
  927. gs->curB->getAccessibilityMap(accessibility,curStack->ID);
  928. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  929. return;
  930. //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
  931. // return false;
  932. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  933. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  934. for(int v=path.size()-1; v>=tilesToMove; --v)
  935. {
  936. //inform clients about move
  937. BattleStackMoved sm;
  938. sm.stack = curStack->ID;
  939. sm.tile = path[v];
  940. if(v==path.size()-1) //move start - set flag
  941. sm.flags |= 1;
  942. if(v==0) //move end - set flag
  943. sm.flags |= 2;
  944. sendAndApply(&sm);
  945. }
  946. }
  947. CGameHandler::CGameHandler(void)
  948. {
  949. gs = NULL;
  950. }
  951. CGameHandler::~CGameHandler(void)
  952. {
  953. delete gs;
  954. }
  955. void CGameHandler::init(StartInfo *si, int Seed)
  956. {
  957. Mapa *map = new Mapa(si->mapname);
  958. std::cout << "Map loaded!" << std::endl;
  959. gs = new CGameState();
  960. std::cout << "Gamestate created!" << std::endl;
  961. gs->init(si,map,Seed);
  962. std::cout << "Gamestate initialized!" << std::endl;
  963. /****************************LUA OBJECT SCRIPTS************************************************/
  964. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  965. //for (int i=0; i<lf->size(); i++)
  966. //{
  967. // try
  968. // {
  969. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  970. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  971. // CLuaCallback::registerFuncs(objs->is);
  972. // //objs
  973. // for (int j=0; j<temp->size(); j++)
  974. // {
  975. // int obid ; //obj ID
  976. // int dspos = (*temp)[j].find_first_of('_');
  977. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  978. // std::string fname = (*temp)[j].substr(0,dspos);
  979. // if (skrypty->find(obid)==skrypty->end())
  980. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  981. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  982. // }
  983. // delete temp;
  984. // }HANDLE_EXCEPTION
  985. //}
  986. //delete lf;
  987. }
  988. int lowestSpeed(CGHeroInstance * chi)
  989. {
  990. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  991. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  992. for (;i!=chi->army.slots.end();i++)
  993. {
  994. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  995. }
  996. return ret;
  997. }
  998. int valMovePoints(CGHeroInstance * chi)
  999. {
  1000. int ret = 1270+70*lowestSpeed(chi);
  1001. if (ret>2000)
  1002. ret=2000;
  1003. //TODO: additional bonuses (but they aren't currently stored in chi)
  1004. return ret;
  1005. }
  1006. void CGameHandler::newTurn()
  1007. {
  1008. NewTurn n;
  1009. n.day = gs->day + 1;
  1010. n.resetBuilded = true;
  1011. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  1012. {
  1013. if(i->first>=PLAYER_LIMIT) continue;
  1014. SetResources r;
  1015. r.player = i->first;
  1016. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1017. r.res[j] = i->second.resources[j];
  1018. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  1019. {
  1020. NewTurn::Hero h;
  1021. h.id = (*i).second.heroes[j]->id;
  1022. h.move = valMovePoints((*i).second.heroes[j]);
  1023. h.mana = (*i).second.heroes[j]->mana;
  1024. n.heroes.insert(h);
  1025. }
  1026. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  1027. {
  1028. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  1029. {
  1030. if((**j).town->primaryRes == 127) //we'll give wood and ore
  1031. {
  1032. r.res[0] += 1;
  1033. r.res[2] += 1;
  1034. }
  1035. else
  1036. {
  1037. r.res[(**j).town->primaryRes] += 1;
  1038. }
  1039. }
  1040. if(gs->getDate(1)==7) //first day of week
  1041. {
  1042. SetAvailableCreatures sac;
  1043. sac.tid = (**j).id;
  1044. sac.creatures = (**j).strInfo.creatures;
  1045. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  1046. {
  1047. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  1048. sac.creatures[k] += (**j).creatureGrowth(k);
  1049. }
  1050. n.cres.push_back(sac);
  1051. }
  1052. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  1053. r.res[6] += (**j).dailyIncome();
  1054. }
  1055. n.res.push_back(r);
  1056. }
  1057. sendAndApply(&n);
  1058. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  1059. {
  1060. (*i)->newTurn();
  1061. }
  1062. }
  1063. void CGameHandler::run()
  1064. {
  1065. BOOST_FOREACH(CConnection *cc, conns)
  1066. {//init conn.
  1067. ui8 quantity, pom;
  1068. //ui32 seed;
  1069. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  1070. (*cc) >> quantity;
  1071. for(int i=0;i<quantity;i++)
  1072. {
  1073. (*cc) >> pom;
  1074. gsm.lock();
  1075. connections[pom] = cc;
  1076. gsm.unlock();
  1077. }
  1078. }
  1079. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1080. {
  1081. std::set<int> pom;
  1082. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1083. if(j->second == *i)
  1084. pom.insert(j->first);
  1085. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1086. }
  1087. /****************************SCRIPTS************************************************/
  1088. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  1089. /****************************C++ OBJECT SCRIPTS************************************************/
  1090. std::map<int,CCPPObjectScript*> scripts;
  1091. CScriptCallback * csc = new CScriptCallback();
  1092. csc->gh = this;
  1093. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  1094. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  1095. handleCPPObjS(&scripts,new CPickable(csc));
  1096. handleCPPObjS(&scripts,new CMines(csc));
  1097. handleCPPObjS(&scripts,new CTownScript(csc));
  1098. handleCPPObjS(&scripts,new CHeroScript(csc));
  1099. handleCPPObjS(&scripts,new CMonsterS(csc));
  1100. handleCPPObjS(&scripts,new CCreatureGen(csc));
  1101. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  1102. //std::string temps("newObject");
  1103. for (unsigned i=0; i<gs->map->objects.size(); i++)
  1104. {
  1105. //c++ scripts
  1106. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  1107. {
  1108. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  1109. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  1110. }
  1111. else
  1112. {
  1113. gs->map->objects[i]->state = NULL;
  1114. }
  1115. //// lua scripts
  1116. //if(checkFunc(map->objects[i]->ID,temps))
  1117. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  1118. }
  1119. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1120. states.addPlayer(i->first);
  1121. while (!end2)
  1122. {
  1123. newTurn();
  1124. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1125. {
  1126. 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
  1127. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1128. gs->currentPlayer = i->first;
  1129. *connections[i->first] << ui16(100) << i->first;
  1130. //wait till turn is done
  1131. boost::unique_lock<boost::mutex> lock(states.mx);
  1132. while(states.players[i->first].makingTurn && !end2)
  1133. {
  1134. boost::posix_time::time_duration p;
  1135. p = boost::posix_time::milliseconds(200);
  1136. #ifdef _MSC_VER
  1137. states.cv.timed_wait(lock,p);
  1138. #else
  1139. boost::xtime time={0,0};
  1140. time.nsec = static_cast<boost::xtime::xtime_nsec_t>(p.total_nanoseconds());
  1141. states.cv.timed_wait(lock,time);
  1142. #endif
  1143. }
  1144. }
  1145. }
  1146. }
  1147. namespace CGH
  1148. {
  1149. using namespace std;
  1150. void readItTo(ifstream & input, vector< vector<int> > & dest)
  1151. {
  1152. for(int j=0; j<7; ++j)
  1153. {
  1154. std::vector<int> pom;
  1155. for(int g=0; g<j+1; ++g)
  1156. {
  1157. int hlp; input>>hlp;
  1158. pom.push_back(hlp);
  1159. }
  1160. dest.push_back(pom);
  1161. }
  1162. }
  1163. }
  1164. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  1165. {
  1166. battleResult.set(NULL);
  1167. std::vector<CStack*> & stacks = (curB->stacks);
  1168. curB->tile = tile;
  1169. curB->siege = 0; //TODO: add sieges
  1170. curB->army1=army1;
  1171. curB->army2=army2;
  1172. curB->hero1=(hero1)?(hero1->id):(-1);
  1173. curB->hero2=(hero2)?(hero2->id):(-1);
  1174. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  1175. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  1176. curB->round = -2;
  1177. curB->activeStack = -1;
  1178. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  1179. {
  1180. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  1181. stacks[stacks.size()-1]->ID = stacks.size()-1;
  1182. }
  1183. //initialization of positions
  1184. std::ifstream positions;
  1185. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1186. if(!positions.is_open())
  1187. {
  1188. log0<<"Unable to open battleStartpos.txt!"<<std::endl;
  1189. }
  1190. std::string dump;
  1191. positions>>dump; positions>>dump;
  1192. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  1193. CGH::readItTo(positions, attackerLoose);
  1194. positions>>dump;
  1195. CGH::readItTo(positions, defenderLoose);
  1196. positions>>dump;
  1197. positions>>dump;
  1198. CGH::readItTo(positions, attackerTight);
  1199. positions>>dump;
  1200. CGH::readItTo(positions, defenderTight);
  1201. positions.close();
  1202. if(army1.formation)
  1203. for(int b=0; b<army1.slots.size(); ++b) //tight
  1204. {
  1205. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  1206. }
  1207. else
  1208. for(int b=0; b<army1.slots.size(); ++b) //loose
  1209. {
  1210. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  1211. }
  1212. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  1213. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  1214. if(army2.formation)
  1215. for(int b=0; b<army2.slots.size(); ++b) //tight
  1216. {
  1217. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  1218. }
  1219. else
  1220. for(int b=0; b<army2.slots.size(); ++b) //loose
  1221. {
  1222. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  1223. }
  1224. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1225. {
  1226. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  1227. {
  1228. stacks[g]->position += 1;
  1229. }
  1230. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  1231. {
  1232. stacks[g]->position -= 1;
  1233. }
  1234. }
  1235. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1236. //block engaged players
  1237. if(hero1->tempOwner<PLAYER_LIMIT)
  1238. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1239. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  1240. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1241. //send info about battles
  1242. BattleStart bs;
  1243. bs.info = curB;
  1244. sendAndApply(&bs);
  1245. }
  1246. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1247. {
  1248. //checking winning condition
  1249. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1250. hasStack[0] = hasStack[1] = false;
  1251. for(int b = 0; b<stacks.size(); ++b)
  1252. {
  1253. if(stacks[b]->alive())
  1254. {
  1255. hasStack[1-stacks[b]->attackerOwned] = true;
  1256. }
  1257. }
  1258. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1259. {
  1260. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1261. br->result = 0;
  1262. br->winner = hasStack[1]; //fleeing side loses
  1263. gs->curB->calculateCasualties(br->casualties);
  1264. battleResult.set(br);
  1265. }
  1266. }
  1267. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1268. {
  1269. if(!vstd::contains(h->artifWorn,17))
  1270. return; //hero hasn't spellbok
  1271. ChangeSpells cs;
  1272. cs.hid = h->id;
  1273. cs.learn = true;
  1274. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+4);i++)
  1275. {
  1276. for(int j=0; j<t->spellsAtLevel(i+1,true); j++)
  1277. {
  1278. if(!vstd::contains(h->spells,t->spells[i][j]))
  1279. cs.spells.insert(t->spells[i][j]);
  1280. }
  1281. }
  1282. if(cs.spells.size())
  1283. sendAndApply(&cs);
  1284. }