CGameHandler.cpp 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564
  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::prepareAttacked(BattleStackAttacked &bsa, CStack *def)
  332. {
  333. bsa.killedAmount = bsa.damageAmount / def->creature->hitPoints;
  334. unsigned damageFirst = bsa.damageAmount % def->creature->hitPoints;
  335. if( def->firstHPleft <= damageFirst )
  336. {
  337. bsa.killedAmount++;
  338. bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  339. }
  340. else
  341. {
  342. bsa.newHP = def->firstHPleft - damageFirst;
  343. }
  344. if(def->amount <= bsa.killedAmount) //stack killed
  345. {
  346. bsa.newAmount = 0;
  347. bsa.flags |= 1;
  348. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  349. }
  350. else
  351. {
  352. bsa.newAmount = def->amount - bsa.killedAmount;
  353. }
  354. }
  355. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  356. {
  357. bat.stackAttacking = att->ID;
  358. bat.bsa.stackAttacked = def->ID;
  359. 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), bat.shot());//counting dealt damage
  360. prepareAttacked(bat.bsa,def);
  361. }
  362. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  363. {
  364. try
  365. {
  366. ui16 pom;
  367. while(!end2)
  368. {
  369. c >> pom;
  370. bool blockvis = false;
  371. switch(pom)
  372. {
  373. case 99: //end!
  374. {
  375. tlog0 << "We have been requested to close.\n";
  376. exit(0);
  377. }
  378. case 100: //my interface ended its turn
  379. {
  380. states.setFlag(gs->currentPlayer,&PlayerStatus::makingTurn,false);
  381. break;
  382. }
  383. case 500: //dismiss hero
  384. {
  385. si32 id;
  386. c >> id;
  387. RemoveObject rh(id);
  388. sendAndApply(&rh);
  389. break;
  390. }
  391. case 501://interface wants to move hero
  392. {
  393. int3 start, end;
  394. si32 id;
  395. c >> id >> start >> end;
  396. tlog5 << "Interface wants to move hero "<<id << " from "<<start << " to " << end << std::endl;
  397. int3 hmpos = end + int3(-1,0,0);
  398. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  399. CGHeroInstance *h = static_cast<CGHeroInstance *>(gs->map->objects[id]);
  400. int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end));
  401. TryMoveHero tmh;
  402. tmh.id = id;
  403. tmh.start = start;
  404. tmh.end = end;
  405. tmh.result = 0;
  406. tmh.movePoints = h->movement;
  407. if((h->getOwner() != gs->currentPlayer) //not turn of that hero
  408. || (distance(start,end)>=1.5) //tiles are not neighouring
  409. || (h->movement < cost) //lack of movement points
  410. || (t.tertype == rock) //rock
  411. || (!h->canWalkOnSea() && t.tertype == water)
  412. || (t.blocked && !t.visitable) //tile is blocked andnot visitable
  413. )
  414. goto fail;
  415. //check if there is blocking visitable object
  416. blockvis = false;
  417. tmh.movePoints = h->movement = (h->movement-cost); //take move points
  418. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  419. {
  420. if(obj->blockVisit)
  421. {
  422. blockvis = true;
  423. break;
  424. }
  425. }
  426. //we start moving
  427. if(blockvis)//interaction with blocking object (like resources)
  428. {
  429. sendAndApply(&tmh); //failed to move to that tile but we visit object
  430. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  431. {
  432. if (obj->blockVisit)
  433. {
  434. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  435. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  436. if(obj->state) //hard-coded function
  437. obj->state->onHeroVisit(obj->id,h->id);
  438. }
  439. }
  440. tlog5 << "Blocing visit at " << hmpos << std::endl;
  441. break;
  442. }
  443. else //normal move
  444. {
  445. tmh.result = 1;
  446. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x-1][start.y][start.z].visitableObjects)
  447. {
  448. //TODO: allow to handle this in script-languages
  449. if(obj->state) //hard-coded function
  450. obj->state->onHeroLeave(obj->id,h->id);
  451. }
  452. tmh.fowRevealed = gs->tilesToReveal(h->getPosition(false),h->getSightDistance(),h->tempOwner);
  453. sendAndApply(&tmh);
  454. tlog5 << "Moved to " <<tmh.end<<std::endl;
  455. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited
  456. {
  457. //if(gs->checkFunc(obj->ID,"heroVisit")) //script function
  458. // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID);
  459. if(obj->state) //hard-coded function
  460. obj->state->onHeroVisit(obj->id,h->id);
  461. }
  462. }
  463. tlog5 << "Movement end!\n";
  464. break;
  465. fail:
  466. tlog2 << "Movement failed to " << tmh.end << std::endl;
  467. sendAndApply(&tmh);
  468. break;
  469. }
  470. case 502: //swap creatures in garrison
  471. {
  472. ui8 what, p1, p2; si32 id1, id2;
  473. c >> what >> id1 >> p1 >> id2 >> p2;
  474. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  475. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  476. CCreatureSet *S1 = &s1->army, *S2 = &s2->army;
  477. if(what==1) //swap
  478. {
  479. int pom = S2->slots[p2].first;
  480. S2->slots[p2].first = S1->slots[p1].first;
  481. S1->slots[p1].first = pom;
  482. int pom2 = S2->slots[p2].second;
  483. S2->slots[p2].second = S1->slots[p1].second;
  484. S1->slots[p1].second = pom2;
  485. if(!S1->slots[p1].second)
  486. S1->slots.erase(p1);
  487. if(!S2->slots[p2].second)
  488. S2->slots.erase(p2);
  489. }
  490. else if(what==2)//merge
  491. {
  492. if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature
  493. S2->slots[p2].second += S1->slots[p1].second;
  494. S1->slots[p1].first = NULL;
  495. S1->slots[p1].second = 0;
  496. S1->slots.erase(p1);
  497. }
  498. else if(what==3) //split
  499. {
  500. si32 val;
  501. c >> val;
  502. if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free
  503. S2->slots[p2].first = S1->slots[p1].first;
  504. S2->slots[p2].second = val;
  505. S1->slots[p1].second -= val;
  506. if(!S1->slots[p1].second) //if we've moved all creatures
  507. S1->slots.erase(p1);
  508. }
  509. if((s1->ID==34 && !S1->slots.size()) //it's not allowed to take last stack from hero army!
  510. || (s2->ID==34 && !S2->slots.size()))
  511. {
  512. break;
  513. }
  514. SetGarrisons sg;
  515. sg.garrs[id1] = *S1;
  516. if(s1 != s2)
  517. sg.garrs[id2] = *S2;
  518. sendAndApply(&sg);
  519. break;
  520. }
  521. case 503: //disband creature
  522. {
  523. si32 id;
  524. ui8 pos;
  525. c >> id >> pos;
  526. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  527. s1->army.slots.erase(pos);
  528. SetGarrisons sg;
  529. sg.garrs[id] = s1->army;
  530. sendAndApply(&sg);
  531. break;
  532. }
  533. case 504: //build structure
  534. {
  535. si32 tid, bid;
  536. c >> tid >> bid;
  537. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  538. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  539. for(int i=0;i<RESOURCE_QUANTITY;i++)
  540. if(b->resources[i] > gs->players[t->tempOwner].resources[i])
  541. break; //no res
  542. for( std::set<int>::iterator ri = VLC->townh->requirements[t->subID][bid].begin();
  543. ri != VLC->townh->requirements[t->subID][bid].end();
  544. ri++ )
  545. {
  546. if(!vstd::contains(t->builtBuildings,*ri))
  547. break; //lack of requirements - cannot build
  548. }
  549. if(vstd::contains(t->forbiddenBuildings,bid))
  550. break; //this building is forbidden
  551. NewStructures ns;
  552. ns.tid = tid;
  553. if(bid>36) //upg dwelling
  554. {
  555. if(t->getHordeLevel(0) == (bid-37))
  556. ns.bid.insert(19);
  557. else if(t->getHordeLevel(1) == (bid-37))
  558. ns.bid.insert(25);
  559. }
  560. else if(bid >= 30) //bas. dwelling
  561. {
  562. SetAvailableCreatures ssi;
  563. ssi.tid = tid;
  564. ssi.creatures = t->strInfo.creatures;
  565. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  566. sendAndApply(&ssi);
  567. }
  568. ns.bid.insert(bid);
  569. ns.builded = t->builded + 1;
  570. sendAndApply(&ns);
  571. SetResources sr;
  572. sr.player = t->tempOwner;
  573. sr.res = gs->players[t->tempOwner].resources;
  574. for(int i=0;i<7;i++)
  575. sr.res[i]-=b->resources[i];
  576. sendAndApply(&sr);
  577. if(bid<5) //it's mage guild
  578. {
  579. if(t->visitingHero)
  580. giveSpells(t,t->visitingHero);
  581. if(t->garrisonHero)
  582. giveSpells(t,t->garrisonHero);
  583. }
  584. break;
  585. }
  586. case 506: //recruit creature
  587. {
  588. si32 objid, ser=-1; //ser - used dwelling level
  589. ui32 crid, cram; //recruited creature id and amount
  590. c >> objid >> crid >> cram;
  591. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  592. //verify
  593. bool found = false;
  594. typedef std::pair<const int,int> Parka;
  595. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  596. {
  597. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  598. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  599. {
  600. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  601. ser = av->first;
  602. break;
  603. }
  604. }
  605. int slot = t->army.getSlotFor(crid);
  606. if(!found || //no such creature
  607. cram > VLC->creh->creatures[crid].maxAmount(gs->players[t->tempOwner].resources) || //lack of resources
  608. cram<=0 ||
  609. slot<0 )
  610. break;
  611. //recruit
  612. SetResources sr;
  613. sr.player = t->tempOwner;
  614. for(int i=0;i<RESOURCE_QUANTITY;i++)
  615. sr.res[i] = gs->players[t->tempOwner].resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  616. SetAvailableCreatures sac;
  617. sac.tid = objid;
  618. sac.creatures = t->strInfo.creatures;
  619. sac.creatures[ser] -= cram;
  620. SetGarrisons sg;
  621. sg.garrs[objid] = t->army;
  622. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  623. {
  624. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  625. }
  626. else //add creatures to a already existing stack
  627. {
  628. sg.garrs[objid].slots[slot].second += cram;
  629. }
  630. sendAndApply(&sr);
  631. sendAndApply(&sac);
  632. sendAndApply(&sg);
  633. break;
  634. }
  635. case 507://upgrade creature
  636. {
  637. ui32 objid, upgID;
  638. ui8 pos;
  639. c >> objid >> pos >> upgID;
  640. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  641. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  642. int player = obj->tempOwner;
  643. int crQuantity = obj->army.slots[pos].second;
  644. //check if upgrade is possible
  645. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  646. break;
  647. //check if player has enough resources
  648. for(int i=0;i<ui.cost.size();i++)
  649. {
  650. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  651. {
  652. if(gs->players[player].resources[j->first] < j->second*crQuantity)
  653. goto upgend;
  654. }
  655. }
  656. //take resources
  657. for(int i=0;i<ui.cost.size();i++)
  658. {
  659. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  660. {
  661. SetResource sr;
  662. sr.player = player;
  663. sr.resid = j->first;
  664. sr.val = gs->players[player].resources[j->first] - j->second*crQuantity;
  665. sendAndApply(&sr);
  666. }
  667. }
  668. {
  669. //upgrade creature
  670. SetGarrisons sg;
  671. sg.garrs[objid] = obj->army;
  672. sg.garrs[objid].slots[pos].first = upgID;
  673. sendAndApply(&sg);
  674. }
  675. upgend:
  676. break;
  677. }
  678. case 508: //garrison swap
  679. {
  680. si32 tid;
  681. c >> tid;
  682. CGTownInstance *town = gs->getTown(tid);
  683. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  684. {
  685. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  686. while(!cso.slots.empty())//while there are unmoved creatures
  687. {
  688. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  689. if(pos<0)
  690. goto handleConEnd;
  691. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  692. {
  693. csn.slots[pos].second += cso.slots.begin()->second.second;
  694. }
  695. else //move stack on the free pos
  696. {
  697. csn.slots[pos].first = cso.slots.begin()->second.first;
  698. csn.slots[pos].second = cso.slots.begin()->second.second;
  699. }
  700. cso.slots.erase(cso.slots.begin());
  701. }
  702. SetGarrisons sg;
  703. sg.garrs[town->visitingHero->id] = csn;
  704. sg.garrs[town->id] = csn;
  705. sendAndApply(&sg);
  706. SetHeroesInTown intown;
  707. intown.tid = tid;
  708. intown.visiting = -1;
  709. intown.garrison = town->visitingHero->id;
  710. sendAndApply(&intown);
  711. }
  712. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  713. {
  714. SetHeroesInTown intown;
  715. intown.tid = tid;
  716. intown.garrison = -1;
  717. intown.visiting = town->garrisonHero->id;
  718. sendAndApply(&intown);
  719. //town will be empty
  720. SetGarrisons sg;
  721. sg.garrs[tid] = CCreatureSet();
  722. sendAndApply(&sg);
  723. }
  724. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  725. {
  726. SetGarrisons sg;
  727. sg.garrs[town->id] = town->visitingHero->army;
  728. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  729. //sg.garrs[town->visitingHero->id] = town->visitingHero->army;
  730. SetHeroesInTown intown;
  731. intown.tid = tid;
  732. intown.garrison = town->visitingHero->id;
  733. intown.visiting = town->garrisonHero->id;
  734. sendAndApply(&intown);
  735. sendAndApply(&sg);
  736. }
  737. else
  738. {
  739. tlog3 << "Warning, wrong garrison swap command for " << tid << std::endl;
  740. }
  741. break;
  742. }
  743. case 509: //swap artifacts
  744. {
  745. si32 hid1, hid2;
  746. ui16 slot1, slot2;
  747. c >> hid1 >> slot1 >> hid2 >> slot2;
  748. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  749. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  750. break;
  751. int a1=h1->getArtAtPos(slot1), a2=h2->getArtAtPos(slot2);
  752. h2->setArtAtPos(slot2,a1);
  753. h1->setArtAtPos(slot1,a2);
  754. SetHeroArtifacts sha;
  755. sha.hid = hid1;
  756. sha.artifacts = h1->artifacts;
  757. sha.artifWorn = h1->artifWorn;
  758. sendAndApply(&sha);
  759. if(hid1 != hid2)
  760. {
  761. sha.hid = hid2;
  762. sha.artifacts = h2->artifacts;
  763. sha.artifWorn = h2->artifWorn;
  764. sendAndApply(&sha);
  765. }
  766. break;
  767. }
  768. case 510: //buy artifact
  769. {
  770. ui32 hid;
  771. si32 aid, bid;
  772. c >> hid >> aid;
  773. CGHeroInstance *hero = gs->getHero(hid);
  774. CGTownInstance *town = hero->visitedTown;
  775. if(aid==0) //spellbok
  776. {
  777. if(!vstd::contains(town->builtBuildings,si32(0)))
  778. break;
  779. SetResource sr;
  780. sr.player = hero->tempOwner;
  781. sr.resid = 6;
  782. sr.val = gs->players[hero->tempOwner].resources[6] - 500;
  783. sendAndApply(&sr);
  784. SetHeroArtifacts sha;
  785. sha.hid = hid;
  786. sha.artifacts = hero->artifacts;
  787. sha.artifWorn = hero->artifWorn;
  788. sha.artifWorn[17] = 0;
  789. sendAndApply(&sha);
  790. giveSpells(town,hero);
  791. }
  792. else if(aid < 7 && aid > 3) //war machine
  793. {
  794. int price = VLC->arth->artifacts[aid].price;
  795. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  796. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  797. || gs->players[hero->tempOwner].resources[6] < price //no gold
  798. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  799. {
  800. break;
  801. }
  802. SetResource sr;
  803. sr.player = hero->tempOwner;
  804. sr.resid = 6;
  805. sr.val = gs->players[hero->tempOwner].resources[6] - price;
  806. sendAndApply(&sr);
  807. SetHeroArtifacts sha;
  808. sha.hid = hid;
  809. sha.artifacts = hero->artifacts;
  810. sha.artifWorn = hero->artifWorn;
  811. sha.artifWorn[9+aid] = aid;
  812. sendAndApply(&sha);
  813. }
  814. break;
  815. }
  816. case 511: //trade at marketplace
  817. {
  818. ui8 player;
  819. ui32 mode, id1, id2, val;
  820. c >> player >> mode >> id1 >> id2 >> val;
  821. val = std::min(si32(val),gs->players[player].resources[id1]);
  822. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  823. uzysk /= gs->resVals[id2];
  824. SetResource sr;
  825. sr.player = player;
  826. sr.resid = id1;
  827. sr.val = gs->players[player].resources[id1] - val;
  828. sendAndApply(&sr);
  829. sr.resid = id2;
  830. sr.val = gs->players[player].resources[id2] + (int)uzysk;
  831. sendAndApply(&sr);
  832. break;
  833. }
  834. case 512:
  835. {
  836. si32 hid;
  837. ui8 formation;
  838. c >> hid >> formation;
  839. gs->getHero(hid)->army.formation = formation;
  840. break;
  841. }
  842. case 2001:
  843. {
  844. ui32 qid, answer;
  845. c >> qid >> answer;
  846. gsm.lock();
  847. CFunctionList<void(ui32)> callb = callbacks[qid];
  848. callbacks.erase(qid);
  849. gsm.unlock();
  850. callb(answer);
  851. break;
  852. }
  853. case 3002:
  854. {
  855. BattleAction ba;
  856. c >> ba;
  857. switch(ba.actionType)
  858. {
  859. case 2: //walk
  860. {
  861. sendAndApply(&StartAction(ba)); //start movement
  862. moveStack(ba.stackNumber,ba.destinationTile); //move
  863. sendDataToClients(ui16(3008)); //endmovement
  864. break;
  865. }
  866. case 3: //defend
  867. {
  868. break;
  869. }
  870. case 4: //retreat/flee
  871. {
  872. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  873. //TODO: calculate casualties
  874. //TODO: remove retreating hero from map and place it in recrutation list
  875. BattleResult *br = new BattleResult;
  876. br->result = 1;
  877. br->winner = !ba.side; //fleeing side loses
  878. gs->curB->calculateCasualties(br->casualties);
  879. giveExp(*br);
  880. battleResult.set(br);
  881. break;
  882. }
  883. case 6: //walk or attack
  884. {
  885. sendAndApply(&StartAction(ba)); //start movement and attack
  886. moveStack(ba.stackNumber,ba.destinationTile);
  887. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  888. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  889. if((curStack->position != ba.destinationTile) || //we wasn't able to reach destination tile
  890. (BattleInfo::mutualPosition(ba.destinationTile,ba.additionalInfo)<0) ) //destination tile is not neighbouring with enemy stack
  891. return;
  892. BattleAttack bat;
  893. prepareAttack(bat,curStack,stackAtEnd);
  894. sendAndApply(&bat);
  895. //counterattack
  896. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  897. && stackAtEnd->alive()
  898. && stackAtEnd->counterAttacks ) //TODO: support for multiple retaliatons per turn
  899. {
  900. prepareAttack(bat,stackAtEnd,curStack);
  901. bat.flags |= 2;
  902. sendAndApply(&bat);
  903. }
  904. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  905. && curStack->alive()
  906. && stackAtEnd->alive() )
  907. {
  908. bat.flags = 0;
  909. prepareAttack(bat,curStack,stackAtEnd);
  910. sendAndApply(&bat);
  911. }
  912. sendDataToClients(ui16(3008)); //end movement and attack
  913. break;
  914. }
  915. case 7: //shoot
  916. {
  917. //TODO: check arrows count
  918. //TODO: check if stack isn't blocked by enemy
  919. sendAndApply(&StartAction(ba)); //start shooting
  920. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  921. *destStack= gs->curB->getStackT(ba.destinationTile);
  922. BattleAttack bat;
  923. prepareAttack(bat,curStack,destStack);
  924. bat.flags |= 1;
  925. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  926. && curStack->alive())
  927. {
  928. prepareAttack(bat,curStack,destStack);
  929. sendAndApply(&bat);
  930. }
  931. sendAndApply(&bat);
  932. sendDataToClients(ui16(3008)); //end shooting
  933. break;
  934. }
  935. }
  936. battleMadeAction.setn(true);
  937. break;
  938. }
  939. case 3003: //custom action (probably spell)
  940. {
  941. BattleAction ba;
  942. c >> ba;
  943. switch(ba.actionType)
  944. {
  945. case 1: //hero casts spell
  946. {
  947. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  948. if(!h)
  949. {
  950. tlog2 << "Wrong caster!\n";
  951. goto customactionend;
  952. }
  953. if(ba.additionalInfo >= VLC->spellh->spells.size())
  954. {
  955. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  956. goto customactionend;
  957. }
  958. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  959. int skill = 0; //skill level
  960. if(s->fire)
  961. skill = std::max(skill,h->getSecSkillLevel(14));
  962. if(s->air)
  963. skill = std::max(skill,h->getSecSkillLevel(15));
  964. if(s->water)
  965. skill = std::max(skill,h->getSecSkillLevel(16));
  966. if(s->earth)
  967. skill = std::max(skill,h->getSecSkillLevel(17));
  968. //TODO: skill level may be different on special terrain
  969. if( // !vstd::contains(h->spells,ba.additionalInfo) //hero doesn't know this spell
  970. /*||*/ (h->mana < s->costs[skill]) //not enough mana
  971. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  972. || 0 )//TODO: hero has already casted a spell in this round
  973. {
  974. tlog2 << "Spell cannot be casted!\n";
  975. goto customactionend;
  976. }
  977. sendAndApply(&StartAction(ba)); //start spell casting
  978. //TODO: check resistances
  979. SpellCasted sc;
  980. sc.side = ba.side;
  981. sc.id = ba.additionalInfo;
  982. sc.skill = skill;
  983. sc.tile = ba.destinationTile;
  984. sendAndApply(&sc);
  985. switch(ba.additionalInfo) //spell id
  986. {
  987. case 15://magic arrow
  988. {
  989. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  990. if(!attacked) break;
  991. BattleStackAttacked bsa;
  992. bsa.flags |= 2;
  993. bsa.effect = 64;
  994. bsa.damageAmount = h->primSkills[2] * 10; //TODO: use skill level
  995. bsa.stackAttacked = attacked->ID;
  996. prepareAttacked(bsa,attacked);
  997. sendAndApply(&bsa);
  998. break;
  999. }
  1000. case 53: //haste
  1001. {
  1002. break;
  1003. }
  1004. }
  1005. //TODO: spells to support possibly soon (list by Zamolxis):
  1006. /*- Magic Arrow
  1007. - Haste
  1008. - Bless
  1009. - Bloodlust
  1010. - Curse
  1011. - Dispel
  1012. - Shield
  1013. - Slow
  1014. - Stone Skin
  1015. - Lightning Bolt
  1016. - Ice Bolt
  1017. - Precision
  1018. - Blind
  1019. - Fire Wall
  1020. - Weakness
  1021. - Death Ripple */
  1022. sendDataToClients(ui16(3008)); //end casting
  1023. break;
  1024. }
  1025. }
  1026. customactionend:
  1027. break;
  1028. }
  1029. default:
  1030. throw std::string("Not supported client message!");
  1031. }
  1032. }
  1033. }
  1034. catch (const std::exception& e)
  1035. {
  1036. tlog1 << "Exception during handling connection: " << e.what() << std::endl;
  1037. end2 = true;
  1038. }
  1039. catch (const std::exception * e)
  1040. {
  1041. tlog1 << "Exception during handling connection: " << e->what()<< std::endl;
  1042. end2 = true;
  1043. delete e;
  1044. }
  1045. catch(...)
  1046. {
  1047. end2 = true;
  1048. }
  1049. handleConEnd:
  1050. tlog1 << "Ended handling connection\n";
  1051. }
  1052. void CGameHandler::moveStack(int stack, int dest)
  1053. {
  1054. CStack *curStack = gs->curB->getStack(stack),
  1055. *stackAtEnd = gs->curB->getStackT(dest);
  1056. //initing necessary tables
  1057. bool accessibility[187];
  1058. if(curStack->creature->isDoubleWide())
  1059. gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned,curStack->ID);
  1060. else
  1061. gs->curB->getAccessibilityMap(accessibility,curStack->ID);
  1062. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  1063. return;
  1064. //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
  1065. // return false;
  1066. std::vector<int> path = gs->curB->getPath(curStack->position,dest,accessibility);
  1067. int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0);
  1068. for(int v=path.size()-1; v>=tilesToMove; --v)
  1069. {
  1070. //inform clients about move
  1071. BattleStackMoved sm;
  1072. sm.stack = curStack->ID;
  1073. sm.tile = path[v];
  1074. sendAndApply(&sm);
  1075. }
  1076. }
  1077. CGameHandler::CGameHandler(void)
  1078. {
  1079. gs = NULL;
  1080. }
  1081. CGameHandler::~CGameHandler(void)
  1082. {
  1083. delete gs;
  1084. }
  1085. void CGameHandler::init(StartInfo *si, int Seed)
  1086. {
  1087. Mapa *map = new Mapa(si->mapname);
  1088. tlog0 << "Map loaded!" << std::endl;
  1089. gs = new CGameState();
  1090. tlog0 << "Gamestate created!" << std::endl;
  1091. gs->init(si,map,Seed);
  1092. tlog0 << "Gamestate initialized!" << std::endl;
  1093. /****************************LUA OBJECT SCRIPTS************************************************/
  1094. //std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
  1095. //for (int i=0; i<lf->size(); i++)
  1096. //{
  1097. // try
  1098. // {
  1099. // std::vector<std::string> * temp = CLuaHandler::functionList((*lf)[i]);
  1100. // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
  1101. // CLuaCallback::registerFuncs(objs->is);
  1102. // //objs
  1103. // for (int j=0; j<temp->size(); j++)
  1104. // {
  1105. // int obid ; //obj ID
  1106. // int dspos = (*temp)[j].find_first_of('_');
  1107. // obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
  1108. // std::string fname = (*temp)[j].substr(0,dspos);
  1109. // if (skrypty->find(obid)==skrypty->end())
  1110. // skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
  1111. // (*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
  1112. // }
  1113. // delete temp;
  1114. // }HANDLE_EXCEPTION
  1115. //}
  1116. //delete lf;
  1117. }
  1118. int lowestSpeed(CGHeroInstance * chi)
  1119. {
  1120. std::map<si32,std::pair<ui32,si32> >::iterator i = chi->army.slots.begin();
  1121. int ret = VLC->creh->creatures[(*i++).second.first].speed;
  1122. for (;i!=chi->army.slots.end();i++)
  1123. {
  1124. ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed);
  1125. }
  1126. return ret;
  1127. }
  1128. int valMovePoints(CGHeroInstance * chi, bool onLand)
  1129. {
  1130. int ret = 1270+70*lowestSpeed(chi);
  1131. if (ret>2000)
  1132. ret=2000;
  1133. if(onLand)
  1134. {
  1135. //logistics:
  1136. switch(chi->getSecSkillLevel(2))
  1137. {
  1138. case 1:
  1139. ret *= 1.1f;
  1140. break;
  1141. case 2:
  1142. ret *= 1.2f;
  1143. break;
  1144. case 3:
  1145. ret *= 1.3f;
  1146. break;
  1147. }
  1148. }
  1149. else
  1150. {
  1151. //navigation:
  1152. switch(chi->getSecSkillLevel(2))
  1153. {
  1154. case 1:
  1155. ret *= 1.5f;
  1156. break;
  1157. case 2:
  1158. ret *= 2.0f;
  1159. break;
  1160. case 3:
  1161. ret *= 2.5f;
  1162. break;
  1163. }
  1164. }
  1165. //TODO: additional bonuses (but they aren't currently stored in chi)
  1166. return ret;
  1167. }
  1168. void CGameHandler::newTurn()
  1169. {
  1170. NewTurn n;
  1171. n.day = gs->day + 1;
  1172. n.resetBuilded = true;
  1173. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  1174. {
  1175. if(i->first>=PLAYER_LIMIT) continue;
  1176. SetResources r;
  1177. r.player = i->first;
  1178. for(int j=0;j<RESOURCE_QUANTITY;j++)
  1179. r.res[j] = i->second.resources[j];
  1180. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  1181. {
  1182. NewTurn::Hero hth;
  1183. hth.id = h->id;
  1184. hth.move = valMovePoints(h, true); //TODO: check if hero is really on the land
  1185. hth.mana = std::min(h->mana+1+h->getSecSkillLevel(8), h->manaLimit()); //hero regains 1 mana point + mysticism lvel
  1186. n.heroes.insert(hth);
  1187. switch(h->getSecSkillLevel(13)) //handle estates - give gols
  1188. {
  1189. case 1: //basic
  1190. r.res[6] += 125;
  1191. break;
  1192. case 2: //advanced
  1193. r.res[6] += 250;
  1194. break;
  1195. case 3: //expert
  1196. r.res[6] += 500;
  1197. break;
  1198. }
  1199. }
  1200. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  1201. {
  1202. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  1203. {
  1204. if((**j).town->primaryRes == 127) //we'll give wood and ore
  1205. {
  1206. r.res[0] += 1;
  1207. r.res[2] += 1;
  1208. }
  1209. else
  1210. {
  1211. r.res[(**j).town->primaryRes] += 1;
  1212. }
  1213. }
  1214. if(gs->getDate(1)==7) //first day of week
  1215. {
  1216. SetAvailableCreatures sac;
  1217. sac.tid = (**j).id;
  1218. sac.creatures = (**j).strInfo.creatures;
  1219. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  1220. {
  1221. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  1222. sac.creatures[k] += (**j).creatureGrowth(k);
  1223. }
  1224. n.cres.push_back(sac);
  1225. }
  1226. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  1227. r.res[6] += (**j).dailyIncome();
  1228. }
  1229. n.res.push_back(r);
  1230. }
  1231. sendAndApply(&n);
  1232. for (std::set<CCPPObjectScript *>::iterator i=cppscripts.begin();i!=cppscripts.end();i++)
  1233. {
  1234. (*i)->newTurn();
  1235. }
  1236. }
  1237. void CGameHandler::run()
  1238. {
  1239. BOOST_FOREACH(CConnection *cc, conns)
  1240. {//init conn.
  1241. ui8 quantity, pom;
  1242. //ui32 seed;
  1243. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  1244. (*cc) >> quantity; //how many players will be handled at that client
  1245. for(int i=0;i<quantity;i++)
  1246. {
  1247. (*cc) >> pom; //read player color
  1248. gsm.lock();
  1249. connections[pom] = cc;
  1250. gsm.unlock();
  1251. }
  1252. }
  1253. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  1254. {
  1255. std::set<int> pom;
  1256. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  1257. if(j->second == *i)
  1258. pom.insert(j->first);
  1259. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  1260. }
  1261. /****************************SCRIPTS************************************************/
  1262. //std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &objscr; //alias for easier access
  1263. /****************************C++ OBJECT SCRIPTS************************************************/
  1264. std::map<int,CCPPObjectScript*> scripts;
  1265. CScriptCallback * csc = new CScriptCallback();
  1266. csc->gh = this;
  1267. handleCPPObjS(&scripts,new CVisitableOPH(csc));
  1268. handleCPPObjS(&scripts,new CVisitableOPW(csc));
  1269. handleCPPObjS(&scripts,new CPickable(csc));
  1270. handleCPPObjS(&scripts,new CMines(csc));
  1271. handleCPPObjS(&scripts,new CTownScript(csc));
  1272. handleCPPObjS(&scripts,new CHeroScript(csc));
  1273. handleCPPObjS(&scripts,new CMonsterS(csc));
  1274. handleCPPObjS(&scripts,new CCreatureGen(csc));
  1275. handleCPPObjS(&scripts,new CTeleports(csc));
  1276. /****************************INITIALIZING OBJECT SCRIPTS************************************************/
  1277. //std::string temps("newObject");
  1278. for (unsigned i=0; i<gs->map->objects.size(); i++)
  1279. {
  1280. //c++ scripts
  1281. if (scripts.find(gs->map->objects[i]->ID) != scripts.end())
  1282. {
  1283. gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID];
  1284. gs->map->objects[i]->state->newObject(gs->map->objects[i]->id);
  1285. }
  1286. else
  1287. {
  1288. gs->map->objects[i]->state = NULL;
  1289. }
  1290. //// lua scripts
  1291. //if(checkFunc(map->objects[i]->ID,temps))
  1292. // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]);
  1293. }
  1294. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1295. states.addPlayer(i->first);
  1296. while (!end2)
  1297. {
  1298. newTurn();
  1299. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  1300. {
  1301. 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
  1302. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  1303. gs->currentPlayer = i->first;
  1304. *connections[i->first] << ui16(100) << i->first;
  1305. //wait till turn is done
  1306. boost::unique_lock<boost::mutex> lock(states.mx);
  1307. while(states.players[i->first].makingTurn && !end2)
  1308. {
  1309. boost::posix_time::time_duration p;
  1310. p = boost::posix_time::milliseconds(200);
  1311. #ifdef _MSC_VER
  1312. states.cv.timed_wait(lock,p);
  1313. #else
  1314. boost::xtime time={0,0};
  1315. time.nsec = static_cast<boost::xtime::xtime_nsec_t>(p.total_nanoseconds());
  1316. states.cv.timed_wait(lock,time);
  1317. #endif
  1318. }
  1319. }
  1320. }
  1321. }
  1322. namespace CGH
  1323. {
  1324. using namespace std;
  1325. void readItTo(ifstream & input, vector< vector<int> > & dest)
  1326. {
  1327. for(int j=0; j<7; ++j)
  1328. {
  1329. std::vector<int> pom;
  1330. for(int g=0; g<j+1; ++g)
  1331. {
  1332. int hlp; input>>hlp;
  1333. pom.push_back(hlp);
  1334. }
  1335. dest.push_back(pom);
  1336. }
  1337. }
  1338. }
  1339. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  1340. {
  1341. battleResult.set(NULL);
  1342. std::vector<CStack*> & stacks = (curB->stacks);
  1343. curB->tile = tile;
  1344. curB->siege = 0; //TODO: add sieges
  1345. curB->army1=army1;
  1346. curB->army2=army2;
  1347. curB->hero1=(hero1)?(hero1->id):(-1);
  1348. curB->hero2=(hero2)?(hero2->id):(-1);
  1349. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  1350. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  1351. curB->round = -2;
  1352. curB->activeStack = -1;
  1353. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  1354. {
  1355. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  1356. stacks[stacks.size()-1]->ID = stacks.size()-1;
  1357. }
  1358. //initialization of positions
  1359. std::ifstream positions;
  1360. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  1361. if(!positions.is_open())
  1362. {
  1363. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  1364. }
  1365. std::string dump;
  1366. positions>>dump; positions>>dump;
  1367. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  1368. CGH::readItTo(positions, attackerLoose);
  1369. positions>>dump;
  1370. CGH::readItTo(positions, defenderLoose);
  1371. positions>>dump;
  1372. positions>>dump;
  1373. CGH::readItTo(positions, attackerTight);
  1374. positions>>dump;
  1375. CGH::readItTo(positions, defenderTight);
  1376. positions.close();
  1377. if(army1.formation)
  1378. for(int b=0; b<army1.slots.size(); ++b) //tight
  1379. {
  1380. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  1381. }
  1382. else
  1383. for(int b=0; b<army1.slots.size(); ++b) //loose
  1384. {
  1385. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  1386. }
  1387. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  1388. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  1389. if(army2.formation)
  1390. for(int b=0; b<army2.slots.size(); ++b) //tight
  1391. {
  1392. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  1393. }
  1394. else
  1395. for(int b=0; b<army2.slots.size(); ++b) //loose
  1396. {
  1397. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  1398. }
  1399. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  1400. {
  1401. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  1402. {
  1403. stacks[g]->position += 1;
  1404. }
  1405. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  1406. {
  1407. stacks[g]->position -= 1;
  1408. }
  1409. }
  1410. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  1411. //block engaged players
  1412. if(hero1->tempOwner<PLAYER_LIMIT)
  1413. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1414. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  1415. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  1416. //send info about battles
  1417. BattleStart bs;
  1418. bs.info = curB;
  1419. sendAndApply(&bs);
  1420. }
  1421. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  1422. {
  1423. //checking winning condition
  1424. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  1425. hasStack[0] = hasStack[1] = false;
  1426. for(int b = 0; b<stacks.size(); ++b)
  1427. {
  1428. if(stacks[b]->alive())
  1429. {
  1430. hasStack[1-stacks[b]->attackerOwned] = true;
  1431. }
  1432. }
  1433. if(!hasStack[0] || !hasStack[1]) //somebody has won
  1434. {
  1435. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  1436. br->result = 0;
  1437. br->winner = hasStack[1]; //fleeing side loses
  1438. gs->curB->calculateCasualties(br->casualties);
  1439. battleResult.set(br);
  1440. }
  1441. }
  1442. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  1443. {
  1444. if(!vstd::contains(h->artifWorn,17))
  1445. return; //hero hasn't spellbok
  1446. ChangeSpells cs;
  1447. cs.hid = h->id;
  1448. cs.learn = true;
  1449. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+4);i++)
  1450. {
  1451. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  1452. {
  1453. if(!vstd::contains(h->spells,t->spells[i][j]))
  1454. cs.spells.insert(t->spells[i][j]);
  1455. }
  1456. }
  1457. if(cs.spells.size())
  1458. sendAndApply(&cs);
  1459. }