CGameHandler.cpp 14 KB

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