CGameHandler.cpp 85 KB

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