CGameHandler.cpp 123 KB

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