CGameHandler.cpp 96 KB

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