CGameHandler.cpp 146 KB

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