CGameHandler.cpp 68 KB

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