CGameHandler.cpp 15 KB

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