CGameHandler.cpp 91 KB

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