CGameHandler.cpp 187 KB

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