CGameHandler.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401
  1. #include "../StartInfo.h"
  2. #include "../hch/CArtHandler.h"
  3. #include "../hch/CBuildingHandler.h"
  4. #include "../hch/CDefObjInfoHandler.h"
  5. #include "../hch/CGeneralTextHandler.h"
  6. #include "../hch/CHeroHandler.h"
  7. #include "../hch/CObjectHandler.h"
  8. #include "../hch/CSpellHandler.h"
  9. #include "../hch/CTownHandler.h"
  10. #include "../CGameState.h"
  11. #include "../lib/CondSh.h"
  12. #include "../lib/NetPacks.h"
  13. #include "../lib/Connection.h"
  14. #include "../lib/VCMI_Lib.h"
  15. #include "../map.h"
  16. #include "CGameHandler.h"
  17. #include <boost/bind.hpp>
  18. #include <boost/date_time/posix_time/posix_time_types.hpp> //no i/o just types
  19. #include <boost/foreach.hpp>
  20. #include <boost/thread.hpp>
  21. #include <boost/thread/shared_mutex.hpp>
  22. #include <fstream>
  23. #undef DLL_EXPORT
  24. #define DLL_EXPORT
  25. #include "../lib/RegisterTypes.cpp"
  26. #ifndef _MSC_VER
  27. #include <boost/thread/xtime.hpp>
  28. #endif
  29. extern bool end2;
  30. #ifdef min
  31. #undef min
  32. #endif
  33. #ifdef max
  34. #undef max
  35. #endif
  36. #define NEW_ROUND BattleNextRound bnr;\
  37. bnr.round = gs->curB->round + 1;\
  38. sendAndApply(&bnr);
  39. boost::mutex gsm;
  40. ui32 CGameHandler::QID = 1;
  41. CondSh<bool> battleMadeAction;
  42. CondSh<BattleResult *> battleResult(NULL);
  43. std::map<ui32, CFunctionList<void(ui32)> > callbacks; //question id => callback function - for selection dialogs
  44. class CBaseForGHApply
  45. {
  46. public:
  47. virtual void applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const =0;
  48. };
  49. template <typename T> class CApplyOnGH : public CBaseForGHApply
  50. {
  51. public:
  52. void applyOnGH(CGameHandler *gh, CConnection *c, void *pack) const
  53. {
  54. T *ptr = static_cast<T*>(pack);
  55. ptr->c = c;
  56. ptr->applyGh(gh);
  57. }
  58. };
  59. class CGHApplier
  60. {
  61. public:
  62. std::map<ui16,CBaseForGHApply*> apps;
  63. CGHApplier()
  64. {
  65. registerTypes3(*this);
  66. }
  67. template<typename T> void registerType(const T * t=NULL)
  68. {
  69. ui16 ID = typeList.registerType(t);
  70. apps[ID] = new CApplyOnGH<T>;
  71. }
  72. } *applier = NULL;
  73. class CMP_stack
  74. {
  75. public:
  76. inline bool operator ()(const CStack* a, const CStack* b)
  77. {
  78. return (a->Speed())>(b->Speed());
  79. }
  80. } cmpst ;
  81. double distance(int3 a, int3 b)
  82. {
  83. return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) );
  84. }
  85. int getSchoolLevel(const CGHeroInstance *h, const CSpell *s)
  86. {
  87. ui8 ret = 0;
  88. if(s->fire)
  89. ret = std::max(ret,h->getSecSkillLevel(14));
  90. if(s->air)
  91. ret = std::max(ret,h->getSecSkillLevel(15));
  92. if(s->water)
  93. ret = std::max(ret,h->getSecSkillLevel(16));
  94. if(s->earth)
  95. ret = std::max(ret,h->getSecSkillLevel(17));
  96. return ret;
  97. }
  98. void giveExp(BattleResult &r)
  99. {
  100. r.exp[0] = 0;
  101. r.exp[1] = 0;
  102. for(std::set<std::pair<ui32,si32> >::iterator i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  103. {
  104. r.exp[r.winner] += VLC->creh->creatures[i->first].hitPoints * i->second;
  105. }
  106. }
  107. PlayerStatus PlayerStatuses::operator[](ui8 player)
  108. {
  109. boost::unique_lock<boost::mutex> l(mx);
  110. if(players.find(player) != players.end())
  111. {
  112. return players[player];
  113. }
  114. else
  115. {
  116. throw std::string("No such player!");
  117. }
  118. }
  119. void PlayerStatuses::addPlayer(ui8 player)
  120. {
  121. boost::unique_lock<boost::mutex> l(mx);
  122. players[player];
  123. }
  124. bool PlayerStatuses::hasQueries(ui8 player)
  125. {
  126. boost::unique_lock<boost::mutex> l(mx);
  127. if(players.find(player) != players.end())
  128. {
  129. return players[player].queries.size();
  130. }
  131. else
  132. {
  133. throw std::string("No such player!");
  134. }
  135. }
  136. bool PlayerStatuses::checkFlag(ui8 player, bool PlayerStatus::*flag)
  137. {
  138. boost::unique_lock<boost::mutex> l(mx);
  139. if(players.find(player) != players.end())
  140. {
  141. return players[player].*flag;
  142. }
  143. else
  144. {
  145. throw std::string("No such player!");
  146. }
  147. }
  148. void PlayerStatuses::setFlag(ui8 player, bool PlayerStatus::*flag, bool val)
  149. {
  150. boost::unique_lock<boost::mutex> l(mx);
  151. if(players.find(player) != players.end())
  152. {
  153. players[player].*flag = val;
  154. }
  155. else
  156. {
  157. throw std::string("No such player!");
  158. }
  159. cv.notify_all();
  160. }
  161. void PlayerStatuses::addQuery(ui8 player, ui32 id)
  162. {
  163. boost::unique_lock<boost::mutex> l(mx);
  164. if(players.find(player) != players.end())
  165. {
  166. players[player].queries.insert(id);
  167. }
  168. else
  169. {
  170. throw std::string("No such player!");
  171. }
  172. cv.notify_all();
  173. }
  174. void PlayerStatuses::removeQuery(ui8 player, ui32 id)
  175. {
  176. boost::unique_lock<boost::mutex> l(mx);
  177. if(players.find(player) != players.end())
  178. {
  179. players[player].queries.erase(id);
  180. }
  181. else
  182. {
  183. throw std::string("No such player!");
  184. }
  185. cv.notify_all();
  186. }
  187. template <typename T>
  188. void callWith(std::vector<T> args, boost::function<void(T)> fun, ui32 which)
  189. {
  190. fun(args[which]);
  191. }
  192. void CGameHandler::changeSecSkill( int ID, int which, int val, bool abs/*=false*/ )
  193. {
  194. SetSecSkill sss;
  195. sss.id = ID;
  196. sss.which = which;
  197. sss.val = val;
  198. sss.abs = abs;
  199. sendAndApply(&sss);
  200. }
  201. void CGameHandler::changePrimSkill(int ID, int which, int val, bool abs)
  202. {
  203. SetPrimSkill sps;
  204. sps.id = ID;
  205. sps.which = which;
  206. sps.abs = abs;
  207. sps.val = val;
  208. sendAndApply(&sps);
  209. if(which==4) //only for exp - hero may level up
  210. {
  211. CGHeroInstance *hero = static_cast<CGHeroInstance *>(gs->map->objects[ID]);
  212. if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level
  213. {
  214. //give prim skill
  215. tlog5 << hero->name <<" got level "<<hero->level<<std::endl;
  216. int r = rand()%100, pom=0, x=0;
  217. int std::pair<int,int>::*g = (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
  218. for(;x<PRIMARY_SKILLS;x++)
  219. {
  220. pom += hero->type->heroClass->primChance[x].*g;
  221. if(r<pom)
  222. break;
  223. }
  224. tlog5 << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
  225. SetPrimSkill sps;
  226. sps.id = ID;
  227. sps.which = x;
  228. sps.abs = false;
  229. sps.val = 1;
  230. sendAndApply(&sps);
  231. HeroLevelUp hlu;
  232. hlu.heroid = ID;
  233. hlu.primskill = x;
  234. hlu.level = hero->level+1;
  235. //picking sec. skills for choice
  236. std::set<int> basicAndAdv, expert, none;
  237. for(int i=0;i<SKILL_QUANTITY;i++) none.insert(i);
  238. for(unsigned i=0;i<hero->secSkills.size();i++)
  239. {
  240. if(hero->secSkills[i].second < 3)
  241. basicAndAdv.insert(hero->secSkills[i].first);
  242. else
  243. expert.insert(hero->secSkills[i].first);
  244. none.erase(hero->secSkills[i].first);
  245. }
  246. //first offered skill
  247. if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot
  248. {
  249. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  250. none.erase(hlu.skills.back());
  251. }
  252. else if(basicAndAdv.size())
  253. {
  254. int s = hero->type->heroClass->chooseSecSkill(basicAndAdv);
  255. hlu.skills.push_back(s);
  256. basicAndAdv.erase(s);
  257. }
  258. //second offered skill
  259. if(basicAndAdv.size())
  260. {
  261. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill
  262. }
  263. else if(hero->secSkills.size() < hero->type->heroClass->skillLimit)
  264. {
  265. hlu.skills.push_back(hero->type->heroClass->chooseSecSkill(none)); //new skill
  266. }
  267. if(hlu.skills.size() > 1) //apply and ask for secondary skill
  268. {
  269. 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));
  270. applyAndAsk(&hlu,hero->tempOwner,callback); //call changeSecSkill with appropriate args when client responds
  271. }
  272. else if(hlu.skills.size() == 1) //apply, give only possible skill and send info
  273. {
  274. sendAndApply(&hlu);
  275. changeSecSkill(ID,hlu.skills.back(),1,false);
  276. }
  277. else //apply and send info
  278. {
  279. sendAndApply(&hlu);
  280. }
  281. }
  282. }
  283. }
  284. CCreatureSet takeCasualties(int color, const CCreatureSet &set, BattleInfo *bat)
  285. {
  286. CCreatureSet ret(set);
  287. for(int i=0; i<bat->stacks.size();i++)
  288. {
  289. CStack *st = bat->stacks[i];
  290. if(st->owner==color && vstd::contains(set.slots,st->slot) && st->amount < set.slots.find(st->slot)->second.second)
  291. {
  292. if(st->alive())
  293. ret.slots[st->slot].second = st->amount;
  294. else
  295. ret.slots.erase(st->slot);
  296. }
  297. }
  298. return ret;
  299. }
  300. void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb)
  301. {
  302. BattleInfo *curB = new BattleInfo;
  303. setupBattle(curB, tile, army1, army2, hero1, hero2); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  304. NEW_ROUND;
  305. //TODO: pre-tactic stuff, call scripts etc.
  306. //tactic round
  307. {
  308. NEW_ROUND;
  309. if( (hero1 && hero1->getSecSkillLevel(19)>0) ||
  310. ( hero2 && hero2->getSecSkillLevel(19)>0) )//someone has tactics
  311. {
  312. //TODO: tactic round (round -1)
  313. }
  314. }
  315. //main loop
  316. while(!battleResult.get()) //till the end of the battle ;]
  317. {
  318. NEW_ROUND;
  319. std::vector<CStack*> & stacks = (gs->curB->stacks);
  320. const BattleInfo & curB = *gs->curB;
  321. //stack loop
  322. CStack *next;
  323. while(!battleResult.get() && (next=gs->curB->getNextStack()))
  324. {
  325. next->state -= WAITING; //if stack was waiting it'll now make move, so it won't be "waiting" anymore
  326. //check for bad morale => freeze
  327. if(next->Morale() < 0)
  328. {
  329. if( rand()%24 < (-next->Morale())*2 )
  330. {
  331. //unit loses its turn - empty freeze action
  332. BattleAction ba;
  333. ba.actionType = 11;
  334. ba.additionalInfo = 1;
  335. ba.side = !next->attackerOwned;
  336. ba.stackNumber = next->ID;
  337. sendAndApply(&StartAction(ba));
  338. sendAndApply(&EndAction());
  339. checkForBattleEnd(stacks); //check if this "action" ended the battle (not likely but who knows...)
  340. continue;
  341. }
  342. }
  343. askInterfaceForMove:
  344. //ask interface and wait for answer
  345. if(!battleResult.get())
  346. {
  347. BattleSetActiveStack sas;
  348. sas.stack = next->ID;
  349. sendAndApply(&sas);
  350. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  351. while(!battleMadeAction.data && !battleResult.get()) //active stack hasn't made its action and battle is still going
  352. battleMadeAction.cond.wait(lock);
  353. battleMadeAction.data = false;
  354. }
  355. else
  356. {
  357. break;
  358. }
  359. //we're after action, all results applied
  360. checkForBattleEnd(stacks); //check if this action ended the battle
  361. //check for good morale
  362. if(!vstd::contains(next->state,HAD_MORALE) //only one extra move per turn possible
  363. && !vstd::contains(next->state,DEFENDING)
  364. && !vstd::contains(next->state,WAITING)
  365. && next->alive()
  366. && next->Morale() > 0
  367. )
  368. if(rand()%24 < next->Morale()) //this stack hasn't got morale this turn
  369. goto askInterfaceForMove; //move this stack once more
  370. }
  371. }
  372. //unblock engaged players
  373. if(hero1->tempOwner<PLAYER_LIMIT)
  374. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  375. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  376. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,false);
  377. //casualties among heroes armies
  378. SetGarrisons sg;
  379. if(hero1)
  380. sg.garrs[hero1->id] = takeCasualties(hero1->tempOwner,hero1->army,gs->curB);
  381. if(hero2)
  382. sg.garrs[hero2->id] = takeCasualties(hero2->tempOwner,hero2->army,gs->curB);
  383. sendAndApply(&sg);
  384. //end battle, remove all info, free memory
  385. giveExp(*battleResult.data);
  386. sendAndApply(battleResult.data);
  387. if(cb)
  388. cb(battleResult.data);
  389. //if one hero has lost we will erase him
  390. if(battleResult.data->winner!=0 && hero1)
  391. {
  392. RemoveObject ro(hero1->id);
  393. sendAndApply(&ro);
  394. }
  395. if(battleResult.data->winner!=1 && hero2)
  396. {
  397. RemoveObject ro(hero2->id);
  398. sendAndApply(&ro);
  399. }
  400. //give exp
  401. if(battleResult.data->exp[0] && hero1)
  402. changePrimSkill(hero1->id,4,battleResult.data->exp[0]);
  403. if(battleResult.data->exp[1] && hero2)
  404. changePrimSkill(hero2->id,4,battleResult.data->exp[1]);
  405. delete battleResult.data;
  406. }
  407. void CGameHandler::prepareAttacked(BattleStackAttacked &bsa, CStack *def)
  408. {
  409. bsa.killedAmount = bsa.damageAmount / def->creature->hitPoints;
  410. unsigned damageFirst = bsa.damageAmount % def->creature->hitPoints;
  411. if( def->firstHPleft <= damageFirst )
  412. {
  413. bsa.killedAmount++;
  414. bsa.newHP = def->firstHPleft + def->creature->hitPoints - damageFirst;
  415. }
  416. else
  417. {
  418. bsa.newHP = def->firstHPleft - damageFirst;
  419. }
  420. if(def->amount <= bsa.killedAmount) //stack killed
  421. {
  422. bsa.newAmount = 0;
  423. bsa.flags |= 1;
  424. bsa.killedAmount = def->amount; //we cannot kill more creatures than we have
  425. }
  426. else
  427. {
  428. bsa.newAmount = def->amount - bsa.killedAmount;
  429. }
  430. }
  431. void CGameHandler::prepareAttack(BattleAttack &bat, CStack *att, CStack *def)
  432. {
  433. bat.bsa.clear();
  434. bat.stackAttacking = att->ID;
  435. std::set<BattleStackAttacked>::iterator i = bat.bsa.insert(BattleStackAttacked()).first;
  436. BattleStackAttacked *bsa = (BattleStackAttacked *) &*i;
  437. bsa->stackAttacked = def->ID;
  438. 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
  439. if(att->Luck() > 0 && rand()%24 < att->Luck())
  440. {
  441. bsa->damageAmount *= 2;
  442. bsa->flags |= 4;
  443. }
  444. prepareAttacked(*bsa,def);
  445. }
  446. void CGameHandler::handleConnection(std::set<int> players, CConnection &c)
  447. {
  448. srand(time(NULL));
  449. CPack *pack = NULL;
  450. try
  451. {
  452. while(!end2)
  453. {
  454. c >> pack;
  455. tlog5 << "Received client message of type " << typeid(*pack).name() << std::endl;
  456. CBaseForGHApply *apply = applier->apps[typeList.getTypeID(pack)];
  457. if(apply)
  458. {
  459. apply->applyOnGH(this,&c,pack);
  460. tlog5 << "Message successfully applied!\n";
  461. }
  462. else
  463. {
  464. tlog5 << "Message cannot be applied, cannot find applier!\n";
  465. }
  466. delete pack;
  467. pack = NULL;
  468. }
  469. }
  470. HANDLE_EXCEPTION(end2 = true);
  471. handleConEnd:
  472. tlog1 << "Ended handling connection\n";
  473. #undef SPELL_CAST_TEMPLATE_1
  474. }
  475. void CGameHandler::moveStack(int stack, int dest)
  476. {
  477. CStack *curStack = gs->curB->getStack(stack),
  478. *stackAtEnd = gs->curB->getStackT(dest);
  479. //initing necessary tables
  480. bool accessibility[BFIELD_SIZE];
  481. std::vector<int> accessible = gs->curB->getAccessibility(curStack->ID, false);
  482. for(int b=0; b<BFIELD_SIZE; ++b)
  483. {
  484. accessibility[b] = false;
  485. }
  486. for(int g=0; g<accessible.size(); ++g)
  487. {
  488. accessibility[accessible[g]] = true;
  489. }
  490. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  491. if(!stackAtEnd && curStack->creature->isDoubleWide() && !accessibility[dest])
  492. {
  493. if(curStack->attackerOwned)
  494. {
  495. if(accessibility[dest+1])
  496. dest+=1;
  497. }
  498. else
  499. {
  500. if(accessibility[dest-1])
  501. dest-=1;
  502. }
  503. }
  504. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility[dest])
  505. return;
  506. //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
  507. // return false;
  508. std::pair< std::vector<int>, int > path = gs->curB->getPath(curStack->position, dest, accessibility, curStack->creature->isFlying());
  509. if(curStack->creature->isFlying())
  510. {
  511. if(path.second <= curStack->Speed() && path.first.size() > 0)
  512. {
  513. //inform clients about move
  514. BattleStackMoved sm;
  515. sm.stack = curStack->ID;
  516. sm.tile = path.first[0];
  517. sm.distance = path.second;
  518. sm.ending = true;
  519. sendAndApply(&sm);
  520. }
  521. }
  522. else //for non-flying creatures
  523. {
  524. int tilesToMove = std::max((int)(path.first.size() - curStack->Speed()), 0);
  525. for(int v=path.first.size()-1; v>=tilesToMove; --v)
  526. {
  527. //inform clients about move
  528. BattleStackMoved sm;
  529. sm.stack = curStack->ID;
  530. sm.tile = path.first[v];
  531. sm.distance = path.second;
  532. sm.ending = v==tilesToMove;
  533. sendAndApply(&sm);
  534. }
  535. }
  536. }
  537. CGameHandler::CGameHandler(void)
  538. {
  539. gs = NULL;
  540. IObjectInterface::cb = this;
  541. applier = new CGHApplier;
  542. }
  543. CGameHandler::~CGameHandler(void)
  544. {
  545. delete applier;
  546. applier = NULL;
  547. delete gs;
  548. }
  549. void CGameHandler::init(StartInfo *si, int Seed)
  550. {
  551. Mapa *map = new Mapa(si->mapname);
  552. tlog0 << "Map loaded!" << std::endl;
  553. gs = new CGameState();
  554. tlog0 << "Gamestate created!" << std::endl;
  555. gs->init(si,map,Seed);
  556. tlog0 << "Gamestate initialized!" << std::endl;
  557. for(std::map<ui8,PlayerState>::iterator i = gs->players.begin(); i != gs->players.end(); i++)
  558. states.addPlayer(i->first);
  559. }
  560. bool evntCmp(const CMapEvent *a, const CMapEvent *b)
  561. {
  562. return *a < *b;
  563. }
  564. void CGameHandler::newTurn()
  565. {
  566. tlog5 << "Turn " << gs->day+1 << std::endl;
  567. NewTurn n;
  568. n.day = gs->day + 1;
  569. n.resetBuilded = true;
  570. for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
  571. {
  572. if(i->first == 255) continue;
  573. if(gs->getDate(1)==7) //first day of week - new heroes in tavern
  574. {
  575. SetAvailableHeroes sah;
  576. sah.player = i->first;
  577. CGHeroInstance *h = gs->hpool.pickHeroFor(true,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle]);
  578. if(h)
  579. sah.hid1 = h->subID;
  580. else
  581. sah.hid1 = -1;
  582. h = gs->hpool.pickHeroFor(false,i->first,&VLC->townh->towns[gs->scenarioOps->getIthPlayersSettings(i->first).castle],sah.hid1);
  583. if(h)
  584. sah.hid2 = h->subID;
  585. else
  586. sah.hid2 = -1;
  587. sendAndApply(&sah);
  588. }
  589. if(i->first>=PLAYER_LIMIT) continue;
  590. SetResources r;
  591. r.player = i->first;
  592. for(int j=0;j<RESOURCE_QUANTITY;j++)
  593. r.res[j] = i->second.resources[j];
  594. BOOST_FOREACH(CGHeroInstance *h, (*i).second.heroes)
  595. {
  596. NewTurn::Hero hth;
  597. hth.id = h->id;
  598. hth.move = h->maxMovePoints(true); //TODO: check if hero is really on the land
  599. if(h->visitedTown && vstd::contains(h->visitedTown->builtBuildings,0)) //if hero starts turn in town with mage guild
  600. hth.mana = h->manaLimit(); //restore all mana
  601. else
  602. hth.mana = std::max(si32(0), std::min(h->mana + h->manaRegain(), h->manaLimit()) );
  603. n.heroes.insert(hth);
  604. switch(h->getSecSkillLevel(13)) //handle estates - give gold
  605. {
  606. case 1: //basic
  607. r.res[6] += 125;
  608. break;
  609. case 2: //advanced
  610. r.res[6] += 250;
  611. break;
  612. case 3: //expert
  613. r.res[6] += 500;
  614. break;
  615. }
  616. for(std::list<HeroBonus>::iterator i = h->bonuses.begin(); i != h->bonuses.end(); i++)
  617. if(i->type == HeroBonus::GENERATE_RESOURCE)
  618. r.res[i->subtype] += i->val;
  619. }
  620. for(std::vector<CGTownInstance *>::iterator j=i->second.towns.begin();j!=i->second.towns.end();j++)//handle towns
  621. {
  622. if(vstd::contains((**j).builtBuildings,15)) //there is resource silo
  623. {
  624. if((**j).town->primaryRes == 127) //we'll give wood and ore
  625. {
  626. r.res[0] += 1;
  627. r.res[2] += 1;
  628. }
  629. else
  630. {
  631. r.res[(**j).town->primaryRes] += 1;
  632. }
  633. }
  634. if(gs->getDate(1)==7) //first day of week
  635. {
  636. SetAvailableCreatures sac;
  637. sac.tid = (**j).id;
  638. sac.creatures = (**j).strInfo.creatures;
  639. for(int k=0;k<CREATURES_PER_TOWN;k++) //creature growths
  640. {
  641. if((**j).creatureDwelling(k))//there is dwelling (k-level)
  642. sac.creatures[k] += (**j).creatureGrowth(k);
  643. }
  644. n.cres.push_back(sac);
  645. }
  646. if((gs->day) && i->first<PLAYER_LIMIT)//not the first day and town not neutral
  647. r.res[6] += (**j).dailyIncome();
  648. }
  649. n.res.push_back(r);
  650. }
  651. sendAndApply(&n);
  652. tlog5 << "Info about turn " << n.day << "has been sent!" << std::endl;
  653. handleTimeEvents();
  654. //call objects
  655. for(size_t i = 0; i<gs->map->objects.size(); i++)
  656. if(gs->map->objects[i])
  657. gs->map->objects[i]->newTurn();
  658. }
  659. void CGameHandler::run(bool resume)
  660. {
  661. BOOST_FOREACH(CConnection *cc, conns)
  662. {//init conn.
  663. ui8 quantity, pom;
  664. //ui32 seed;
  665. if(!resume)
  666. (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed;
  667. (*cc) >> quantity; //how many players will be handled at that client
  668. for(int i=0;i<quantity;i++)
  669. {
  670. (*cc) >> pom; //read player color
  671. gsm.lock();
  672. connections[pom] = cc;
  673. gsm.unlock();
  674. }
  675. }
  676. for(std::set<CConnection*>::iterator i = conns.begin(); i!=conns.end();i++)
  677. {
  678. std::set<int> pom;
  679. for(std::map<int,CConnection*>::iterator j = connections.begin(); j!=connections.end();j++)
  680. if(j->second == *i)
  681. pom.insert(j->first);
  682. boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i)));
  683. }
  684. while (!end2)
  685. {
  686. if(!resume)
  687. newTurn();
  688. else
  689. resume = false;
  690. std::map<ui8,PlayerState>::iterator i;
  691. if(!resume)
  692. i = gs->players.begin();
  693. else
  694. i = gs->players.find(gs->currentPlayer);
  695. for(; i != gs->players.end(); i++)
  696. {
  697. 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
  698. states.setFlag(i->first,&PlayerStatus::makingTurn,true);
  699. gs->currentPlayer = i->first;
  700. {
  701. YourTurn yt;
  702. yt.player = i->first;
  703. *connections[i->first] << &yt;
  704. }
  705. //wait till turn is done
  706. boost::unique_lock<boost::mutex> lock(states.mx);
  707. while(states.players[i->first].makingTurn && !end2)
  708. {
  709. boost::posix_time::time_duration p;
  710. p = boost::posix_time::milliseconds(200);
  711. states.cv.timed_wait(lock,p);
  712. }
  713. }
  714. }
  715. }
  716. namespace CGH
  717. {
  718. using namespace std;
  719. void readItTo(ifstream & input, vector< vector<int> > & dest)
  720. {
  721. for(int j=0; j<7; ++j)
  722. {
  723. std::vector<int> pom;
  724. for(int g=0; g<j+1; ++g)
  725. {
  726. int hlp; input>>hlp;
  727. pom.push_back(hlp);
  728. }
  729. dest.push_back(pom);
  730. }
  731. }
  732. }
  733. void CGameHandler::setupBattle( BattleInfo * curB, int3 tile, CCreatureSet &army1, CCreatureSet &army2, CGHeroInstance * hero1, CGHeroInstance * hero2 )
  734. {
  735. battleResult.set(NULL);
  736. std::vector<CStack*> & stacks = (curB->stacks);
  737. curB->tile = tile;
  738. curB->siege = 0; //TODO: add sieges
  739. curB->army1=army1;
  740. curB->army2=army2;
  741. curB->hero1=(hero1)?(hero1->id):(-1);
  742. curB->hero2=(hero2)?(hero2->id):(-1);
  743. curB->side1=(hero1)?(hero1->tempOwner):(-1);
  744. curB->side2=(hero2)?(hero2->tempOwner):(-1);
  745. curB->round = -2;
  746. curB->activeStack = -1;
  747. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++)
  748. {
  749. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true,i->first));
  750. if(hero1)
  751. {
  752. stacks.back()->speed += hero1->valOfBonuses(HeroBonus::STACKS_SPEED);
  753. //base luck/morale calculations
  754. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  755. stacks.back()->morale = hero1->getCurrentMorale(i->first,false);
  756. stacks.back()->luck = hero1->getCurrentLuck(i->first,false);
  757. }
  758. else
  759. {
  760. stacks.back()->morale = 0;
  761. stacks.back()->luck = 0;
  762. }
  763. stacks[stacks.size()-1]->ID = stacks.size()-1;
  764. }
  765. //initialization of positions
  766. std::ifstream positions;
  767. positions.open("config" PATHSEPARATOR "battleStartpos.txt", std::ios_base::in|std::ios_base::binary);
  768. if(!positions.is_open())
  769. {
  770. tlog1<<"Unable to open battleStartpos.txt!"<<std::endl;
  771. }
  772. std::string dump;
  773. positions>>dump; positions>>dump;
  774. std::vector< std::vector<int> > attackerLoose, defenderLoose, attackerTight, defenderTight;
  775. CGH::readItTo(positions, attackerLoose);
  776. positions>>dump;
  777. CGH::readItTo(positions, defenderLoose);
  778. positions>>dump;
  779. positions>>dump;
  780. CGH::readItTo(positions, attackerTight);
  781. positions>>dump;
  782. CGH::readItTo(positions, defenderTight);
  783. positions.close();
  784. if(army1.formation)
  785. for(int b=0; b<army1.slots.size(); ++b) //tight
  786. {
  787. stacks[b]->position = attackerTight[army1.slots.size()-1][b];
  788. }
  789. else
  790. for(int b=0; b<army1.slots.size(); ++b) //loose
  791. {
  792. stacks[b]->position = attackerLoose[army1.slots.size()-1][b];
  793. }
  794. for(std::map<si32,std::pair<ui32,si32> >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++)
  795. {
  796. stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false, i->first));
  797. //base luck/morale calculations
  798. //TODO: check if terrain is native, add bonuses for neutral stacks, bonuses from town
  799. if(hero2)
  800. {
  801. stacks.back()->speed += hero2->valOfBonuses(HeroBonus::STACKS_SPEED);
  802. stacks.back()->morale = hero2->getCurrentMorale(i->first,false);
  803. stacks.back()->luck = hero2->getCurrentLuck(i->first,false);
  804. }
  805. else
  806. {
  807. stacks.back()->morale = 0;
  808. stacks.back()->luck = 0;
  809. }
  810. }
  811. if(army2.formation)
  812. for(int b=0; b<army2.slots.size(); ++b) //tight
  813. {
  814. stacks[b+army1.slots.size()]->position = defenderTight[army2.slots.size()-1][b];
  815. }
  816. else
  817. for(int b=0; b<army2.slots.size(); ++b) //loose
  818. {
  819. stacks[b+army1.slots.size()]->position = defenderLoose[army2.slots.size()-1][b];
  820. }
  821. for(unsigned g=0; g<stacks.size(); ++g) //shifting positions of two-hex creatures
  822. {
  823. if((stacks[g]->position%17)==1 && stacks[g]->creature->isDoubleWide())
  824. {
  825. stacks[g]->position += 1;
  826. }
  827. else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide())
  828. {
  829. stacks[g]->position -= 1;
  830. }
  831. }
  832. //adding war machines
  833. if(hero1)
  834. {
  835. if(hero1->getArt(13)) //ballista
  836. {
  837. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero1->tempOwner, stacks.size(), true, 255));
  838. stacks[stacks.size()-1]->position = 52;
  839. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  840. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  841. }
  842. if(hero1->getArt(14)) //ammo cart
  843. {
  844. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero1->tempOwner, stacks.size(), true, 255));
  845. stacks[stacks.size()-1]->position = 18;
  846. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  847. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  848. }
  849. if(hero1->getArt(15)) //first aid tent
  850. {
  851. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero1->tempOwner, stacks.size(), true, 255));
  852. stacks[stacks.size()-1]->position = 154;
  853. stacks.back()->morale = hero1->getCurrentMorale(stacks.back()->ID,false);
  854. stacks.back()->luck = hero1->getCurrentLuck(stacks.back()->ID,false);
  855. }
  856. }
  857. if(hero2)
  858. {
  859. if(hero2->getArt(13)) //ballista
  860. {
  861. stacks.push_back(new CStack(&VLC->creh->creatures[146], 1, hero2->tempOwner, stacks.size(), false, 255));
  862. stacks[stacks.size()-1]->position = 66;
  863. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  864. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  865. }
  866. if(hero2->getArt(14)) //ammo cart
  867. {
  868. stacks.push_back(new CStack(&VLC->creh->creatures[148], 1, hero2->tempOwner, stacks.size(), false, 255));
  869. stacks[stacks.size()-1]->position = 32;
  870. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  871. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  872. }
  873. if(hero2->getArt(15)) //first aid tent
  874. {
  875. stacks.push_back(new CStack(&VLC->creh->creatures[147], 1, hero2->tempOwner, stacks.size(), false, 255));
  876. stacks[stacks.size()-1]->position = 168;
  877. stacks.back()->morale = hero2->getCurrentMorale(stacks.back()->ID,false);
  878. stacks.back()->luck = hero2->getCurrentLuck(stacks.back()->ID,false);
  879. }
  880. }
  881. //war machiens added
  882. std::stable_sort(stacks.begin(),stacks.end(),cmpst);
  883. //randomize obstacles
  884. bool obAv[BFIELD_SIZE]; //availability of hexes for obstacles;
  885. std::vector<int> possibleObstacles;
  886. for(int i=0; i<BFIELD_SIZE; ++i)
  887. {
  888. if(i%17 < 4 || i%17 > 12)
  889. {
  890. obAv[i] = false;
  891. }
  892. else
  893. {
  894. obAv[i] = true;
  895. }
  896. }
  897. int terType = gs->battleGetBattlefieldType(tile);
  898. for(std::map<int, CObstacleInfo>::const_iterator g=VLC->heroh->obstacles.begin(); g!=VLC->heroh->obstacles.end(); ++g)
  899. {
  900. if(g->second.allowedTerrains[terType-1] == '1') //we need to take terType with -1 because terrain ids start from 1 and allowedTerrains array is indexed from 0
  901. {
  902. possibleObstacles.push_back(g->first);
  903. }
  904. }
  905. srand(time(NULL));
  906. if(possibleObstacles.size() > 0) //we cannot place any obstacles when we don't have them
  907. {
  908. int toBlock = rand()%6 + 6; //how many hexes should be blocked by obstacles
  909. while(toBlock>0)
  910. {
  911. CObstacleInstance coi;
  912. coi.ID = possibleObstacles[rand()%possibleObstacles.size()];
  913. coi.pos = rand()%BFIELD_SIZE;
  914. std::vector<int> block = VLC->heroh->obstacles[coi.ID].getBlocked(coi.pos);
  915. bool badObstacle = false;
  916. for(int b=0; b<block.size(); ++b)
  917. {
  918. if(!obAv[block[b]])
  919. {
  920. badObstacle = true;
  921. break;
  922. }
  923. }
  924. if(badObstacle) continue;
  925. //obstacle can be placed
  926. curB->obstacles.push_back(coi);
  927. for(int b=0; b<block.size(); ++b)
  928. {
  929. if(block[b] >= 0 && block[b] < BFIELD_SIZE)
  930. obAv[block[b]] = false;
  931. }
  932. toBlock -= block.size();
  933. }
  934. }
  935. //block engaged players
  936. if(hero1->tempOwner<PLAYER_LIMIT)
  937. states.setFlag(hero1->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  938. if(hero2 && hero2->tempOwner<PLAYER_LIMIT)
  939. states.setFlag(hero2->tempOwner,&PlayerStatus::engagedIntoBattle,true);
  940. //send info about battles
  941. BattleStart bs;
  942. bs.info = curB;
  943. sendAndApply(&bs);
  944. }
  945. void CGameHandler::checkForBattleEnd( std::vector<CStack*> &stacks )
  946. {
  947. //checking winning condition
  948. bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarily
  949. hasStack[0] = hasStack[1] = false;
  950. for(int b = 0; b<stacks.size(); ++b)
  951. {
  952. if(stacks[b]->alive() && !vstd::contains(stacks[b]->abilities,SIEGE_WEAPON))
  953. {
  954. hasStack[1-stacks[b]->attackerOwned] = true;
  955. }
  956. }
  957. if(!hasStack[0] || !hasStack[1]) //somebody has won
  958. {
  959. BattleResult *br = new BattleResult; //will be deleted at the end of startBattle(...)
  960. br->result = 0;
  961. br->winner = hasStack[1]; //fleeing side loses
  962. gs->curB->calculateCasualties(br->casualties);
  963. battleResult.set(br);
  964. }
  965. }
  966. void CGameHandler::giveSpells( const CGTownInstance *t, const CGHeroInstance *h )
  967. {
  968. if(!vstd::contains(h->artifWorn,17))
  969. return; //hero hasn't spellbok
  970. ChangeSpells cs;
  971. cs.hid = h->id;
  972. cs.learn = true;
  973. for(int i=0; i<std::min(t->mageGuildLevel(),h->getSecSkillLevel(7)+2);i++)
  974. {
  975. for(int j=0; j<t->spellsAtLevel(i+1,true) && j<t->spells[i].size(); j++)
  976. {
  977. if(!vstd::contains(h->spells,t->spells[i][j]))
  978. cs.spells.insert(t->spells[i][j]);
  979. }
  980. }
  981. if(cs.spells.size())
  982. sendAndApply(&cs);
  983. }
  984. void CGameHandler::setBlockVis(int objid, bool bv)
  985. {
  986. SetObjectProperty sop(objid,2,bv);
  987. sendAndApply(&sop);
  988. }
  989. void CGameHandler::removeObject(int objid)
  990. {
  991. RemoveObject ro;
  992. ro.id = objid;
  993. sendAndApply(&ro);
  994. }
  995. void CGameHandler::setAmount(int objid, ui32 val)
  996. {
  997. SetObjectProperty sop(objid,3,val);
  998. sendAndApply(&sop);
  999. }
  1000. void CGameHandler::moveHero(si32 hid, int3 dst, ui8 instant, ui8 asker)
  1001. {
  1002. bool blockvis = false;
  1003. const CGHeroInstance *h = getHero(hid);
  1004. if(!h || asker != 255 && (instant || h->getOwner() != gs->currentPlayer) //not turn of that hero or player can't simply teleport hero (at least not with this function)
  1005. )
  1006. {
  1007. tlog1 << "Illegal call to move hero!\n";
  1008. return;
  1009. }
  1010. tlog5 << "Player " <<int(asker) << " wants to move hero "<< hid << " from "<< h->pos << " to " << dst << std::endl;
  1011. int3 hmpos = dst + int3(-1,0,0);
  1012. TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z];
  1013. int cost = gs->getMovementCost(h,h->getPosition(false),CGHeroInstance::convertPosition(dst,false),h->movement);
  1014. //result structure for start - movement failed, no move points used
  1015. TryMoveHero tmh;
  1016. tmh.id = hid;
  1017. tmh.start = h->pos;
  1018. tmh.end = dst;
  1019. tmh.result = 0;
  1020. tmh.movePoints = h->movement;
  1021. //check if destination tile is available
  1022. if( t.tertype == rock
  1023. || (!h->canWalkOnSea() && t.tertype == water)
  1024. || (t.blocked && !t.visitable) //tile is blocked andnot visitable
  1025. )
  1026. {
  1027. tlog2 << "Cannot move hero, destination tile is blocked!\n";
  1028. sendAndApply(&tmh);
  1029. return;
  1030. }
  1031. //checks for standard movement
  1032. if(!instant)
  1033. {
  1034. if( (distance(h->pos,dst)>=1.5) //tiles are not neighouring
  1035. || (h->movement < cost && h->movement < 100) //lack of movement points
  1036. )
  1037. {
  1038. tlog2 << "Cannot move hero, not enough move points or tiles are not neighbouring!\n";
  1039. sendAndApply(&tmh);
  1040. return;
  1041. }
  1042. //check if there is blocking visitable object
  1043. blockvis = false;
  1044. tmh.movePoints = std::max(si32(0),h->movement-cost); //take move points
  1045. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1046. {
  1047. if(obj != h && obj->blockVisit)
  1048. {
  1049. blockvis = true;
  1050. break;
  1051. }
  1052. }
  1053. //we start moving
  1054. if(blockvis)//interaction with blocking object (like resources)
  1055. {
  1056. sendAndApply(&tmh);
  1057. //failed to move to that tile but we visit object
  1058. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1059. {
  1060. if (obj->blockVisit)
  1061. {
  1062. obj->onHeroVisit(h);
  1063. }
  1064. }
  1065. tlog5 << "Blocking visit at " << hmpos << std::endl;
  1066. return;
  1067. }
  1068. else //normal move
  1069. {
  1070. tmh.result = 1;
  1071. BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[h->pos.x-1][h->pos.y][h->pos.z].visitableObjects)
  1072. {
  1073. obj->onHeroLeave(h);
  1074. }
  1075. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1076. sendAndApply(&tmh);
  1077. tlog5 << "Moved to " <<tmh.end<<std::endl;
  1078. //call objects if they are visited
  1079. BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)
  1080. {
  1081. obj->onHeroVisit(h);
  1082. }
  1083. }
  1084. tlog5 << "Movement end!\n";
  1085. }
  1086. else //instant move - teleportation
  1087. {
  1088. BOOST_FOREACH(CGObjectInstance* obj, t.blockingObjects)
  1089. {
  1090. if(obj->ID==HEROI_TYPE)
  1091. {
  1092. if(obj->tempOwner==h->tempOwner)
  1093. return;//TODO: exchange
  1094. //TODO: check for ally
  1095. CGHeroInstance *dh = static_cast<CGHeroInstance *>(obj);
  1096. startBattleI(&h->army,&dh->army,dst,h,dh,0);
  1097. return;
  1098. }
  1099. }
  1100. tmh.result = instant+1;
  1101. getTilesInRange(tmh.fowRevealed,h->getSightCenter()+(tmh.end-tmh.start),h->getSightRadious(),h->tempOwner,1);
  1102. sendAndApply(&tmh);
  1103. }
  1104. }
  1105. void CGameHandler::setOwner(int objid, ui8 owner)
  1106. {
  1107. SetObjectProperty sop(objid,1,owner);
  1108. sendAndApply(&sop);
  1109. }
  1110. void CGameHandler::setHoverName(int objid, MetaString* name)
  1111. {
  1112. SetHoverName shn(objid, *name);
  1113. sendAndApply(&shn);
  1114. }
  1115. void CGameHandler::showInfoDialog(InfoWindow *iw)
  1116. {
  1117. sendToAllClients(iw);
  1118. }
  1119. void CGameHandler::showBlockingDialog( BlockingDialog *iw, const CFunctionList<void(ui32)> &callback )
  1120. {
  1121. ask(iw,iw->player,callback);
  1122. }
  1123. ui32 CGameHandler::showBlockingDialog( BlockingDialog *iw )
  1124. {
  1125. //TODO
  1126. //gsm.lock();
  1127. //int query = QID++;
  1128. //states.addQuery(player,query);
  1129. //sendToAllClients(iw);
  1130. //gsm.unlock();
  1131. //ui32 ret = getQueryResult(iw->player, query);
  1132. //gsm.lock();
  1133. //states.removeQuery(player, query);
  1134. //gsm.unlock();
  1135. return 0;
  1136. }
  1137. int CGameHandler::getCurrentPlayer()
  1138. {
  1139. return gs->currentPlayer;
  1140. }
  1141. void CGameHandler::giveResource(int player, int which, int val)
  1142. {
  1143. SetResource sr;
  1144. sr.player = player;
  1145. sr.resid = which;
  1146. sr.val = (gs->players.find(player)->second.resources[which]+val);
  1147. sendAndApply(&sr);
  1148. }
  1149. void CGameHandler::showCompInfo(ShowInInfobox * comp)
  1150. {
  1151. sendToAllClients(comp);
  1152. }
  1153. void CGameHandler::heroVisitCastle(int obj, int heroID)
  1154. {
  1155. HeroVisitCastle vc;
  1156. vc.hid = heroID;
  1157. vc.tid = obj;
  1158. vc.flags |= 1;
  1159. sendAndApply(&vc);
  1160. giveSpells(getTown(obj),getHero(heroID));
  1161. }
  1162. void CGameHandler::stopHeroVisitCastle(int obj, int heroID)
  1163. {
  1164. HeroVisitCastle vc;
  1165. vc.hid = heroID;
  1166. vc.tid = obj;
  1167. sendAndApply(&vc);
  1168. }
  1169. void CGameHandler::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
  1170. {
  1171. const CGHeroInstance* h = getHero(hid);
  1172. const CArtifact &art = VLC->arth->artifacts[artid];
  1173. SetHeroArtifacts sha;
  1174. sha.hid = hid;
  1175. sha.artifacts = h->artifacts;
  1176. sha.artifWorn = h->artifWorn;
  1177. if(position<0)
  1178. {
  1179. if(position == -2)
  1180. {
  1181. int i;
  1182. for(i=0; i<art.possibleSlots.size(); i++) //try to put artifact into first available slot
  1183. {
  1184. if( !vstd::contains(sha.artifWorn,art.possibleSlots[i]) )
  1185. {
  1186. //we've found a free suitable slot
  1187. sha.artifWorn[art.possibleSlots[i]] = artid;
  1188. break;
  1189. }
  1190. }
  1191. if(i == art.possibleSlots.size()) //if haven't find proper slot, use backpack
  1192. sha.artifacts.push_back(artid);
  1193. }
  1194. else //should be -1 => put artifact into backpack
  1195. {
  1196. sha.artifacts.push_back(artid);
  1197. }
  1198. }
  1199. else
  1200. {
  1201. if(!vstd::contains(sha.artifWorn,ui16(position)))
  1202. {
  1203. sha.artifWorn[position] = artid;
  1204. }
  1205. else
  1206. {
  1207. sha.artifacts.push_back(artid);
  1208. }
  1209. }
  1210. sendAndApply(&sha);
  1211. }
  1212. void CGameHandler::startBattleI(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2, boost::function<void(BattleResult*)> cb) //use hero=NULL for no hero
  1213. {
  1214. boost::thread(boost::bind(&CGameHandler::startBattle,this,*(CCreatureSet *)army1,*(CCreatureSet *)army2,tile,(CGHeroInstance *)hero1,(CGHeroInstance *)hero2,cb));
  1215. }
  1216. void CGameHandler::startBattleI(int heroID, CCreatureSet army, int3 tile, boost::function<void(BattleResult*)> cb) //for hero<=>neutral army
  1217. {
  1218. CGHeroInstance* h = const_cast<CGHeroInstance*>(getHero(heroID));
  1219. startBattleI(&h->army,&army,tile,h,NULL,cb);
  1220. //battle(&h->army,army,tile,h,NULL);
  1221. }
  1222. void CGameHandler::changeSpells( int hid, bool give, const std::set<ui32> &spells )
  1223. {
  1224. ChangeSpells cs;
  1225. cs.hid = hid;
  1226. cs.spells = spells;
  1227. cs.learn = give;
  1228. sendAndApply(&cs);
  1229. }
  1230. int CGameHandler::getSelectedHero()
  1231. {
  1232. return IGameCallback::getSelectedHero(getCurrentPlayer())->id;
  1233. }
  1234. void CGameHandler::setObjProperty( int objid, int prop, int val )
  1235. {
  1236. SetObjectProperty sob;
  1237. sob.id = objid;
  1238. sob.what = prop;
  1239. sob.val = val;
  1240. sendAndApply(&sob);
  1241. }
  1242. void CGameHandler::sendMessageTo( CConnection &c, const std::string &message )
  1243. {
  1244. SystemMessage sm;
  1245. sm.text = message;
  1246. c << &sm;
  1247. }
  1248. void CGameHandler::giveHeroBonus( GiveBonus * bonus )
  1249. {
  1250. sendAndApply(bonus);
  1251. }
  1252. void CGameHandler::setMovePoints( SetMovePoints * smp )
  1253. {
  1254. sendAndApply(smp);
  1255. }
  1256. void CGameHandler::setManaPoints( int hid, int val )
  1257. {
  1258. SetMana sm;
  1259. sm.hid = hid;
  1260. sm.val = val;
  1261. sendAndApply(&sm);
  1262. }
  1263. void CGameHandler::giveHero( int id, int player )
  1264. {
  1265. GiveHero gh;
  1266. gh.id = id;
  1267. gh.player = player;
  1268. sendAndApply(&gh);
  1269. }
  1270. void CGameHandler::changeObjPos( int objid, int3 newPos, ui8 flags )
  1271. {
  1272. ChangeObjPos cop;
  1273. cop.objid = objid;
  1274. cop.nPos = newPos;
  1275. cop.flags = flags;
  1276. sendAndApply(&cop);
  1277. }
  1278. void CGameHandler::applyAndAsk( Query * sel, ui8 player, boost::function<void(ui32)> &callback )
  1279. {
  1280. gsm.lock();
  1281. sel->id = QID;
  1282. callbacks[QID] = callback;
  1283. states.addQuery(player,QID);
  1284. QID++;
  1285. sendAndApply(sel);
  1286. gsm.unlock();
  1287. }
  1288. void CGameHandler::ask( Query * sel, ui8 player, const CFunctionList<void(ui32)> &callback )
  1289. {
  1290. gsm.lock();
  1291. sel->id = QID;
  1292. callbacks[QID] = callback;
  1293. states.addQuery(player,QID);
  1294. sendToAllClients(sel);
  1295. QID++;
  1296. gsm.unlock();
  1297. }
  1298. void CGameHandler::sendToAllClients( CPackForClient * info )
  1299. {
  1300. tlog5 << "Sending to all clients a package of type " << typeid(*info).name() << std::endl;
  1301. for(std::set<CConnection*>::iterator i=conns.begin(); i!=conns.end();i++)
  1302. {
  1303. (*i)->wmx->lock();
  1304. **i << info;
  1305. (*i)->wmx->unlock();
  1306. }
  1307. }
  1308. void CGameHandler::sendAndApply( CPackForClient * info )
  1309. {
  1310. gs->apply(info);
  1311. sendToAllClients(info);
  1312. }
  1313. void CGameHandler::save( const std::string &fname )
  1314. {
  1315. {
  1316. tlog0 << "Ordering clients to serialize...\n";
  1317. SaveGame sg(fname);
  1318. //TODO: uncomment when client saving is ready
  1319. //sendToAllClients(&sg);
  1320. }
  1321. {
  1322. tlog0 << "Serializing game info...\n";
  1323. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vlgm1");
  1324. char hlp[8] = "VCMISVG";
  1325. save << hlp << version << static_cast<CMapHeader&>(*gs->map) << gs->scenarioOps->difficulty << *VLC << gs;
  1326. }
  1327. {
  1328. tlog0 << "Serializing server info...\n";
  1329. CSaveFile save(std::string("Games") + PATHSEPARATOR + fname + ".vsgm1");
  1330. save << *this;
  1331. }
  1332. tlog0 << "Game has been succesfully saved!\n";
  1333. }
  1334. void CGameHandler::close()
  1335. {
  1336. tlog0 << "We have been requested to close.\n";
  1337. //BOOST_FOREACH(CConnection *cc, conns)
  1338. // if(cc && cc->socket && cc->socket->is_open())
  1339. // cc->socket->close();
  1340. //exit(0);
  1341. }
  1342. void CGameHandler::arrangeStacks(si32 id1, si32 id2, ui8 what, ui8 p1, ui8 p2, si32 val)
  1343. {
  1344. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id1]),
  1345. *s2 = static_cast<CArmedInstance*>(gs->map->objects[id2]);
  1346. CCreatureSet temp1 = s1->army, temp2 = s2->army,
  1347. &S1 = temp1, &S2 = (s1!=s2)?(temp2):(temp1);
  1348. if(what==1) //swap
  1349. {
  1350. std::swap(S1.slots[p1],S2.slots[p2]); //swap slots
  1351. //if one of them is empty, remove entry
  1352. if(!S1.slots[p1].second)
  1353. S1.slots.erase(p1);
  1354. if(!S2.slots[p2].second)
  1355. S2.slots.erase(p2);
  1356. }
  1357. else if(what==2)//merge
  1358. {
  1359. if(S1.slots[p1].first != S2.slots[p2].first) //not same creature
  1360. {
  1361. complain("Cannot merge different creatures stacks!");
  1362. return;
  1363. }
  1364. S2.slots[p2].second += S1.slots[p1].second;
  1365. S1.slots.erase(p1);
  1366. }
  1367. else if(what==3) //split
  1368. {
  1369. //general conditions checking
  1370. if((!vstd::contains(S1.slots,p1) && complain("no creatures to split"))
  1371. || (val<1 && complain("no creatures to split")) )
  1372. {
  1373. return;
  1374. }
  1375. if(vstd::contains(S2.slots,p2)) //dest. slot not free - it must be "rebalancing"...
  1376. {
  1377. int total = S1.slots[p1].second + S2.slots[p2].second;
  1378. if( (total < val && complain("Cannot split that stack, not enough creatures!"))
  1379. || (S2.slots[p2].first != S1.slots[p1].first && complain("Cannot rebalance different creatures stacks!"))
  1380. )
  1381. {
  1382. return;
  1383. }
  1384. S2.slots[p2].second = val;
  1385. S1.slots[p1].second = total - val;
  1386. }
  1387. else //split one stack to the two
  1388. {
  1389. if(S1.slots[p1].second < val)//not enough creatures
  1390. {
  1391. complain("Cannot split that stack, not enough creatures!");
  1392. return;
  1393. }
  1394. S2.slots[p2].first = S1.slots[p1].first;
  1395. S2.slots[p2].second = val;
  1396. S1.slots[p1].second -= val;
  1397. }
  1398. if(!S1.slots[p1].second) //if we've moved all creatures
  1399. S1.slots.erase(p1);
  1400. }
  1401. if((s1->needsLastStack() && !S1.slots.size()) //it's not allowed to take last stack from hero army!
  1402. || (s2->needsLastStack() && !S2.slots.size())
  1403. )
  1404. {
  1405. complain("Cannot take the last stack!");
  1406. return; //leave without applying changes to garrison
  1407. }
  1408. //apply changes
  1409. SetGarrisons sg;
  1410. sg.garrs[id1] = S1;
  1411. if(s1 != s2)
  1412. sg.garrs[id2] = S2;
  1413. sendAndApply(&sg);
  1414. }
  1415. int CGameHandler::getPlayerAt( CConnection *c ) const
  1416. {
  1417. std::set<int> all;
  1418. for(std::map<int,CConnection*>::const_iterator i=connections.begin(); i!=connections.end(); i++)
  1419. if(i->second == c)
  1420. all.insert(i->first);
  1421. switch(all.size())
  1422. {
  1423. case 0:
  1424. return 255;
  1425. case 1:
  1426. return *all.begin();
  1427. default:
  1428. {
  1429. //if we have more than one player at this connection, try to pick active one
  1430. if(vstd::contains(all,int(gs->currentPlayer)))
  1431. return gs->currentPlayer;
  1432. else
  1433. return 253; //cannot say which player is it
  1434. }
  1435. }
  1436. }
  1437. void CGameHandler::disbandCreature(si32 id, ui8 pos)
  1438. {
  1439. CArmedInstance *s1 = static_cast<CArmedInstance*>(gs->map->objects[id]);
  1440. if(!vstd::contains(s1->army.slots,pos))
  1441. {
  1442. complain("Illegal call to disbandCreature - no such stack in army!");
  1443. return;
  1444. }
  1445. s1->army.slots.erase(pos);
  1446. SetGarrisons sg;
  1447. sg.garrs[id] = s1->army;
  1448. sendAndApply(&sg);
  1449. }
  1450. void CGameHandler::buildStructure(si32 tid, si32 bid)
  1451. {
  1452. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[tid]);
  1453. CBuilding * b = VLC->buildh->buildings[t->subID][bid];
  1454. if(gs->canBuildStructure(t,bid) != 7)
  1455. {
  1456. complain("Cannot build that building!");
  1457. return;
  1458. }
  1459. NewStructures ns;
  1460. ns.tid = tid;
  1461. if(bid>36) //upg dwelling
  1462. {
  1463. if(t->getHordeLevel(0) == (bid-37))
  1464. ns.bid.insert(19);
  1465. else if(t->getHordeLevel(1) == (bid-37))
  1466. ns.bid.insert(25);
  1467. }
  1468. else if(bid >= 30) //bas. dwelling
  1469. {
  1470. SetAvailableCreatures ssi;
  1471. ssi.tid = tid;
  1472. ssi.creatures = t->strInfo.creatures;
  1473. ssi.creatures[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth;
  1474. sendAndApply(&ssi);
  1475. }
  1476. ns.bid.insert(bid);
  1477. ns.builded = t->builded + 1;
  1478. sendAndApply(&ns);
  1479. SetResources sr;
  1480. sr.player = t->tempOwner;
  1481. sr.res = gs->getPlayer(t->tempOwner)->resources;
  1482. for(int i=0;i<7;i++)
  1483. sr.res[i]-=b->resources[i];
  1484. sendAndApply(&sr);
  1485. if(bid<5) //it's mage guild
  1486. {
  1487. if(t->visitingHero)
  1488. giveSpells(t,t->visitingHero);
  1489. if(t->garrisonHero)
  1490. giveSpells(t,t->garrisonHero);
  1491. }
  1492. }
  1493. void CGameHandler::sendMessageToAll( const std::string &message )
  1494. {
  1495. SystemMessage sm;
  1496. sm.text = message;
  1497. sendToAllClients(&sm);
  1498. }
  1499. void CGameHandler::recruitCreatures( si32 objid, ui32 crid, ui32 cram )
  1500. {
  1501. si32 ser = -1;
  1502. CGTownInstance * t = static_cast<CGTownInstance*>(gs->map->objects[objid]);
  1503. //verify
  1504. bool found = false;
  1505. typedef std::pair<const int,int> Parka;
  1506. for(std::map<si32,ui32>::iterator av = t->strInfo.creatures.begin(); av!=t->strInfo.creatures.end(); av++)
  1507. {
  1508. if( ( found = (crid == t->town->basicCreatures[av->first]) ) //creature is available among basic cretures
  1509. || (found = (crid == t->town->upgradedCreatures[av->first])) )//creature is available among upgraded cretures
  1510. {
  1511. cram = std::min(cram,av->second); //reduce recruited amount up to available amount
  1512. ser = av->first;
  1513. break;
  1514. }
  1515. }
  1516. int slot = t->army.getSlotFor(crid);
  1517. if(!found || //no such creature
  1518. cram > VLC->creh->creatures[crid].maxAmount(gs->getPlayer(t->tempOwner)->resources) || //lack of resources
  1519. cram<=0 ||
  1520. slot<0 )
  1521. return;
  1522. //recruit
  1523. SetResources sr;
  1524. sr.player = t->tempOwner;
  1525. for(int i=0;i<RESOURCE_QUANTITY;i++)
  1526. sr.res[i] = gs->getPlayer(t->tempOwner)->resources[i] - (VLC->creh->creatures[crid].cost[i] * cram);
  1527. SetAvailableCreatures sac;
  1528. sac.tid = objid;
  1529. sac.creatures = t->strInfo.creatures;
  1530. sac.creatures[ser] -= cram;
  1531. SetGarrisons sg;
  1532. sg.garrs[objid] = t->army;
  1533. if(sg.garrs[objid].slots.find(slot) == sg.garrs[objid].slots.end()) //take a free slot
  1534. {
  1535. sg.garrs[objid].slots[slot] = std::make_pair(crid,cram);
  1536. }
  1537. else //add creatures to a already existing stack
  1538. {
  1539. sg.garrs[objid].slots[slot].second += cram;
  1540. }
  1541. sendAndApply(&sr);
  1542. sendAndApply(&sac);
  1543. sendAndApply(&sg);
  1544. }
  1545. void CGameHandler::upgradeCreature( ui32 objid, ui8 pos, ui32 upgID )
  1546. {
  1547. CArmedInstance *obj = static_cast<CArmedInstance*>(gs->map->objects[objid]);
  1548. UpgradeInfo ui = gs->getUpgradeInfo(obj,pos);
  1549. int player = obj->tempOwner;
  1550. int crQuantity = obj->army.slots[pos].second;
  1551. //check if upgrade is possible
  1552. if(ui.oldID<0 || !vstd::contains(ui.newID,upgID))
  1553. return;
  1554. //check if player has enough resources
  1555. for(int i=0;i<ui.cost.size();i++)
  1556. {
  1557. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1558. {
  1559. if(gs->getPlayer(player)->resources[j->first] < j->second*crQuantity)
  1560. return;
  1561. }
  1562. }
  1563. //take resources
  1564. for(int i=0;i<ui.cost.size();i++)
  1565. {
  1566. for (std::set<std::pair<int,int> >::iterator j=ui.cost[i].begin(); j!=ui.cost[i].end(); j++)
  1567. {
  1568. SetResource sr;
  1569. sr.player = player;
  1570. sr.resid = j->first;
  1571. sr.val = gs->getPlayer(player)->resources[j->first] - j->second*crQuantity;
  1572. sendAndApply(&sr);
  1573. }
  1574. }
  1575. //upgrade creature
  1576. SetGarrisons sg;
  1577. sg.garrs[objid] = obj->army;
  1578. sg.garrs[objid].slots[pos].first = upgID;
  1579. sendAndApply(&sg);
  1580. }
  1581. void CGameHandler::garrisonSwap(si32 tid)
  1582. {
  1583. CGTownInstance *town = gs->getTown(tid);
  1584. if(!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies
  1585. {
  1586. CCreatureSet csn = town->visitingHero->army, cso = town->army;
  1587. while(!cso.slots.empty())//while there are unmoved creatures
  1588. {
  1589. int pos = csn.getSlotFor(cso.slots.begin()->second.first);
  1590. if(pos<0)
  1591. return;
  1592. if(csn.slots.find(pos)!=csn.slots.end()) //add creatures to the existing stack
  1593. {
  1594. csn.slots[pos].second += cso.slots.begin()->second.second;
  1595. }
  1596. else //move stack on the free pos
  1597. {
  1598. csn.slots[pos].first = cso.slots.begin()->second.first;
  1599. csn.slots[pos].second = cso.slots.begin()->second.second;
  1600. }
  1601. cso.slots.erase(cso.slots.begin());
  1602. }
  1603. SetGarrisons sg;
  1604. sg.garrs[town->visitingHero->id] = csn;
  1605. sg.garrs[town->id] = csn;
  1606. sendAndApply(&sg);
  1607. SetHeroesInTown intown;
  1608. intown.tid = tid;
  1609. intown.visiting = -1;
  1610. intown.garrison = town->visitingHero->id;
  1611. sendAndApply(&intown);
  1612. }
  1613. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  1614. {
  1615. //check if moving hero out of town will break 8 wandering heroes limit
  1616. if(getHeroCount(town->garrisonHero->tempOwner,true) >= 8)
  1617. {
  1618. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  1619. return;
  1620. }
  1621. SetHeroesInTown intown;
  1622. intown.tid = tid;
  1623. intown.garrison = -1;
  1624. intown.visiting = town->garrisonHero->id;
  1625. sendAndApply(&intown);
  1626. //town will be empty
  1627. SetGarrisons sg;
  1628. sg.garrs[tid] = CCreatureSet();
  1629. sendAndApply(&sg);
  1630. }
  1631. else if (town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  1632. {
  1633. SetGarrisons sg;
  1634. sg.garrs[town->id] = town->visitingHero->army;
  1635. sg.garrs[town->garrisonHero->id] = town->garrisonHero->army;
  1636. SetHeroesInTown intown;
  1637. intown.tid = tid;
  1638. intown.garrison = town->visitingHero->id;
  1639. intown.visiting = town->garrisonHero->id;
  1640. sendAndApply(&intown);
  1641. sendAndApply(&sg);
  1642. }
  1643. else
  1644. {
  1645. complain("Cannot swap garrison hero!");
  1646. }
  1647. }
  1648. void CGameHandler::swapArtifacts( si32 hid1, si32 hid2, ui16 slot1, ui16 slot2 )
  1649. {
  1650. CGHeroInstance *h1 = gs->getHero(hid1), *h2 = gs->getHero(hid2);
  1651. if((distance(h1->pos,h2->pos) > 1.0) || (h1->tempOwner != h2->tempOwner))
  1652. return;
  1653. const CArtifact *a1 = h1->getArt(slot1),
  1654. *a2=h2->getArt(slot2);
  1655. if(a1 && slot2<19 && !vstd::contains(a1->possibleSlots,slot2)
  1656. || a2 && slot1<19 && !vstd::contains(a2->possibleSlots,slot1)
  1657. )
  1658. {
  1659. //artifact doesn't fit dst slot
  1660. complain("Cannot swap artifacts!");
  1661. return;
  1662. }
  1663. SetHeroArtifacts sha;
  1664. sha.hid = hid1;
  1665. sha.artifacts = h1->artifacts;
  1666. sha.artifWorn = h1->artifWorn;
  1667. sha.setArtAtPos(slot1,h2->getArtAtPos(slot2));
  1668. if(h1 == h2) sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  1669. sendAndApply(&sha);
  1670. if(hid1 != hid2)
  1671. {
  1672. sha.hid = hid2;
  1673. sha.artifacts = h2->artifacts;
  1674. sha.artifWorn = h2->artifWorn;
  1675. sha.setArtAtPos(slot2,h1->getArtAtPos(slot1));
  1676. sendAndApply(&sha);
  1677. }
  1678. }
  1679. void CGameHandler::buyArtifact( ui32 hid, si32 aid )
  1680. {
  1681. CGHeroInstance *hero = gs->getHero(hid);
  1682. CGTownInstance *town = hero->visitedTown;
  1683. if(aid==0) //spellbook
  1684. {
  1685. if(!vstd::contains(town->builtBuildings,si32(0)) && complain("Cannot buy a spellbook, no mage guild in the town!")
  1686. || getResource(hero->getOwner(),6)<500 && complain("Cannot buy a spellbook, not enough gold!")
  1687. || hero->getArt(17) && complain("Cannot buy a spellbook, hero already has a one!")
  1688. )
  1689. return;
  1690. giveResource(hero->getOwner(),6,-500);
  1691. giveHeroArtifact(0,hid,17);
  1692. giveSpells(town,hero);
  1693. }
  1694. else if(aid < 7 && aid > 3) //war machine
  1695. {
  1696. int price = VLC->arth->artifacts[aid].price;
  1697. if(vstd::contains(hero->artifWorn,ui16(9+aid)) //hero already has this machine
  1698. || !vstd::contains(town->builtBuildings,si32(16)) //no blackismith
  1699. || gs->getPlayer(hero->getOwner())->resources[6] < price //no gold
  1700. || town->town->warMachine!= aid ) //this machine is not available here (//TODO: support ballista yard in stronghold)
  1701. {
  1702. return;
  1703. }
  1704. giveResource(hero->getOwner(),6,-price);
  1705. giveHeroArtifact(aid,hid,9+aid);
  1706. }
  1707. }
  1708. void CGameHandler::tradeResources( ui32 val, ui8 player, ui32 id1, ui32 id2 )
  1709. {
  1710. val = std::min(si32(val),gs->getPlayer(player)->resources[id1]);
  1711. double uzysk = (double)gs->resVals[id1] * val * gs->getMarketEfficiency(player);
  1712. uzysk /= gs->resVals[id2];
  1713. SetResource sr;
  1714. sr.player = player;
  1715. sr.resid = id1;
  1716. sr.val = gs->getPlayer(player)->resources[id1] - val;
  1717. sendAndApply(&sr);
  1718. sr.resid = id2;
  1719. sr.val = gs->getPlayer(player)->resources[id2] + (int)uzysk;
  1720. sendAndApply(&sr);
  1721. }
  1722. void CGameHandler::setFormation( si32 hid, ui8 formation )
  1723. {
  1724. gs->getHero(hid)->army.formation = formation;
  1725. }
  1726. void CGameHandler::hireHero( ui32 tid, ui8 hid )
  1727. {
  1728. CGTownInstance *t = gs->getTown(tid);
  1729. if(!vstd::contains(t->builtBuildings,5) //no tavern in the town
  1730. || gs->getPlayer(t->tempOwner)->resources[6]<2500 //not enough gold
  1731. || t->visitingHero //there is visiting hero - no place
  1732. || getHeroCount(t->tempOwner,false) >= 8 && complain("Cannot hire hero, only 8 wandering heroes are allowed!")
  1733. )
  1734. return;
  1735. CGHeroInstance *nh = gs->getPlayer(t->tempOwner)->availableHeroes[hid];
  1736. HeroRecruited hr;
  1737. hr.tid = tid;
  1738. hr.hid = nh->subID;
  1739. hr.player = t->tempOwner;
  1740. hr.tile = t->pos - int3(1,0,0);
  1741. sendAndApply(&hr);
  1742. SetAvailableHeroes sah;
  1743. (hid ? sah.hid2 : sah.hid1) = gs->hpool.pickHeroFor(false,t->tempOwner,t->town)->subID;
  1744. (hid ? sah.hid1 : sah.hid2) = gs->getPlayer(t->tempOwner)->availableHeroes[!hid]->subID;
  1745. sah.player = t->tempOwner;
  1746. sah.flags = hid+1;
  1747. sendAndApply(&sah);
  1748. SetResource sr;
  1749. sr.player = t->tempOwner;
  1750. sr.resid = 6;
  1751. sr.val = gs->getPlayer(t->tempOwner)->resources[6] - 2500;
  1752. sendAndApply(&sr);
  1753. giveSpells(t,nh);
  1754. }
  1755. void CGameHandler::queryReply( ui32 qid, ui32 answer )
  1756. {
  1757. gsm.lock();
  1758. CFunctionList<void(ui32)> callb = callbacks[qid];
  1759. callbacks.erase(qid);
  1760. gsm.unlock();
  1761. callb(answer);
  1762. }
  1763. void CGameHandler::makeBattleAction( BattleAction &ba )
  1764. {
  1765. switch(ba.actionType)
  1766. {
  1767. case 2: //walk
  1768. {
  1769. sendAndApply(&StartAction(ba)); //start movement
  1770. moveStack(ba.stackNumber,ba.destinationTile); //move
  1771. sendAndApply(&EndAction());
  1772. break;
  1773. }
  1774. case 3: //defend
  1775. case 8: //wait
  1776. {
  1777. sendAndApply(&StartAction(ba));
  1778. sendAndApply(&EndAction());
  1779. break;
  1780. }
  1781. case 4: //retreat/flee
  1782. {
  1783. //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War)
  1784. //TODO: calculate casualties
  1785. //TODO: remove retreating hero from map and place it in recruitment list
  1786. BattleResult *br = new BattleResult;
  1787. br->result = 1;
  1788. br->winner = !ba.side; //fleeing side loses
  1789. gs->curB->calculateCasualties(br->casualties);
  1790. giveExp(*br);
  1791. battleResult.set(br);
  1792. break;
  1793. }
  1794. case 6: //walk or attack
  1795. {
  1796. sendAndApply(&StartAction(ba)); //start movement and attack
  1797. moveStack(ba.stackNumber,ba.destinationTile);
  1798. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1799. *stackAtEnd = gs->curB->getStackT(ba.additionalInfo);
  1800. if(curStack->position != ba.destinationTile) //we wasn't able to reach destination tile
  1801. {
  1802. tlog3<<"We cannot move this stack to its destination "<<curStack->creature->namePl<<std::endl;
  1803. }
  1804. if(!stackAtEnd)
  1805. {
  1806. tlog3 << "There is no stack on " << ba.additionalInfo << " tile (no attack)!";
  1807. break;
  1808. }
  1809. ui16 curpos = curStack->position,
  1810. enemypos = stackAtEnd->position;
  1811. if( !(
  1812. (BattleInfo::mutualPosition(curpos, enemypos) >= 0) //front <=> front
  1813. || (curStack->creature->isDoubleWide() //back <=> front
  1814. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos) >= 0)
  1815. || (stackAtEnd->creature->isDoubleWide() //front <=> back
  1816. && BattleInfo::mutualPosition(curpos, enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1817. || (stackAtEnd->creature->isDoubleWide() && curStack->creature->isDoubleWide()//back <=> back
  1818. && BattleInfo::mutualPosition(curpos + (curStack->attackerOwned ? -1 : 1), enemypos + (stackAtEnd->attackerOwned ? -1 : 1)) >= 0)
  1819. )
  1820. )
  1821. {
  1822. tlog3 << "Attack cannot be performed!";
  1823. sendAndApply(&EndAction());
  1824. break;
  1825. }
  1826. //attack
  1827. BattleAttack bat;
  1828. prepareAttack(bat,curStack,stackAtEnd);
  1829. sendAndApply(&bat);
  1830. //counterattack
  1831. if(!vstd::contains(curStack->abilities,NO_ENEMY_RETALIATION)
  1832. && stackAtEnd->alive()
  1833. && stackAtEnd->counterAttacks
  1834. && !vstd::contains(stackAtEnd->abilities, SIEGE_WEAPON)) //TODO: support for multiple retaliatons per turn
  1835. {
  1836. prepareAttack(bat,stackAtEnd,curStack);
  1837. bat.flags |= 2;
  1838. sendAndApply(&bat);
  1839. }
  1840. //second attack
  1841. if(vstd::contains(curStack->abilities,TWICE_ATTACK)
  1842. && curStack->alive()
  1843. && stackAtEnd->alive() )
  1844. {
  1845. bat.flags = 0;
  1846. prepareAttack(bat,curStack,stackAtEnd);
  1847. sendAndApply(&bat);
  1848. }
  1849. sendAndApply(&EndAction());
  1850. break;
  1851. }
  1852. case 7: //shoot
  1853. {
  1854. CStack *curStack = gs->curB->getStack(ba.stackNumber),
  1855. *destStack= gs->curB->getStackT(ba.destinationTile);
  1856. if(!curStack //our stack exists
  1857. || !destStack //there is a stack at destination tile
  1858. || !curStack->shots //stack has shots
  1859. || gs->curB->isStackBlocked(curStack->ID) //we are not blocked
  1860. || !vstd::contains(curStack->abilities,SHOOTER) //our stack is shooting unit
  1861. )
  1862. break;
  1863. for(int g=0; g<curStack->effects.size(); ++g)
  1864. {
  1865. if(61 == curStack->effects[g].id) //forgetfulness
  1866. break;
  1867. }
  1868. sendAndApply(&StartAction(ba)); //start shooting
  1869. BattleAttack bat;
  1870. prepareAttack(bat,curStack,destStack);
  1871. bat.flags |= 1;
  1872. sendAndApply(&bat);
  1873. if(vstd::contains(curStack->abilities,TWICE_ATTACK) //if unit shots twice let's make another shot
  1874. && curStack->alive()
  1875. && destStack->alive()
  1876. && curStack->shots
  1877. )
  1878. {
  1879. prepareAttack(bat,curStack,destStack);
  1880. sendAndApply(&bat);
  1881. }
  1882. sendAndApply(&EndAction());
  1883. break;
  1884. }
  1885. }
  1886. battleMadeAction.setn(true);
  1887. }
  1888. void CGameHandler::playerMessage( ui8 player, const std::string &message )
  1889. {
  1890. bool cheated=true;
  1891. sendAndApply(&PlayerMessage(player,message));
  1892. if(message == "vcmiistari") //give all spells and 999 mana
  1893. {
  1894. SetMana sm;
  1895. ChangeSpells cs;
  1896. cs.learn = 1;
  1897. for(int i=0;i<VLC->spellh->spells.size();i++)
  1898. {
  1899. if(!VLC->spellh->spells[i].creatureAbility)
  1900. cs.spells.insert(i);
  1901. }
  1902. sm.hid = cs.hid = gs->players[player].currentSelection;
  1903. sm.val = 999;
  1904. if(gs->getHero(cs.hid))
  1905. {
  1906. sendAndApply(&cs);
  1907. sendAndApply(&sm);
  1908. }
  1909. }
  1910. else if(message == "vcmiainur") //gives 5 archangels into each slot
  1911. {
  1912. SetGarrisons sg;
  1913. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1914. if(!hero) return;
  1915. sg.garrs[hero->id] = hero->army;
  1916. for(int i=0;i<7;i++)
  1917. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1918. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(13,5);
  1919. sendAndApply(&sg);
  1920. }
  1921. else if(message == "vcmiangband") //gives 10 black knightinto each slot
  1922. {
  1923. SetGarrisons sg;
  1924. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1925. if(!hero) return;
  1926. sg.garrs[hero->id] = hero->army;
  1927. for(int i=0;i<7;i++)
  1928. if(!vstd::contains(sg.garrs[hero->id].slots,i))
  1929. sg.garrs[hero->id].slots[i] = std::pair<ui32,si32>(66,10);
  1930. sendAndApply(&sg);
  1931. }
  1932. else if(message == "vcminoldor") //all war machines
  1933. {
  1934. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1935. if(!hero) return;
  1936. SetHeroArtifacts sha;
  1937. sha.hid = hero->id;
  1938. sha.artifacts = hero->artifacts;
  1939. sha.artifWorn = hero->artifWorn;
  1940. sha.artifWorn[13] = 4;
  1941. sha.artifWorn[14] = 5;
  1942. sha.artifWorn[15] = 6;
  1943. sendAndApply(&sha);
  1944. }
  1945. else if(message == "vcminahar") //1000000 movement points
  1946. {
  1947. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1948. if(!hero) return;
  1949. SetMovePoints smp;
  1950. smp.hid = hero->id;
  1951. smp.val = 1000000;
  1952. sendAndApply(&smp);
  1953. }
  1954. else if(message == "vcmiformenos") //give resources
  1955. {
  1956. SetResources sr;
  1957. sr.player = player;
  1958. sr.res = gs->getPlayer(player)->resources;
  1959. for(int i=0;i<7;i++)
  1960. sr.res[i] += 100;
  1961. sr.res[6] += 19900;
  1962. sendAndApply(&sr);
  1963. }
  1964. else if(message == "vcmieagles") //reveal FoW
  1965. {
  1966. FoWChange fc;
  1967. fc.player = player;
  1968. for(int i=0;i<gs->map->width;i++)
  1969. for(int j=0;j<gs->map->height;j++)
  1970. for(int k=0;k<gs->map->twoLevel+1;k++)
  1971. if(!gs->getPlayer(fc.player)->fogOfWarMap[i][j][k])
  1972. fc.tiles.insert(int3(i,j,k));
  1973. sendAndApply(&fc);
  1974. }
  1975. else if(message == "vcmiglorfindel")
  1976. {
  1977. CGHeroInstance *hero = gs->getHero(gs->getPlayer(player)->currentSelection);
  1978. changePrimSkill(hero->id,4,VLC->heroh->reqExp(hero->level+1) - VLC->heroh->reqExp(hero->level));
  1979. }
  1980. else
  1981. cheated = false;
  1982. if(cheated)
  1983. {
  1984. sendAndApply(&SystemMessage("CHEATER!!!"));
  1985. }
  1986. }
  1987. void CGameHandler::makeCustomAction( BattleAction &ba )
  1988. {
  1989. switch(ba.actionType)
  1990. {
  1991. case 1: //hero casts spell
  1992. {
  1993. CGHeroInstance *h = (ba.side) ? gs->getHero(gs->curB->hero2) : gs->getHero(gs->curB->hero1);
  1994. if(!h)
  1995. {
  1996. tlog2 << "Wrong caster!\n";
  1997. return;
  1998. }
  1999. if(ba.additionalInfo >= VLC->spellh->spells.size())
  2000. {
  2001. tlog2 << "Wrong spell id (" << ba.additionalInfo << ")!\n";
  2002. return;
  2003. }
  2004. CSpell *s = &VLC->spellh->spells[ba.additionalInfo];
  2005. ui8 skill = 0; //skill level
  2006. if(s->fire)
  2007. skill = std::max(skill,h->getSecSkillLevel(14));
  2008. if(s->air)
  2009. skill = std::max(skill,h->getSecSkillLevel(15));
  2010. if(s->water)
  2011. skill = std::max(skill,h->getSecSkillLevel(16));
  2012. if(s->earth)
  2013. skill = std::max(skill,h->getSecSkillLevel(17));
  2014. //TODO: skill level may be different on special terrain
  2015. if( !(vstd::contains(h->spells,ba.additionalInfo)) //hero doesn't know this spell
  2016. || (h->mana < s->costs[skill]) //not enough mana
  2017. || (ba.additionalInfo < 10) //it's adventure spell (not combat)
  2018. || (gs->curB->castedSpells[ba.side])
  2019. )
  2020. {
  2021. tlog2 << "Spell cannot be casted!\n";
  2022. return;
  2023. }
  2024. sendAndApply(&StartAction(ba)); //start spell casting
  2025. //TODO: check resistances
  2026. #define SPELL_CAST_TEMPLATE_1(NUMBER, DURATION) SetStackEffect sse; \
  2027. if(getSchoolLevel(h,s) < 3) /*not expert */ \
  2028. { \
  2029. sse.stacks.insert(gs->curB->getStackT(ba.destinationTile)->ID); \
  2030. sse.effect.id = (NUMBER); \
  2031. sse.effect.level = getSchoolLevel(h,s); \
  2032. sse.effect.turnsRemain = (DURATION); /*! - any duration */ \
  2033. sendAndApply(&sse); \
  2034. } \
  2035. else \
  2036. { \
  2037. for(int it=0; it<gs->curB->stacks.size(); ++it) \
  2038. { \
  2039. /*if it's non negative spell and our unit or non positive spell and hostile unit */ \
  2040. if((VLC->spellh->spells[ba.additionalInfo].positiveness >= 0 && gs->curB->stacks[it]->owner == h->tempOwner) \
  2041. ||(VLC->spellh->spells[ba.additionalInfo].positiveness <= 0 && gs->curB->stacks[it]->owner != h->tempOwner ) \
  2042. ) \
  2043. { \
  2044. sse.stacks.insert(gs->curB->stacks[it]->ID); \
  2045. } \
  2046. } \
  2047. sse.effect.id = (NUMBER); \
  2048. sse.effect.level = getSchoolLevel(h,s); \
  2049. sse.effect.turnsRemain = (DURATION); \
  2050. sendAndApply(&sse); \
  2051. }
  2052. SpellCasted sc;
  2053. sc.side = ba.side;
  2054. sc.id = ba.additionalInfo;
  2055. sc.skill = skill;
  2056. sc.tile = ba.destinationTile;
  2057. sendAndApply(&sc);
  2058. switch(ba.additionalInfo) //spell id
  2059. {
  2060. case 15: //magic arrow
  2061. {
  2062. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2063. if(!attacked) break;
  2064. BattleStackAttacked bsa;
  2065. bsa.flags |= 2;
  2066. bsa.effect = 64;
  2067. bsa.damageAmount = h->getPrimSkillLevel(2) * 10 + s->powers[getSchoolLevel(h,s)];
  2068. bsa.stackAttacked = attacked->ID;
  2069. prepareAttacked(bsa,attacked);
  2070. sendAndApply(&bsa);
  2071. break;
  2072. }
  2073. case 16: //ice bolt
  2074. {
  2075. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2076. if(!attacked) break;
  2077. BattleStackAttacked bsa;
  2078. bsa.flags |= 2;
  2079. bsa.effect = 46;
  2080. bsa.damageAmount = h->getPrimSkillLevel(2) * 20 + s->powers[getSchoolLevel(h,s)];
  2081. bsa.stackAttacked = attacked->ID;
  2082. prepareAttacked(bsa,attacked);
  2083. sendAndApply(&bsa);
  2084. break;
  2085. }
  2086. case 17: //lightning bolt
  2087. {
  2088. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2089. if(!attacked) break;
  2090. BattleStackAttacked bsa;
  2091. bsa.flags |= 2;
  2092. bsa.effect = 38;
  2093. bsa.damageAmount = h->getPrimSkillLevel(2) * 25 + s->powers[getSchoolLevel(h,s)];
  2094. bsa.stackAttacked = attacked->ID;
  2095. prepareAttacked(bsa,attacked);
  2096. sendAndApply(&bsa);
  2097. break;
  2098. }
  2099. case 18: //implosion
  2100. {
  2101. CStack * attacked = gs->curB->getStackT(ba.destinationTile);
  2102. if(!attacked) break;
  2103. BattleStackAttacked bsa;
  2104. bsa.flags |= 2;
  2105. bsa.effect = 10;
  2106. bsa.damageAmount = h->getPrimSkillLevel(2) * 75 + s->powers[getSchoolLevel(h,s)];
  2107. bsa.stackAttacked = attacked->ID;
  2108. prepareAttacked(bsa,attacked);
  2109. sendAndApply(&bsa);
  2110. break;
  2111. }
  2112. case 27: //shield
  2113. case 28: //air shield
  2114. case 41: //bless
  2115. case 42: //curse
  2116. case 43: //bloodlust
  2117. case 45: //weakness
  2118. case 46: //stone skin
  2119. case 48: //prayer
  2120. case 49: //mirth
  2121. case 50: //sorrow
  2122. case 51: //fortune
  2123. case 52: //misfortune
  2124. case 53: //haste
  2125. case 54: //slow
  2126. case 61: //forgetfulness
  2127. {
  2128. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, h->getPrimSkillLevel(2) + h->valOfBonuses(HeroBonus::SPELL_DURATION) )
  2129. break;
  2130. }
  2131. case 56: //frenzy
  2132. {
  2133. SPELL_CAST_TEMPLATE_1(ba.additionalInfo, 1)
  2134. break;
  2135. }
  2136. }
  2137. sendAndApply(&EndAction());
  2138. }
  2139. }
  2140. }
  2141. void CGameHandler::handleTimeEvents()
  2142. {
  2143. while(gs->map->events.size() && gs->map->events.front()->firstOccurence+1 == gs->day)
  2144. {
  2145. CMapEvent *ev = gs->map->events.front();
  2146. for(int player = 0; player < PLAYER_LIMIT; player++)
  2147. {
  2148. PlayerState *pinfo = gs->getPlayer(player);
  2149. if( pinfo //player exists
  2150. && (ev->players & 1<<player) //event is enabled to this player
  2151. && ((ev->computerAffected && !pinfo->human)
  2152. || (ev->humanAffected && pinfo->human)
  2153. )
  2154. )
  2155. {
  2156. //give resources
  2157. SetResources sr;
  2158. sr.player = player;
  2159. sr.res = pinfo->resources;
  2160. //prepare dialog
  2161. InfoWindow iw;
  2162. iw.player = player;
  2163. iw.text << ev->message;
  2164. for (int i=0; i<ev->resources.size(); i++)
  2165. {
  2166. if(ev->resources[i]) //if resource is changed, we add it to the dialog
  2167. {
  2168. iw.components.push_back(Component(Component::RESOURCE,i,ev->resources[i],0));
  2169. sr.res[i] += ev->resources[i];
  2170. }
  2171. }
  2172. if (iw.components.size())
  2173. {
  2174. sendAndApply(&sr); //update player resources if changed
  2175. }
  2176. sendAndApply(&iw); //show dialog
  2177. }
  2178. } //PLAYERS LOOP
  2179. if(ev->nextOccurence)
  2180. {
  2181. ev->firstOccurence += ev->nextOccurence;
  2182. gs->map->events.sort(evntCmp);
  2183. }
  2184. else
  2185. {
  2186. delete ev;
  2187. gs->map->events.pop_front();
  2188. }
  2189. }
  2190. }
  2191. bool CGameHandler::complain( const std::string &problem )
  2192. {
  2193. sendMessageToAll("Server encountered a problem: " + problem);
  2194. tlog1 << problem << std::endl;
  2195. return true;
  2196. }
  2197. ui32 CGameHandler::getQueryResult( ui8 player, int queryID )
  2198. {
  2199. //TODO: write
  2200. return 0;
  2201. }