CGameHandler.cpp 161 KB

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