CGameHandler.cpp 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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/CArtHandler.h"
  14. #include "../hch/CObjectHandler.h"
  15. #include "../hch/CSpellHandler.h"
  16. #include "../hch/CTownHandler.h"
  17. #include "../hch/CBuildingHandler.h"
  18. #include "../hch/CHeroHandler.h"
  19. #include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types
  20. #include "../lib/VCMI_Lib.h"
  21. #include "../lib/CondSh.h"
  22. #include <fstream>
  23. #ifndef _MSC_VER
  24. #include <boost/thread/xtime.hpp>
  25. #endif
  26. extern bool end2;
  27. #include "../lib/BattleAction.h"
  28. #ifdef min
  29. #undef min
  30. #endif
  31. #ifdef max
  32. #undef max
  33. #endif
  34. #define NEW_ROUND BattleNextRound bnr;\
  35. bnr.round = gs->curB->round + 1;\
  36. sendAndApply(&bnr);
  37. boost::mutex gsm;
  38. ui32 CGameHandler::QID = 1;
  39. CondSh<bool> battleMadeAction;
  40. CondSh<BattleResult *> battleResult(NULL);
  41. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  42. class CMP_stack
  43. {
  44. public:
  45. bool operator ()(const CStack* a, const CStack* b)
  46. {
  47. return (a->creature->speed)>(b->creature->speed);
  48. }
  49. } cmpst ;
  50. double distance(int3 a, int3 b)
  51. {
  52. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  53. }
  54. void giveExp(BattleResult &r)
  55. {
  56. r.exp[0] = 0;
  57. r.exp[1] = 0;
  58. for(std::set<std::pair<ui32,si32> >::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  59. {
  60. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  61. }
  62. }
  63. //bool CGameState::checkFunc(int obid, std::string name)
  64. //{
  65. // if (objscr.find(obid)!=objscr.end())
  66. // {
  67. // if(objscr[obid].find(name)!=objscr[obid].end())
  68. // {
  69. // return true;
  70. // }
  71. // }
  72. // return false;
  73. //}
  74. PlayerStatus PlayerStatuses::operator[](ui8 player)
  75. {
  76. boost::unique_lock<boost::mutex> l(mx);
  77. if(players.find(player) != players.end())
  78. {
  79. return players[player];
  80. }
  81. else
  82. {
  83. throw std::string("No such player!");
  84. }
  85. }
  86. void PlayerStatuses::addPlayer(ui8 player)
  87. {
  88. boost::unique_lock<boost::mutex> l(mx);
  89. players[player];
  90. }
  91. bool PlayerStatuses::hasQueries(ui8 player)
  92. {
  93. boost::unique_lock<boost::mutex> l(mx);
  94. if(players.find(player) != players.end())
  95. {
  96. return players[player].queries.size();
  97. }
  98. else
  99. {
  100. throw std::string("No such player!");
  101. }
  102. }
  103. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  104. {
  105. boost::unique_lock<boost::mutex> l(mx);
  106. if(players.find(player) != players.end())
  107. {
  108. return players[player].*flag;
  109. }
  110. else
  111. {
  112. throw std::string("No such player!");
  113. }
  114. }
  115. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  116. {
  117. boost::unique_lock<boost::mutex> l(mx);
  118. if(players.find(player) != players.end())
  119. {
  120. players[player].*flag = val;
  121. }
  122. else
  123. {
  124. throw std::string("No such player!");
  125. }
  126. cv.notify_all();
  127. }
  128. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  129. {
  130. boost::unique_lock<boost::mutex> l(mx);
  131. if(players.find(player) != players.end())
  132. {
  133. players[player].queries.insert(id);
  134. }
  135. else
  136. {
  137. throw std::string("No such player!");
  138. }
  139. cv.notify_all();
  140. }
  141. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  142. {
  143. boost::unique_lock<boost::mutex> l(mx);
  144. if(players.find(player) != players.end())
  145. {
  146. players[player].queries.erase(id);
  147. }
  148. else
  149. {
  150. throw std::string("No such player!");
  151. }
  152. cv.notify_all();
  153. }
  154. void CGameHandler::handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
  155. {
  156. std::vector<int> tempv = script->yourObjects();
  157. for (unsigned i=0;i<tempv.size();i++)
  158. {
  159. (*mapa)[tempv[i]]=script;
  160. }
  161. cppscripts.insert(script);
  162. }
  163. template <typename T>
  164. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  165. {
  166. fun(args[which]);
  167. }
  168. void CGameHandler::changeSecSkill(int ID, ui16 which, int val, bool abs)
  169. {
  170. SetSecSkill sps;
  171. sps.id = ID;
  172. sps.which = which;
  173. sps.abs = abs;
  174. sps.val = val;
  175. sendAndApply(&sps);
  176. }
  177. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  178. {
  179. SetPrimSkill sps;
  180. sps.id = ID;
  181. sps.which = which;
  182. sps.abs = abs;
  183. sps.val = val;
  184. sendAndApply(&sps);
  185. if(which==4) //only for exp - hero may level up
  186. {
  187. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  188. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  189. {
  190. //give prim skill
  191. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  192. int r = rand()%100, pom=0, x=0;
  193. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  194. for(;x<PRIMARY_SKILLS;x++)
  195. {
  196. pom += hero->type->heroClass->primChance[x].*g;
  197. if(r<pom)
  198. break;
  199. }
  200. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  201. SetPrimSkill sps;
  202. sps.id = ID;
  203. sps.which = x;
  204. sps.abs = false;
  205. sps.val = 1;
  206. sendAndApply(&sps);
  207. HeroLevelUp hlu;
  208. hlu.heroid = ID;
  209. hlu.primskill = x;
  210. hlu.level = hero->level+1;
  211. //picking sec. skills for choice
  212. std::set<int> basicAndAdv, expert, none;
  213. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  214. for(unsigned i=0;i<hero->secSkills.size();i++)
  215. {
  216. if(hero->secSkills[i].second < 3)
  217. basicAndAdv.insert(hero->secSkills[i].first);
  218. else
  219. expert.insert(hero->secSkills[i].first);
  220. none.erase(hero->secSkills[i].first);
  221. }
  222. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  223. {
  224. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  225. }
  226. else
  227. {
  228. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  229. hlu.skills.push_back(s);
  230. basicAndAdv.erase(s);
  231. }
  232. if(basicAndAdv.size())
  233. {
  234. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  235. }
  236. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  237. {
  238. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  239. }
  240. boost::function<void(ui32)> callback = boost::function<void(ui32)>(boost::bind(callWith<ui16>,hlu.skills,boost::function<void(ui16)>(boost::bind(&CGameHandler::changeSecSkill,this,ID,_1,1,0)),_1));
  241. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  242. }
  243. }
  244. }
  245. CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  246. {
  247. CCreatureSet ret(set);
  248. for(int i=0; i<bat->stacks.size();i++)
  249. {
  250. CStack *st = bat->stacks[i];
  251. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  252. {
  253. if(st->alive())
  254. ret.slots[st->slot].second = st->amount;
  255. else
  256. ret.slots.erase(st->slot);
  257. }
  258. }
  259. return ret;
  260. }
  261. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  262. {
  263. BattleInfo *curB = new BattleInfo;
  264. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  265. NEW_ROUND;
  266. //TODO: pre-tactic stuff, call scripts etc.
  267. //tactic round
  268. {
  269. NEW_ROUND;
  270. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  271. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  272. {
  273. //TODO: tactic round (round -1)
  274. }
  275. }
  276. //main loop
  277. while(!battleResult.get()) //till the end of the battle ;]
  278. {
  279. NEW_ROUND;
  280. std::vector<CStack*> & stacks = (gs->curB->stacks);
  281. const BattleInfo & curB = *gs->curB;
  282. //stack loop
  283. for(unsigned i=0;i<stacks.size() && !battleResult.get();i++)
  284. {
  285. if(!stacks[i]->alive()) continue;//indicates imposiibility of making action for this dead unit
  286. BattleSetActiveStack sas;
  287. sas.stack = stacks[i]->ID;
  288. sendAndApply(&sas);
  289. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  290. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  291. battleMadeAction.cond.wait(lock);
  292. battleMadeAction.data = false;
  293. checkForBattleEnd(stacks); //check if this action ended the battle
  294. }
  295. }
  296. //unblock engaged players
  297. if(hero1->tempOwner<PLAYER_LIMIT)
  298. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  299. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  300. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  301. //casualties among heroes armies
  302. SetGarrisons sg;
  303. if(hero1)
  304. sg.garrs[hero1->id] = takeCasualties(hero1->tempOwner,hero1->army,gs->curB);
  305. if(hero2)
  306. sg.garrs[hero2->id] = takeCasualties(hero2->tempOwner,hero2->army,gs->curB);
  307. sendAndApply(&sg);
  308. //end battle, remove all info, free memory
  309. giveExp(*battleResult.data);
  310. sendAndApply(battleResult.data);
  311. if(cb)
  312. cb(battleResult.data);
  313. //if one hero has lost we will erase him
  314. if(battleResult.data->winner!=0 && hero1)
  315. {
  316. RemoveObject ro(hero1->id);
  317. sendAndApply(&ro);
  318. }
  319. if(battleResult.data->winner!=1 && hero2)
  320. {
  321. RemoveObject ro(hero2->id);
  322. sendAndApply(&ro);
  323. }
  324. //give exp
  325. if(battleResult.data->exp[0] && hero1)
  326. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  327. if(battleResult.data->exp[1] && hero2)
  328. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  329. delete battleResult.data;
  330. }
  331. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def, bool shooting)
  332. {
  333. bat.stackAttacking = att->ID;
  334. bat.bsa.stackAttacked = def->ID;
  335. bat.bsa.damageAmount = BattleInfo::calculateDmg(att, def, gs->getHero(att->attackerOwned ? gs->curB->hero1 : gs->curB->hero2), gs->getHero(def->attackerOwned ? gs->curB->hero1 : gs->curB->hero2), shooting);//counting dealt damage
  336. //applying damages
  337. bat.bsa.killedAmount = bat.bsa.damageAmount / def->creature->hitPoints;
  338. unsigned damageFirst = bat.bsa.damageAmount % def->creature->hitPoints;
  339. if( def->firstHPleft <= damageFirst )
  340. {
  341. bat.bsa.killedAmount++;
  342. bat.bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  343. }
  344. else
  345. {
  346. bat.bsa.newHP = def->firstHPleft - damageFirst;
  347. }
  348. if(def->amount <= bat.bsa.killedAmount) //stack killed
  349. {
  350. bat.bsa.newAmount = 0;
  351. bat.bsa.flags |= 1;
  352. bat.bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  353. }
  354. else
  355. {
  356. bat.bsa.newAmount = def->amount - bat.bsa.killedAmount;
  357. }
  358. }
  359. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  360. {
  361. try
  362. {
  363. ui16 pom;
  364. while(!end2)
  365. {
  366. c >> pom;
  367. bool blockvis = false;
  368. switch(pom)
  369. {
  370. case 99: //end!
  371. {
  372. tlog0 << "We have been requested to close.\n";
  373. exit(0);
  374. }
  375. case 100: //my interface ended its turn
  376. {
  377. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  378. break;
  379. }
  380. case 500: //dismiss hero
  381. {
  382. si32 id;
  383. c >> id;
  384. RemoveObject rh(id);
  385. sendAndApply(&rh);
  386. break;
  387. }
  388. case 501://interface wants to move hero
  389. {
  390. int3 start, end;
  391. si32 id;
  392. c >> id >> start >> end;
  393. tlog5 << "Interface wants to move hero "<<id << " from "<<start << " to " << end << std::endl;
  394. int3 hmpos = end + int3(-1,0,0);
  395. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  396. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  397. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  398. TryMoveHero tmh;
  399. tmh.id = id;
  400. tmh.start = start;
  401. tmh.end = end;
  402. tmh.result = 0;
  403. tmh.movePoints = h->movement;
  404. if((h->getOwner() != gs->currentPlayer) || //not turn of that hero
  405. (distance(start,end)>=1.5) || //tiles are not neighouring
  406. (h->movement < cost) || //lack of movement points
  407. (t.tertype == rock) || //rock
  408. (!h->canWalkOnSea() && t.tertype == water) ||
  409. (t.blocked && !t.visitable) ) //tile is blocked andnot visitable
  410. goto fail;
  411. //check if there is blocking visitable object
  412. blockvis = false;
  413. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  414. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  415. {
  416. if(obj->blockVisit)
  417. {
  418. blockvis = true;
  419. break;
  420. }
  421. }
  422. //we start moving
  423. if(blockvis)//interaction with blocking object (like resources)
  424. {
  425. sendAndApply(&tmh); //failed to move to that tile but we visit object
  426. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  427. {
  428. if (obj->blockVisit)
  429. {
  430. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  431. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  432. if(obj->state) //hard-coded function
  433. obj->state->onHeroVisit(obj->id,h->id);
  434. }
  435. }
  436. tlog5 << "Blocing visit at " << hmpos << std::endl;
  437. break;
  438. }
  439. else //normal move
  440. {
  441. tmh.result = 1;
  442. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x-1][start.y][start.z].visitableObjects)
  443. {
  444. //TODO: allow to handle this in script-languages
  445. if(obj->state) //hard-coded function
  446. obj->state->onHeroLeave(obj->id,h->id);
  447. }
  448. tmh.fowRevealed = gs->tilesToReveal(h->getPosition(false),h->getSightDistance(),h->tempOwner);
  449. sendAndApply(&tmh);
  450. tlog5 << "Moved to " <<tmh.end<<std::endl;
  451. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  452. {
  453. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  454. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  455. if(obj->state) //hard-coded function
  456. obj->state->onHeroVisit(obj->id,h->id);
  457. }
  458. }
  459. tlog5 << "Movement end!\n";
  460. break;
  461. fail:
  462. tlog2 << "Movement failed to " << tmh.end << std::endl;
  463. sendAndApply(&tmh);
  464. break;
  465. }
  466. case 502: //swap creatures in garrison
  467. {
  468. ui8 what, p1, p2; si32 id1, id2;
  469. c >> what >> id1 >> p1 >> id2 >> p2;
  470. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  471. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  472. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  473. if(what==1) //swap
  474. {
  475. int pom = S2->slots[p2].first;
  476. S2->slots[p2].first = S1->slots[p1].first;
  477. S1->slots[p1].first = pom;
  478. int pom2 = S2->slots[p2].second;
  479. S2->slots[p2].second = S1->slots[p1].second;
  480. S1->slots[p1].second = pom2;
  481. if(!S1->slots[p1].second)
  482. S1->slots.erase(p1);
  483. if(!S2->slots[p2].second)
  484. S2->slots.erase(p2);
  485. }
  486. else if(what==2)//merge
  487. {
  488. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  489. S2->slots[p2].second += S1->slots[p1].second;
  490. S1->slots[p1].first = NULL;
  491. S1->slots[p1].second = 0;
  492. S1->slots.erase(p1);
  493. }
  494. else if(what==3) //split
  495. {
  496. si32 val;
  497. c >> val;
  498. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  499. S2->slots[p2].first = S1->slots[p1].first;
  500. S2->slots[p2].second = val;
  501. S1->slots[p1].second -= val;
  502. if(!S1->slots[p1].second) //if we've moved all creatures
  503. S1->slots.erase(p1);
  504. }
  505. if((s1->ID==34 && !S1->slots.size()) //it's not allowed to take last stack from hero army!
  506. || (s2->ID==34 && !S2->slots.size()))
  507. {
  508. break;
  509. }
  510. SetGarrisons sg;
  511. sg.garrs[id1] = *S1;
  512. if(s1 != s2)
  513. sg.garrs[id2] = *S2;
  514. sendAndApply(&sg);
  515. break;
  516. }
  517. case 503: //disband creature
  518. {
  519. si32 id;
  520. ui8 pos;
  521. c >> id >> pos;
  522. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  523. s1->army.slots.erase(pos);
  524. SetGarrisons sg;
  525. sg.garrs[id] = s1->army;
  526. sendAndApply(&sg);
  527. break;
  528. }
  529. case 504: //build structure
  530. {
  531. si32 tid, bid;
  532. c >> tid >> bid;
  533. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  534. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  535. for(int i=0;i<RESOURCE_QUANTITY;i++)
  536. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  537. break; //no res
  538. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][bid].begin();
  539. ri != VLC->townh->requirements[t->subID][bid].end();
  540. ri++ )
  541. {
  542. if(!vstd::contains(t->builtBuildings,*ri))
  543. break; //lack of requirements - cannot build
  544. }
  545. if(vstd::contains(t->forbiddenBuildings,bid))
  546. break; //this building is forbidden
  547. NewStructures ns;
  548. ns.tid = tid;
  549. if(bid>36) //upg dwelling
  550. {
  551. if(t->getHordeLevel(0) == (bid-37))
  552. ns.bid.insert(19);
  553. else if(t->getHordeLevel(1) == (bid-37))
  554. ns.bid.insert(25);
  555. }
  556. else if(bid >= 30) //bas. dwelling
  557. {
  558. SetAvailableCreatures ssi;
  559. ssi.tid = tid;
  560. ssi.creatures = t->strInfo.creatures;
  561. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  562. sendAndApply(&ssi);
  563. }
  564. ns.bid.insert(bid);
  565. ns.builded = t->builded + 1;
  566. sendAndApply(&ns);
  567. SetResources sr;
  568. sr.player = t->tempOwner;
  569. sr.res = gs->players[t->tempOwner].resources;
  570. for(int i=0;i<7;i++)
  571. sr.res[i]-=b->resources[i];
  572. sendAndApply(&sr);
  573. if(bid<5) //it's mage guild
  574. {
  575. if(t->visitingHero)
  576. giveSpells(t,t->visitingHero);
  577. if(t->garrisonHero)
  578. giveSpells(t,t->garrisonHero);
  579. }
  580. break;
  581. }
  582. case 506: //recruit creature
  583. {
  584. si32 objid, ser=-1; //ser - used dwelling level
  585. ui32 crid, cram; //recruited creature id and amount
  586. c >> objid >> crid >> cram;
  587. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  588. //verify
  589. bool found = false;
  590. typedef std::pair<const int,int> Parka;
  591. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  592. {
  593. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  594. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  595. {
  596. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  597. ser = av->first;
  598. break;
  599. }
  600. }
  601. int slot = t->army.getSlotFor(crid);
  602. if(!found || //no such creature
  603. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  604. cram<=0 ||
  605. slot<0 )
  606. break;
  607. //recruit
  608. SetResources sr;
  609. sr.player = t->tempOwner;
  610. for(int i=0;i<RESOURCE_QUANTITY;i++)
  611. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  612. SetAvailableCreatures sac;
  613. sac.tid = objid;
  614. sac.creatures = t->strInfo.creatures;
  615. sac.creatures[ser] -= cram;
  616. SetGarrisons sg;
  617. sg.garrs[objid] = t->army;
  618. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  619. {
  620. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  621. }
  622. else //add creatures to a already existing stack
  623. {
  624. sg.garrs[objid].slots[slot].second += cram;
  625. }
  626. sendAndApply(&sr);
  627. sendAndApply(&sac);
  628. sendAndApply(&sg);
  629. break;
  630. }
  631. case 507://upgrade creature
  632. {
  633. ui32 objid, upgID;
  634. ui8 pos;
  635. c >> objid >> pos >> upgID;
  636. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  637. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  638. int player = obj->tempOwner;
  639. int crQuantity = obj->army.slots[pos].second;
  640. //check if upgrade is possible
  641. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  642. break;
  643. //check if player has enough resources
  644. for(int i=0;i<ui.cost.size();i++)
  645. {
  646. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  647. {
  648. if(gs->players[player].resources[j->first] < j->second*crQuantity)
  649. goto upgend;
  650. }
  651. }
  652. //take resources
  653. for(int i=0;i<ui.cost.size();i++)
  654. {
  655. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  656. {
  657. SetResource sr;
  658. sr.player = player;
  659. sr.resid = j->first;
  660. sr.val = gs->players[player].resources[j->first] - j->second*crQuantity;
  661. sendAndApply(&sr);
  662. }
  663. }
  664. {
  665. //upgrade creature
  666. SetGarrisons sg;
  667. sg.garrs[objid] = obj->army;
  668. sg.garrs[objid].slots[pos].first = upgID;
  669. sendAndApply(&sg);
  670. }
  671. upgend:
  672. break;
  673. }
  674. case 508: //garrison swap
  675. {
  676. si32 tid;
  677. c >> tid;
  678. CGTownInstance *town = gs->getTown(tid);
  679. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  680. {
  681. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  682. while(!cso.slots.empty())//while there are unmoved creatures
  683. {
  684. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  685. if(pos<0)
  686. goto handleConEnd;
  687. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  688. {
  689. csn.slots[pos].second += cso.slots.begin()->second.second;
  690. }
  691. else //move stack on the free pos
  692. {
  693. csn.slots[pos].first = cso.slots.begin()->second.first;
  694. csn.slots[pos].second = cso.slots.begin()->second.second;
  695. }
  696. cso.slots.erase(cso.slots.begin());
  697. }
  698. SetGarrisons sg;
  699. sg.garrs[town->visitingHero->id] = csn;
  700. sg.garrs[town->id] = csn;
  701. sendAndApply(&sg);
  702. SetHeroesInTown intown;
  703. intown.tid = tid;
  704. intown.visiting = -1;
  705. intown.garrison = town->visitingHero->id;
  706. sendAndApply(&intown);
  707. }
  708. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  709. {
  710. SetHeroesInTown intown;
  711. intown.tid = tid;
  712. intown.garrison = -1;
  713. intown.visiting = town->garrisonHero->id;
  714. sendAndApply(&intown);
  715. //town will be empty
  716. SetGarrisons sg;
  717. sg.garrs[tid] = CCreatureSet();
  718. sendAndApply(&sg);
  719. }
  720. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  721. {
  722. SetGarrisons sg;
  723. sg.garrs[town->id] = town->visitingHero->army;
  724. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  725. //sg.garrs[town->visitingHero->id] = town->visitingHero->army;
  726. SetHeroesInTown intown;
  727. intown.tid = tid;
  728. intown.garrison = town->visitingHero->id;
  729. intown.visiting = town->garrisonHero->id;
  730. sendAndApply(&intown);
  731. sendAndApply(&sg);
  732. }
  733. else
  734. {
  735. tlog3 << "Warning, wrong garrison swap command for " << tid << std::endl;
  736. }
  737. break;
  738. }
  739. case 509: //swap artifacts
  740. {
  741. si32 hid1, hid2;
  742. ui16 slot1, slot2;
  743. c >> hid1 >> slot1 >> hid2 >> slot2;
  744. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  745. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  746. break;
  747. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  748. h2->setArtAtPos(slot2,a1);
  749. h1->setArtAtPos(slot1,a2);
  750. SetHeroArtifacts sha;
  751. sha.hid = hid1;
  752. sha.artifacts = h1->artifacts;
  753. sha.artifWorn = h1->artifWorn;
  754. sendAndApply(&sha);
  755. if(hid1 != hid2)
  756. {
  757. sha.hid = hid2;
  758. sha.artifacts = h2->artifacts;
  759. sha.artifWorn = h2->artifWorn;
  760. sendAndApply(&sha);
  761. }
  762. break;
  763. }
  764. case 510: //buy artifact
  765. {
  766. ui32 hid;
  767. si32 aid, bid;
  768. c >> hid >> aid;
  769. CGHeroInstance *hero = gs->getHero(hid);
  770. CGTownInstance *town = hero->visitedTown;
  771. if(aid==0) //spellbok
  772. {
  773. if(!vstd::contains(town->builtBuildings,si32(0)))
  774. break;
  775. SetResource sr;
  776. sr.player = hero->tempOwner;
  777. sr.resid = 6;
  778. sr.val = gs->players[hero->tempOwner].resources[6] - 500;
  779. sendAndApply(&sr);
  780. SetHeroArtifacts sha;
  781. sha.hid = hid;
  782. sha.artifacts = hero->artifacts;
  783. sha.artifWorn = hero->artifWorn;
  784. sha.artifWorn[17] = 0;
  785. sendAndApply(&sha);
  786. giveSpells(town,hero);
  787. }
  788. else if(aid < 7 && aid > 3) //war machine
  789. {
  790. int price = VLC->arth->artifacts[aid].price;
  791. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  792. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  793. || gs->players[hero->tempOwner].resources[6] < price //no gold
  794. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  795. {
  796. break;
  797. }
  798. SetResource sr;
  799. sr.player = hero->tempOwner;
  800. sr.resid = 6;
  801. sr.val = gs->players[hero->tempOwner].resources[6] - price;
  802. sendAndApply(&sr);
  803. SetHeroArtifacts sha;
  804. sha.hid = hid;
  805. sha.artifacts = hero->artifacts;
  806. sha.artifWorn = hero->artifWorn;
  807. sha.artifWorn[9+aid] = aid;
  808. sendAndApply(&sha);
  809. }
  810. break;
  811. }
  812. case 511: //trade at marketplace
  813. {
  814. ui8 player;
  815. ui32 mode, id1, id2, val;
  816. c >> player >> mode >> id1 >> id2 >> val;
  817. val = std::min(si32(val),gs->players[player].resources[id1]);
  818. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  819. uzysk /= gs->resVals[id2];
  820. SetResource sr;
  821. sr.player = player;
  822. sr.resid = id1;
  823. sr.val = gs->players[player].resources[id1] - val;
  824. sendAndApply(&sr);
  825. sr.resid = id2;
  826. sr.val = gs->players[player].resources[id2] + (int)uzysk;
  827. sendAndApply(&sr);
  828. break;
  829. }
  830. case 512:
  831. {
  832. si32 hid;
  833. ui8 formation;
  834. c >> hid >> formation;
  835. gs->getHero(hid)->army.formation = formation;
  836. break;
  837. }
  838. case 2001:
  839. {
  840. ui32 qid, answer;
  841. c >> qid >> answer;
  842. gsm.lock();
  843. CFunctionList<void(ui32)> callb = callbacks[qid];
  844. callbacks.erase(qid);
  845. gsm.unlock();
  846. callb(answer);
  847. break;
  848. }
  849. case 3002:
  850. {
  851. BattleAction ba;
  852. c >> ba;
  853. switch(ba.actionType)
  854. {
  855. case 2: //walk
  856. {
  857. sendAndApply(&StartAction(ba)); //start movement
  858. moveStack(ba.stackNumber,ba.destinationTile); //move
  859. sendDataToClients(ui16(3008)); //endmovement
  860. break;
  861. }
  862. case 3: //defend
  863. {
  864. break;
  865. }
  866. case 4: //retreat/flee
  867. {
  868. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  869. //TODO: calculate casualties
  870. //TODO: remove retreating hero from map and place it in recrutation list
  871. BattleResult *br = new BattleResult;
  872. br->result = 1;
  873. br->winner = !ba.side; //fleeing side loses
  874. gs->curB->calculateCasualties(br->casualties);
  875. giveExp(*br);
  876. battleResult.set(br);
  877. break;
  878. }
  879. case 6: //walk or attack
  880. {
  881. sendAndApply(&StartAction(ba)); //start movement and attack
  882. moveStack(ba.stackNumber,ba.destinationTile);
  883. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  884. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  885. if((curStack->position != ba.destinationTile) || //we wasn't able to reach destination tile
  886. (BattleInfo::mutualPosition(ba.destinationTile,ba.additionalInfo)<0) ) //destination tile is not neighbouring with enemy stack
  887. return;
  888. BattleAttack bat;
  889. prepareAttack(bat,curStack,stackAtEnd,false);
  890. sendAndApply(&bat);
  891. //counterattack
  892. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  893. && stackAtEnd->alive()
  894. && stackAtEnd->counterAttacks ) //TODO: support for multiple retaliatons per turn
  895. {
  896. prepareAttack(bat,stackAtEnd,curStack,false);
  897. bat.flags |= 2;
  898. sendAndApply(&bat);
  899. }
  900. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  901. && curStack->alive()
  902. && stackAtEnd->alive() )
  903. {
  904. bat.flags = 0;
  905. prepareAttack(bat,curStack,stackAtEnd,false);
  906. sendAndApply(&bat);
  907. }
  908. sendDataToClients(ui16(3008)); //end movement and attack
  909. break;
  910. }
  911. case 7: //shoot
  912. {
  913. //TODO: check arrows count
  914. //TODO: check if stack isn't blocked by enemy
  915. sendAndApply(&StartAction(ba)); //start shooting
  916. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  917. *destStack= gs->curB->getStackT(ba.destinationTile);
  918. BattleAttack bat;
  919. prepareAttack(bat,curStack,destStack,true);
  920. bat.flags |= 1;
  921. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  922. && curStack->alive())
  923. {
  924. prepareAttack(bat,curStack,destStack,true);
  925. sendAndApply(&bat);
  926. }
  927. sendAndApply(&bat);
  928. sendDataToClients(ui16(3008)); //end shooting
  929. break;
  930. }
  931. }
  932. battleMadeAction.setn(true);
  933. break;
  934. }
  935. case 3003: //custom action (probably spell)
  936. {
  937. BattleAction ba;
  938. c >> ba;
  939. switch(ba.actionType)
  940. {
  941. case 1: //hero casts spell
  942. {
  943. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  944. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  945. int skill = 0;
  946. if(s->fire)
  947. skill = std::max(skill,h->getSecSkillLevel(14));
  948. if(s->air)
  949. skill = std::max(skill,h->getSecSkillLevel(15));
  950. if(s->water)
  951. skill = std::max(skill,h->getSecSkillLevel(16));
  952. if(s->earth)
  953. skill = std::max(skill,h->getSecSkillLevel(17));
  954. if( !vstd::contains(h->spells,ba.additionalInfo) //hero doesn't know this spell
  955. || (h->mana < s->costs[skill]) //not enough mana
  956. || 0 )//TODO: hero has already casted a spell in this round
  957. {
  958. goto customactionend;
  959. }
  960. sendAndApply(&StartAction(ba)); //start spell casting
  961. //TODO: spell efects
  962. sendDataToClients(ui16(3008)); //end casting
  963. break;
  964. }
  965. }
  966. customactionend:
  967. break;
  968. }
  969. default:
  970. throw std::string("Not supported client message!");
  971. }
  972. }
  973. }
  974. catch (const std::exception& e)
  975. {
  976. tlog1 << "Exception during handling connection: " << e.what() << std::endl;
  977. end2 = true;
  978. }
  979. catch (const std::exception * e)
  980. {
  981. tlog1 << "Exception during handling connection: " << e->what()<< std::endl;
  982. end2 = true;
  983. delete e;
  984. }
  985. catch(...)
  986. {
  987. end2 = true;
  988. }
  989. handleConEnd:
  990. tlog1 << "Ended handling connection\n";
  991. }
  992. void CGameHandler::moveStack(int stack, int dest)
  993. {
  994. CStack *curStack = gs->curB->getStack(stack),
  995. *stackAtEnd = gs->curB->getStackT(dest);
  996. //initing necessary tables
  997. bool accessibility[187];
  998. if(curStack->creature->isDoubleWide())
  999. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned,curStack->ID);
  1000. else
  1001. gs->curB->getAccessibilityMap(accessibility,curStack->ID);
  1002. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  1003. return;
  1004. //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
  1005. // return false;
  1006. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  1007. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  1008. for(int v=path.size()-1; v>=tilesToMove; --v)
  1009. {
  1010. //inform clients about move
  1011. BattleStackMoved sm;
  1012. sm.stack = curStack->ID;
  1013. sm.tile = path[v];
  1014. sendAndApply(&sm);
  1015. }
  1016. }
  1017. CGameHandler::CGameHandler(void)
  1018. {
  1019. gs = NULL;
  1020. }
  1021. CGameHandler::~CGameHandler(void)
  1022. {
  1023. delete gs;
  1024. }
  1025. void CGameHandler::init(StartInfo *si, int Seed)
  1026. {
  1027. Mapa *map = new Mapa(si->mapname);
  1028. tlog0 << "Map loaded!" << std::endl;
  1029. gs = new CGameState();
  1030. tlog0 << "Gamestate created!" << std::endl;
  1031. gs->init(si,map,Seed);
  1032. tlog0 << "Gamestate initialized!" << std::endl;
  1033. /****************************LUA OBJECT SCRIPTS************************************************/
  1034. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  1035. //for (int i=0; i<lf->size(); i++)
  1036. //{
  1037. // try
  1038. // {
  1039. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  1040. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  1041. // CLuaCallback::registerFuncs(objs->is);
  1042. // //objs
  1043. // for (int j=0; j<temp->size(); j++)
  1044. // {
  1045. // int obid ; //obj ID
  1046. // int dspos = (*temp)[j].find_first_of('_');
  1047. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  1048. // std::string fname = (*temp)[j].substr(0,dspos);
  1049. // if (skrypty->find(obid)==skrypty->end())
  1050. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  1051. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  1052. // }
  1053. // delete temp;
  1054. // }HANDLE_EXCEPTION
  1055. //}
  1056. //delete lf;
  1057. }
  1058. int lowestSpeed(CGHeroInstance * chi)
  1059. {
  1060. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  1061. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  1062. for (;i!=chi->army.slots.end();i++)
  1063. {
  1064. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  1065. }
  1066. return ret;
  1067. }
  1068. int valMovePoints(CGHeroInstance * chi, bool onLand)
  1069. {
  1070. int ret = 1270+70*lowestSpeed(chi);
  1071. if (ret>2000)
  1072. ret=2000;
  1073. if(onLand)
  1074. {
  1075. //logistics:
  1076. switch(chi->getSecSkillLevel(2))
  1077. {
  1078. case 1:
  1079. ret *= 1.1f;
  1080. break;
  1081. case 2:
  1082. ret *= 1.2f;
  1083. break;
  1084. case 3:
  1085. ret *= 1.3f;
  1086. break;
  1087. }
  1088. }
  1089. else
  1090. {
  1091. //navigation:
  1092. switch(chi->getSecSkillLevel(2))
  1093. {
  1094. case 1:
  1095. ret *= 1.5f;
  1096. break;
  1097. case 2:
  1098. ret *= 2.0f;
  1099. break;
  1100. case 3:
  1101. ret *= 2.5f;
  1102. break;
  1103. }
  1104. }
  1105. //TODO: additional bonuses (but they aren't currently stored in chi)
  1106. return ret;
  1107. }
  1108. void CGameHandler::newTurn()
  1109. {
  1110. NewTurn n;
  1111. n.day = gs->day + 1;
  1112. n.resetBuilded = true;
  1113. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  1114. {
  1115. if(i->first>=PLAYER_LIMIT) continue;
  1116. SetResources r;
  1117. r.player = i->first;
  1118. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1119. r.res[j] = i->second.resources[j];
  1120. for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes
  1121. {
  1122. NewTurn::Hero h;
  1123. h.id = (*i).second.heroes[j]->id;
  1124. h.move = valMovePoints((*i).second.heroes[j], true); //TODO: check if hero is really on the land
  1125. h.mana = (*i).second.heroes[j]->mana;
  1126. n.heroes.insert(h);
  1127. //handle estates
  1128. switch((*i).second.heroes[j]->getSecSkillLevel(13))
  1129. {
  1130. case 1: //basic
  1131. r.res[6] += 125;
  1132. break;
  1133. case 2: //advanced
  1134. r.res[6] += 250;
  1135. break;
  1136. case 3: //expert
  1137. r.res[6] += 500;
  1138. break;
  1139. }
  1140. }
  1141. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  1142. {
  1143. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  1144. {
  1145. if((**j).town->primaryRes == 127) //we'll give wood and ore
  1146. {
  1147. r.res[0] += 1;
  1148. r.res[2] += 1;
  1149. }
  1150. else
  1151. {
  1152. r.res[(**j).town->primaryRes] += 1;
  1153. }
  1154. }
  1155. if(gs->getDate(1)==7) //first day of week
  1156. {
  1157. SetAvailableCreatures sac;
  1158. sac.tid = (**j).id;
  1159. sac.creatures = (**j).strInfo.creatures;
  1160. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  1161. {
  1162. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  1163. sac.creatures[k] += (**j).creatureGrowth(k);
  1164. }
  1165. n.cres.push_back(sac);
  1166. }
  1167. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  1168. r.res[6] += (**j).dailyIncome();
  1169. }
  1170. n.res.push_back(r);
  1171. }
  1172. sendAndApply(&n);
  1173. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  1174. {
  1175. (*i)->newTurn();
  1176. }
  1177. }
  1178. void CGameHandler::run()
  1179. {
  1180. BOOST_FOREACH(CConnection *cc, conns)
  1181. {//init conn.
  1182. ui8 quantity, pom;
  1183. //ui32 seed;
  1184. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  1185. (*cc) >> quantity;
  1186. for(int i=0;i<quantity;i++)
  1187. {
  1188. (*cc) >> pom;
  1189. gsm.lock();
  1190. connections[pom] = cc;
  1191. gsm.unlock();
  1192. }
  1193. }
  1194. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1195. {
  1196. std::set<int> pom;
  1197. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1198. if(j->second == *i)
  1199. pom.insert(j->first);
  1200. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1201. }
  1202. /****************************SCRIPTS************************************************/
  1203. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  1204. /****************************C++ OBJECT SCRIPTS************************************************/
  1205. std::map<int,CCPPObjectScript*> scripts;
  1206. CScriptCallback * csc = new CScriptCallback();
  1207. csc->gh = this;
  1208. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  1209. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  1210. handleCPPObjS(&scripts,new CPickable(csc));
  1211. handleCPPObjS(&scripts,new CMines(csc));
  1212. handleCPPObjS(&scripts,new CTownScript(csc));
  1213. handleCPPObjS(&scripts,new CHeroScript(csc));
  1214. handleCPPObjS(&scripts,new CMonsterS(csc));
  1215. handleCPPObjS(&scripts,new CCreatureGen(csc));
  1216. handleCPPObjS(&scripts,new CTeleports(csc));
  1217. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  1218. //std::string temps("newObject");
  1219. for (unsigned i=0; i<gs->map->objects.size(); i++)
  1220. {
  1221. //c++ scripts
  1222. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  1223. {
  1224. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  1225. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  1226. }
  1227. else
  1228. {
  1229. gs->map->objects[i]->state = NULL;
  1230. }
  1231. //// lua scripts
  1232. //if(checkFunc(map->objects[i]->ID,temps))
  1233. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  1234. }
  1235. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1236. states.addPlayer(i->first);
  1237. while (!end2)
  1238. {
  1239. newTurn();
  1240. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1241. {
  1242. 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
  1243. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1244. gs->currentPlayer = i->first;
  1245. *connections[i->first] << ui16(100) << i->first;
  1246. //wait till turn is done
  1247. boost::unique_lock<boost::mutex> lock(states.mx);
  1248. while(states.players[i->first].makingTurn && !end2)
  1249. {
  1250. boost::posix_time::time_duration p;
  1251. p = boost::posix_time::milliseconds(200);
  1252. #ifdef _MSC_VER
  1253. states.cv.timed_wait(lock,p);
  1254. #else
  1255. boost::xtime time={0,0};
  1256. time.nsec = static_cast<boost::xtime::xtime_nsec_t>(p.total_nanoseconds());
  1257. states.cv.timed_wait(lock,time);
  1258. #endif
  1259. }
  1260. }
  1261. }
  1262. }
  1263. namespace CGH
  1264. {
  1265. using namespace std;
  1266. void readItTo(ifstream & input, vector< vector<int> > & dest)
  1267. {
  1268. for(int j=0; j<7; ++j)
  1269. {
  1270. std::vector<int> pom;
  1271. for(int g=0; g<j+1; ++g)
  1272. {
  1273. int hlp; input>>hlp;
  1274. pom.push_back(hlp);
  1275. }
  1276. dest.push_back(pom);
  1277. }
  1278. }
  1279. }
  1280. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  1281. {
  1282. battleResult.set(NULL);
  1283. std::vector<CStack*> & stacks = (curB->stacks);
  1284. curB->tile = tile;
  1285. curB->siege = 0; //TODO: add sieges
  1286. curB->army1=army1;
  1287. curB->army2=army2;
  1288. curB->hero1=(hero1)?(hero1->id):(-1);
  1289. curB->hero2=(hero2)?(hero2->id):(-1);
  1290. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  1291. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  1292. curB->round = -2;
  1293. curB->activeStack = -1;
  1294. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  1295. {
  1296. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  1297. stacks[stacks.size()-1]->ID = stacks.size()-1;
  1298. }
  1299. //initialization of positions
  1300. std::ifstream positions;
  1301. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1302. if(!positions.is_open())
  1303. {
  1304. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1305. }
  1306. std::string dump;
  1307. positions>>dump; positions>>dump;
  1308. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  1309. CGH::readItTo(positions, attackerLoose);
  1310. positions>>dump;
  1311. CGH::readItTo(positions, defenderLoose);
  1312. positions>>dump;
  1313. positions>>dump;
  1314. CGH::readItTo(positions, attackerTight);
  1315. positions>>dump;
  1316. CGH::readItTo(positions, defenderTight);
  1317. positions.close();
  1318. if(army1.formation)
  1319. for(int b=0; b<army1.slots.size(); ++b) //tight
  1320. {
  1321. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  1322. }
  1323. else
  1324. for(int b=0; b<army1.slots.size(); ++b) //loose
  1325. {
  1326. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  1327. }
  1328. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  1329. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  1330. if(army2.formation)
  1331. for(int b=0; b<army2.slots.size(); ++b) //tight
  1332. {
  1333. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  1334. }
  1335. else
  1336. for(int b=0; b<army2.slots.size(); ++b) //loose
  1337. {
  1338. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  1339. }
  1340. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1341. {
  1342. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  1343. {
  1344. stacks[g]->position += 1;
  1345. }
  1346. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  1347. {
  1348. stacks[g]->position -= 1;
  1349. }
  1350. }
  1351. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1352. //block engaged players
  1353. if(hero1->tempOwner<PLAYER_LIMIT)
  1354. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1355. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  1356. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1357. //send info about battles
  1358. BattleStart bs;
  1359. bs.info = curB;
  1360. sendAndApply(&bs);
  1361. }
  1362. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1363. {
  1364. //checking winning condition
  1365. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1366. hasStack[0] = hasStack[1] = false;
  1367. for(int b = 0; b<stacks.size(); ++b)
  1368. {
  1369. if(stacks[b]->alive())
  1370. {
  1371. hasStack[1-stacks[b]->attackerOwned] = true;
  1372. }
  1373. }
  1374. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1375. {
  1376. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1377. br->result = 0;
  1378. br->winner = hasStack[1]; //fleeing side loses
  1379. gs->curB->calculateCasualties(br->casualties);
  1380. battleResult.set(br);
  1381. }
  1382. }
  1383. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1384. {
  1385. if(!vstd::contains(h->artifWorn,17))
  1386. return; //hero hasn't spellbok
  1387. ChangeSpells cs;
  1388. cs.hid = h->id;
  1389. cs.learn = true;
  1390. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+4);i++)
  1391. {
  1392. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1393. {
  1394. if(!vstd::contains(h->spells,t->spells[i][j]))
  1395. cs.spells.insert(t->spells[i][j]);
  1396. }
  1397. }
  1398. if(cs.spells.size())
  1399. sendAndApply(&cs);
  1400. }