CGameHandler.cpp 33 KB

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