CGameHandler.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. extern bool end;
  21. bool makingTurn;
  22. boost::condition_variable cTurn;
  23. boost::mutex mTurn;
  24. boost::shared_mutex gsm;
  25. double distance(int3 a, int3 b)
  26. {
  27. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  28. }
  29. //bool CGameState::checkFunc(int obid, std::string name)
  30. //{
  31. // if (objscr.find(obid)!=objscr.end())
  32. // {
  33. // if(objscr[obid].find(name)!=objscr[obid].end())
  34. // {
  35. // return true;
  36. // }
  37. // }
  38. // return false;
  39. //}
  40. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  41. {
  42. std::vector<int> tempv = script->yourObjects();
  43. for (unsigned i=0;i<tempv.size();i++)
  44. {
  45. (*mapa)[tempv[i]]=script;
  46. }
  47. cppscripts.insert(script);
  48. }
  49. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  50. {
  51. try
  52. {
  53. ui16 pom;
  54. while(!end)
  55. {
  56. c >> pom;
  57. switch(pom)
  58. {
  59. case 100: //my interface ended its turn
  60. {
  61. mTurn.lock();
  62. makingTurn = false;
  63. mTurn.unlock();
  64. cTurn.notify_all();
  65. break;
  66. }
  67. case 501://interface wants to move hero
  68. {
  69. int3 start, end;
  70. si32 id;
  71. c >> id >> start >> end;
  72. int3 hmpos = end + int3(-1,0,0);
  73. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  74. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  75. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  76. TryMoveHero tmh;
  77. tmh.id = id;
  78. tmh.start = start;
  79. tmh.end = end;
  80. tmh.result = 0;
  81. tmh.movePoints = h->movement;
  82. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  83. (distance(start,end)>=1.5) || //tiles are not neighouring
  84. (h->movement < cost) || //lack of movement points
  85. (t.tertype == rock) || //rock
  86. (!h->canWalkOnSea() && t.tertype == water) ||
  87. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  88. goto fail;
  89. //check if there is blocking visitable object
  90. bool blockvis = false;
  91. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  92. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  93. {
  94. if(obj->blockVisit)
  95. {
  96. blockvis = true;
  97. break;
  98. }
  99. }
  100. //we start moving
  101. if(blockvis)//interaction with blocking object (like resources)
  102. {
  103. sendAndApply(&tmh); //failed to move to that tile but we visit object
  104. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  105. {
  106. if (obj->blockVisit)
  107. {
  108. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  109. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  110. if(obj->state) //hard-coded function
  111. obj->state->onHeroVisit(obj->id,h->subID);
  112. }
  113. }
  114. break;
  115. }
  116. else //normal move
  117. {
  118. tmh.result = 1;
  119. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x][start.y][start.z].visitableObjects)
  120. {
  121. //TODO: allow to handle this in script-languages
  122. if(obj->state) //hard-coded function
  123. obj->state->onHeroLeave(obj->id,h->subID);
  124. }
  125. //reveal fog of war
  126. int heroSight = h->getSightDistance();
  127. int xbeg = start.x - heroSight - 2;
  128. if(xbeg < 0)
  129. xbeg = 0;
  130. int xend = start.x + heroSight + 2;
  131. if(xend >= gs->map->width)
  132. xend = gs->map->width;
  133. int ybeg = start.y - heroSight - 2;
  134. if(ybeg < 0)
  135. ybeg = 0;
  136. int yend = start.y + heroSight + 2;
  137. if(yend >= gs->map->height)
  138. yend = gs->map->height;
  139. for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
  140. {
  141. for(int yd=ybeg; yd<yend; ++yd)
  142. {
  143. int deltaX = (hmpos.x-xd)*(hmpos.x-xd);
  144. int deltaY = (hmpos.y-yd)*(hmpos.y-yd);
  145. if(deltaX+deltaY<h->getSightDistance()*h->getSightDistance())
  146. {
  147. if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0)
  148. {
  149. tmh.fowRevealed.insert(int3(xd,yd,hmpos.z));
  150. }
  151. }
  152. }
  153. }
  154. sendAndApply(&tmh);
  155. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  156. {
  157. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  158. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  159. if(obj->state) //hard-coded function
  160. obj->state->onHeroVisit(obj->id,h->id);
  161. }
  162. }
  163. break;
  164. fail:
  165. sendAndApply(&tmh);
  166. break;
  167. }
  168. case 502: //swap creatures in garrison
  169. {
  170. ui8 what, p1, p2; si32 id1, id2;
  171. c >> what >> id1 >> p1 >> id2 >> p2;
  172. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  173. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  174. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  175. if(what==1) //swap
  176. {
  177. int pom = S2->slots[p2].first;
  178. S2->slots[p2].first = S1->slots[p1].first;
  179. S1->slots[p1].first = pom;
  180. int pom2 = S2->slots[p2].second;
  181. S2->slots[p2].second = S1->slots[p1].second;
  182. S1->slots[p1].second = pom2;
  183. if(!S1->slots[p1].first)
  184. S1->slots.erase(p1);
  185. if(!S2->slots[p2].first)
  186. S2->slots.erase(p2);
  187. }
  188. else if(what==2)//merge
  189. {
  190. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  191. S2->slots[p2].second += S1->slots[p1].second;
  192. S1->slots[p1].first = NULL;
  193. S1->slots[p1].second = 0;
  194. S1->slots.erase(p1);
  195. }
  196. else if(what==3) //split
  197. {
  198. si32 val;
  199. c >> val;
  200. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  201. S2->slots[p2].first = S1->slots[p1].first;
  202. S2->slots[p2].second = val;
  203. S1->slots[p1].second -= val;
  204. if(!S1->slots[p1].second) //if we've moved all creatures
  205. S1->slots.erase(p1);
  206. }
  207. SetGarrisons sg;
  208. sg.garrs[id1] = *S1;
  209. if(s1 != s2)
  210. sg.garrs[id2] = *S2;
  211. sendAndApply(&sg);
  212. break;
  213. }
  214. case 503:
  215. {
  216. si32 id;
  217. ui8 pos;
  218. c >> id >> pos;
  219. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  220. s1->army.slots.erase(pos);
  221. SetGarrisons sg;
  222. sg.garrs[id] = s1->army;
  223. sendAndApply(&sg);
  224. break;
  225. }
  226. case 504:
  227. {
  228. si32 tid, bid;
  229. c >> tid >> bid;
  230. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  231. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  232. for(int i=0;i<RESOURCE_QUANTITY;i++)
  233. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  234. break; //no res
  235. //TODO: check requirements
  236. //TODO: check if building isn't forbidden
  237. NewStructures ns;
  238. ns.tid = tid;
  239. if(bid>36) //upg dwelling
  240. {
  241. if(t->getHordeLevel(0) == (bid-37))
  242. ns.bid.insert(19);
  243. else if(t->getHordeLevel(1) == (bid-37))
  244. ns.bid.insert(25);
  245. }
  246. else if(bid >= 30) //bas. dwelling
  247. {
  248. SetStrInfo ssi;
  249. ssi.tid = tid;
  250. ssi.cres = t->strInfo.creatures;
  251. ssi.cres[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  252. sendAndApply(&ssi);
  253. }
  254. ns.bid.insert(bid);
  255. ns.builded = t->builded + 1;
  256. sendAndApply(&ns);
  257. SetResources sr;
  258. sr.player = t->tempOwner;
  259. sr.res = gs->players[t->tempOwner].resources;
  260. for(int i=0;i<7;i++)
  261. sr.res[i]-=b->resources[i];
  262. sendAndApply(&sr);
  263. break;
  264. }
  265. default:
  266. throw std::exception("Not supported client message!");
  267. break;
  268. }
  269. }
  270. }
  271. catch (const std::exception& e)
  272. {
  273. std::cerr << e.what() << std::endl;
  274. end = true;
  275. }
  276. catch (const std::exception * e)
  277. {
  278. std::cerr << e->what()<< std::endl;
  279. end = true;
  280. delete e;
  281. }
  282. catch(...)
  283. {
  284. end = true;
  285. }
  286. }
  287. CGameHandler::CGameHandler(void)
  288. {
  289. gs = NULL;
  290. }
  291. CGameHandler::~CGameHandler(void)
  292. {
  293. delete gs;
  294. }
  295. void CGameHandler::init(StartInfo *si, int Seed)
  296. {
  297. Mapa *map = new Mapa(si->mapname);
  298. gs = new CGameState();
  299. gs->init(si,map,Seed);
  300. /****************************LUA OBJECT SCRIPTS************************************************/
  301. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  302. //for (int i=0; i<lf->size(); i++)
  303. //{
  304. // try
  305. // {
  306. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  307. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  308. // CLuaCallback::registerFuncs(objs->is);
  309. // //objs
  310. // for (int j=0; j<temp->size(); j++)
  311. // {
  312. // int obid ; //obj ID
  313. // int dspos = (*temp)[j].find_first_of('_');
  314. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  315. // std::string fname = (*temp)[j].substr(0,dspos);
  316. // if (skrypty->find(obid)==skrypty->end())
  317. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  318. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  319. // }
  320. // delete temp;
  321. // }HANDLE_EXCEPTION
  322. //}
  323. //delete lf;
  324. }
  325. int lowestSpeed(CGHeroInstance * chi)
  326. {
  327. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  328. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  329. for (;i!=chi->army.slots.end();i++)
  330. {
  331. ret = min(ret,VLC->creh->creatures[(*i).second.first].speed);
  332. }
  333. return ret;
  334. }
  335. int valMovePoints(CGHeroInstance * chi)
  336. {
  337. int ret = 1270+70*lowestSpeed(chi);
  338. if (ret>2000)
  339. ret=2000;
  340. //TODO: additional bonuses (but they aren't currently stored in chi)
  341. return ret;
  342. }
  343. void CGameHandler::newTurn()
  344. {
  345. NewTurn n;
  346. n.day = gs->day + 1;
  347. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  348. {
  349. if(i->first>=PLAYER_LIMIT) continue;
  350. NewTurn::Resources r;
  351. r.player = i->first;
  352. for(int j=0;j<RESOURCE_QUANTITY;j++)
  353. r.resources[j] = i->second.resources[j];
  354. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  355. {
  356. NewTurn::Hero h;
  357. h.id = (*i).second.heroes[j]->id;
  358. h.move = valMovePoints((*i).second.heroes[j]);
  359. h.mana = (*i).second.heroes[j]->mana;
  360. n.heroes.insert(h);
  361. }
  362. for(unsigned j=0;j<i->second.towns.size();j++)//handle towns
  363. {
  364. i->second.towns[j]->builded=0;
  365. //if(gs->getDate(1)==1) //first day of week
  366. //{
  367. // for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  368. // {
  369. // if(i->second.towns[j]->creatureDwelling(k))//there is dwelling (k-level)
  370. // i->second.towns[j]->strInfo.creatures[k]+=i->second.towns[j]->creatureGrowth(k);
  371. // }
  372. //}
  373. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  374. r.resources[6] += i->second.towns[j]->dailyIncome();
  375. }
  376. n.res.insert(r);
  377. }
  378. sendAndApply(&n);
  379. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  380. {
  381. (*i)->newTurn();
  382. }
  383. }
  384. void CGameHandler::run()
  385. {
  386. BOOST_FOREACH(CConnection *cc, conns)
  387. {//init conn.
  388. ui8 quantity, pom;
  389. //ui32 seed;
  390. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  391. (*cc) >> quantity;
  392. for(int i=0;i<quantity;i++)
  393. {
  394. (*cc) >> pom;
  395. gsm.lock();
  396. connections[pom] = cc;
  397. gsm.unlock();
  398. }
  399. }
  400. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  401. {
  402. std::set<int> pom;
  403. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  404. if(j->second == *i)
  405. pom.insert(j->first);
  406. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  407. }
  408. /****************************SCRIPTS************************************************/
  409. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  410. /****************************C++ OBJECT SCRIPTS************************************************/
  411. std::map<int,CCPPObjectScript*> scripts;
  412. CScriptCallback * csc = new CScriptCallback();
  413. csc->gh = this;
  414. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  415. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  416. handleCPPObjS(&scripts,new CPickable(csc));
  417. handleCPPObjS(&scripts,new CMines(csc));
  418. handleCPPObjS(&scripts,new CTownScript(csc));
  419. handleCPPObjS(&scripts,new CHeroScript(csc));
  420. handleCPPObjS(&scripts,new CMonsterS(csc));
  421. handleCPPObjS(&scripts,new CCreatureGen(csc));
  422. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  423. //std::string temps("newObject");
  424. for (unsigned i=0; i<gs->map->objects.size(); i++)
  425. {
  426. //c++ scripts
  427. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  428. {
  429. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  430. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  431. }
  432. else
  433. {
  434. gs->map->objects[i]->state = NULL;
  435. }
  436. //// lua scripts
  437. //if(checkFunc(map->objects[i]->ID,temps))
  438. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  439. }
  440. while (!end)
  441. {
  442. newTurn();
  443. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  444. {
  445. if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0) continue; //players has not towns/castle - loser
  446. makingTurn = true;
  447. gs->currentPlayer = i->first;
  448. *connections[i->first] << ui16(100) << i->first;
  449. //wait till turn is done
  450. boost::unique_lock<boost::mutex> lock(mTurn);
  451. while(makingTurn && !end)
  452. {
  453. boost::posix_time::time_duration p;
  454. p= boost::posix_time::seconds(1);
  455. cTurn.timed_wait(lock,p);
  456. }
  457. }
  458. }
  459. }