CGameHandler.cpp 94 KB

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