CGameHandler.cpp 28 KB

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