CGameHandler.cpp 206 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878
  1. /*
  2. * CGameHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CGameHandler.h"
  12. #include "HeroPoolProcessor.h"
  13. #include "ServerNetPackVisitors.h"
  14. #include "ServerSpellCastEnvironment.h"
  15. #include "CVCMIServer.h"
  16. #include "PlayerMessageProcessor.h"
  17. #include "../lib/filesystem/Filesystem.h"
  18. #include "../lib/filesystem/FileInfo.h"
  19. #include "../lib/int3.h"
  20. #include "../lib/ArtifactUtils.h"
  21. #include "../lib/StartInfo.h"
  22. #include "../lib/CModHandler.h"
  23. #include "../lib/CArtHandler.h"
  24. #include "../lib/CBuildingHandler.h"
  25. #include "../lib/CHeroHandler.h"
  26. #include "../lib/pathfinder/CPathfinder.h"
  27. #include "../lib/pathfinder/PathfinderOptions.h"
  28. #include "../lib/pathfinder/TurnInfo.h"
  29. #include "../lib/spells/AbilityCaster.h"
  30. #include "../lib/spells/BonusCaster.h"
  31. #include "../lib/spells/CSpellHandler.h"
  32. #include "../lib/spells/ISpellMechanics.h"
  33. #include "../lib/spells/ObstacleCasterProxy.h"
  34. #include "../lib/spells/Problem.h"
  35. #include "../lib/CGeneralTextHandler.h"
  36. #include "../lib/CTownHandler.h"
  37. #include "../lib/CCreatureHandler.h"
  38. #include "../lib/gameState/CGameState.h"
  39. #include "../lib/CStack.h"
  40. #include "../lib/GameSettings.h"
  41. #include "../lib/battle/BattleInfo.h"
  42. #include "../lib/CondSh.h"
  43. #include "../lib/VCMI_Lib.h"
  44. #include "../lib/mapping/CMap.h"
  45. #include "../lib/mapping/CMapService.h"
  46. #include "../lib/rmg/CMapGenOptions.h"
  47. #include "../lib/VCMIDirs.h"
  48. #include "../lib/ScopeGuard.h"
  49. #include "../lib/CSoundBase.h"
  50. #include "../lib/TerrainHandler.h"
  51. #include "../lib/CCreatureSet.h"
  52. #include "../lib/CThreadHelper.h"
  53. #include "../lib/GameConstants.h"
  54. #include "../lib/registerTypes/RegisterTypes.h"
  55. #include "../lib/serializer/CTypeList.h"
  56. #include "../lib/serializer/Connection.h"
  57. #include "../lib/serializer/Cast.h"
  58. #include "../lib/serializer/JsonSerializer.h"
  59. #include "../lib/ScriptHandler.h"
  60. #include "vstd/CLoggerBase.h"
  61. #include <memory>
  62. #include <vcmi/events/EventBus.h>
  63. #include <vcmi/events/GenericEvents.h>
  64. #include <vcmi/events/AdventureEvents.h>
  65. #ifndef _MSC_VER
  66. #include <boost/thread/xtime.hpp>
  67. #endif
  68. #define COMPLAIN_RET_IF(cond, txt) do {if (cond){complain(txt); return;}} while(0)
  69. #define COMPLAIN_RET_FALSE_IF(cond, txt) do {if (cond){complain(txt); return false;}} while(0)
  70. #define COMPLAIN_RET(txt) {complain(txt); return false;}
  71. #define COMPLAIN_RETF(txt, FORMAT) {complain(boost::str(boost::format(txt) % FORMAT)); return false;}
  72. CondSh<bool> battleMadeAction(false);
  73. CondSh<BattleResult *> battleResult(nullptr);
  74. template <typename T> class CApplyOnGH;
  75. class CBaseForGHApply
  76. {
  77. public:
  78. virtual bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const =0;
  79. virtual ~CBaseForGHApply(){}
  80. template<typename U> static CBaseForGHApply *getApplier(const U * t=nullptr)
  81. {
  82. return new CApplyOnGH<U>();
  83. }
  84. };
  85. template <typename T> class CApplyOnGH : public CBaseForGHApply
  86. {
  87. public:
  88. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  89. {
  90. T *ptr = static_cast<T*>(pack);
  91. try
  92. {
  93. ApplyGhNetPackVisitor applier(*gh, *gs);
  94. ptr->visit(applier);
  95. return applier.getResult();
  96. }
  97. catch(ExceptionNotAllowedAction & e)
  98. {
  99. (void)e;
  100. return false;
  101. }
  102. catch(...)
  103. {
  104. throw;
  105. }
  106. }
  107. };
  108. template <>
  109. class CApplyOnGH<CPack> : public CBaseForGHApply
  110. {
  111. public:
  112. bool applyOnGH(CGameHandler * gh, CGameState * gs, void * pack) const override
  113. {
  114. logGlobal->error("Cannot apply on GH plain CPack!");
  115. assert(0);
  116. return false;
  117. }
  118. };
  119. static inline double distance(int3 a, int3 b)
  120. {
  121. return std::sqrt((double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));
  122. }
  123. static void giveExp(BattleResult &r)
  124. {
  125. if (r.winner > 1)
  126. {
  127. // draw
  128. return;
  129. }
  130. r.exp[0] = 0;
  131. r.exp[1] = 0;
  132. for (auto i = r.casualties[!r.winner].begin(); i!=r.casualties[!r.winner].end(); i++)
  133. {
  134. r.exp[r.winner] += VLC->creh->objects.at(i->first)->valOfBonuses(BonusType::STACK_HEALTH) * i->second;
  135. }
  136. }
  137. static void summonGuardiansHelper(std::vector<BattleHex> & output, const BattleHex & targetPosition, ui8 side, bool targetIsTwoHex) //return hexes for summoning two hex monsters in output, target = unit to guard
  138. {
  139. int x = targetPosition.getX();
  140. int y = targetPosition.getY();
  141. const bool targetIsAttacker = side == BattleSide::ATTACKER;
  142. if (targetIsAttacker) //handle front guardians, TODO: should we handle situation when units start battle near opposite side of the battlefield? Cannot happen in normal H3...
  143. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  144. else
  145. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  146. //guardian spawn locations for four default position cases for attacker and defender, non-default starting location for att and def is handled in first two if's
  147. if (targetIsAttacker && ((y % 2 == 0) || (x > 1)))
  148. {
  149. if (targetIsTwoHex && (y % 2 == 1) && (x == 2)) //handle exceptional case
  150. {
  151. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  152. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  153. }
  154. else
  155. { //add back-side guardians for two-hex target, side guardians for one-hex
  156. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_LEFT : BattleHex::EDir::TOP_RIGHT, false), output);
  157. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_LEFT : BattleHex::EDir::BOTTOM_RIGHT, false), output);
  158. if (!targetIsTwoHex && x > 2) //back guard for one-hex
  159. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false), output);
  160. else if (targetIsTwoHex)//front-side guardians for two-hex target
  161. {
  162. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  163. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  164. if (x > 3) //back guard for two-hex
  165. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::LEFT, false), output);
  166. }
  167. }
  168. }
  169. else if (!targetIsAttacker && ((y % 2 == 1) || (x < GameConstants::BFIELD_WIDTH - 2)))
  170. {
  171. if (targetIsTwoHex && (y % 2 == 0) && (x == GameConstants::BFIELD_WIDTH - 3)) //handle exceptional case... equivalent for above for defender side
  172. {
  173. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  174. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  175. }
  176. else
  177. {
  178. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::TOP_RIGHT : BattleHex::EDir::TOP_LEFT, false), output);
  179. BattleHex::checkAndPush(targetPosition.cloneInDirection(targetIsTwoHex ? BattleHex::EDir::BOTTOM_RIGHT : BattleHex::EDir::BOTTOM_LEFT, false), output);
  180. if (!targetIsTwoHex && x < GameConstants::BFIELD_WIDTH - 3)
  181. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  182. else if (targetIsTwoHex)
  183. {
  184. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  185. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  186. if (x < GameConstants::BFIELD_WIDTH - 4)
  187. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::RIGHT, false), output);
  188. }
  189. }
  190. }
  191. else if (!targetIsAttacker && y % 2 == 0)
  192. {
  193. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::TOP_LEFT, false), output);
  194. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::LEFT, false).cloneInDirection(BattleHex::EDir::BOTTOM_LEFT, false), output);
  195. }
  196. else if (targetIsAttacker && y % 2 == 1)
  197. {
  198. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::TOP_RIGHT, false), output);
  199. BattleHex::checkAndPush(targetPosition.cloneInDirection(BattleHex::EDir::RIGHT, false).cloneInDirection(BattleHex::EDir::BOTTOM_RIGHT, false), output);
  200. }
  201. }
  202. PlayerStatus PlayerStatuses::operator[](PlayerColor player)
  203. {
  204. boost::unique_lock<boost::mutex> l(mx);
  205. if (players.find(player) != players.end())
  206. {
  207. return players.at(player);
  208. }
  209. else
  210. {
  211. throw std::runtime_error("No such player!");
  212. }
  213. }
  214. void PlayerStatuses::addPlayer(PlayerColor player)
  215. {
  216. boost::unique_lock<boost::mutex> l(mx);
  217. players[player];
  218. }
  219. bool PlayerStatuses::checkFlag(PlayerColor player, bool PlayerStatus::*flag)
  220. {
  221. boost::unique_lock<boost::mutex> l(mx);
  222. if (players.find(player) != players.end())
  223. {
  224. return players[player].*flag;
  225. }
  226. else
  227. {
  228. throw std::runtime_error("No such player!");
  229. }
  230. }
  231. void PlayerStatuses::setFlag(PlayerColor player, bool PlayerStatus::*flag, bool val)
  232. {
  233. boost::unique_lock<boost::mutex> l(mx);
  234. if (players.find(player) != players.end())
  235. {
  236. players[player].*flag = val;
  237. }
  238. else
  239. {
  240. throw std::runtime_error("No such player!");
  241. }
  242. cv.notify_all();
  243. }
  244. template <typename T>
  245. void callWith(std::vector<T> args, std::function<void(T)> fun, ui32 which)
  246. {
  247. fun(args[which]);
  248. }
  249. const Services * CGameHandler::services() const
  250. {
  251. return VLC;
  252. }
  253. const CGameHandler::BattleCb * CGameHandler::battle() const
  254. {
  255. return this;
  256. }
  257. const CGameHandler::GameCb * CGameHandler::game() const
  258. {
  259. return this;
  260. }
  261. vstd::CLoggerBase * CGameHandler::logger() const
  262. {
  263. return logGlobal;
  264. }
  265. events::EventBus * CGameHandler::eventBus() const
  266. {
  267. return serverEventBus.get();
  268. }
  269. CVCMIServer * CGameHandler::gameLobby() const
  270. {
  271. return lobby;
  272. }
  273. void CGameHandler::levelUpHero(const CGHeroInstance * hero, SecondarySkill skill)
  274. {
  275. changeSecSkill(hero, skill, 1, 0);
  276. expGiven(hero);
  277. }
  278. void CGameHandler::levelUpHero(const CGHeroInstance * hero)
  279. {
  280. // required exp for at least 1 lvl-up hasn't been reached
  281. if (!hero->gainsLevel())
  282. {
  283. return;
  284. }
  285. // give primary skill
  286. logGlobal->trace("%s got level %d", hero->getNameTranslated(), hero->level);
  287. auto primarySkill = hero->nextPrimarySkill(getRandomGenerator());
  288. SetPrimSkill sps;
  289. sps.id = hero->id;
  290. sps.which = primarySkill;
  291. sps.abs = false;
  292. sps.val = 1;
  293. sendAndApply(&sps);
  294. PrepareHeroLevelUp pre;
  295. pre.heroId = hero->id;
  296. sendAndApply(&pre);
  297. HeroLevelUp hlu;
  298. hlu.player = hero->tempOwner;
  299. hlu.heroId = hero->id;
  300. hlu.primskill = primarySkill;
  301. hlu.skills = pre.skills;
  302. if (hlu.skills.size() == 0)
  303. {
  304. sendAndApply(&hlu);
  305. levelUpHero(hero);
  306. }
  307. else if (hlu.skills.size() == 1)
  308. {
  309. sendAndApply(&hlu);
  310. levelUpHero(hero, pre.skills.front());
  311. }
  312. else if (hlu.skills.size() > 1)
  313. {
  314. auto levelUpQuery = std::make_shared<CHeroLevelUpDialogQuery>(this, hlu, hero);
  315. hlu.queryID = levelUpQuery->queryID;
  316. queries.addQuery(levelUpQuery);
  317. sendAndApply(&hlu);
  318. //level up will be called on query reply
  319. }
  320. }
  321. void CGameHandler::levelUpCommander (const CCommanderInstance * c, int skill)
  322. {
  323. SetCommanderProperty scp;
  324. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  325. if (hero)
  326. scp.heroid = hero->id;
  327. else
  328. {
  329. complain ("Commander is not led by hero!");
  330. return;
  331. }
  332. scp.accumulatedBonus.subtype = 0;
  333. scp.accumulatedBonus.additionalInfo = 0;
  334. scp.accumulatedBonus.duration = BonusDuration::PERMANENT;
  335. scp.accumulatedBonus.turnsRemain = 0;
  336. scp.accumulatedBonus.source = BonusSource::COMMANDER;
  337. scp.accumulatedBonus.valType = BonusValueType::BASE_NUMBER;
  338. if (skill <= ECommander::SPELL_POWER)
  339. {
  340. scp.which = SetCommanderProperty::BONUS;
  341. auto difference = [](std::vector< std::vector <ui8> > skillLevels, std::vector <ui8> secondarySkills, int skill)->int
  342. {
  343. int s = std::min (skill, (int)ECommander::SPELL_POWER); //spell power level controls also casts and resistance
  344. return skillLevels.at(skill).at(secondarySkills.at(s)) - (secondarySkills.at(s) ? skillLevels.at(skill).at(secondarySkills.at(s)-1) : 0);
  345. };
  346. switch (skill)
  347. {
  348. case ECommander::ATTACK:
  349. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  350. scp.accumulatedBonus.subtype = PrimarySkill::ATTACK;
  351. break;
  352. case ECommander::DEFENSE:
  353. scp.accumulatedBonus.type = BonusType::PRIMARY_SKILL;
  354. scp.accumulatedBonus.subtype = PrimarySkill::DEFENSE;
  355. break;
  356. case ECommander::HEALTH:
  357. scp.accumulatedBonus.type = BonusType::STACK_HEALTH;
  358. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  359. break;
  360. case ECommander::DAMAGE:
  361. scp.accumulatedBonus.type = BonusType::CREATURE_DAMAGE;
  362. scp.accumulatedBonus.subtype = 0;
  363. scp.accumulatedBonus.valType = BonusValueType::PERCENT_TO_BASE;
  364. break;
  365. case ECommander::SPEED:
  366. scp.accumulatedBonus.type = BonusType::STACKS_SPEED;
  367. break;
  368. case ECommander::SPELL_POWER:
  369. scp.accumulatedBonus.type = BonusType::MAGIC_RESISTANCE;
  370. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::RESISTANCE);
  371. sendAndApply (&scp); //additional pack
  372. scp.accumulatedBonus.type = BonusType::CREATURE_SPELL_POWER;
  373. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::SPELL_POWER) * 100; //like hero with spellpower = ability level
  374. sendAndApply (&scp); //additional pack
  375. scp.accumulatedBonus.type = BonusType::CASTS;
  376. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, ECommander::CASTS);
  377. sendAndApply (&scp); //additional pack
  378. scp.accumulatedBonus.type = BonusType::CREATURE_ENCHANT_POWER; //send normally
  379. break;
  380. }
  381. scp.accumulatedBonus.val = difference (VLC->creh->skillLevels, c->secondarySkills, skill);
  382. sendAndApply (&scp);
  383. scp.which = SetCommanderProperty::SECONDARY_SKILL;
  384. scp.additionalInfo = skill;
  385. scp.amount = c->secondarySkills.at(skill) + 1;
  386. sendAndApply (&scp);
  387. }
  388. else if (skill >= 100)
  389. {
  390. scp.which = SetCommanderProperty::SPECIAL_SKILL;
  391. scp.accumulatedBonus = *VLC->creh->skillRequirements.at(skill-100).first;
  392. scp.additionalInfo = skill; //unnormalized
  393. sendAndApply (&scp);
  394. }
  395. expGiven(hero);
  396. }
  397. void CGameHandler::levelUpCommander(const CCommanderInstance * c)
  398. {
  399. if (!c->gainsLevel())
  400. {
  401. return;
  402. }
  403. CommanderLevelUp clu;
  404. auto hero = dynamic_cast<const CGHeroInstance *>(c->armyObj);
  405. if(hero)
  406. {
  407. clu.heroId = hero->id;
  408. clu.player = hero->tempOwner;
  409. }
  410. else
  411. {
  412. complain ("Commander is not led by hero!");
  413. return;
  414. }
  415. //picking sec. skills for choice
  416. for (int i = 0; i <= ECommander::SPELL_POWER; ++i)
  417. {
  418. if (c->secondarySkills.at(i) < ECommander::MAX_SKILL_LEVEL)
  419. clu.skills.push_back(i);
  420. }
  421. int i = 100;
  422. for (auto specialSkill : VLC->creh->skillRequirements)
  423. {
  424. if (c->secondarySkills.at(specialSkill.second.first) == ECommander::MAX_SKILL_LEVEL
  425. && c->secondarySkills.at(specialSkill.second.second) == ECommander::MAX_SKILL_LEVEL
  426. && !vstd::contains (c->specialSKills, i))
  427. clu.skills.push_back (i);
  428. ++i;
  429. }
  430. int skillAmount = static_cast<int>(clu.skills.size());
  431. if (!skillAmount)
  432. {
  433. sendAndApply(&clu);
  434. levelUpCommander(c);
  435. }
  436. else if (skillAmount == 1 || hero->tempOwner == PlayerColor::NEUTRAL) //choose skill automatically
  437. {
  438. sendAndApply(&clu);
  439. levelUpCommander(c, *RandomGeneratorUtil::nextItem(clu.skills, getRandomGenerator()));
  440. }
  441. else if (skillAmount > 1) //apply and ask for secondary skill
  442. {
  443. auto commanderLevelUp = std::make_shared<CCommanderLevelUpDialogQuery>(this, clu, hero);
  444. clu.queryID = commanderLevelUp->queryID;
  445. queries.addQuery(commanderLevelUp);
  446. sendAndApply(&clu);
  447. }
  448. }
  449. void CGameHandler::expGiven(const CGHeroInstance *hero)
  450. {
  451. if (hero->gainsLevel())
  452. levelUpHero(hero);
  453. else if (hero->commander && hero->commander->gainsLevel())
  454. levelUpCommander(hero->commander);
  455. //if (hero->commander && hero->level > hero->commander->level && hero->commander->gainsLevel())
  456. // levelUpCommander(hero->commander);
  457. // else
  458. // levelUpHero(hero);
  459. }
  460. void CGameHandler::changePrimSkill(const CGHeroInstance * hero, PrimarySkill::PrimarySkill which, si64 val, bool abs)
  461. {
  462. if (which == PrimarySkill::EXPERIENCE) // Check if scenario limit reached
  463. {
  464. if (gs->map->levelLimit != 0)
  465. {
  466. TExpType expLimit = VLC->heroh->reqExp(gs->map->levelLimit);
  467. TExpType resultingExp = abs ? val : hero->exp + val;
  468. if (resultingExp > expLimit)
  469. {
  470. // set given experience to max possible, but don't decrease if hero already over top
  471. abs = true;
  472. val = std::max(expLimit, hero->exp);
  473. InfoWindow iw;
  474. iw.player = hero->tempOwner;
  475. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 1); //can gain no more XP
  476. iw.text.replaceRawString(hero->getNameTranslated());
  477. sendAndApply(&iw);
  478. }
  479. }
  480. }
  481. SetPrimSkill sps;
  482. sps.id = hero->id;
  483. sps.which = which;
  484. sps.abs = abs;
  485. sps.val = val;
  486. sendAndApply(&sps);
  487. //only for exp - hero may level up
  488. if (which == PrimarySkill::EXPERIENCE)
  489. {
  490. if (hero->commander && hero->commander->alive)
  491. {
  492. //FIXME: trim experience according to map limit?
  493. SetCommanderProperty scp;
  494. scp.heroid = hero->id;
  495. scp.which = SetCommanderProperty::EXPERIENCE;
  496. scp.amount = val;
  497. sendAndApply (&scp);
  498. CBonusSystemNode::treeHasChanged();
  499. }
  500. expGiven(hero);
  501. }
  502. }
  503. void CGameHandler::changeSecSkill(const CGHeroInstance * hero, SecondarySkill which, int val, bool abs)
  504. {
  505. if(!hero)
  506. {
  507. logGlobal->error("changeSecSkill provided no hero");
  508. return;
  509. }
  510. SetSecSkill sss;
  511. sss.id = hero->id;
  512. sss.which = which;
  513. sss.val = val;
  514. sss.abs = abs;
  515. sendAndApply(&sss);
  516. if (hero->visitedTown)
  517. giveSpells(hero->visitedTown, hero);
  518. }
  519. void CGameHandler::endBattle(int3 tile, const CGHeroInstance * heroAttacker, const CGHeroInstance * heroDefender)
  520. {
  521. LOG_TRACE(logGlobal);
  522. //Fill BattleResult structure with exp info
  523. giveExp(*battleResult.data);
  524. if (battleResult.get()->result == BattleResult::NORMAL) // give 500 exp for defeating hero, unless he escaped
  525. {
  526. if(heroAttacker)
  527. battleResult.data->exp[1] += 500;
  528. if(heroDefender)
  529. battleResult.data->exp[0] += 500;
  530. }
  531. if(heroAttacker)
  532. battleResult.data->exp[0] = heroAttacker->calculateXp(battleResult.data->exp[0]);//scholar skill
  533. if(heroDefender)
  534. battleResult.data->exp[1] = heroDefender->calculateXp(battleResult.data->exp[1]);
  535. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(gs->curB->sides[0].color));
  536. if (!battleQuery)
  537. {
  538. logGlobal->error("Cannot find battle query!");
  539. complain("Player " + boost::lexical_cast<std::string>(gs->curB->sides[0].color) + " has no battle query at the top!");
  540. return;
  541. }
  542. battleQuery->result = std::make_optional(*battleResult.data);
  543. //Check how many battle queries were created (number of players blocked by battle)
  544. const int queriedPlayers = battleQuery ? (int)boost::count(queries.allQueries(), battleQuery) : 0;
  545. finishingBattle = std::make_unique<FinishingBattleHelper>(battleQuery, queriedPlayers);
  546. auto battleDialogQuery = std::make_shared<CBattleDialogQuery>(this, gs->curB);
  547. battleResult.data->queryID = battleDialogQuery->queryID;
  548. queries.addQuery(battleDialogQuery);
  549. //set same battle result for all queries
  550. for(auto q : queries.allQueries())
  551. {
  552. auto otherBattleQuery = std::dynamic_pointer_cast<CBattleQuery>(q);
  553. if(otherBattleQuery)
  554. otherBattleQuery->result = battleQuery->result;
  555. }
  556. sendAndApply(battleResult.data); //after this point casualties objects are destroyed
  557. }
  558. void CGameHandler::endBattleConfirm(const BattleInfo * battleInfo)
  559. {
  560. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(battleInfo->sides.at(0).color));
  561. if(!battleQuery)
  562. {
  563. logGlobal->trace("No battle query, battle end was confirmed by another player");
  564. return;
  565. }
  566. const BattleResult::EResult result = battleResult.get()->result;
  567. CasualtiesAfterBattle cab1(battleInfo->sides.at(0), battleInfo), cab2(battleInfo->sides.at(1), battleInfo); //calculate casualties before deleting battle
  568. ChangeSpells cs; //for Eagle Eye
  569. if(!finishingBattle->isDraw() && finishingBattle->winnerHero)
  570. {
  571. if (int eagleEyeLevel = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_LEVEL_LIMIT, -1))
  572. {
  573. double eagleEyeChance = finishingBattle->winnerHero->valOfBonuses(BonusType::LEARN_BATTLE_SPELL_CHANCE, 0);
  574. for(auto & spellId : battleInfo->sides.at(!battleResult.data->winner).usedSpellsHistory)
  575. {
  576. auto spell = spellId.toSpell(VLC->spells());
  577. if(spell && spell->getLevel() <= eagleEyeLevel && !finishingBattle->winnerHero->spellbookContainsSpell(spell->getId()) && getRandomGenerator().nextInt(99) < eagleEyeChance)
  578. cs.spells.insert(spell->getId());
  579. }
  580. }
  581. }
  582. std::vector<const CArtifactInstance *> arts; //display them in window
  583. if(result == BattleResult::NORMAL && !finishingBattle->isDraw() && finishingBattle->winnerHero)
  584. {
  585. auto sendMoveArtifact = [&](const CArtifactInstance *art, MoveArtifact *ma)
  586. {
  587. const auto slot = ArtifactUtils::getArtAnyPosition(finishingBattle->winnerHero, art->getTypeId());
  588. if(slot != ArtifactPosition::PRE_FIRST)
  589. {
  590. arts.push_back(art);
  591. ma->dst = ArtifactLocation(finishingBattle->winnerHero, slot);
  592. if(ArtifactUtils::isSlotBackpack(slot))
  593. ma->askAssemble = false;
  594. sendAndApply(ma);
  595. }
  596. };
  597. if (finishingBattle->loserHero)
  598. {
  599. //TODO: wrap it into a function, somehow (std::variant -_-)
  600. auto artifactsWorn = finishingBattle->loserHero->artifactsWorn;
  601. for (auto artSlot : artifactsWorn)
  602. {
  603. MoveArtifact ma;
  604. ma.src = ArtifactLocation(finishingBattle->loserHero, artSlot.first);
  605. const CArtifactInstance * art = ma.src.getArt();
  606. if (art && !art->artType->isBig() &&
  607. art->artType->getId() != ArtifactID::SPELLBOOK)
  608. // don't move war machines or locked arts (spellbook)
  609. {
  610. sendMoveArtifact(art, &ma);
  611. }
  612. }
  613. for(int slotNumber = finishingBattle->loserHero->artifactsInBackpack.size() - 1; slotNumber >= 0; slotNumber--)
  614. {
  615. //we assume that no big artifacts can be found
  616. MoveArtifact ma;
  617. ma.src = ArtifactLocation(finishingBattle->loserHero,
  618. ArtifactPosition(GameConstants::BACKPACK_START + slotNumber)); //backpack automatically shifts arts to beginning
  619. const CArtifactInstance * art = ma.src.getArt();
  620. if (art->artType->getId() != ArtifactID::GRAIL) //grail may not be won
  621. {
  622. sendMoveArtifact(art, &ma);
  623. }
  624. }
  625. if (finishingBattle->loserHero->commander) //TODO: what if commanders belong to no hero?
  626. {
  627. artifactsWorn = finishingBattle->loserHero->commander->artifactsWorn;
  628. for (auto artSlot : artifactsWorn)
  629. {
  630. MoveArtifact ma;
  631. ma.src = ArtifactLocation(finishingBattle->loserHero->commander.get(), artSlot.first);
  632. const CArtifactInstance * art = ma.src.getArt();
  633. if (art && !art->artType->isBig())
  634. {
  635. sendMoveArtifact(art, &ma);
  636. }
  637. }
  638. }
  639. }
  640. for (auto armySlot : battleInfo->sides.at(!battleResult.data->winner).armyObject->stacks)
  641. {
  642. auto artifactsWorn = armySlot.second->artifactsWorn;
  643. for (auto artSlot : artifactsWorn)
  644. {
  645. MoveArtifact ma;
  646. ma.src = ArtifactLocation(armySlot.second, artSlot.first);
  647. const CArtifactInstance * art = ma.src.getArt();
  648. if (art && !art->artType->isBig())
  649. {
  650. sendMoveArtifact(art, &ma);
  651. }
  652. }
  653. }
  654. }
  655. if (arts.size()) //display loot
  656. {
  657. InfoWindow iw;
  658. iw.player = finishingBattle->winnerHero->tempOwner;
  659. iw.text.appendLocalString (EMetaText::GENERAL_TXT, 30); //You have captured enemy artifact
  660. for (auto art : arts) //TODO; separate function to display loot for various ojects?
  661. {
  662. iw.components.emplace_back(
  663. Component::EComponentType::ARTIFACT, art->artType->getId(),
  664. art->artType->getId() == ArtifactID::SPELL_SCROLL? art->getScrollSpellID() : 0, 0);
  665. if (iw.components.size() >= 14)
  666. {
  667. sendAndApply(&iw);
  668. iw.components.clear();
  669. }
  670. }
  671. if (iw.components.size())
  672. {
  673. sendAndApply(&iw);
  674. }
  675. }
  676. //Eagle Eye secondary skill handling
  677. if (!cs.spells.empty())
  678. {
  679. cs.learn = 1;
  680. cs.hid = finishingBattle->winnerHero->id;
  681. InfoWindow iw;
  682. iw.player = finishingBattle->winnerHero->tempOwner;
  683. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 221); //Through eagle-eyed observation, %s is able to learn %s
  684. iw.text.replaceRawString(finishingBattle->winnerHero->getNameTranslated());
  685. std::ostringstream names;
  686. for (int i = 0; i < cs.spells.size(); i++)
  687. {
  688. names << "%s";
  689. if (i < cs.spells.size() - 2)
  690. names << ", ";
  691. else if (i < cs.spells.size() - 1)
  692. names << "%s";
  693. }
  694. names << ".";
  695. iw.text.replaceRawString(names.str());
  696. auto it = cs.spells.begin();
  697. for (int i = 0; i < cs.spells.size(); i++, it++)
  698. {
  699. iw.text.replaceLocalString(EMetaText::SPELL_NAME, it->toEnum());
  700. if (i == cs.spells.size() - 2) //we just added pre-last name
  701. iw.text.replaceLocalString(EMetaText::GENERAL_TXT, 141); // " and "
  702. iw.components.emplace_back(Component::EComponentType::SPELL, *it, 0, 0);
  703. }
  704. sendAndApply(&iw);
  705. sendAndApply(&cs);
  706. }
  707. cab1.updateArmy(this);
  708. cab2.updateArmy(this); //take casualties after battle is deleted
  709. if(finishingBattle->loserHero) //remove beaten hero
  710. {
  711. RemoveObject ro(finishingBattle->loserHero->id);
  712. sendAndApply(&ro);
  713. }
  714. if(finishingBattle->isDraw() && finishingBattle->winnerHero) //for draw case both heroes should be removed
  715. {
  716. RemoveObject ro(finishingBattle->winnerHero->id);
  717. sendAndApply(&ro);
  718. }
  719. if(battleResult.data->winner == BattleSide::DEFENDER
  720. && finishingBattle->winnerHero
  721. && finishingBattle->winnerHero->visitedTown
  722. && !finishingBattle->winnerHero->inTownGarrison
  723. && finishingBattle->winnerHero->visitedTown->garrisonHero == finishingBattle->winnerHero)
  724. {
  725. swapGarrisonOnSiege(finishingBattle->winnerHero->visitedTown->id); //return defending visitor from garrison to its rightful place
  726. }
  727. //give exp
  728. if(!finishingBattle->isDraw() && battleResult.data->exp[finishingBattle->winnerSide] && finishingBattle->winnerHero)
  729. changePrimSkill(finishingBattle->winnerHero, PrimarySkill::EXPERIENCE, battleResult.data->exp[finishingBattle->winnerSide]);
  730. BattleResultAccepted raccepted;
  731. raccepted.heroResult[0].army = const_cast<CArmedInstance*>(battleInfo->sides.at(0).armyObject);
  732. raccepted.heroResult[1].army = const_cast<CArmedInstance*>(battleInfo->sides.at(1).armyObject);
  733. raccepted.heroResult[0].hero = const_cast<CGHeroInstance*>(battleInfo->sides.at(0).hero);
  734. raccepted.heroResult[1].hero = const_cast<CGHeroInstance*>(battleInfo->sides.at(1).hero);
  735. raccepted.heroResult[0].exp = battleResult.data->exp[0];
  736. raccepted.heroResult[1].exp = battleResult.data->exp[1];
  737. raccepted.winnerSide = finishingBattle->winnerSide;
  738. sendAndApply(&raccepted);
  739. queries.popIfTop(battleQuery);
  740. //--> continuation (battleAfterLevelUp) occurs after level-up queries are handled or on removing query
  741. }
  742. void CGameHandler::battleAfterLevelUp(const BattleResult &result)
  743. {
  744. LOG_TRACE(logGlobal);
  745. if(!finishingBattle)
  746. return;
  747. finishingBattle->remainingBattleQueriesCount--;
  748. logGlobal->trace("Decremented queries count to %d", finishingBattle->remainingBattleQueriesCount);
  749. if (finishingBattle->remainingBattleQueriesCount > 0)
  750. //Battle results will be handled when all battle queries are closed
  751. return;
  752. //TODO consider if we really want it to work like above. ATM each player as unblocked as soon as possible
  753. // but the battle consequences are applied after final player is unblocked. Hard to abuse...
  754. // Still, it looks like a hole.
  755. // Necromancy if applicable.
  756. const CStackBasicDescriptor raisedStack = finishingBattle->winnerHero ? finishingBattle->winnerHero->calculateNecromancy(*battleResult.data) : CStackBasicDescriptor();
  757. // Give raised units to winner and show dialog, if any were raised,
  758. // units will be given after casualties are taken
  759. const SlotID necroSlot = raisedStack.type ? finishingBattle->winnerHero->getSlotFor(raisedStack.type) : SlotID();
  760. if (necroSlot != SlotID())
  761. {
  762. finishingBattle->winnerHero->showNecromancyDialog(raisedStack, getRandomGenerator());
  763. addToSlot(StackLocation(finishingBattle->winnerHero, necroSlot), raisedStack.type, raisedStack.count);
  764. }
  765. BattleResultsApplied resultsApplied;
  766. resultsApplied.player1 = finishingBattle->victor;
  767. resultsApplied.player2 = finishingBattle->loser;
  768. sendAndApply(&resultsApplied);
  769. setBattle(nullptr);
  770. if (visitObjectAfterVictory && result.winner==0 && !finishingBattle->winnerHero->stacks.empty())
  771. {
  772. logGlobal->trace("post-victory visit");
  773. visitObjectOnTile(*getTile(finishingBattle->winnerHero->visitablePos()), finishingBattle->winnerHero);
  774. }
  775. visitObjectAfterVictory = false;
  776. //handle victory/loss of engaged players
  777. std::set<PlayerColor> playerColors = {finishingBattle->loser, finishingBattle->victor};
  778. checkVictoryLossConditions(playerColors);
  779. if (result.result == BattleResult::SURRENDER)
  780. heroPool->onHeroSurrendered(finishingBattle->loser, finishingBattle->loserHero);
  781. if (result.result == BattleResult::ESCAPE)
  782. heroPool->onHeroEscaped(finishingBattle->loser, finishingBattle->loserHero);
  783. if (result.winner != 2 && finishingBattle->winnerHero && finishingBattle->winnerHero->stacks.empty()
  784. && (!finishingBattle->winnerHero->commander || !finishingBattle->winnerHero->commander->alive))
  785. {
  786. RemoveObject ro(finishingBattle->winnerHero->id);
  787. sendAndApply(&ro);
  788. if (VLC->settings()->getBoolean(EGameSettings::HEROES_RETREAT_ON_WIN_WITHOUT_TROOPS))
  789. heroPool->onHeroEscaped(finishingBattle->victor, finishingBattle->winnerHero);
  790. }
  791. finishingBattle.reset();
  792. }
  793. void CGameHandler::makeAttack(const CStack * attacker, const CStack * defender, int distance, BattleHex targetHex, bool first, bool ranged, bool counter)
  794. {
  795. if(first && !counter)
  796. handleAttackBeforeCasting(ranged, attacker, defender);
  797. FireShieldInfo fireShield;
  798. BattleAttack bat;
  799. BattleLogMessage blm;
  800. bat.stackAttacking = attacker->unitId();
  801. bat.tile = targetHex;
  802. std::shared_ptr<battle::CUnitState> attackerState = attacker->acquireState();
  803. if(ranged)
  804. bat.flags |= BattleAttack::SHOT;
  805. if(counter)
  806. bat.flags |= BattleAttack::COUNTER;
  807. const int attackerLuck = attacker->luckVal();
  808. if(attackerLuck > 0)
  809. {
  810. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_LUCK_DICE);
  811. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, attackerLuck);
  812. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  813. bat.flags |= BattleAttack::LUCKY;
  814. }
  815. if(attackerLuck < 0)
  816. {
  817. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_LUCK_DICE);
  818. size_t diceIndex = std::min<size_t>(diceSize.size() - 1, -attackerLuck);
  819. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  820. bat.flags |= BattleAttack::UNLUCKY;
  821. }
  822. if (getRandomGenerator().nextInt(99) < attacker->valOfBonuses(BonusType::DOUBLE_DAMAGE_CHANCE))
  823. {
  824. bat.flags |= BattleAttack::DEATH_BLOW;
  825. }
  826. const auto * owner = gs->curB->getHero(attacker->unitOwner());
  827. if(owner)
  828. {
  829. int chance = owner->valOfBonuses(BonusType::BONUS_DAMAGE_CHANCE, attacker->creatureIndex());
  830. if (chance > getRandomGenerator().nextInt(99))
  831. bat.flags |= BattleAttack::BALLISTA_DOUBLE_DMG;
  832. }
  833. int64_t drainedLife = 0;
  834. // only primary target
  835. if(defender->alive())
  836. drainedLife += applyBattleEffects(bat, attackerState, fireShield, defender, distance, false);
  837. //multiple-hex normal attack
  838. std::set<const CStack*> attackedCreatures = gs->curB->getAttackedCreatures(attacker, targetHex, bat.shot()); //creatures other than primary target
  839. for(const CStack * stack : attackedCreatures)
  840. {
  841. if(stack != defender && stack->alive()) //do not hit same stack twice
  842. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  843. }
  844. std::shared_ptr<const Bonus> bonus = attacker->getBonusLocalFirst(Selector::type()(BonusType::SPELL_LIKE_ATTACK));
  845. if(bonus && ranged) //TODO: make it work in melee?
  846. {
  847. //this is need for displaying hit animation
  848. bat.flags |= BattleAttack::SPELL_LIKE;
  849. bat.spellID = SpellID(bonus->subtype);
  850. //TODO: should spell override creature`s projectile?
  851. auto spell = bat.spellID.toSpell();
  852. battle::Target target;
  853. target.emplace_back(defender, targetHex);
  854. spells::BattleCast event(gs->curB, attacker, spells::Mode::SPELL_LIKE_ATTACK, spell);
  855. event.setSpellLevel(bonus->val);
  856. auto attackedCreatures = spell->battleMechanics(&event)->getAffectedStacks(target);
  857. //TODO: get exact attacked hex for defender
  858. for(const CStack * stack : attackedCreatures)
  859. {
  860. if(stack != defender && stack->alive()) //do not hit same stack twice
  861. {
  862. drainedLife += applyBattleEffects(bat, attackerState, fireShield, stack, distance, true);
  863. }
  864. }
  865. //now add effect info for all attacked stacks
  866. for (BattleStackAttacked & bsa : bat.bsa)
  867. {
  868. if (bsa.attackerID == attacker->unitId()) //this is our attack and not f.e. fire shield
  869. {
  870. //this is need for displaying affect animation
  871. bsa.flags |= BattleStackAttacked::SPELL_EFFECT;
  872. bsa.spellID = SpellID(bonus->subtype);
  873. }
  874. }
  875. }
  876. attackerState->afterAttack(ranged, counter);
  877. {
  878. UnitChanges info(attackerState->unitId(), UnitChanges::EOperation::RESET_STATE);
  879. attackerState->save(info.data);
  880. bat.attackerChanges.changedStacks.push_back(info);
  881. }
  882. if (drainedLife > 0)
  883. bat.flags |= BattleAttack::LIFE_DRAIN;
  884. sendAndApply(&bat);
  885. {
  886. const bool multipleTargets = bat.bsa.size() > 1;
  887. int64_t totalDamage = 0;
  888. int32_t totalKills = 0;
  889. for(const BattleStackAttacked & bsa : bat.bsa)
  890. {
  891. totalDamage += bsa.damageAmount;
  892. totalKills += bsa.killedAmount;
  893. }
  894. {
  895. MetaString text;
  896. attacker->addText(text, EMetaText::GENERAL_TXT, 376);
  897. attacker->addNameReplacement(text);
  898. text.replaceNumber(totalDamage);
  899. blm.lines.push_back(text);
  900. }
  901. addGenericKilledLog(blm, defender, totalKills, multipleTargets);
  902. }
  903. // drain life effect (as well as log entry) must be applied after the attack
  904. if(drainedLife > 0)
  905. {
  906. MetaString text;
  907. attackerState->addText(text, EMetaText::GENERAL_TXT, 361);
  908. attackerState->addNameReplacement(text, false);
  909. text.replaceNumber(drainedLife);
  910. defender->addNameReplacement(text, true);
  911. blm.lines.push_back(std::move(text));
  912. }
  913. if(!fireShield.empty())
  914. {
  915. //todo: this should be "virtual" spell instead, we only need fire spell school bonus here
  916. const CSpell * fireShieldSpell = SpellID(SpellID::FIRE_SHIELD).toSpell();
  917. int64_t totalDamage = 0;
  918. for(const auto & item : fireShield)
  919. {
  920. const CStack * actor = item.first;
  921. int64_t rawDamage = item.second;
  922. const CGHeroInstance * actorOwner = gs->curB->getHero(actor->unitOwner());
  923. if(actorOwner)
  924. {
  925. rawDamage = fireShieldSpell->adjustRawDamage(actorOwner, attacker, rawDamage);
  926. }
  927. else
  928. {
  929. rawDamage = fireShieldSpell->adjustRawDamage(actor, attacker, rawDamage);
  930. }
  931. totalDamage+=rawDamage;
  932. //FIXME: add custom effect on actor
  933. }
  934. if (totalDamage > 0)
  935. {
  936. BattleStackAttacked bsa;
  937. bsa.flags |= BattleStackAttacked::FIRE_SHIELD;
  938. bsa.stackAttacked = attacker->unitId(); //invert
  939. bsa.attackerID = defender->unitId();
  940. bsa.damageAmount = totalDamage;
  941. attacker->prepareAttacked(bsa, getRandomGenerator());
  942. StacksInjured pack;
  943. pack.stacks.push_back(bsa);
  944. sendAndApply(&pack);
  945. // TODO: this is already implemented in Damage::describeEffect()
  946. {
  947. MetaString text;
  948. text.appendLocalString(EMetaText::GENERAL_TXT, 376);
  949. text.replaceLocalString(EMetaText::SPELL_NAME, SpellID::FIRE_SHIELD);
  950. text.replaceNumber(totalDamage);
  951. blm.lines.push_back(std::move(text));
  952. }
  953. addGenericKilledLog(blm, attacker, bsa.killedAmount, false);
  954. }
  955. }
  956. sendAndApply(&blm);
  957. handleAfterAttackCasting(ranged, attacker, defender);
  958. }
  959. int64_t CGameHandler::applyBattleEffects(BattleAttack & bat, std::shared_ptr<battle::CUnitState> attackerState, FireShieldInfo & fireShield, const CStack * def, int distance, bool secondary)
  960. {
  961. BattleStackAttacked bsa;
  962. if(secondary)
  963. bsa.flags |= BattleStackAttacked::SECONDARY; //all other targets do not suffer from spells & spell-like abilities
  964. bsa.attackerID = attackerState->unitId();
  965. bsa.stackAttacked = def->unitId();
  966. {
  967. BattleAttackInfo bai(attackerState.get(), def, distance, bat.shot());
  968. bai.deathBlow = bat.deathBlow();
  969. bai.doubleDamage = bat.ballistaDoubleDmg();
  970. bai.luckyStrike = bat.lucky();
  971. bai.unluckyStrike = bat.unlucky();
  972. auto range = gs->curB->calculateDmgRange(bai);
  973. bsa.damageAmount = gs->curB->getActualDamage(range.damage, attackerState->getCount(), getRandomGenerator());
  974. CStack::prepareAttacked(bsa, getRandomGenerator(), bai.defender->acquireState()); //calculate casualties
  975. }
  976. int64_t drainedLife = 0;
  977. //life drain handling
  978. if(attackerState->hasBonusOfType(BonusType::LIFE_DRAIN) && def->isLiving())
  979. {
  980. int64_t toHeal = bsa.damageAmount * attackerState->valOfBonuses(BonusType::LIFE_DRAIN) / 100;
  981. attackerState->heal(toHeal, EHealLevel::RESURRECT, EHealPower::PERMANENT);
  982. drainedLife += toHeal;
  983. }
  984. //soul steal handling
  985. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL) && def->isLiving())
  986. {
  987. //we can have two bonuses - one with subtype 0 and another with subtype 1
  988. //try to use permanent first, use only one of two
  989. for(si32 subtype = 1; subtype >= 0; subtype--)
  990. {
  991. if(attackerState->hasBonusOfType(BonusType::SOUL_STEAL, subtype))
  992. {
  993. int64_t toHeal = bsa.killedAmount * attackerState->valOfBonuses(BonusType::SOUL_STEAL, subtype) * attackerState->getMaxHealth();
  994. attackerState->heal(toHeal, EHealLevel::OVERHEAL, ((subtype == 0) ? EHealPower::ONE_BATTLE : EHealPower::PERMANENT));
  995. drainedLife += toHeal;
  996. break;
  997. }
  998. }
  999. }
  1000. bat.bsa.push_back(bsa); //add this stack to the list of victims after drain life has been calculated
  1001. //fire shield handling
  1002. if(!bat.shot() &&
  1003. !def->isClone() &&
  1004. def->hasBonusOfType(BonusType::FIRE_SHIELD) &&
  1005. !attackerState->hasBonusOfType(BonusType::FIRE_IMMUNITY) &&
  1006. CStack::isMeleeAttackPossible(attackerState.get(), def) // attacked needs to be adjacent to defender for fire shield to trigger (e.g. Dragon Breath attack)
  1007. )
  1008. {
  1009. //TODO: use damage with bonus but without penalties
  1010. auto fireShieldDamage = (std::min<int64_t>(def->getAvailableHealth(), bsa.damageAmount) * def->valOfBonuses(BonusType::FIRE_SHIELD)) / 100;
  1011. fireShield.push_back(std::make_pair(def, fireShieldDamage));
  1012. }
  1013. return drainedLife;
  1014. }
  1015. void CGameHandler::sendGenericKilledLog(const CStack * defender, int32_t killed, bool multiple)
  1016. {
  1017. if(killed > 0)
  1018. {
  1019. BattleLogMessage blm;
  1020. addGenericKilledLog(blm, defender, killed, multiple);
  1021. sendAndApply(&blm);
  1022. }
  1023. }
  1024. void CGameHandler::addGenericKilledLog(BattleLogMessage & blm, const CStack * defender, int32_t killed, bool multiple)
  1025. {
  1026. if(killed > 0)
  1027. {
  1028. const int32_t txtIndex = (killed > 1) ? 379 : 378;
  1029. std::string formatString = VLC->generaltexth->allTexts[txtIndex];
  1030. // these default h3 texts have unnecessary new lines, so get rid of them before displaying (and trim just in case, trimming newlines does not works for some reason)
  1031. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\n'), formatString.end());
  1032. formatString.erase(std::remove(formatString.begin(), formatString.end(), '\r'), formatString.end());
  1033. boost::algorithm::trim(formatString);
  1034. boost::format txt(formatString);
  1035. if(killed > 1)
  1036. {
  1037. txt % killed % (multiple ? VLC->generaltexth->allTexts[43] : defender->unitType()->getNamePluralTranslated()); // creatures perish
  1038. }
  1039. else //killed == 1
  1040. {
  1041. txt % (multiple ? VLC->generaltexth->allTexts[42] : defender->unitType()->getNameSingularTranslated()); // creature perishes
  1042. }
  1043. MetaString line;
  1044. line.appendRawString(txt.str());
  1045. blm.lines.push_back(std::move(line));
  1046. }
  1047. }
  1048. void CGameHandler::handleClientDisconnection(std::shared_ptr<CConnection> c)
  1049. {
  1050. if(lobby->state == EServerState::SHUTDOWN || !gs || !gs->scenarioOps)
  1051. return;
  1052. for(auto & playerConnections : connections)
  1053. {
  1054. PlayerColor playerId = playerConnections.first;
  1055. auto * playerSettings = gs->scenarioOps->getPlayersSettings(playerId.getNum());
  1056. if(!playerSettings)
  1057. continue;
  1058. auto playerConnection = vstd::find(playerConnections.second, c);
  1059. if(playerConnection != playerConnections.second.end())
  1060. {
  1061. std::string messageText = boost::str(boost::format("%s (cid %d) was disconnected") % playerSettings->name % c->connectionID);
  1062. playerMessages->broadcastMessage(playerId, messageText);
  1063. }
  1064. }
  1065. }
  1066. void CGameHandler::handleReceivedPack(CPackForServer * pack)
  1067. {
  1068. //prepare struct informing that action was applied
  1069. auto sendPackageResponse = [&](bool succesfullyApplied)
  1070. {
  1071. PackageApplied applied;
  1072. applied.player = pack->player;
  1073. applied.result = succesfullyApplied;
  1074. applied.packType = typeList.getTypeID(pack);
  1075. applied.requestID = pack->requestID;
  1076. pack->c->sendPack(&applied);
  1077. };
  1078. CBaseForGHApply * apply = applier->getApplier(typeList.getTypeID(pack)); //and appropriate applier object
  1079. if(isBlockedByQueries(pack, pack->player))
  1080. {
  1081. sendPackageResponse(false);
  1082. }
  1083. else if(apply)
  1084. {
  1085. const bool result = apply->applyOnGH(this, this->gs, pack);
  1086. if(result)
  1087. logGlobal->trace("Message %s successfully applied!", typeid(*pack).name());
  1088. else
  1089. complain((boost::format("Got false in applying %s... that request must have been fishy!")
  1090. % typeid(*pack).name()).str());
  1091. sendPackageResponse(true);
  1092. }
  1093. else
  1094. {
  1095. logGlobal->error("Message cannot be applied, cannot find applier (unregistered type)!");
  1096. sendPackageResponse(false);
  1097. }
  1098. vstd::clear_pointer(pack);
  1099. }
  1100. int CGameHandler::moveStack(int stack, BattleHex dest)
  1101. {
  1102. int ret = 0;
  1103. const CStack *curStack = gs->curB->battleGetStackByID(stack),
  1104. *stackAtEnd = gs->curB->battleGetStackByPos(dest);
  1105. assert(curStack);
  1106. assert(dest < GameConstants::BFIELD_SIZE);
  1107. if (gs->curB->tacticDistance)
  1108. {
  1109. assert(gs->curB->isInTacticRange(dest));
  1110. }
  1111. auto start = curStack->getPosition();
  1112. if (start == dest)
  1113. return 0;
  1114. //initing necessary tables
  1115. auto accessibility = getAccesibility(curStack);
  1116. std::set<BattleHex> passed;
  1117. //Ignore obstacles on starting position
  1118. passed.insert(curStack->getPosition());
  1119. if(curStack->doubleWide())
  1120. passed.insert(curStack->occupiedHex());
  1121. //shifting destination (if we have double wide stack and we can occupy dest but not be exactly there)
  1122. if(!stackAtEnd && curStack->doubleWide() && !accessibility.accessible(dest, curStack))
  1123. {
  1124. BattleHex shifted = dest.cloneInDirection(curStack->destShiftDir(), false);
  1125. if(accessibility.accessible(shifted, curStack))
  1126. dest = shifted;
  1127. }
  1128. if((stackAtEnd && stackAtEnd!=curStack && stackAtEnd->alive()) || !accessibility.accessible(dest, curStack))
  1129. {
  1130. complain("Given destination is not accessible!");
  1131. return 0;
  1132. }
  1133. bool canUseGate = false;
  1134. auto dbState = gs->curB->si.gateState;
  1135. if(battleGetSiegeLevel() > 0 && curStack->unitSide() == BattleSide::DEFENDER &&
  1136. dbState != EGateState::DESTROYED &&
  1137. dbState != EGateState::BLOCKED)
  1138. {
  1139. canUseGate = true;
  1140. }
  1141. std::pair< std::vector<BattleHex>, int > path = gs->curB->getPath(start, dest, curStack);
  1142. ret = path.second;
  1143. int creSpeed = curStack->speed(0, true);
  1144. if (gs->curB->tacticDistance > 0 && creSpeed > 0)
  1145. creSpeed = GameConstants::BFIELD_SIZE;
  1146. bool hasWideMoat = vstd::contains_if(battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  1147. {
  1148. return obst->obstacleType == CObstacleInstance::MOAT;
  1149. });
  1150. auto isGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1151. {
  1152. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1153. return true;
  1154. if (hex == ESiegeHex::GATE_OUTER)
  1155. return true;
  1156. if (hex == ESiegeHex::GATE_INNER)
  1157. return true;
  1158. return false;
  1159. };
  1160. auto occupyGateDrawbridgeHex = [&](BattleHex hex) -> bool
  1161. {
  1162. if (isGateDrawbridgeHex(hex))
  1163. return true;
  1164. if (curStack->doubleWide())
  1165. {
  1166. BattleHex otherHex = curStack->occupiedHex(hex);
  1167. if (otherHex.isValid() && isGateDrawbridgeHex(otherHex))
  1168. return true;
  1169. }
  1170. return false;
  1171. };
  1172. if (curStack->hasBonusOfType(BonusType::FLYING))
  1173. {
  1174. if (path.second <= creSpeed && path.first.size() > 0)
  1175. {
  1176. if (canUseGate && dbState != EGateState::OPENED &&
  1177. occupyGateDrawbridgeHex(dest))
  1178. {
  1179. BattleUpdateGateState db;
  1180. db.state = EGateState::OPENED;
  1181. sendAndApply(&db);
  1182. }
  1183. //inform clients about move
  1184. BattleStackMoved sm;
  1185. sm.stack = curStack->unitId();
  1186. std::vector<BattleHex> tiles;
  1187. tiles.push_back(path.first[0]);
  1188. sm.tilesToMove = tiles;
  1189. sm.distance = path.second;
  1190. sm.teleporting = false;
  1191. sendAndApply(&sm);
  1192. }
  1193. }
  1194. else //for non-flying creatures
  1195. {
  1196. std::vector<BattleHex> tiles;
  1197. const int tilesToMove = std::max((int)(path.first.size() - creSpeed), 0);
  1198. int v = (int)path.first.size()-1;
  1199. path.first.push_back(start);
  1200. // check if gate need to be open or closed at some point
  1201. BattleHex openGateAtHex, gateMayCloseAtHex;
  1202. if (canUseGate)
  1203. {
  1204. for (int i = (int)path.first.size()-1; i >= 0; i--)
  1205. {
  1206. auto needOpenGates = [&](BattleHex hex) -> bool
  1207. {
  1208. if (hasWideMoat && hex == ESiegeHex::GATE_BRIDGE)
  1209. return true;
  1210. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] == ESiegeHex::GATE_OUTER)
  1211. return true;
  1212. else if (hex == ESiegeHex::GATE_OUTER || hex == ESiegeHex::GATE_INNER)
  1213. return true;
  1214. return false;
  1215. };
  1216. auto hex = path.first[i];
  1217. if (!openGateAtHex.isValid() && dbState != EGateState::OPENED)
  1218. {
  1219. if (needOpenGates(hex))
  1220. openGateAtHex = path.first[i+1];
  1221. //TODO we need find batter way to handle double-wide stacks
  1222. //currently if only second occupied stack part is standing on gate / bridge hex then stack will start to wait for bridge to lower before it's needed. Though this is just a visual bug.
  1223. if (curStack->doubleWide())
  1224. {
  1225. BattleHex otherHex = curStack->occupiedHex(hex);
  1226. if (otherHex.isValid() && needOpenGates(otherHex))
  1227. openGateAtHex = path.first[i+2];
  1228. }
  1229. //gate may be opened and then closed during stack movement, but not other way around
  1230. if (openGateAtHex.isValid())
  1231. dbState = EGateState::OPENED;
  1232. }
  1233. if (!gateMayCloseAtHex.isValid() && dbState != EGateState::CLOSED)
  1234. {
  1235. if (hex == ESiegeHex::GATE_INNER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1236. {
  1237. gateMayCloseAtHex = path.first[i-1];
  1238. }
  1239. if (hasWideMoat)
  1240. {
  1241. if (hex == ESiegeHex::GATE_BRIDGE && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_OUTER)
  1242. {
  1243. gateMayCloseAtHex = path.first[i-1];
  1244. }
  1245. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 &&
  1246. path.first[i-1] != ESiegeHex::GATE_INNER &&
  1247. path.first[i-1] != ESiegeHex::GATE_BRIDGE)
  1248. {
  1249. gateMayCloseAtHex = path.first[i-1];
  1250. }
  1251. }
  1252. else if (hex == ESiegeHex::GATE_OUTER && i-1 >= 0 && path.first[i-1] != ESiegeHex::GATE_INNER)
  1253. {
  1254. gateMayCloseAtHex = path.first[i-1];
  1255. }
  1256. }
  1257. }
  1258. }
  1259. bool stackIsMoving = true;
  1260. while(stackIsMoving)
  1261. {
  1262. if (v<tilesToMove)
  1263. {
  1264. logGlobal->error("Movement terminated abnormally");
  1265. break;
  1266. }
  1267. bool gateStateChanging = false;
  1268. //special handling for opening gate on from starting hex
  1269. if (openGateAtHex.isValid() && openGateAtHex == start)
  1270. gateStateChanging = true;
  1271. else
  1272. {
  1273. for (bool obstacleHit = false; (!obstacleHit) && (!gateStateChanging) && (v >= tilesToMove); --v)
  1274. {
  1275. BattleHex hex = path.first[v];
  1276. tiles.push_back(hex);
  1277. if ((openGateAtHex.isValid() && openGateAtHex == hex) ||
  1278. (gateMayCloseAtHex.isValid() && gateMayCloseAtHex == hex))
  1279. {
  1280. gateStateChanging = true;
  1281. }
  1282. //if we walked onto something, finalize this portion of stack movement check into obstacle
  1283. if(!battleGetAllObstaclesOnPos(hex, false).empty())
  1284. obstacleHit = true;
  1285. if (curStack->doubleWide())
  1286. {
  1287. BattleHex otherHex = curStack->occupiedHex(hex);
  1288. //two hex creature hit obstacle by backside
  1289. auto obstacle2 = battleGetAllObstaclesOnPos(otherHex, false);
  1290. if(otherHex.isValid() && !obstacle2.empty())
  1291. obstacleHit = true;
  1292. }
  1293. if(!obstacleHit)
  1294. passed.insert(hex);
  1295. }
  1296. }
  1297. if (!tiles.empty())
  1298. {
  1299. //commit movement
  1300. BattleStackMoved sm;
  1301. sm.stack = curStack->unitId();
  1302. sm.distance = path.second;
  1303. sm.teleporting = false;
  1304. sm.tilesToMove = tiles;
  1305. sendAndApply(&sm);
  1306. tiles.clear();
  1307. }
  1308. //we don't handle obstacle at the destination tile -> it's handled separately in the if at the end
  1309. if (curStack->getPosition() != dest)
  1310. {
  1311. if(stackIsMoving && start != curStack->getPosition())
  1312. {
  1313. stackIsMoving = handleObstacleTriggersForUnit(*spellEnv, *curStack, passed);
  1314. passed.insert(curStack->getPosition());
  1315. if(curStack->doubleWide())
  1316. passed.insert(curStack->occupiedHex());
  1317. }
  1318. if (gateStateChanging)
  1319. {
  1320. if (curStack->getPosition() == openGateAtHex)
  1321. {
  1322. openGateAtHex = BattleHex();
  1323. //only open gate if stack is still alive
  1324. if (curStack->alive())
  1325. {
  1326. BattleUpdateGateState db;
  1327. db.state = EGateState::OPENED;
  1328. sendAndApply(&db);
  1329. }
  1330. }
  1331. else if (curStack->getPosition() == gateMayCloseAtHex)
  1332. {
  1333. gateMayCloseAtHex = BattleHex();
  1334. updateGateState();
  1335. }
  1336. }
  1337. }
  1338. else
  1339. //movement finished normally: we reached destination
  1340. stackIsMoving = false;
  1341. }
  1342. }
  1343. //handle last hex separately for deviation
  1344. if (VLC->settings()->getBoolean(EGameSettings::COMBAT_ONE_HEX_TRIGGERS_OBSTACLES))
  1345. {
  1346. if (dest == battle::Unit::occupiedHex(start, curStack->doubleWide(), curStack->unitSide())
  1347. || start == battle::Unit::occupiedHex(dest, curStack->doubleWide(), curStack->unitSide()))
  1348. passed.clear(); //Just empty passed, obstacles will handled automatically
  1349. }
  1350. //handling obstacle on the final field (separate, because it affects both flying and walking stacks)
  1351. handleObstacleTriggersForUnit(*spellEnv, *curStack, passed);
  1352. return ret;
  1353. }
  1354. CGameHandler::CGameHandler(CVCMIServer * lobby)
  1355. : lobby(lobby)
  1356. , heroPool(std::make_unique<HeroPoolProcessor>(this))
  1357. , playerMessages(std::make_unique<PlayerMessageProcessor>(this))
  1358. , complainNoCreatures("No creatures to split")
  1359. , complainNotEnoughCreatures("Cannot split that stack, not enough creatures!")
  1360. , complainInvalidSlot("Invalid slot accessed!")
  1361. {
  1362. QID = 1;
  1363. IObjectInterface::cb = this;
  1364. applier = std::make_shared<CApplier<CBaseForGHApply>>();
  1365. registerTypesServerPacks(*applier);
  1366. visitObjectAfterVictory = false;
  1367. spellEnv = new ServerSpellCastEnvironment(this);
  1368. }
  1369. CGameHandler::~CGameHandler()
  1370. {
  1371. if (battleThread)
  1372. {
  1373. //Setting battleMadeAction is needed because battleThread waits for the action to continue the main loop
  1374. battleMadeAction.setn(true);
  1375. battleThread->join();
  1376. }
  1377. delete spellEnv;
  1378. delete gs;
  1379. }
  1380. void CGameHandler::reinitScripting()
  1381. {
  1382. serverEventBus = std::make_unique<events::EventBus>();
  1383. #if SCRIPTING_ENABLED
  1384. serverScripts.reset(new scripting::PoolImpl(this, spellEnv));
  1385. #endif
  1386. }
  1387. void CGameHandler::init(StartInfo *si)
  1388. {
  1389. if (si->seedToBeUsed == 0)
  1390. {
  1391. si->seedToBeUsed = static_cast<ui32>(std::time(nullptr));
  1392. }
  1393. CMapService mapService;
  1394. gs = new CGameState();
  1395. gs->preInit(VLC);
  1396. logGlobal->info("Gamestate created!");
  1397. gs->init(&mapService, si);
  1398. logGlobal->info("Gamestate initialized!");
  1399. // reset seed, so that clients can't predict any following random values
  1400. getRandomGenerator().resetSeed();
  1401. for (auto & elem : gs->players)
  1402. {
  1403. states.addPlayer(elem.first);
  1404. }
  1405. reinitScripting();
  1406. }
  1407. static bool evntCmp(const CMapEvent &a, const CMapEvent &b)
  1408. {
  1409. return a.earlierThan(b);
  1410. }
  1411. void CGameHandler::setPortalDwelling(const CGTownInstance * town, bool forced=false, bool clear = false)
  1412. {// bool forced = true - if creature should be replaced, if false - only if no creature was set
  1413. const PlayerState * p = getPlayerState(town->tempOwner);
  1414. if (!p)
  1415. {
  1416. assert(town->tempOwner == PlayerColor::NEUTRAL);
  1417. return;
  1418. }
  1419. if (forced || town->creatures.at(GameConstants::CREATURES_PER_TOWN).second.empty())//we need to change creature
  1420. {
  1421. SetAvailableCreatures ssi;
  1422. ssi.tid = town->id;
  1423. ssi.creatures = town->creatures;
  1424. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.clear();//remove old one
  1425. const std::vector<ConstTransitivePtr<CGDwelling> > &dwellings = p->dwellings;
  1426. if (dwellings.empty())//no dwellings - just remove
  1427. {
  1428. sendAndApply(&ssi);
  1429. return;
  1430. }
  1431. auto dwelling = *RandomGeneratorUtil::nextItem(dwellings, getRandomGenerator());
  1432. // for multi-creature dwellings like Golem Factory
  1433. auto creatureId = RandomGeneratorUtil::nextItem(dwelling->creatures, getRandomGenerator())->second[0];
  1434. if (clear)
  1435. {
  1436. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = std::max(1, (VLC->creh->objects.at(creatureId)->getGrowth())/2);
  1437. }
  1438. else
  1439. {
  1440. ssi.creatures[GameConstants::CREATURES_PER_TOWN].first = VLC->creh->objects.at(creatureId)->getGrowth();
  1441. }
  1442. ssi.creatures[GameConstants::CREATURES_PER_TOWN].second.push_back(creatureId);
  1443. sendAndApply(&ssi);
  1444. }
  1445. }
  1446. void CGameHandler::newTurn()
  1447. {
  1448. logGlobal->trace("Turn %d", gs->day+1);
  1449. NewTurn n;
  1450. n.specialWeek = NewTurn::NO_ACTION;
  1451. n.creatureid = CreatureID::NONE;
  1452. n.day = gs->day + 1;
  1453. bool firstTurn = !getDate(Date::DAY);
  1454. bool newWeek = getDate(Date::DAY_OF_WEEK) == 7; //day numbers are confusing, as day was not yet switched
  1455. bool newMonth = getDate(Date::DAY_OF_MONTH) == 28;
  1456. std::map<PlayerColor, si32> hadGold;//starting gold - for buildings like dwarven treasury
  1457. if (firstTurn)
  1458. {
  1459. for (auto obj : gs->map->objects)
  1460. {
  1461. if (obj && obj->ID == Obj::PRISON) //give imprisoned hero 0 exp to level him up. easiest to do at this point
  1462. {
  1463. changePrimSkill (getHero(obj->id), PrimarySkill::EXPERIENCE, 0);
  1464. }
  1465. }
  1466. }
  1467. if (newWeek && !firstTurn)
  1468. {
  1469. n.specialWeek = NewTurn::NORMAL;
  1470. bool deityOfFireBuilt = false;
  1471. for (const CGTownInstance *t : gs->map->towns)
  1472. {
  1473. if (t->hasBuilt(BuildingID::GRAIL, ETownType::INFERNO))
  1474. {
  1475. deityOfFireBuilt = true;
  1476. break;
  1477. }
  1478. }
  1479. if (deityOfFireBuilt)
  1480. {
  1481. n.specialWeek = NewTurn::DEITYOFFIRE;
  1482. n.creatureid = CreatureID::IMP;
  1483. }
  1484. else if(VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_RANDOM_SPECIAL_WEEKS))
  1485. {
  1486. int monthType = getRandomGenerator().nextInt(99);
  1487. if (newMonth) //new month
  1488. {
  1489. if (monthType < 40) //double growth
  1490. {
  1491. n.specialWeek = NewTurn::DOUBLE_GROWTH;
  1492. if (VLC->settings()->getBoolean(EGameSettings::CREATURES_ALLOW_ALL_FOR_DOUBLE_MONTH))
  1493. {
  1494. n.creatureid = VLC->creh->pickRandomMonster(getRandomGenerator());
  1495. }
  1496. else if (VLC->creh->doubledCreatures.size())
  1497. {
  1498. n.creatureid = *RandomGeneratorUtil::nextItem(VLC->creh->doubledCreatures, getRandomGenerator());
  1499. }
  1500. else
  1501. {
  1502. complain("Cannot find creature that can be spawned!");
  1503. n.specialWeek = NewTurn::NORMAL;
  1504. }
  1505. }
  1506. else if (monthType < 50)
  1507. n.specialWeek = NewTurn::PLAGUE;
  1508. }
  1509. else //it's a week, but not full month
  1510. {
  1511. if (monthType < 25)
  1512. {
  1513. n.specialWeek = NewTurn::BONUS_GROWTH; //+5
  1514. std::pair<int, CreatureID> newMonster(54, CreatureID());
  1515. do
  1516. {
  1517. newMonster.second = VLC->creh->pickRandomMonster(getRandomGenerator());
  1518. } while (VLC->creh->objects[newMonster.second] &&
  1519. (*VLC->townh)[VLC->creatures()->getById(newMonster.second)->getFaction()]->town == nullptr); // find first non neutral creature
  1520. n.creatureid = newMonster.second;
  1521. }
  1522. }
  1523. }
  1524. }
  1525. for (auto & elem : gs->players)
  1526. {
  1527. if (elem.first == PlayerColor::NEUTRAL)
  1528. continue;
  1529. else if (elem.first >= PlayerColor::PLAYER_LIMIT)
  1530. assert(0); //illegal player number!
  1531. std::pair<PlayerColor, si32> playerGold(elem.first, elem.second.resources[EGameResID::GOLD]);
  1532. hadGold.insert(playerGold);
  1533. if (newWeek) //new heroes in tavern
  1534. heroPool->onNewWeek(elem.first);
  1535. n.res[elem.first] = elem.second.resources;
  1536. if(!firstTurn && newWeek) //weekly crystal generation if 1 or more crystal dragons in any hero army or town garrison
  1537. {
  1538. bool hasCrystalGenCreature = false;
  1539. for(CGHeroInstance * hero : elem.second.heroes)
  1540. {
  1541. for(auto stack : hero->stacks)
  1542. {
  1543. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  1544. {
  1545. hasCrystalGenCreature = true;
  1546. break;
  1547. }
  1548. }
  1549. }
  1550. if(!hasCrystalGenCreature) //not found in armies, check towns
  1551. {
  1552. for(CGTownInstance * town : elem.second.towns)
  1553. {
  1554. for(auto stack : town->stacks)
  1555. {
  1556. if(stack.second->hasBonusOfType(BonusType::SPECIAL_CRYSTAL_GENERATION))
  1557. {
  1558. hasCrystalGenCreature = true;
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. if(hasCrystalGenCreature)
  1565. n.res[elem.first][EGameResID::CRYSTAL] += 3;
  1566. }
  1567. for (CGHeroInstance *h : (elem).second.heroes)
  1568. {
  1569. if (h->visitedTown)
  1570. giveSpells(h->visitedTown, h);
  1571. NewTurn::Hero hth;
  1572. hth.id = h->id;
  1573. auto ti = std::make_unique<TurnInfo>(h, 1);
  1574. // TODO: this code executed when bonuses of previous day not yet updated (this happen in NewTurn::applyGs). See issue 2356
  1575. hth.move = h->movementPointsLimitCached(gs->map->getTile(h->visitablePos()).terType->isLand(), ti.get());
  1576. hth.mana = h->getManaNewTurn();
  1577. n.heroes.insert(hth);
  1578. if (!firstTurn) //not first day
  1579. {
  1580. for (int k = 0; k < GameConstants::RESOURCE_QUANTITY; k++)
  1581. {
  1582. n.res[elem.first][k] += h->valOfBonuses(BonusType::GENERATE_RESOURCE, k);
  1583. }
  1584. }
  1585. }
  1586. }
  1587. for (CGTownInstance *t : gs->map->towns)
  1588. {
  1589. PlayerColor player = t->tempOwner;
  1590. handleTownEvents(t, n);
  1591. if (newWeek) //first day of week
  1592. {
  1593. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  1594. setPortalDwelling(t, true, (n.specialWeek == NewTurn::PLAGUE ? true : false)); //set creatures for Portal of Summoning
  1595. if (!firstTurn)
  1596. if (t->hasBuilt(BuildingSubID::TREASURY) && player < PlayerColor::PLAYER_LIMIT)
  1597. n.res[player][EGameResID::GOLD] += hadGold.at(player)/10; //give 10% of starting gold
  1598. if (!vstd::contains(n.cres, t->id))
  1599. {
  1600. n.cres[t->id].tid = t->id;
  1601. n.cres[t->id].creatures = t->creatures;
  1602. }
  1603. auto & sac = n.cres.at(t->id);
  1604. for (int k=0; k < GameConstants::CREATURES_PER_TOWN; k++) //creature growths
  1605. {
  1606. if (!t->creatures.at(k).second.empty()) // there are creatures at this level
  1607. {
  1608. ui32 &availableCount = sac.creatures.at(k).first;
  1609. const CCreature *cre = VLC->creh->objects.at(t->creatures.at(k).second.back());
  1610. if (n.specialWeek == NewTurn::PLAGUE)
  1611. availableCount = t->creatures.at(k).first / 2; //halve their number, no growth
  1612. else
  1613. {
  1614. if (firstTurn) //first day of game: use only basic growths
  1615. availableCount = cre->getGrowth();
  1616. else
  1617. availableCount += t->creatureGrowth(k);
  1618. //Deity of fire week - upgrade both imps and upgrades
  1619. if (n.specialWeek == NewTurn::DEITYOFFIRE && vstd::contains(t->creatures.at(k).second, n.creatureid))
  1620. availableCount += 15;
  1621. if (cre->getId() == n.creatureid) //bonus week, effect applies only to identical creatures
  1622. {
  1623. if (n.specialWeek == NewTurn::DOUBLE_GROWTH)
  1624. availableCount *= 2;
  1625. else if (n.specialWeek == NewTurn::BONUS_GROWTH)
  1626. availableCount += 5;
  1627. }
  1628. }
  1629. }
  1630. }
  1631. }
  1632. if (!firstTurn && player < PlayerColor::PLAYER_LIMIT)//not the first day and town not neutral
  1633. {
  1634. n.res[player] = n.res[player] + t->dailyIncome();
  1635. }
  1636. if(t->hasBuilt(BuildingID::GRAIL)
  1637. && t->town->buildings.at(BuildingID::GRAIL)->height == CBuilding::HEIGHT_SKYSHIP)
  1638. {
  1639. // Skyship, probably easier to handle same as Veil of darkness
  1640. //do it every new day after veils apply
  1641. if (player != PlayerColor::NEUTRAL) //do not reveal fow for neutral player
  1642. {
  1643. FoWChange fw;
  1644. fw.mode = 1;
  1645. fw.player = player;
  1646. // find all hidden tiles
  1647. const auto fow = getPlayerTeam(player)->fogOfWarMap;
  1648. auto shape = fow->shape();
  1649. for(size_t z = 0; z < shape[0]; z++)
  1650. for(size_t x = 0; x < shape[1]; x++)
  1651. for(size_t y = 0; y < shape[2]; y++)
  1652. if (!(*fow)[z][x][y])
  1653. fw.tiles.insert(int3(x, y, z));
  1654. sendAndApply (&fw);
  1655. }
  1656. }
  1657. if (t->hasBonusOfType (BonusType::DARKNESS))
  1658. {
  1659. for (auto & player : gs->players)
  1660. {
  1661. if (getPlayerStatus(player.first) == EPlayerStatus::INGAME &&
  1662. getPlayerRelations(player.first, t->tempOwner) == PlayerRelations::ENEMIES)
  1663. changeFogOfWar(t->visitablePos(), t->getBonusLocalFirst(Selector::type()(BonusType::DARKNESS))->val, player.first, true);
  1664. }
  1665. }
  1666. }
  1667. if (newMonth)
  1668. {
  1669. SetAvailableArtifacts saa;
  1670. saa.id = -1;
  1671. pickAllowedArtsSet(saa.arts, getRandomGenerator());
  1672. sendAndApply(&saa);
  1673. }
  1674. sendAndApply(&n);
  1675. if (newWeek)
  1676. {
  1677. //spawn wandering monsters
  1678. if (newMonth && (n.specialWeek == NewTurn::DOUBLE_GROWTH || n.specialWeek == NewTurn::DEITYOFFIRE))
  1679. {
  1680. spawnWanderingMonsters(n.creatureid);
  1681. }
  1682. //new week info popup
  1683. if (!firstTurn)
  1684. {
  1685. InfoWindow iw;
  1686. switch (n.specialWeek)
  1687. {
  1688. case NewTurn::DOUBLE_GROWTH:
  1689. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 131);
  1690. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1691. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1692. break;
  1693. case NewTurn::PLAGUE:
  1694. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 132);
  1695. break;
  1696. case NewTurn::BONUS_GROWTH:
  1697. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 134);
  1698. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1699. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, n.creatureid);
  1700. break;
  1701. case NewTurn::DEITYOFFIRE:
  1702. iw.text.appendLocalString(EMetaText::ARRAY_TXT, 135);
  1703. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  1704. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 42); //%s imp
  1705. iw.text.replacePositiveNumber(15); //%+d 15
  1706. iw.text.replaceLocalString(EMetaText::CRE_SING_NAMES, 43); //%s familiar
  1707. iw.text.replacePositiveNumber(15); //%+d 15
  1708. break;
  1709. default:
  1710. if (newMonth)
  1711. {
  1712. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (130));
  1713. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(32, 41));
  1714. }
  1715. else
  1716. {
  1717. iw.text.appendLocalString(EMetaText::ARRAY_TXT, (133));
  1718. iw.text.replaceLocalString(EMetaText::ARRAY_TXT, getRandomGenerator().nextInt(43, 57));
  1719. }
  1720. }
  1721. for (auto & elem : gs->players)
  1722. {
  1723. iw.player = elem.first;
  1724. sendAndApply(&iw);
  1725. }
  1726. }
  1727. }
  1728. logGlobal->trace("Info about turn %d has been sent!", n.day);
  1729. handleTimeEvents();
  1730. //call objects
  1731. for (auto & elem : gs->map->objects)
  1732. {
  1733. if (elem)
  1734. elem->newTurn(getRandomGenerator());
  1735. }
  1736. synchronizeArtifactHandlerLists(); //new day events may have changed them. TODO better of managing that
  1737. }
  1738. void CGameHandler::run(bool resume)
  1739. {
  1740. LOG_TRACE_PARAMS(logGlobal, "resume=%d", resume);
  1741. using namespace boost::posix_time;
  1742. for (auto cc : lobby->connections)
  1743. {
  1744. auto players = lobby->getAllClientPlayers(cc->connectionID);
  1745. std::stringstream sbuffer;
  1746. sbuffer << "Connection " << cc->connectionID << " will handle " << players.size() << " player: ";
  1747. for (PlayerColor color : players)
  1748. {
  1749. sbuffer << color << " ";
  1750. {
  1751. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  1752. connections[color].insert(cc);
  1753. }
  1754. }
  1755. logGlobal->info(sbuffer.str());
  1756. }
  1757. #if SCRIPTING_ENABLED
  1758. services()->scripts()->run(serverScripts);
  1759. #endif
  1760. if(resume)
  1761. events::GameResumed::defaultExecute(serverEventBus.get());
  1762. auto playerTurnOrder = generatePlayerTurnOrder();
  1763. while(lobby->state == EServerState::GAMEPLAY)
  1764. {
  1765. if(!resume)
  1766. {
  1767. newTurn();
  1768. events::TurnStarted::defaultExecute(serverEventBus.get());
  1769. }
  1770. std::list<PlayerColor>::iterator it;
  1771. if (resume)
  1772. {
  1773. it = std::find(playerTurnOrder.begin(), playerTurnOrder.end(), gs->currentPlayer);
  1774. }
  1775. else
  1776. {
  1777. it = playerTurnOrder.begin();
  1778. }
  1779. resume = false;
  1780. for (; (it != playerTurnOrder.end()) && (lobby->state == EServerState::GAMEPLAY) ; it++)
  1781. {
  1782. auto playerColor = *it;
  1783. auto onGetTurn = [&](events::PlayerGotTurn & event)
  1784. {
  1785. //if player runs out of time, he shouldn't get the turn (especially AI)
  1786. //pre-trigger may change anything, should check before each player
  1787. //TODO: is it enough to check only one player?
  1788. checkVictoryLossConditionsForAll();
  1789. auto player = event.getPlayer();
  1790. const PlayerState * playerState = &gs->players[player];
  1791. if(playerState->status != EPlayerStatus::INGAME)
  1792. {
  1793. event.setPlayer(PlayerColor::CANNOT_DETERMINE);
  1794. }
  1795. else
  1796. {
  1797. states.setFlag(player, &PlayerStatus::makingTurn, true);
  1798. YourTurn yt;
  1799. yt.player = player;
  1800. //Change local daysWithoutCastle counter for local interface message //TODO: needed?
  1801. yt.daysWithoutCastle = playerState->daysWithoutCastle;
  1802. applyAndSend(&yt);
  1803. }
  1804. };
  1805. events::PlayerGotTurn::defaultExecute(serverEventBus.get(), onGetTurn, playerColor);
  1806. if(playerColor != PlayerColor::CANNOT_DETERMINE)
  1807. {
  1808. //wait till turn is done
  1809. boost::unique_lock<boost::mutex> lock(states.mx);
  1810. while(states.players.at(playerColor).makingTurn && lobby->state == EServerState::GAMEPLAY)
  1811. {
  1812. static time_duration p = milliseconds(100);
  1813. states.cv.timed_wait(lock, p);
  1814. }
  1815. }
  1816. }
  1817. //additional check that game is not finished
  1818. bool activePlayer = false;
  1819. for (auto player : playerTurnOrder)
  1820. {
  1821. if (gs->players[player].status == EPlayerStatus::INGAME)
  1822. activePlayer = true;
  1823. }
  1824. if(!activePlayer)
  1825. lobby->state = EServerState::GAMEPLAY_ENDED;
  1826. }
  1827. }
  1828. std::list<PlayerColor> CGameHandler::generatePlayerTurnOrder() const
  1829. {
  1830. // Generate player turn order
  1831. std::list<PlayerColor> playerTurnOrder;
  1832. for (const auto & player : gs->players) // add human players first
  1833. {
  1834. if (player.second.human)
  1835. playerTurnOrder.push_back(player.first);
  1836. }
  1837. for (const auto & player : gs->players) // then add non-human players
  1838. {
  1839. if (!player.second.human)
  1840. playerTurnOrder.push_back(player.first);
  1841. }
  1842. return playerTurnOrder;
  1843. }
  1844. void CGameHandler::setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance *heroes[2], bool creatureBank, const CGTownInstance *town)
  1845. {
  1846. battleResult.set(nullptr);
  1847. const auto & t = *getTile(tile);
  1848. TerrainId terrain = t.terType->getId();
  1849. if (gs->map->isCoastalTile(tile)) //coastal tile is always ground
  1850. terrain = ETerrainId::SAND;
  1851. BattleField terType = gs->battleGetBattlefieldType(tile, getRandomGenerator());
  1852. if (heroes[0] && heroes[0]->boat && heroes[1] && heroes[1]->boat)
  1853. terType = BattleField::fromString("ship_to_ship");
  1854. //send info about battles
  1855. BattleStart bs;
  1856. bs.info = BattleInfo::setupBattle(tile, terrain, terType, armies, heroes, creatureBank, town);
  1857. sendAndApply(&bs);
  1858. }
  1859. void CGameHandler::checkBattleStateChanges()
  1860. {
  1861. //check if drawbridge state need to be changes
  1862. if (battleGetSiegeLevel() > 0)
  1863. updateGateState();
  1864. //check if battle ended
  1865. if (auto result = battleIsFinished())
  1866. {
  1867. setBattleResult(BattleResult::NORMAL, *result);
  1868. }
  1869. }
  1870. void CGameHandler::giveSpells(const CGTownInstance *t, const CGHeroInstance *h)
  1871. {
  1872. if (!h->hasSpellbook())
  1873. return; //hero hasn't spellbook
  1874. ChangeSpells cs;
  1875. cs.hid = h->id;
  1876. cs.learn = true;
  1877. if (t->hasBuilt(BuildingID::GRAIL, ETownType::CONFLUX) && t->hasBuilt(BuildingID::MAGES_GUILD_1))
  1878. {
  1879. // Aurora Borealis give spells of all levels even if only level 1 mages guild built
  1880. for (int i = 0; i < h->maxSpellLevel(); i++)
  1881. {
  1882. std::vector<SpellID> spells;
  1883. getAllowedSpells(spells, i+1);
  1884. for (auto & spell : spells)
  1885. cs.spells.insert(spell);
  1886. }
  1887. }
  1888. else
  1889. {
  1890. for (int i = 0; i < std::min(t->mageGuildLevel(), h->maxSpellLevel()); i++)
  1891. {
  1892. for (int j = 0; j < t->spellsAtLevel(i+1, true) && j < t->spells.at(i).size(); j++)
  1893. {
  1894. if (!h->spellbookContainsSpell(t->spells.at(i).at(j)))
  1895. cs.spells.insert(t->spells.at(i).at(j));
  1896. }
  1897. }
  1898. }
  1899. if (!cs.spells.empty())
  1900. sendAndApply(&cs);
  1901. }
  1902. bool CGameHandler::removeObject(const CGObjectInstance * obj)
  1903. {
  1904. if (!obj || !getObj(obj->id))
  1905. {
  1906. logGlobal->error("Something wrong, that object already has been removed or hasn't existed!");
  1907. return false;
  1908. }
  1909. RemoveObject ro;
  1910. ro.id = obj->id;
  1911. sendAndApply(&ro);
  1912. checkVictoryLossConditionsForAll(); //eg if monster escaped (removing objs after battle is done dircetly by endBattle, not this function)
  1913. return true;
  1914. }
  1915. bool CGameHandler::moveHero(ObjectInstanceID hid, int3 dst, ui8 teleporting, bool transit, PlayerColor asker)
  1916. {
  1917. const CGHeroInstance *h = getHero(hid);
  1918. // not turn of that hero or player can't simply teleport hero (at least not with this function)
  1919. if (!h || (asker != PlayerColor::NEUTRAL && (teleporting || h->getOwner() != gs->currentPlayer)))
  1920. {
  1921. logGlobal->error("Illegal call to move hero!");
  1922. return false;
  1923. }
  1924. logGlobal->trace("Player %d (%s) wants to move hero %d from %s to %s", asker, asker.getStr(), hid.getNum(), h->pos.toString(), dst.toString());
  1925. const int3 hmpos = h->convertToVisitablePos(dst);
  1926. if (!gs->map->isInTheMap(hmpos))
  1927. {
  1928. logGlobal->error("Destination tile is outside the map!");
  1929. return false;
  1930. }
  1931. const TerrainTile t = *getTile(hmpos);
  1932. const int3 guardPos = gs->guardingCreaturePosition(hmpos);
  1933. const bool embarking = !h->boat && !t.visitableObjects.empty() && t.visitableObjects.back()->ID == Obj::BOAT;
  1934. const bool disembarking = h->boat
  1935. && t.terType->isLand()
  1936. && (dst == h->pos
  1937. || (h->boat->layer == EPathfindingLayer::SAIL && !t.blocked));
  1938. //result structure for start - movement failed, no move points used
  1939. TryMoveHero tmh;
  1940. tmh.id = hid;
  1941. tmh.start = h->pos;
  1942. tmh.end = dst;
  1943. tmh.result = TryMoveHero::FAILED;
  1944. tmh.movePoints = h->movementPointsRemaining();
  1945. //check if destination tile is available
  1946. auto pathfinderHelper = std::make_unique<CPathfinderHelper>(gs, h, PathfinderOptions());
  1947. auto ti = pathfinderHelper->getTurnInfo();
  1948. const bool canFly = pathfinderHelper->hasBonusOfType(BonusType::FLYING_MOVEMENT) || (h->boat && h->boat->layer == EPathfindingLayer::AIR);
  1949. const bool canWalkOnSea = pathfinderHelper->hasBonusOfType(BonusType::WATER_WALKING) || (h->boat && h->boat->layer == EPathfindingLayer::WATER);
  1950. const int cost = pathfinderHelper->getMovementCost(h->visitablePos(), hmpos, nullptr, nullptr, h->movementPointsRemaining());
  1951. //it's a rock or blocked and not visitable tile
  1952. //OR hero is on land and dest is water and (there is not present only one object - boat)
  1953. if (((!t.terType->isPassable() || (t.blocked && !t.visitable && !canFly))
  1954. && complain("Cannot move hero, destination tile is blocked!"))
  1955. || ((!h->boat && !canWalkOnSea && !canFly && t.terType->isWater() && (t.visitableObjects.size() < 1 || !t.visitableObjects.back()->isCoastVisitable())) //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)
  1956. && complain("Cannot move hero, destination tile is on water!"))
  1957. || ((h->boat && h->boat->layer == EPathfindingLayer::SAIL && t.terType->isLand() && t.blocked)
  1958. && complain("Cannot disembark hero, tile is blocked!"))
  1959. || ((distance(h->pos, dst) >= 1.5 && !teleporting)
  1960. && complain("Tiles are not neighboring!"))
  1961. || ((h->inTownGarrison)
  1962. && complain("Can not move garrisoned hero!"))
  1963. || (((int)h->movementPointsRemaining() < cost && dst != h->pos && !teleporting)
  1964. && complain("Hero doesn't have any movement points left!"))
  1965. || ((transit && !canFly && !CGTeleport::isTeleport(t.topVisitableObj()))
  1966. && complain("Hero cannot transit over this tile!"))
  1967. /*|| (states.checkFlag(h->tempOwner, &PlayerStatus::engagedIntoBattle)
  1968. && complain("Cannot move hero during the battle"))*/)
  1969. {
  1970. //send info about movement failure
  1971. sendAndApply(&tmh);
  1972. return false;
  1973. }
  1974. //several generic blocks of code
  1975. // should be called if hero changes tile but before applying TryMoveHero package
  1976. auto leaveTile = [&]()
  1977. {
  1978. for (CGObjectInstance *obj : gs->map->getTile(int3(h->pos.x-1, h->pos.y, h->pos.z)).visitableObjects)
  1979. {
  1980. obj->onHeroLeave(h);
  1981. }
  1982. this->getTilesInRange(tmh.fowRevealed, h->getSightCenter()+(tmh.end-tmh.start), h->getSightRadius(), h->tempOwner, 1);
  1983. };
  1984. auto doMove = [&](TryMoveHero::EResult result, EGuardLook lookForGuards,
  1985. EVisitDest visitDest, ELEaveTile leavingTile) -> bool
  1986. {
  1987. LOG_TRACE_PARAMS(logGlobal, "Hero %s starts movement from %s to %s", h->getNameTranslated() % tmh.start.toString() % tmh.end.toString());
  1988. auto moveQuery = std::make_shared<CHeroMovementQuery>(this, tmh, h);
  1989. queries.addQuery(moveQuery);
  1990. if (leavingTile == LEAVING_TILE)
  1991. leaveTile();
  1992. if (isInTheMap(guardPos))
  1993. tmh.attackedFrom = std::make_optional(guardPos);
  1994. tmh.result = result;
  1995. sendAndApply(&tmh);
  1996. if (visitDest == VISIT_DEST && t.topVisitableObj() && t.topVisitableObj()->id == h->id)
  1997. { // Hero should be always able to visit any object he staying on even if there guards around
  1998. visitObjectOnTile(t, h);
  1999. }
  2000. else if (lookForGuards == CHECK_FOR_GUARDS && isInTheMap(guardPos))
  2001. {
  2002. const TerrainTile &guardTile = *gs->getTile(guardPos);
  2003. objectVisited(guardTile.visitableObjects.back(), h);
  2004. moveQuery->visitDestAfterVictory = visitDest==VISIT_DEST;
  2005. }
  2006. else if (visitDest == VISIT_DEST)
  2007. {
  2008. visitObjectOnTile(t, h);
  2009. }
  2010. queries.popIfTop(moveQuery);
  2011. logGlobal->trace("Hero %s ends movement", h->getNameTranslated());
  2012. return result != TryMoveHero::FAILED;
  2013. };
  2014. //interaction with blocking object (like resources)
  2015. auto blockingVisit = [&]() -> bool
  2016. {
  2017. for (CGObjectInstance *obj : t.visitableObjects)
  2018. {
  2019. if(h->boat && !obj->isBlockedVisitable() && !h->boat->onboardVisitAllowed)
  2020. return doMove(TryMoveHero::SUCCESS, this->IGNORE_GUARDS, DONT_VISIT_DEST, REMAINING_ON_TILE);
  2021. if (obj != h && obj->isBlockedVisitable() && !obj->passableFor(h->tempOwner))
  2022. {
  2023. EVisitDest visitDest = VISIT_DEST;
  2024. if(h->boat && !h->boat->onboardVisitAllowed)
  2025. visitDest = DONT_VISIT_DEST;
  2026. return doMove(TryMoveHero::BLOCKING_VISIT, this->IGNORE_GUARDS, visitDest, REMAINING_ON_TILE);
  2027. }
  2028. }
  2029. return false;
  2030. };
  2031. if (!transit && embarking)
  2032. {
  2033. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, false, ti);
  2034. return doMove(TryMoveHero::EMBARK, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  2035. // In H3 embark ignore guards
  2036. }
  2037. if (disembarking)
  2038. {
  2039. tmh.movePoints = h->movementPointsAfterEmbark(h->movementPointsRemaining(), cost, true, ti);
  2040. return doMove(TryMoveHero::DISEMBARK, CHECK_FOR_GUARDS, VISIT_DEST, LEAVING_TILE);
  2041. }
  2042. if (teleporting)
  2043. {
  2044. if (blockingVisit()) // e.g. hero on the other side of teleporter
  2045. return true;
  2046. doMove(TryMoveHero::TELEPORTATION, IGNORE_GUARDS, DONT_VISIT_DEST, LEAVING_TILE);
  2047. // visit town for town portal \ castle gates
  2048. // do not use generic visitObjectOnTile to avoid double-teleporting
  2049. // if this moveHero call was triggered by teleporter
  2050. if (!t.visitableObjects.empty())
  2051. {
  2052. if (CGTownInstance * town = dynamic_cast<CGTownInstance *>(t.visitableObjects.back()))
  2053. town->onHeroVisit(h);
  2054. }
  2055. return true;
  2056. }
  2057. //still here? it is standard movement!
  2058. {
  2059. tmh.movePoints = (int)h->movementPointsRemaining() >= cost
  2060. ? h->movementPointsRemaining() - cost
  2061. : 0;
  2062. EGuardLook lookForGuards = CHECK_FOR_GUARDS;
  2063. EVisitDest visitDest = VISIT_DEST;
  2064. if (transit)
  2065. {
  2066. if (CGTeleport::isTeleport(t.topVisitableObj()))
  2067. visitDest = DONT_VISIT_DEST;
  2068. if (canFly)
  2069. {
  2070. lookForGuards = IGNORE_GUARDS;
  2071. visitDest = DONT_VISIT_DEST;
  2072. }
  2073. }
  2074. else if (blockingVisit())
  2075. return true;
  2076. if(h->boat && !h->boat->onboardAssaultAllowed)
  2077. lookForGuards = IGNORE_GUARDS;
  2078. doMove(TryMoveHero::SUCCESS, lookForGuards, visitDest, LEAVING_TILE);
  2079. return true;
  2080. }
  2081. }
  2082. bool CGameHandler::teleportHero(ObjectInstanceID hid, ObjectInstanceID dstid, ui8 source, PlayerColor asker)
  2083. {
  2084. const CGHeroInstance *h = getHero(hid);
  2085. const CGTownInstance *t = getTown(dstid);
  2086. if (!h || !t || h->getOwner() != gs->currentPlayer)
  2087. COMPLAIN_RET("Invalid call to teleportHero!");
  2088. const CGTownInstance *from = h->visitedTown;
  2089. if (((h->getOwner() != t->getOwner())
  2090. && complain("Cannot teleport hero to another player"))
  2091. || (from->town->faction->getId() != t->town->faction->getId()
  2092. && complain("Source town and destination town should belong to the same faction"))
  2093. || ((!from || !from->hasBuilt(BuildingSubID::CASTLE_GATE))
  2094. && complain("Hero must be in town with Castle gate for teleporting"))
  2095. || (!t->hasBuilt(BuildingSubID::CASTLE_GATE)
  2096. && complain("Cannot teleport hero to town without Castle gate in it")))
  2097. return false;
  2098. int3 pos = h->convertFromVisitablePos(t->visitablePos());
  2099. moveHero(hid,pos,1);
  2100. return true;
  2101. }
  2102. void CGameHandler::setOwner(const CGObjectInstance * obj, const PlayerColor owner)
  2103. {
  2104. PlayerColor oldOwner = getOwner(obj->id);
  2105. SetObjectProperty sop(obj->id, ObjProperty::OWNER, owner.getNum());
  2106. sendAndApply(&sop);
  2107. std::set<PlayerColor> playerColors = {owner, oldOwner};
  2108. checkVictoryLossConditions(playerColors);
  2109. const CGTownInstance * town = dynamic_cast<const CGTownInstance *>(obj);
  2110. if (town) //town captured
  2111. {
  2112. if (owner < PlayerColor::PLAYER_LIMIT) //new owner is real player
  2113. {
  2114. if (town->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  2115. setPortalDwelling(town, true, false);
  2116. }
  2117. if (oldOwner < PlayerColor::PLAYER_LIMIT) //old owner is real player
  2118. {
  2119. if (getPlayerState(oldOwner)->towns.empty() && getPlayerState(oldOwner)->status != EPlayerStatus::LOSER) //previous player lost last last town
  2120. {
  2121. InfoWindow iw;
  2122. iw.player = oldOwner;
  2123. iw.text.appendLocalString(EMetaText::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.
  2124. iw.text.replaceLocalString(EMetaText::COLOR, oldOwner.getNum());
  2125. sendAndApply(&iw);
  2126. }
  2127. }
  2128. }
  2129. const PlayerState * p = getPlayerState(owner);
  2130. if ((obj->ID == Obj::CREATURE_GENERATOR1 || obj->ID == Obj::CREATURE_GENERATOR4) && p && p->dwellings.size()==1)//first dwelling captured
  2131. {
  2132. for (const CGTownInstance * t : getPlayerState(owner)->towns)
  2133. {
  2134. if (t->hasBuilt(BuildingSubID::PORTAL_OF_SUMMONING))
  2135. setPortalDwelling(t);//set initial creatures for all portals of summoning
  2136. }
  2137. }
  2138. }
  2139. void CGameHandler::showBlockingDialog(BlockingDialog *iw)
  2140. {
  2141. auto dialogQuery = std::make_shared<CBlockingDialogQuery>(this, *iw);
  2142. queries.addQuery(dialogQuery);
  2143. iw->queryID = dialogQuery->queryID;
  2144. sendToAllClients(iw);
  2145. }
  2146. void CGameHandler::showTeleportDialog(TeleportDialog *iw)
  2147. {
  2148. auto dialogQuery = std::make_shared<CTeleportDialogQuery>(this, *iw);
  2149. queries.addQuery(dialogQuery);
  2150. iw->queryID = dialogQuery->queryID;
  2151. sendToAllClients(iw);
  2152. }
  2153. void CGameHandler::giveResource(PlayerColor player, GameResID which, int val) //TODO: cap according to Bersy's suggestion
  2154. {
  2155. if (!val) return; //don't waste time on empty call
  2156. TResources resources;
  2157. resources[which] = val;
  2158. giveResources(player, resources);
  2159. }
  2160. void CGameHandler::giveResources(PlayerColor player, TResources resources)
  2161. {
  2162. SetResources sr;
  2163. sr.abs = false;
  2164. sr.player = player;
  2165. sr.res = resources;
  2166. sendAndApply(&sr);
  2167. }
  2168. void CGameHandler::giveCreatures(const CArmedInstance *obj, const CGHeroInstance * h, const CCreatureSet &creatures, bool remove)
  2169. {
  2170. COMPLAIN_RET_IF(!creatures.stacksCount(), "Strange, giveCreatures called without args!");
  2171. COMPLAIN_RET_IF(obj->stacksCount(), "Cannot give creatures from not-cleared object!");
  2172. COMPLAIN_RET_IF(creatures.stacksCount() > GameConstants::ARMY_SIZE, "Too many stacks to give!");
  2173. //first we move creatures to give to make them army of object-source
  2174. for (auto & elem : creatures.Slots())
  2175. {
  2176. addToSlot(StackLocation(obj, obj->getSlotFor(elem.second->type)), elem.second->type, elem.second->count);
  2177. }
  2178. tryJoiningArmy(obj, h, remove, true);
  2179. }
  2180. void CGameHandler::takeCreatures(ObjectInstanceID objid, const std::vector<CStackBasicDescriptor> &creatures)
  2181. {
  2182. std::vector<CStackBasicDescriptor> cres = creatures;
  2183. if (cres.size() <= 0)
  2184. return;
  2185. const CArmedInstance* obj = static_cast<const CArmedInstance*>(getObj(objid));
  2186. for (CStackBasicDescriptor &sbd : cres)
  2187. {
  2188. TQuantity collected = 0;
  2189. while(collected < sbd.count)
  2190. {
  2191. bool foundSth = false;
  2192. for (auto i = obj->Slots().begin(); i != obj->Slots().end(); i++)
  2193. {
  2194. if (i->second->type == sbd.type)
  2195. {
  2196. TQuantity take = std::min(sbd.count - collected, i->second->count); //collect as much cres as we can
  2197. changeStackCount(StackLocation(obj, i->first), -take, false);
  2198. collected += take;
  2199. foundSth = true;
  2200. break;
  2201. }
  2202. }
  2203. if (!foundSth) //we went through the whole loop and haven't found appropriate cres
  2204. {
  2205. complain("Unexpected failure during taking creatures!");
  2206. return;
  2207. }
  2208. }
  2209. }
  2210. }
  2211. void CGameHandler::heroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  2212. {
  2213. HeroVisitCastle vc;
  2214. vc.hid = hero->id;
  2215. vc.tid = obj->id;
  2216. vc.flags |= 1;
  2217. sendAndApply(&vc);
  2218. visitCastleObjects(obj, hero);
  2219. giveSpells (obj, hero);
  2220. checkVictoryLossConditionsForPlayer(hero->tempOwner); //transported artifact?
  2221. }
  2222. void CGameHandler::visitCastleObjects(const CGTownInstance * t, const CGHeroInstance * h)
  2223. {
  2224. for (auto building : t->bonusingBuildings)
  2225. building->onHeroVisit(h);
  2226. }
  2227. void CGameHandler::stopHeroVisitCastle(const CGTownInstance * obj, const CGHeroInstance * hero)
  2228. {
  2229. HeroVisitCastle vc;
  2230. vc.hid = hero->id;
  2231. vc.tid = obj->id;
  2232. sendAndApply(&vc);
  2233. }
  2234. void CGameHandler::removeArtifact(const ArtifactLocation &al)
  2235. {
  2236. EraseArtifact ea;
  2237. ea.al = al;
  2238. sendAndApply(&ea);
  2239. }
  2240. void CGameHandler::startBattlePrimary(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile,
  2241. const CGHeroInstance *hero1, const CGHeroInstance *hero2, bool creatureBank,
  2242. const CGTownInstance *town) //use hero=nullptr for no hero
  2243. {
  2244. if(gs->curB)
  2245. gs->curB.dellNull();
  2246. engageIntoBattle(army1->tempOwner);
  2247. engageIntoBattle(army2->tempOwner);
  2248. static const CArmedInstance *armies[2];
  2249. armies[0] = army1;
  2250. armies[1] = army2;
  2251. static const CGHeroInstance*heroes[2];
  2252. heroes[0] = hero1;
  2253. heroes[1] = hero2;
  2254. setupBattle(tile, armies, heroes, creatureBank, town); //initializes stacks, places creatures on battlefield, blocks and informs player interfaces
  2255. //existing battle query for retying auto-combat
  2256. auto battleQuery = std::dynamic_pointer_cast<CBattleQuery>(queries.topQuery(gs->curB->sides[0].color));
  2257. if(battleQuery)
  2258. {
  2259. for(int i : {0, 1})
  2260. {
  2261. if(heroes[i])
  2262. {
  2263. SetMana restoreInitialMana;
  2264. restoreInitialMana.val = battleQuery->initialHeroMana[i];
  2265. restoreInitialMana.hid = heroes[i]->id;
  2266. sendAndApply(&restoreInitialMana);
  2267. }
  2268. }
  2269. battleQuery->bi = gs->curB;
  2270. battleQuery->result = std::nullopt;
  2271. battleQuery->belligerents[0] = gs->curB->sides[0].armyObject;
  2272. battleQuery->belligerents[1] = gs->curB->sides[1].armyObject;
  2273. }
  2274. battleQuery = std::make_shared<CBattleQuery>(this, gs->curB);
  2275. for(int i : {0, 1})
  2276. {
  2277. if(heroes[i])
  2278. {
  2279. battleQuery->initialHeroMana[i] = heroes[i]->mana;
  2280. }
  2281. }
  2282. queries.addQuery(battleQuery);
  2283. this->battleThread = std::make_unique<boost::thread>(boost::thread(&CGameHandler::runBattle, this));
  2284. }
  2285. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, int3 tile, bool creatureBank)
  2286. {
  2287. startBattlePrimary(army1, army2, tile,
  2288. army1->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army1) : nullptr,
  2289. army2->ID == Obj::HERO ? static_cast<const CGHeroInstance*>(army2) : nullptr,
  2290. creatureBank);
  2291. }
  2292. void CGameHandler::startBattleI(const CArmedInstance *army1, const CArmedInstance *army2, bool creatureBank)
  2293. {
  2294. startBattleI(army1, army2, army2->visitablePos(), creatureBank);
  2295. }
  2296. void CGameHandler::changeSpells(const CGHeroInstance * hero, bool give, const std::set<SpellID> &spells)
  2297. {
  2298. ChangeSpells cs;
  2299. cs.hid = hero->id;
  2300. cs.spells = spells;
  2301. cs.learn = give;
  2302. sendAndApply(&cs);
  2303. }
  2304. void CGameHandler::giveHeroBonus(GiveBonus * bonus)
  2305. {
  2306. sendAndApply(bonus);
  2307. }
  2308. void CGameHandler::setMovePoints(SetMovePoints * smp)
  2309. {
  2310. sendAndApply(smp);
  2311. }
  2312. void CGameHandler::setManaPoints(ObjectInstanceID hid, int val)
  2313. {
  2314. SetMana sm;
  2315. sm.hid = hid;
  2316. sm.val = val;
  2317. sm.absolute = true;
  2318. sendAndApply(&sm);
  2319. }
  2320. void CGameHandler::giveHero(ObjectInstanceID id, PlayerColor player, ObjectInstanceID boatId)
  2321. {
  2322. GiveHero gh;
  2323. gh.id = id;
  2324. gh.player = player;
  2325. gh.boatId = boatId;
  2326. sendAndApply(&gh);
  2327. //Reveal fow around new hero, especially released from Prison
  2328. auto h = getHero(id);
  2329. changeFogOfWar(h->pos, h->getSightRadius(), player, false);
  2330. }
  2331. void CGameHandler::changeObjPos(ObjectInstanceID objid, int3 newPos)
  2332. {
  2333. ChangeObjPos cop;
  2334. cop.objid = objid;
  2335. cop.nPos = newPos;
  2336. sendAndApply(&cop);
  2337. }
  2338. void CGameHandler::useScholarSkill(ObjectInstanceID fromHero, ObjectInstanceID toHero)
  2339. {
  2340. const CGHeroInstance * h1 = getHero(fromHero);
  2341. const CGHeroInstance * h2 = getHero(toHero);
  2342. int h1_scholarSpellLevel = h1->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  2343. int h2_scholarSpellLevel = h2->valOfBonuses(BonusType::LEARN_MEETING_SPELL_LIMIT, -1);
  2344. if (h1_scholarSpellLevel < h2_scholarSpellLevel)
  2345. {
  2346. std::swap (h1,h2);//1st hero need to have higher scholar level for correct message
  2347. std::swap(fromHero, toHero);
  2348. }
  2349. int ScholarSpellLevel = std::max(h1_scholarSpellLevel, h2_scholarSpellLevel);//heroes can trade up to this level
  2350. if (!ScholarSpellLevel || !h1->hasSpellbook() || !h2->hasSpellbook())
  2351. return;//no scholar skill or no spellbook
  2352. int h1Lvl = std::min(ScholarSpellLevel, h1->maxSpellLevel()),
  2353. h2Lvl = std::min(ScholarSpellLevel, h2->maxSpellLevel());//heroes can receive this levels
  2354. ChangeSpells cs1;
  2355. cs1.learn = true;
  2356. cs1.hid = toHero;//giving spells to first hero
  2357. for (auto it : h1->getSpellsInSpellbook())
  2358. if (h2Lvl >= it.toSpell()->level && !h2->spellbookContainsSpell(it))//hero can learn it and don't have it yet
  2359. cs1.spells.insert(it);//spell to learn
  2360. ChangeSpells cs2;
  2361. cs2.learn = true;
  2362. cs2.hid = fromHero;
  2363. for (auto it : h2->getSpellsInSpellbook())
  2364. if (h1Lvl >= it.toSpell()->level && !h1->spellbookContainsSpell(it))
  2365. cs2.spells.insert(it);
  2366. if (!cs1.spells.empty() || !cs2.spells.empty())//create a message
  2367. {
  2368. int ScholarSkillLevel = std::max(h1->getSecSkillLevel(SecondarySkill::SCHOLAR),
  2369. h2->getSecSkillLevel(SecondarySkill::SCHOLAR));
  2370. InfoWindow iw;
  2371. iw.player = h1->tempOwner;
  2372. iw.components.emplace_back(Component::EComponentType::SEC_SKILL, 18, ScholarSkillLevel, 0);
  2373. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 139);//"%s, who has studied magic extensively,
  2374. iw.text.replaceRawString(h1->getNameTranslated());
  2375. if (!cs2.spells.empty())//if found new spell - apply
  2376. {
  2377. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 140);//learns
  2378. int size = static_cast<int>(cs2.spells.size());
  2379. for (auto it : cs2.spells)
  2380. {
  2381. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  2382. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  2383. switch (size--)
  2384. {
  2385. case 2:
  2386. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  2387. case 1:
  2388. break;
  2389. default:
  2390. iw.text.appendRawString(", ");
  2391. }
  2392. }
  2393. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 142);//from %s
  2394. iw.text.replaceRawString(h2->getNameTranslated());
  2395. sendAndApply(&cs2);
  2396. }
  2397. if (!cs1.spells.empty() && !cs2.spells.empty())
  2398. {
  2399. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);//and
  2400. }
  2401. if (!cs1.spells.empty())
  2402. {
  2403. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 147);//teaches
  2404. int size = static_cast<int>(cs1.spells.size());
  2405. for (auto it : cs1.spells)
  2406. {
  2407. iw.components.emplace_back(Component::EComponentType::SPELL, it, 1, 0);
  2408. iw.text.appendLocalString(EMetaText::SPELL_NAME, it.toEnum());
  2409. switch (size--)
  2410. {
  2411. case 2:
  2412. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 141);
  2413. case 1:
  2414. break;
  2415. default:
  2416. iw.text.appendRawString(", ");
  2417. }
  2418. }
  2419. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 148);//from %s
  2420. iw.text.replaceRawString(h2->getNameTranslated());
  2421. sendAndApply(&cs1);
  2422. }
  2423. sendAndApply(&iw);
  2424. }
  2425. }
  2426. void CGameHandler::heroExchange(ObjectInstanceID hero1, ObjectInstanceID hero2)
  2427. {
  2428. auto h1 = getHero(hero1), h2 = getHero(hero2);
  2429. if (getPlayerRelations(h1->getOwner(), h2->getOwner()))
  2430. {
  2431. auto exchange = std::make_shared<CGarrisonDialogQuery>(this, h1, h2);
  2432. ExchangeDialog hex;
  2433. hex.queryID = exchange->queryID;
  2434. hex.player = h1->getOwner();
  2435. hex.hero1 = hero1;
  2436. hex.hero2 = hero2;
  2437. sendAndApply(&hex);
  2438. useScholarSkill(hero1,hero2);
  2439. queries.addQuery(exchange);
  2440. }
  2441. }
  2442. void CGameHandler::sendToAllClients(CPackForClient * pack)
  2443. {
  2444. logNetwork->trace("\tSending to all clients: %s", typeid(*pack).name());
  2445. for (auto c : lobby->connections)
  2446. {
  2447. if(!c->isOpen())
  2448. continue;
  2449. c->sendPack(pack);
  2450. }
  2451. }
  2452. void CGameHandler::sendAndApply(CPackForClient * pack)
  2453. {
  2454. sendToAllClients(pack);
  2455. gs->apply(pack);
  2456. logNetwork->trace("\tApplied on gs: %s", typeid(*pack).name());
  2457. }
  2458. void CGameHandler::applyAndSend(CPackForClient * pack)
  2459. {
  2460. gs->apply(pack);
  2461. sendToAllClients(pack);
  2462. }
  2463. void CGameHandler::sendAndApply(CGarrisonOperationPack * pack)
  2464. {
  2465. sendAndApply(static_cast<CPackForClient *>(pack));
  2466. checkVictoryLossConditionsForAll();
  2467. }
  2468. void CGameHandler::sendAndApply(SetResources * pack)
  2469. {
  2470. sendAndApply(static_cast<CPackForClient *>(pack));
  2471. checkVictoryLossConditionsForPlayer(pack->player);
  2472. }
  2473. void CGameHandler::sendAndApply(NewStructures * pack)
  2474. {
  2475. sendAndApply(static_cast<CPackForClient *>(pack));
  2476. checkVictoryLossConditionsForPlayer(getTown(pack->tid)->tempOwner);
  2477. }
  2478. bool CGameHandler::isPlayerOwns(CPackForServer * pack, ObjectInstanceID id)
  2479. {
  2480. return getPlayerAt(pack->c) == getOwner(id);
  2481. }
  2482. void CGameHandler::throwNotAllowedAction(CPackForServer * pack)
  2483. {
  2484. if(pack->c)
  2485. playerMessages->sendSystemMessage(pack->c, "You are not allowed to perform this action!");
  2486. logNetwork->error("Player is not allowed to perform this action!");
  2487. throw ExceptionNotAllowedAction();
  2488. }
  2489. void CGameHandler::wrongPlayerMessage(CPackForServer * pack, PlayerColor expectedplayer)
  2490. {
  2491. std::ostringstream oss;
  2492. oss << "You were identified as player " << getPlayerAt(pack->c) << " while expecting " << expectedplayer;
  2493. logNetwork->error(oss.str());
  2494. if(pack->c)
  2495. playerMessages->sendSystemMessage(pack->c, oss.str());
  2496. }
  2497. void CGameHandler::throwOnWrongOwner(CPackForServer * pack, ObjectInstanceID id)
  2498. {
  2499. if(!isPlayerOwns(pack, id))
  2500. {
  2501. wrongPlayerMessage(pack, getOwner(id));
  2502. throwNotAllowedAction(pack);
  2503. }
  2504. }
  2505. void CGameHandler::throwOnWrongPlayer(CPackForServer * pack, PlayerColor player)
  2506. {
  2507. if(!hasPlayerAt(player, pack->c) && player != getPlayerAt(pack->c))
  2508. {
  2509. wrongPlayerMessage(pack, player);
  2510. throwNotAllowedAction(pack);
  2511. }
  2512. }
  2513. void CGameHandler::throwAndComplain(CPackForServer * pack, std::string txt)
  2514. {
  2515. complain(txt);
  2516. throwNotAllowedAction(pack);
  2517. }
  2518. void CGameHandler::save(const std::string & filename)
  2519. {
  2520. logGlobal->info("Saving to %s", filename);
  2521. const auto stem = FileInfo::GetPathStem(filename);
  2522. const auto savefname = stem.to_string() + ".vsgm1";
  2523. CResourceHandler::get("local")->createResource(savefname);
  2524. try
  2525. {
  2526. {
  2527. CSaveFile save(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)));
  2528. saveCommonState(save);
  2529. logGlobal->info("Saving server state");
  2530. save << *this;
  2531. }
  2532. logGlobal->info("Game has been successfully saved!");
  2533. }
  2534. catch(std::exception &e)
  2535. {
  2536. logGlobal->error("Failed to save game: %s", e.what());
  2537. }
  2538. }
  2539. bool CGameHandler::load(const std::string & filename)
  2540. {
  2541. logGlobal->info("Loading from %s", filename);
  2542. const auto stem = FileInfo::GetPathStem(filename);
  2543. reinitScripting();
  2544. try
  2545. {
  2546. {
  2547. CLoadFile lf(*CResourceHandler::get("local")->getResourceName(ResourceID(stem.to_string(), EResType::SAVEGAME)), MINIMAL_SERIALIZATION_VERSION);
  2548. loadCommonState(lf);
  2549. logGlobal->info("Loading server state");
  2550. lf >> *this;
  2551. }
  2552. logGlobal->info("Game has been successfully loaded!");
  2553. }
  2554. catch(const CModHandler::Incompatibility & e)
  2555. {
  2556. logGlobal->error("Failed to load game: %s", e.what());
  2557. auto errorMsg = VLC->generaltexth->translate("vcmi.server.errors.modsIncompatibility") + '\n';
  2558. errorMsg += e.what();
  2559. lobby->announceMessage(errorMsg);
  2560. return false;
  2561. }
  2562. catch(const std::exception & e)
  2563. {
  2564. logGlobal->error("Failed to load game: %s", e.what());
  2565. return false;
  2566. }
  2567. gs->preInit(VLC);
  2568. gs->updateOnLoad(lobby->si.get());
  2569. return true;
  2570. }
  2571. bool CGameHandler::bulkSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner, si32 howMany)
  2572. {
  2573. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2574. return false;
  2575. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2576. const CCreatureSet & creatureSet = *army;
  2577. if((!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2578. || (howMany < 1 && complain("Invalid split parameter!")))
  2579. {
  2580. return false;
  2581. }
  2582. auto actualAmount = army->getStackCount(slotSrc);
  2583. if(actualAmount <= howMany && complain(complainNotEnoughCreatures)) // '<=' because it's not intended just for moving a stack
  2584. return false;
  2585. auto freeSlots = creatureSet.getFreeSlots();
  2586. if(freeSlots.empty() && complain("No empty stacks"))
  2587. return false;
  2588. BulkRebalanceStacks bulkRS;
  2589. for(auto slot : freeSlots)
  2590. {
  2591. RebalanceStacks rs;
  2592. rs.srcArmy = army->id;
  2593. rs.dstArmy = army->id;
  2594. rs.srcSlot = slotSrc;
  2595. rs.dstSlot = slot;
  2596. rs.count = howMany;
  2597. bulkRS.moves.push_back(rs);
  2598. actualAmount -= howMany;
  2599. if(actualAmount <= howMany)
  2600. break;
  2601. }
  2602. sendAndApply(&bulkRS);
  2603. return true;
  2604. }
  2605. bool CGameHandler::bulkMergeStacks(SlotID slotSrc, ObjectInstanceID srcOwner)
  2606. {
  2607. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2608. return false;
  2609. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2610. const CCreatureSet & creatureSet = *army;
  2611. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2612. return false;
  2613. auto actualAmount = creatureSet.getStackCount(slotSrc);
  2614. if(actualAmount < 1 && complain(complainNoCreatures))
  2615. return false;
  2616. auto currentCreature = creatureSet.getCreature(slotSrc);
  2617. if(!currentCreature && complain(complainNoCreatures))
  2618. return false;
  2619. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, slotSrc);
  2620. if(!creatureSlots.size())
  2621. return false;
  2622. BulkRebalanceStacks bulkRS;
  2623. for(auto slot : creatureSlots)
  2624. {
  2625. RebalanceStacks rs;
  2626. rs.srcArmy = army->id;
  2627. rs.dstArmy = army->id;
  2628. rs.srcSlot = slot;
  2629. rs.dstSlot = slotSrc;
  2630. rs.count = creatureSet.getStackCount(slot);
  2631. bulkRS.moves.push_back(rs);
  2632. }
  2633. sendAndApply(&bulkRS);
  2634. return true;
  2635. }
  2636. bool CGameHandler::bulkMoveArmy(ObjectInstanceID srcArmy, ObjectInstanceID destArmy, SlotID srcSlot)
  2637. {
  2638. if(!srcSlot.validSlot() && complain(complainInvalidSlot))
  2639. return false;
  2640. const CArmedInstance * armySrc = static_cast<const CArmedInstance*>(getObjInstance(srcArmy));
  2641. const CCreatureSet & setSrc = *armySrc;
  2642. if(!vstd::contains(setSrc.stacks, srcSlot) && complain(complainNoCreatures))
  2643. return false;
  2644. const CArmedInstance * armyDest = static_cast<const CArmedInstance*>(getObjInstance(destArmy));
  2645. const CCreatureSet & setDest = *armyDest;
  2646. auto freeSlots = setDest.getFreeSlotsQueue();
  2647. typedef std::map<SlotID, std::pair<SlotID, TQuantity>> TRebalanceMap;
  2648. TRebalanceMap moves;
  2649. auto srcQueue = setSrc.getCreatureQueue(srcSlot); // Exclude srcSlot, it should be moved last
  2650. auto slotsLeft = setSrc.stacksCount();
  2651. auto destMap = setDest.getCreatureMap();
  2652. TMapCreatureSlot::key_compare keyComp = destMap.key_comp();
  2653. while(!srcQueue.empty())
  2654. {
  2655. auto pair = srcQueue.top();
  2656. srcQueue.pop();
  2657. auto currCreature = pair.first;
  2658. auto currSlot = pair.second;
  2659. const auto quantity = setSrc.getStackCount(currSlot);
  2660. TMapCreatureSlot::iterator lb = destMap.lower_bound(currCreature);
  2661. const bool alreadyExists = (lb != destMap.end() && !(keyComp(currCreature, lb->first)));
  2662. if(!alreadyExists)
  2663. {
  2664. if(freeSlots.empty())
  2665. continue;
  2666. auto currFreeSlot = freeSlots.front();
  2667. freeSlots.pop();
  2668. destMap.insert(lb, TMapCreatureSlot::value_type(currCreature, currFreeSlot));
  2669. }
  2670. moves.insert(std::make_pair(currSlot, std::make_pair(destMap[currCreature], quantity)));
  2671. slotsLeft--;
  2672. }
  2673. if(slotsLeft == 1)
  2674. {
  2675. auto lastCreature = setSrc.getCreature(srcSlot);
  2676. auto slotToMove = SlotID();
  2677. // Try to find a slot for last creature
  2678. if(destMap.find(lastCreature) == destMap.end())
  2679. {
  2680. if(!freeSlots.empty())
  2681. slotToMove = freeSlots.front();
  2682. }
  2683. else
  2684. {
  2685. slotToMove = destMap[lastCreature];
  2686. }
  2687. if(slotToMove != SlotID())
  2688. {
  2689. const bool needsLastStack = armySrc->needsLastStack();
  2690. const auto quantity = setSrc.getStackCount(srcSlot) - (needsLastStack ? 1 : 0);
  2691. moves.insert(std::make_pair(srcSlot, std::make_pair(slotToMove, quantity)));
  2692. }
  2693. }
  2694. BulkRebalanceStacks bulkRS;
  2695. for(auto & move : moves)
  2696. {
  2697. RebalanceStacks rs;
  2698. rs.srcArmy = armySrc->id;
  2699. rs.dstArmy = armyDest->id;
  2700. rs.srcSlot = move.first;
  2701. rs.dstSlot = move.second.first;
  2702. rs.count = move.second.second;
  2703. bulkRS.moves.push_back(rs);
  2704. }
  2705. sendAndApply(&bulkRS);
  2706. return true;
  2707. }
  2708. bool CGameHandler::bulkSmartSplitStack(SlotID slotSrc, ObjectInstanceID srcOwner)
  2709. {
  2710. if(!slotSrc.validSlot() && complain(complainInvalidSlot))
  2711. return false;
  2712. const CArmedInstance * army = static_cast<const CArmedInstance*>(getObjInstance(srcOwner));
  2713. const CCreatureSet & creatureSet = *army;
  2714. if(!vstd::contains(creatureSet.stacks, slotSrc) && complain(complainNoCreatures))
  2715. return false;
  2716. auto actualAmount = creatureSet.getStackCount(slotSrc);
  2717. if(actualAmount <= 1 && complain(complainNoCreatures))
  2718. return false;
  2719. auto freeSlot = creatureSet.getFreeSlot();
  2720. auto currentCreature = creatureSet.getCreature(slotSrc);
  2721. if(freeSlot == SlotID() && creatureSet.isCreatureBalanced(currentCreature))
  2722. return true;
  2723. auto creatureSlots = creatureSet.getCreatureSlots(currentCreature, SlotID(-1), 1); // Ignore slots where's only 1 creature, don't ignore slotSrc
  2724. TQuantity totalCreatures = 0;
  2725. for(auto slot : creatureSlots)
  2726. totalCreatures += creatureSet.getStackCount(slot);
  2727. if(totalCreatures <= 1 && complain("Total creatures number is invalid"))
  2728. return false;
  2729. if(freeSlot != SlotID())
  2730. creatureSlots.push_back(freeSlot);
  2731. if(creatureSlots.empty() && complain("No available slots for smart rebalancing"))
  2732. return false;
  2733. const auto totalCreatureSlots = creatureSlots.size();
  2734. const auto rem = totalCreatures % totalCreatureSlots;
  2735. const auto quotient = totalCreatures / totalCreatureSlots;
  2736. // totalCreatures == rem * (quotient + 1) + (totalCreatureSlots - rem) * quotient;
  2737. // Proof: r(q+1)+(s-r)q = rq+r+qs-rq = r+qs = total, where total/s = q+r/s
  2738. BulkSmartRebalanceStacks bulkSRS;
  2739. if(freeSlot != SlotID())
  2740. {
  2741. RebalanceStacks rs;
  2742. rs.srcArmy = rs.dstArmy = army->id;
  2743. rs.srcSlot = slotSrc;
  2744. rs.dstSlot = freeSlot;
  2745. rs.count = 1;
  2746. bulkSRS.moves.push_back(rs);
  2747. }
  2748. auto currSlot = 0;
  2749. auto check = 0;
  2750. for(auto slot : creatureSlots)
  2751. {
  2752. ChangeStackCount csc;
  2753. csc.army = army->id;
  2754. csc.slot = slot;
  2755. csc.count = (currSlot < rem)
  2756. ? quotient + 1
  2757. : quotient;
  2758. csc.absoluteValue = true;
  2759. bulkSRS.changes.push_back(csc);
  2760. currSlot++;
  2761. check += csc.count;
  2762. }
  2763. if(check != totalCreatures)
  2764. {
  2765. complain((boost::format("Failure: totalCreatures=%d but check=%d") % totalCreatures % check).str());
  2766. return false;
  2767. }
  2768. sendAndApply(&bulkSRS);
  2769. return true;
  2770. }
  2771. bool CGameHandler::arrangeStacks(ObjectInstanceID id1, ObjectInstanceID id2, ui8 what, SlotID p1, SlotID p2, si32 val, PlayerColor player)
  2772. {
  2773. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id1)),
  2774. * s2 = static_cast<const CArmedInstance *>(getObjInstance(id2));
  2775. const CCreatureSet &S1 = *s1, &S2 = *s2;
  2776. StackLocation sl1(s1, p1), sl2(s2, p2);
  2777. if (!sl1.slot.validSlot() || !sl2.slot.validSlot())
  2778. {
  2779. complain(complainInvalidSlot);
  2780. return false;
  2781. }
  2782. if (!isAllowedExchange(id1,id2))
  2783. {
  2784. complain("Cannot exchange stacks between these two objects!\n");
  2785. return false;
  2786. }
  2787. // We can always put stacks into locked garrison, but not take them out of it
  2788. auto notRemovable = [&](const CArmedInstance * army)
  2789. {
  2790. if (id1 != id2) // Stack arrangement inside locked garrison is allowed
  2791. {
  2792. auto g = dynamic_cast<const CGGarrison *>(army);
  2793. if (g && !g->removableUnits)
  2794. {
  2795. complain("Stacks in this garrison are not removable!\n");
  2796. return true;
  2797. }
  2798. }
  2799. return false;
  2800. };
  2801. if (what==1) //swap
  2802. {
  2803. if (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s1->getStackCount(p1))
  2804. || ((s2->tempOwner != player && s2->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)))
  2805. {
  2806. complain("Can't take troops from another player!");
  2807. return false;
  2808. }
  2809. if (sl1.army == sl2.army && sl1.slot == sl2.slot)
  2810. {
  2811. complain("Cannot swap stacks - slots are the same!");
  2812. return false;
  2813. }
  2814. if (!s1->slotEmpty(p1) && !s2->slotEmpty(p2))
  2815. {
  2816. if (notRemovable(sl1.army) || notRemovable(sl2.army))
  2817. return false;
  2818. }
  2819. if (s1->slotEmpty(p1) && notRemovable(sl2.army))
  2820. return false;
  2821. else if (s2->slotEmpty(p2) && notRemovable(sl1.army))
  2822. return false;
  2823. swapStacks(sl1, sl2);
  2824. }
  2825. else if (what==2)//merge
  2826. {
  2827. if ((s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot merge different creatures stacks!"))
  2828. || (((s1->tempOwner != player && s1->tempOwner != PlayerColor::UNFLAGGABLE) && s2->getStackCount(p2)) && complain("Can't take troops from another player!")))
  2829. return false;
  2830. if (s1->slotEmpty(p1) || s2->slotEmpty(p2))
  2831. {
  2832. complain("Cannot merge empty stack!");
  2833. return false;
  2834. }
  2835. else if (notRemovable(sl1.army))
  2836. return false;
  2837. moveStack(sl1, sl2);
  2838. }
  2839. else if (what==3) //split
  2840. {
  2841. const int countToMove = val - s2->getStackCount(p2);
  2842. const int countLeftOnSrc = s1->getStackCount(p1) - countToMove;
  2843. if ( (s1->tempOwner != player && countLeftOnSrc < s1->getStackCount(p1))
  2844. || (s2->tempOwner != player && val < s2->getStackCount(p2)))
  2845. {
  2846. complain("Can't move troops of another player!");
  2847. return false;
  2848. }
  2849. //general conditions checking
  2850. if ((!vstd::contains(S1.stacks,p1) && complain(complainNoCreatures))
  2851. || (val<1 && complain(complainNoCreatures)) )
  2852. {
  2853. return false;
  2854. }
  2855. if (vstd::contains(S2.stacks,p2)) //dest. slot not free - it must be "rebalancing"...
  2856. {
  2857. int total = s1->getStackCount(p1) + s2->getStackCount(p2);
  2858. if ((total < val && complain("Cannot split that stack, not enough creatures!"))
  2859. || (s1->getCreature(p1) != s2->getCreature(p2) && complain("Cannot rebalance different creatures stacks!"))
  2860. )
  2861. {
  2862. return false;
  2863. }
  2864. if (notRemovable(sl1.army))
  2865. {
  2866. if (s1->getStackCount(p1) > countLeftOnSrc)
  2867. return false;
  2868. }
  2869. else if (notRemovable(sl2.army))
  2870. {
  2871. if (s2->getStackCount(p1) < countLeftOnSrc)
  2872. return false;
  2873. }
  2874. moveStack(sl1, sl2, countToMove);
  2875. //S2.slots[p2]->count = val;
  2876. //S1.slots[p1]->count = total - val;
  2877. }
  2878. else //split one stack to the two
  2879. {
  2880. if (s1->getStackCount(p1) < val)//not enough creatures
  2881. {
  2882. complain(complainNotEnoughCreatures);
  2883. return false;
  2884. }
  2885. if (notRemovable(sl1.army))
  2886. return false;
  2887. moveStack(sl1, sl2, val);
  2888. }
  2889. }
  2890. return true;
  2891. }
  2892. bool CGameHandler::hasPlayerAt(PlayerColor player, std::shared_ptr<CConnection> c) const
  2893. {
  2894. return connections.at(player).count(c);
  2895. }
  2896. PlayerColor CGameHandler::getPlayerAt(std::shared_ptr<CConnection> c) const
  2897. {
  2898. std::set<PlayerColor> all;
  2899. for (auto i=connections.cbegin(); i!=connections.cend(); i++)
  2900. if(vstd::contains(i->second, c))
  2901. all.insert(i->first);
  2902. switch(all.size())
  2903. {
  2904. case 0:
  2905. return PlayerColor::NEUTRAL;
  2906. case 1:
  2907. return *all.begin();
  2908. default:
  2909. {
  2910. //if we have more than one player at this connection, try to pick active one
  2911. if (vstd::contains(all, gs->currentPlayer))
  2912. return gs->currentPlayer;
  2913. else
  2914. return PlayerColor::CANNOT_DETERMINE; //cannot say which player is it
  2915. }
  2916. }
  2917. }
  2918. bool CGameHandler::disbandCreature(ObjectInstanceID id, SlotID pos)
  2919. {
  2920. const CArmedInstance * s1 = static_cast<const CArmedInstance *>(getObjInstance(id));
  2921. if (!vstd::contains(s1->stacks,pos))
  2922. {
  2923. complain("Illegal call to disbandCreature - no such stack in army!");
  2924. return false;
  2925. }
  2926. eraseStack(StackLocation(s1, pos));
  2927. return true;
  2928. }
  2929. bool CGameHandler::buildStructure(ObjectInstanceID tid, BuildingID requestedID, bool force)
  2930. {
  2931. const CGTownInstance * t = getTown(tid);
  2932. if(!t)
  2933. COMPLAIN_RETF("No such town (ID=%s)!", tid);
  2934. if(!t->town->buildings.count(requestedID))
  2935. COMPLAIN_RETF("Town of faction %s does not have info about building ID=%s!", t->town->faction->getNameTranslated() % requestedID);
  2936. if(t->hasBuilt(requestedID))
  2937. COMPLAIN_RETF("Building %s is already built in %s", t->town->buildings.at(requestedID)->getNameTranslated() % t->getNameTranslated());
  2938. const CBuilding * requestedBuilding = t->town->buildings.at(requestedID);
  2939. //Vector with future list of built building and buildings in auto-mode that are not yet built.
  2940. std::vector<const CBuilding*> remainingAutoBuildings;
  2941. std::set<BuildingID> buildingsThatWillBe;
  2942. //Check validity of request
  2943. if(!force)
  2944. {
  2945. switch(requestedBuilding->mode)
  2946. {
  2947. case CBuilding::BUILD_NORMAL :
  2948. if (canBuildStructure(t, requestedID) != EBuildingState::ALLOWED)
  2949. COMPLAIN_RET("Cannot build that building!");
  2950. break;
  2951. case CBuilding::BUILD_AUTO :
  2952. case CBuilding::BUILD_SPECIAL:
  2953. COMPLAIN_RET("This building can not be constructed normally!");
  2954. case CBuilding::BUILD_GRAIL :
  2955. if(requestedBuilding->mode == CBuilding::BUILD_GRAIL) //needs grail
  2956. {
  2957. if(!t->visitingHero || !t->visitingHero->hasArt(ArtifactID::GRAIL))
  2958. COMPLAIN_RET("Cannot build this without grail!")
  2959. else
  2960. removeArtifact(ArtifactLocation(t->visitingHero, t->visitingHero->getArtPos(ArtifactID::GRAIL, false)));
  2961. }
  2962. break;
  2963. }
  2964. }
  2965. //Performs stuff that has to be done before new building is built
  2966. auto processBeforeBuiltStructure = [t, this](const BuildingID buildingID)
  2967. {
  2968. if(buildingID >= BuildingID::DWELL_FIRST) //dwelling
  2969. {
  2970. int level = (buildingID - BuildingID::DWELL_FIRST) % GameConstants::CREATURES_PER_TOWN;
  2971. int upgradeNumber = (buildingID - BuildingID::DWELL_FIRST) / GameConstants::CREATURES_PER_TOWN;
  2972. if(upgradeNumber >= t->town->creatures.at(level).size())
  2973. {
  2974. complain(boost::str(boost::format("Error ecountered when building dwelling (bid=%s):"
  2975. "no creature found (upgrade number %d, level %d!")
  2976. % buildingID % upgradeNumber % level));
  2977. return;
  2978. }
  2979. CCreature * crea = VLC->creh->objects.at(t->town->creatures.at(level).at(upgradeNumber));
  2980. SetAvailableCreatures ssi;
  2981. ssi.tid = t->id;
  2982. ssi.creatures = t->creatures;
  2983. if (ssi.creatures[level].second.empty()) // first creature in a dwelling
  2984. ssi.creatures[level].first = crea->getGrowth();
  2985. ssi.creatures[level].second.push_back(crea->getId());
  2986. sendAndApply(&ssi);
  2987. }
  2988. if(t->town->buildings.at(buildingID)->subId == BuildingSubID::PORTAL_OF_SUMMONING)
  2989. {
  2990. setPortalDwelling(t);
  2991. }
  2992. };
  2993. //Performs stuff that has to be done after new building is built
  2994. auto processAfterBuiltStructure = [t, this](const BuildingID buildingID)
  2995. {
  2996. auto isMageGuild = (buildingID <= BuildingID::MAGES_GUILD_5 && buildingID >= BuildingID::MAGES_GUILD_1);
  2997. auto isLibrary = isMageGuild ? false
  2998. : t->town->buildings.at(buildingID)->subId == BuildingSubID::EBuildingSubID::LIBRARY;
  2999. if(isMageGuild || isLibrary || (t->subID == ETownType::CONFLUX && buildingID == BuildingID::GRAIL))
  3000. {
  3001. if(t->visitingHero)
  3002. giveSpells(t,t->visitingHero);
  3003. if(t->garrisonHero)
  3004. giveSpells(t,t->garrisonHero);
  3005. }
  3006. };
  3007. //Checks if all requirements will be met with expected building list "buildingsThatWillBe"
  3008. auto areRequirementsFullfilled = [&](const BuildingID & buildID)
  3009. {
  3010. return buildingsThatWillBe.count(buildID);
  3011. };
  3012. //Init the vectors
  3013. for(auto & build : t->town->buildings)
  3014. {
  3015. if(t->hasBuilt(build.first))
  3016. {
  3017. buildingsThatWillBe.insert(build.first);
  3018. }
  3019. else
  3020. {
  3021. if(build.second->mode == CBuilding::BUILD_AUTO) //not built auto building
  3022. remainingAutoBuildings.push_back(build.second);
  3023. }
  3024. }
  3025. //Prepare structure (list of building ids will be filled later)
  3026. NewStructures ns;
  3027. ns.tid = tid;
  3028. ns.builded = force ? t->builded : (t->builded+1);
  3029. std::queue<const CBuilding*> buildingsToAdd;
  3030. buildingsToAdd.push(requestedBuilding);
  3031. while(!buildingsToAdd.empty())
  3032. {
  3033. auto b = buildingsToAdd.front();
  3034. buildingsToAdd.pop();
  3035. ns.bid.insert(b->bid);
  3036. buildingsThatWillBe.insert(b->bid);
  3037. remainingAutoBuildings -= b;
  3038. for(auto autoBuilding : remainingAutoBuildings)
  3039. {
  3040. auto actualRequirements = t->genBuildingRequirements(autoBuilding->bid);
  3041. if(actualRequirements.test(areRequirementsFullfilled))
  3042. buildingsToAdd.push(autoBuilding);
  3043. }
  3044. }
  3045. // FIXME: it's done before NewStructures applied because otherwise town window wont be properly updated on client. That should be actually fixed on client and not on server.
  3046. for(auto builtID : ns.bid)
  3047. processBeforeBuiltStructure(builtID);
  3048. //Take cost
  3049. if(!force)
  3050. giveResources(t->tempOwner, -requestedBuilding->resources);
  3051. //We know what has been built, apply changes. Do this as final step to properly update town window
  3052. sendAndApply(&ns);
  3053. //Other post-built events. To some logic like giving spells to work gamestate changes for new building must be already in place!
  3054. for(auto builtID : ns.bid)
  3055. processAfterBuiltStructure(builtID);
  3056. // now when everything is built - reveal tiles for lookout tower
  3057. FoWChange fw;
  3058. fw.player = t->tempOwner;
  3059. fw.mode = 1;
  3060. getTilesInRange(fw.tiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, 1);
  3061. sendAndApply(&fw);
  3062. if(t->visitingHero)
  3063. visitCastleObjects(t, t->visitingHero);
  3064. if(t->garrisonHero)
  3065. visitCastleObjects(t, t->garrisonHero);
  3066. checkVictoryLossConditionsForPlayer(t->tempOwner);
  3067. return true;
  3068. }
  3069. bool CGameHandler::razeStructure (ObjectInstanceID tid, BuildingID bid)
  3070. {
  3071. ///incomplete, simply erases target building
  3072. const CGTownInstance * t = getTown(tid);
  3073. if (!vstd::contains(t->builtBuildings, bid))
  3074. return false;
  3075. RazeStructures rs;
  3076. rs.tid = tid;
  3077. rs.bid.insert(bid);
  3078. rs.destroyed = t->destroyed + 1;
  3079. sendAndApply(&rs);
  3080. //TODO: Remove dwellers
  3081. // if (t->subID == 4 && bid == 17) //Veil of Darkness
  3082. // {
  3083. // RemoveBonus rb(RemoveBonus::TOWN);
  3084. // rb.whoID = t->id;
  3085. // rb.source = BonusSource::TOWN_STRUCTURE;
  3086. // rb.id = 17;
  3087. // sendAndApply(&rb);
  3088. // }
  3089. return true;
  3090. }
  3091. bool CGameHandler::recruitCreatures(ObjectInstanceID objid, ObjectInstanceID dstid, CreatureID crid, ui32 cram, si32 fromLvl)
  3092. {
  3093. const CGDwelling * dw = static_cast<const CGDwelling *>(getObj(objid));
  3094. const CArmedInstance *dst = nullptr;
  3095. const CCreature *c = VLC->creh->objects.at(crid);
  3096. const bool warMachine = c->warMachine != ArtifactID::NONE;
  3097. //TODO: test for owning
  3098. //TODO: check if dst can recruit objects (e.g. hero is actually visiting object, town and source are same, etc)
  3099. dst = dynamic_cast<const CArmedInstance*>(getObj(dstid));
  3100. assert(dw && dst);
  3101. //verify
  3102. bool found = false;
  3103. int level = 0;
  3104. for (; level < dw->creatures.size(); level++) //iterate through all levels
  3105. {
  3106. if ((fromLvl != -1) && (level !=fromLvl))
  3107. continue;
  3108. const auto &cur = dw->creatures.at(level); //current level info <amount, list of cr. ids>
  3109. int i = 0;
  3110. for (; i < cur.second.size(); i++) //look for crid among available creatures list on current level
  3111. if (cur.second.at(i) == crid)
  3112. break;
  3113. if (i < cur.second.size())
  3114. {
  3115. found = true;
  3116. cram = std::min(cram, cur.first); //reduce recruited amount up to available amount
  3117. break;
  3118. }
  3119. }
  3120. SlotID slot = dst->getSlotFor(crid);
  3121. if ((!found && complain("Cannot recruit: no such creatures!"))
  3122. || ((si32)cram > VLC->creh->objects.at(crid)->maxAmount(getPlayerState(dst->tempOwner)->resources) && complain("Cannot recruit: lack of resources!"))
  3123. || (cram<=0 && complain("Cannot recruit: cram <= 0!"))
  3124. || (!slot.validSlot() && !warMachine && complain("Cannot recruit: no available slot!")))
  3125. {
  3126. return false;
  3127. }
  3128. //recruit
  3129. giveResources(dst->tempOwner, -(c->getFullRecruitCost() * cram));
  3130. SetAvailableCreatures sac;
  3131. sac.tid = objid;
  3132. sac.creatures = dw->creatures;
  3133. sac.creatures[level].first -= cram;
  3134. sendAndApply(&sac);
  3135. if (warMachine)
  3136. {
  3137. const CGHeroInstance *h = dynamic_cast<const CGHeroInstance*>(dst);
  3138. COMPLAIN_RET_FALSE_IF(!h, "Only hero can buy war machines");
  3139. ArtifactID artId = c->warMachine;
  3140. COMPLAIN_RET_FALSE_IF(artId == ArtifactID::CATAPULT, "Catapult cannot be recruited!");
  3141. const CArtifact * art = artId.toArtifact();
  3142. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid war machine artifact");
  3143. return giveHeroNewArtifact(h, art);
  3144. }
  3145. else
  3146. {
  3147. addToSlot(StackLocation(dst, slot), c, cram);
  3148. }
  3149. return true;
  3150. }
  3151. bool CGameHandler::upgradeCreature(ObjectInstanceID objid, SlotID pos, CreatureID upgID)
  3152. {
  3153. const CArmedInstance * obj = static_cast<const CArmedInstance *>(getObjInstance(objid));
  3154. if (!obj->hasStackAtSlot(pos))
  3155. {
  3156. COMPLAIN_RET("Cannot upgrade, no stack at slot " + boost::to_string(pos));
  3157. }
  3158. UpgradeInfo ui;
  3159. fillUpgradeInfo(obj, pos, ui);
  3160. PlayerColor player = obj->tempOwner;
  3161. const PlayerState *p = getPlayerState(player);
  3162. int crQuantity = obj->stacks.at(pos)->count;
  3163. int newIDpos= vstd::find_pos(ui.newID, upgID);//get position of new id in UpgradeInfo
  3164. //check if upgrade is possible
  3165. if ((ui.oldID<0 || newIDpos == -1) && complain("That upgrade is not possible!"))
  3166. {
  3167. return false;
  3168. }
  3169. TResources totalCost = ui.cost.at(newIDpos) * crQuantity;
  3170. //check if player has enough resources
  3171. if (!p->resources.canAfford(totalCost))
  3172. COMPLAIN_RET("Cannot upgrade, not enough resources!");
  3173. //take resources
  3174. giveResources(player, -totalCost);
  3175. //upgrade creature
  3176. changeStackType(StackLocation(obj, pos), VLC->creh->objects.at(upgID));
  3177. return true;
  3178. }
  3179. bool CGameHandler::changeStackType(const StackLocation &sl, const CCreature *c)
  3180. {
  3181. if (!sl.army->hasStackAtSlot(sl.slot))
  3182. COMPLAIN_RET("Cannot find a stack to change type");
  3183. SetStackType sst;
  3184. sst.army = sl.army->id;
  3185. sst.slot = sl.slot;
  3186. sst.type = c->getId();
  3187. sendAndApply(&sst);
  3188. return true;
  3189. }
  3190. void CGameHandler::moveArmy(const CArmedInstance *src, const CArmedInstance *dst, bool allowMerging)
  3191. {
  3192. assert(src->canBeMergedWith(*dst, allowMerging));
  3193. while(src->stacksCount())//while there are unmoved creatures
  3194. {
  3195. auto i = src->Slots().begin(); //iterator to stack to move
  3196. StackLocation sl(src, i->first); //location of stack to move
  3197. SlotID pos = dst->getSlotFor(i->second->type);
  3198. if (!pos.validSlot())
  3199. {
  3200. //try to merge two other stacks to make place
  3201. std::pair<SlotID, SlotID> toMerge;
  3202. if (dst->mergableStacks(toMerge, i->first) && allowMerging)
  3203. {
  3204. moveStack(StackLocation(dst, toMerge.first), StackLocation(dst, toMerge.second)); //merge toMerge.first into toMerge.second
  3205. assert(!dst->hasStackAtSlot(toMerge.first)); //we have now a new free slot
  3206. moveStack(sl, StackLocation(dst, toMerge.first)); //move stack to freed slot
  3207. }
  3208. else
  3209. {
  3210. complain("Unexpected failure during an attempt to move army from " + src->nodeName() + " to " + dst->nodeName() + "!");
  3211. return;
  3212. }
  3213. }
  3214. else
  3215. {
  3216. moveStack(sl, StackLocation(dst, pos));
  3217. }
  3218. }
  3219. }
  3220. bool CGameHandler::swapGarrisonOnSiege(ObjectInstanceID tid)
  3221. {
  3222. const CGTownInstance * town = getTown(tid);
  3223. if(!town->garrisonHero == !town->visitingHero)
  3224. return false;
  3225. SetHeroesInTown intown;
  3226. intown.tid = tid;
  3227. if(town->garrisonHero) //garrison -> vising
  3228. {
  3229. intown.garrison = ObjectInstanceID();
  3230. intown.visiting = town->garrisonHero->id;
  3231. }
  3232. else //visiting -> garrison
  3233. {
  3234. if(town->armedGarrison())
  3235. town->mergeGarrisonOnSiege();
  3236. intown.visiting = ObjectInstanceID();
  3237. intown.garrison = town->visitingHero->id;
  3238. }
  3239. sendAndApply(&intown);
  3240. return true;
  3241. }
  3242. bool CGameHandler::garrisonSwap(ObjectInstanceID tid)
  3243. {
  3244. const CGTownInstance * town = getTown(tid);
  3245. if (!town->garrisonHero && town->visitingHero) //visiting => garrison, merge armies: town army => hero army
  3246. {
  3247. if (!town->visitingHero->canBeMergedWith(*town))
  3248. {
  3249. complain("Cannot make garrison swap, not enough free slots!");
  3250. return false;
  3251. }
  3252. moveArmy(town, town->visitingHero, true);
  3253. SetHeroesInTown intown;
  3254. intown.tid = tid;
  3255. intown.visiting = ObjectInstanceID();
  3256. intown.garrison = town->visitingHero->id;
  3257. sendAndApply(&intown);
  3258. return true;
  3259. }
  3260. else if (town->garrisonHero && !town->visitingHero) //move hero out of the garrison
  3261. {
  3262. //check if moving hero out of town will break 8 wandering heroes limit
  3263. if (getHeroCount(town->garrisonHero->tempOwner,false) >= 8)
  3264. {
  3265. complain("Cannot move hero out of the garrison, there are already 8 wandering heroes!");
  3266. return false;
  3267. }
  3268. SetHeroesInTown intown;
  3269. intown.tid = tid;
  3270. intown.garrison = ObjectInstanceID();
  3271. intown.visiting = town->garrisonHero->id;
  3272. sendAndApply(&intown);
  3273. return true;
  3274. }
  3275. else if (!!town->garrisonHero && town->visitingHero) //swap visiting and garrison hero
  3276. {
  3277. SetHeroesInTown intown;
  3278. intown.tid = tid;
  3279. intown.garrison = town->visitingHero->id;
  3280. intown.visiting = town->garrisonHero->id;
  3281. sendAndApply(&intown);
  3282. return true;
  3283. }
  3284. else
  3285. {
  3286. complain("Cannot swap garrison hero!");
  3287. return false;
  3288. }
  3289. }
  3290. // With the amount of changes done to the function, it's more like transferArtifacts.
  3291. // 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.
  3292. bool CGameHandler::moveArtifact(const ArtifactLocation &al1, const ArtifactLocation &al2)
  3293. {
  3294. ArtifactLocation src = al1, dst = al2;
  3295. const PlayerColor srcPlayer = src.owningPlayer(), dstPlayer = dst.owningPlayer();
  3296. const CArmedInstance *srcObj = src.relatedObj(), *dstObj = dst.relatedObj();
  3297. // Make sure exchange is even possible between the two heroes.
  3298. if(!isAllowedExchange(srcObj->id, dstObj->id))
  3299. COMPLAIN_RET("That heroes cannot make any exchange!");
  3300. const CArtifactInstance *srcArtifact = src.getArt();
  3301. const CArtifactInstance *destArtifact = dst.getArt();
  3302. const bool isDstSlotBackpack = ArtifactUtils::isSlotBackpack(dst.slot);
  3303. if(srcArtifact == nullptr)
  3304. COMPLAIN_RET("No artifact to move!");
  3305. if(destArtifact && srcPlayer != dstPlayer && !isDstSlotBackpack)
  3306. COMPLAIN_RET("Can't touch artifact on hero of another player!");
  3307. // Check if src/dest slots are appropriate for the artifacts exchanged.
  3308. // Moving to the backpack is always allowed.
  3309. if((!srcArtifact || !isDstSlotBackpack)
  3310. && srcArtifact && !srcArtifact->canBePutAt(dst, true))
  3311. COMPLAIN_RET("Cannot move artifact!");
  3312. auto srcSlot = src.getSlot();
  3313. auto dstSlot = dst.getSlot();
  3314. if((srcSlot && srcSlot->locked) || (dstSlot && dstSlot->locked))
  3315. COMPLAIN_RET("Cannot move artifact locks.");
  3316. if(isDstSlotBackpack && srcArtifact->artType->isBig())
  3317. COMPLAIN_RET("Cannot put big artifacts in backpack!");
  3318. if(src.slot == ArtifactPosition::MACH4 || dst.slot == ArtifactPosition::MACH4)
  3319. COMPLAIN_RET("Cannot move catapult!");
  3320. if(isDstSlotBackpack)
  3321. {
  3322. if(!ArtifactUtils::isBackpackFreeSlots(dst.getHolderArtSet()))
  3323. COMPLAIN_RET("Backpack is full!");
  3324. vstd::amin(dst.slot, GameConstants::BACKPACK_START + dst.getHolderArtSet()->artifactsInBackpack.size());
  3325. }
  3326. if(!(src.slot == ArtifactPosition::TRANSITION_POS && dst.slot == ArtifactPosition::TRANSITION_POS))
  3327. {
  3328. if(src.slot == dst.slot && src.artHolder == dst.artHolder)
  3329. COMPLAIN_RET("Won't move artifact: Dest same as source!");
  3330. // Check if dst slot is occupied
  3331. if(!isDstSlotBackpack && destArtifact)
  3332. {
  3333. // Previous artifact must be removed first
  3334. moveArtifact(dst, ArtifactLocation(dst.artHolder, ArtifactPosition::TRANSITION_POS));
  3335. }
  3336. try
  3337. {
  3338. auto hero = std::get<ConstTransitivePtr<CGHeroInstance>>(dst.artHolder);
  3339. if(ArtifactUtils::checkSpellbookIsNeeded(hero, srcArtifact->artType->getId(), dst.slot))
  3340. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3341. }
  3342. catch(const std::bad_variant_access &)
  3343. {
  3344. // object other than hero received an art - ignore
  3345. }
  3346. MoveArtifact ma(&src, &dst);
  3347. if(dst.slot == ArtifactPosition::TRANSITION_POS)
  3348. ma.askAssemble = false;
  3349. sendAndApply(&ma);
  3350. }
  3351. return true;
  3352. }
  3353. bool CGameHandler::bulkMoveArtifacts(ObjectInstanceID srcHero, ObjectInstanceID dstHero, bool swap)
  3354. {
  3355. // Make sure exchange is even possible between the two heroes.
  3356. if(!isAllowedExchange(srcHero, dstHero))
  3357. COMPLAIN_RET("That heroes cannot make any exchange!");
  3358. auto psrcHero = getHero(srcHero);
  3359. auto pdstHero = getHero(dstHero);
  3360. if((!psrcHero) || (!pdstHero))
  3361. COMPLAIN_RET("bulkMoveArtifacts: wrong hero's ID");
  3362. BulkMoveArtifacts ma(static_cast<ConstTransitivePtr<CGHeroInstance>>(psrcHero),
  3363. static_cast<ConstTransitivePtr<CGHeroInstance>>(pdstHero), swap);
  3364. auto & slotsSrcDst = ma.artsPack0;
  3365. auto & slotsDstSrc = ma.artsPack1;
  3366. // Temporary fitting set for artifacts. Used to select available slots before sending data.
  3367. CArtifactFittingSet artFittingSet(pdstHero->bearerType());
  3368. auto moveArtifact = [this, &artFittingSet](const CArtifactInstance * artifact,
  3369. ArtifactPosition srcSlot, const CGHeroInstance * dstHero,
  3370. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3371. {
  3372. assert(artifact);
  3373. auto dstSlot = ArtifactUtils::getArtAnyPosition(&artFittingSet, artifact->getTypeId());
  3374. if(dstSlot != ArtifactPosition::PRE_FIRST)
  3375. {
  3376. artFittingSet.putArtifact(dstSlot, static_cast<ConstTransitivePtr<CArtifactInstance>>(artifact));
  3377. slots.push_back(BulkMoveArtifacts::LinkedSlots(srcSlot, dstSlot));
  3378. if(ArtifactUtils::checkSpellbookIsNeeded(dstHero, artifact->getTypeId(), dstSlot))
  3379. giveHeroNewArtifact(dstHero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3380. }
  3381. };
  3382. if(swap)
  3383. {
  3384. auto moveArtsWorn = [moveArtifact](const CGHeroInstance * srcHero, const CGHeroInstance * dstHero,
  3385. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3386. {
  3387. for(auto & artifact : srcHero->artifactsWorn)
  3388. {
  3389. if(ArtifactUtils::isArtRemovable(artifact))
  3390. moveArtifact(artifact.second.getArt(), artifact.first, dstHero, slots);
  3391. }
  3392. };
  3393. auto moveArtsInBackpack = [](const CArtifactSet * artSet,
  3394. std::vector<BulkMoveArtifacts::LinkedSlots> & slots) -> void
  3395. {
  3396. for(auto & slotInfo : artSet->artifactsInBackpack)
  3397. {
  3398. auto slot = artSet->getArtPos(slotInfo.artifact);
  3399. slots.push_back(BulkMoveArtifacts::LinkedSlots(slot, slot));
  3400. }
  3401. };
  3402. // Move over artifacts that are worn srcHero -> dstHero
  3403. moveArtsWorn(psrcHero, pdstHero, slotsSrcDst);
  3404. artFittingSet.artifactsWorn.clear();
  3405. // Move over artifacts that are worn dstHero -> srcHero
  3406. moveArtsWorn(pdstHero, psrcHero, slotsDstSrc);
  3407. // Move over artifacts that are in backpack srcHero -> dstHero
  3408. moveArtsInBackpack(psrcHero, slotsSrcDst);
  3409. // Move over artifacts that are in backpack dstHero -> srcHero
  3410. moveArtsInBackpack(pdstHero, slotsDstSrc);
  3411. }
  3412. else
  3413. {
  3414. artFittingSet.artifactsInBackpack = pdstHero->artifactsInBackpack;
  3415. artFittingSet.artifactsWorn = pdstHero->artifactsWorn;
  3416. // Move over artifacts that are worn
  3417. for(auto & artInfo : psrcHero->artifactsWorn)
  3418. {
  3419. if(ArtifactUtils::isArtRemovable(artInfo))
  3420. {
  3421. moveArtifact(psrcHero->getArt(artInfo.first), artInfo.first, pdstHero, slotsSrcDst);
  3422. }
  3423. }
  3424. // Move over artifacts that are in backpack
  3425. for(auto & slotInfo : psrcHero->artifactsInBackpack)
  3426. {
  3427. moveArtifact(psrcHero->getArt(psrcHero->getArtPos(slotInfo.artifact)),
  3428. psrcHero->getArtPos(slotInfo.artifact), pdstHero, slotsSrcDst);
  3429. }
  3430. }
  3431. sendAndApply(&ma);
  3432. return true;
  3433. }
  3434. /**
  3435. * Assembles or disassembles a combination artifact.
  3436. * @param heroID ID of hero holding the artifact(s).
  3437. * @param artifactSlot The worn slot ID of the combination- or constituent artifact.
  3438. * @param assemble True for assembly operation, false for disassembly.
  3439. * @param assembleTo If assemble is true, this represents the artifact ID of the combination
  3440. * artifact to assemble to. Otherwise it's not used.
  3441. */
  3442. bool CGameHandler::assembleArtifacts (ObjectInstanceID heroID, ArtifactPosition artifactSlot, bool assemble, ArtifactID assembleTo)
  3443. {
  3444. const CGHeroInstance * hero = getHero(heroID);
  3445. const CArtifactInstance * destArtifact = hero->getArt(artifactSlot);
  3446. if(!destArtifact)
  3447. COMPLAIN_RET("assembleArtifacts: there is no such artifact instance!");
  3448. if(assemble)
  3449. {
  3450. CArtifact * combinedArt = VLC->arth->objects[assembleTo];
  3451. if(!combinedArt->isCombined())
  3452. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to assemble is not a combined artifacts!");
  3453. if (!vstd::contains(ArtifactUtils::assemblyPossibilities(hero, destArtifact->getTypeId(),
  3454. ArtifactUtils::isSlotEquipment(artifactSlot)), combinedArt))
  3455. {
  3456. COMPLAIN_RET("assembleArtifacts: It's impossible to assemble requested artifact!");
  3457. }
  3458. if(ArtifactUtils::checkSpellbookIsNeeded(hero, assembleTo, artifactSlot))
  3459. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3460. AssembledArtifact aa;
  3461. aa.al = ArtifactLocation(hero, artifactSlot);
  3462. aa.builtArt = combinedArt;
  3463. sendAndApply(&aa);
  3464. }
  3465. else
  3466. {
  3467. if(!destArtifact->isCombined())
  3468. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble is not a combined artifact!");
  3469. if(ArtifactUtils::isSlotBackpack(artifactSlot)
  3470. && !ArtifactUtils::isBackpackFreeSlots(hero, destArtifact->artType->getConstituents().size() - 1))
  3471. COMPLAIN_RET("assembleArtifacts: Artifact being attempted to disassemble but backpack is full!");
  3472. DisassembledArtifact da;
  3473. da.al = ArtifactLocation(hero, artifactSlot);
  3474. sendAndApply(&da);
  3475. }
  3476. return true;
  3477. }
  3478. bool CGameHandler::eraseArtifactByClient(const ArtifactLocation & al)
  3479. {
  3480. const auto * hero = getHero(al.relatedObj()->id);
  3481. if(hero == nullptr)
  3482. COMPLAIN_RET("eraseArtifactByClient: wrong hero's ID");
  3483. const auto * art = al.getArt();
  3484. if(art == nullptr)
  3485. COMPLAIN_RET("Cannot remove artifact!");
  3486. if(al.getArt()->artType->canBePutAt(hero) || al.slot != ArtifactPosition::TRANSITION_POS)
  3487. COMPLAIN_RET("Illegal artifact removal request");
  3488. removeArtifact(al);
  3489. return true;
  3490. }
  3491. bool CGameHandler::buyArtifact(ObjectInstanceID hid, ArtifactID aid)
  3492. {
  3493. const CGHeroInstance * hero = getHero(hid);
  3494. COMPLAIN_RET_FALSE_IF(nullptr == hero, "Invalid hero index");
  3495. const CGTownInstance * town = hero->visitedTown;
  3496. COMPLAIN_RET_FALSE_IF(nullptr == town, "Hero not in town");
  3497. if (aid==ArtifactID::SPELLBOOK)
  3498. {
  3499. if ((!town->hasBuilt(BuildingID::MAGES_GUILD_1) && complain("Cannot buy a spellbook, no mage guild in the town!"))
  3500. || (getResource(hero->getOwner(), EGameResID::GOLD) < GameConstants::SPELLBOOK_GOLD_COST && complain("Cannot buy a spellbook, not enough gold!"))
  3501. || (hero->getArt(ArtifactPosition::SPELLBOOK) && complain("Cannot buy a spellbook, hero already has a one!"))
  3502. )
  3503. return false;
  3504. giveResource(hero->getOwner(),EGameResID::GOLD,-GameConstants::SPELLBOOK_GOLD_COST);
  3505. giveHeroNewArtifact(hero, VLC->arth->objects[ArtifactID::SPELLBOOK], ArtifactPosition::SPELLBOOK);
  3506. assert(hero->getArt(ArtifactPosition::SPELLBOOK));
  3507. giveSpells(town,hero);
  3508. return true;
  3509. }
  3510. else
  3511. {
  3512. const CArtifact * art = aid.toArtifact();
  3513. COMPLAIN_RET_FALSE_IF(nullptr == art, "Invalid artifact index to buy");
  3514. COMPLAIN_RET_FALSE_IF(art->getWarMachine() == CreatureID::NONE, "War machine artifact required");
  3515. COMPLAIN_RET_FALSE_IF(hero->hasArt(aid),"Hero already has this machine!");
  3516. const int price = art->getPrice();
  3517. COMPLAIN_RET_FALSE_IF(getPlayerState(hero->getOwner())->resources[EGameResID::GOLD] < price, "Not enough gold!");
  3518. if ((town->hasBuilt(BuildingID::BLACKSMITH) && town->town->warMachine == aid)
  3519. || (town->hasBuilt(BuildingSubID::BALLISTA_YARD) && aid == ArtifactID::BALLISTA))
  3520. {
  3521. giveResource(hero->getOwner(),EGameResID::GOLD,-price);
  3522. return giveHeroNewArtifact(hero, art);
  3523. }
  3524. else
  3525. COMPLAIN_RET("This machine is unavailable here!");
  3526. }
  3527. }
  3528. bool CGameHandler::buyArtifact(const IMarket *m, const CGHeroInstance *h, GameResID rid, ArtifactID aid)
  3529. {
  3530. if(!h)
  3531. COMPLAIN_RET("Only hero can buy artifacts!");
  3532. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_ARTIFACT), aid))
  3533. COMPLAIN_RET("That artifact is unavailable!");
  3534. int b1, b2;
  3535. m->getOffer(rid, aid, b1, b2, EMarketMode::RESOURCE_ARTIFACT);
  3536. if (getResource(h->tempOwner, rid) < b1)
  3537. COMPLAIN_RET("You can't afford to buy this artifact!");
  3538. giveResource(h->tempOwner, rid, -b1);
  3539. SetAvailableArtifacts saa;
  3540. if(dynamic_cast<const CGTownInstance *>(m))
  3541. {
  3542. saa.id = -1;
  3543. saa.arts = CGTownInstance::merchantArtifacts;
  3544. }
  3545. else if(const CGBlackMarket *bm = dynamic_cast<const CGBlackMarket *>(m)) //black market
  3546. {
  3547. saa.id = bm->id.getNum();
  3548. saa.arts = bm->artifacts;
  3549. }
  3550. else
  3551. COMPLAIN_RET("Wrong marktet...");
  3552. bool found = false;
  3553. for (const CArtifact *&art : saa.arts)
  3554. {
  3555. if (art && art->getId() == aid)
  3556. {
  3557. art = nullptr;
  3558. found = true;
  3559. break;
  3560. }
  3561. }
  3562. if (!found)
  3563. COMPLAIN_RET("Cannot find selected artifact on the list");
  3564. sendAndApply(&saa);
  3565. giveHeroNewArtifact(h, VLC->arth->objects[aid], ArtifactPosition::FIRST_AVAILABLE);
  3566. return true;
  3567. }
  3568. bool CGameHandler::sellArtifact(const IMarket *m, const CGHeroInstance *h, ArtifactInstanceID aid, GameResID rid)
  3569. {
  3570. COMPLAIN_RET_FALSE_IF((!h), "Only hero can sell artifacts!");
  3571. const CArtifactInstance *art = h->getArtByInstanceId(aid);
  3572. COMPLAIN_RET_FALSE_IF((!art), "There is no artifact to sell!");
  3573. COMPLAIN_RET_FALSE_IF((!art->artType->isTradable()), "Cannot sell a war machine or spellbook!");
  3574. int resVal = 0, dump = 1;
  3575. m->getOffer(art->artType->getId(), rid, dump, resVal, EMarketMode::ARTIFACT_RESOURCE);
  3576. removeArtifact(ArtifactLocation(h, h->getArtPos(art)));
  3577. giveResource(h->tempOwner, rid, resVal);
  3578. return true;
  3579. }
  3580. bool CGameHandler::buySecSkill(const IMarket *m, const CGHeroInstance *h, SecondarySkill skill)
  3581. {
  3582. if (!h)
  3583. COMPLAIN_RET("You need hero to buy a skill!");
  3584. if (h->getSecSkillLevel(SecondarySkill(skill)))
  3585. COMPLAIN_RET("Hero already know this skill");
  3586. if (!h->canLearnSkill())
  3587. COMPLAIN_RET("Hero can't learn any more skills");
  3588. if (!h->canLearnSkill(skill))
  3589. COMPLAIN_RET("The hero can't learn this skill!");
  3590. if (!vstd::contains(m->availableItemsIds(EMarketMode::RESOURCE_SKILL), skill))
  3591. COMPLAIN_RET("That skill is unavailable!");
  3592. if (getResource(h->tempOwner, EGameResID::GOLD) < GameConstants::SKILL_GOLD_COST)//TODO: remove hardcoded resource\summ?
  3593. COMPLAIN_RET("You can't afford to buy this skill");
  3594. giveResource(h->tempOwner, EGameResID::GOLD, -GameConstants::SKILL_GOLD_COST);
  3595. changeSecSkill(h, skill, 1, true);
  3596. return true;
  3597. }
  3598. bool CGameHandler::tradeResources(const IMarket *market, ui32 val, PlayerColor player, ui32 id1, ui32 id2)
  3599. {
  3600. TResourceCap r1 = getPlayerState(player)->resources[id1];
  3601. vstd::amin(val, r1); //can't trade more resources than have
  3602. int b1, b2; //base quantities for trade
  3603. market->getOffer(id1, id2, b1, b2, EMarketMode::RESOURCE_RESOURCE);
  3604. int units = val / b1; //how many base quantities we trade
  3605. if (val%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3606. {
  3607. COMPLAIN_RET("Invalid deal, not all offered units of resource were used.");
  3608. }
  3609. giveResource(player, GameResID(id1), - b1 * units);
  3610. giveResource(player, GameResID(id2), b2 * units);
  3611. return true;
  3612. }
  3613. bool CGameHandler::sellCreatures(ui32 count, const IMarket *market, const CGHeroInstance * hero, SlotID slot, GameResID resourceID)
  3614. {
  3615. if(!hero)
  3616. COMPLAIN_RET("Only hero can sell creatures!");
  3617. if (!vstd::contains(hero->Slots(), slot))
  3618. COMPLAIN_RET("Hero doesn't have any creature in that slot!");
  3619. const CStackInstance &s = hero->getStack(slot);
  3620. if (s.count < (TQuantity)count //can't sell more creatures than have
  3621. || (hero->stacksCount() == 1 && hero->needsLastStack() && s.count == count)) //can't sell last stack
  3622. {
  3623. COMPLAIN_RET("Not enough creatures in army!");
  3624. }
  3625. int b1, b2; //base quantities for trade
  3626. market->getOffer(s.type->getId(), resourceID, b1, b2, EMarketMode::CREATURE_RESOURCE);
  3627. int units = count / b1; //how many base quantities we trade
  3628. if (count%b1) //all offered units of resource should be used, if not -> somewhere in calculations must be an error
  3629. {
  3630. //TODO: complain?
  3631. assert(0);
  3632. }
  3633. changeStackCount(StackLocation(hero, slot), -(TQuantity)count);
  3634. giveResource(hero->tempOwner, resourceID, b2 * units);
  3635. return true;
  3636. }
  3637. bool CGameHandler::transformInUndead(const IMarket *market, const CGHeroInstance * hero, SlotID slot)
  3638. {
  3639. const CArmedInstance *army = nullptr;
  3640. if (hero)
  3641. army = hero;
  3642. else
  3643. army = dynamic_cast<const CGTownInstance *>(market);
  3644. if (!army)
  3645. COMPLAIN_RET("Incorrect call to transform in undead!");
  3646. if (!army->hasStackAtSlot(slot))
  3647. COMPLAIN_RET("Army doesn't have any creature in that slot!");
  3648. const CStackInstance &s = army->getStack(slot);
  3649. //resulting creature - bone dragons or skeletons
  3650. CreatureID resCreature = CreatureID::SKELETON;
  3651. if ((s.hasBonusOfType(BonusType::DRAGON_NATURE)
  3652. && !(s.hasBonusOfType(BonusType::UNDEAD)))
  3653. || (s.getCreatureID() == CreatureID::HYDRA)
  3654. || (s.getCreatureID() == CreatureID::CHAOS_HYDRA))
  3655. resCreature = CreatureID::BONE_DRAGON;
  3656. changeStackType(StackLocation(army, slot), resCreature.toCreature());
  3657. return true;
  3658. }
  3659. bool CGameHandler::sendResources(ui32 val, PlayerColor player, GameResID r1, PlayerColor r2)
  3660. {
  3661. const PlayerState *p2 = getPlayerState(r2, false);
  3662. if (!p2 || p2->status != EPlayerStatus::INGAME)
  3663. {
  3664. complain("Dest player must be in game!");
  3665. return false;
  3666. }
  3667. TResourceCap curRes1 = getPlayerState(player)->resources[r1];
  3668. vstd::amin(val, curRes1);
  3669. giveResource(player, r1, -(int)val);
  3670. giveResource(r2, r1, val);
  3671. return true;
  3672. }
  3673. bool CGameHandler::setFormation(ObjectInstanceID hid, ui8 formation)
  3674. {
  3675. const CGHeroInstance *h = getHero(hid);
  3676. if (!h)
  3677. {
  3678. logGlobal->error("Hero doesn't exist!");
  3679. return false;
  3680. }
  3681. ChangeFormation cf;
  3682. cf.hid = hid;
  3683. cf.formation = formation;
  3684. sendAndApply(&cf);
  3685. return true;
  3686. }
  3687. bool CGameHandler::queryReply(QueryID qid, const JsonNode & answer, PlayerColor player)
  3688. {
  3689. boost::unique_lock<boost::recursive_mutex> lock(gsm);
  3690. logGlobal->trace("Player %s attempts answering query %d with answer:", player, qid);
  3691. logGlobal->trace(answer.toJson());
  3692. auto topQuery = queries.topQuery(player);
  3693. COMPLAIN_RET_FALSE_IF(!topQuery, "This player doesn't have any queries!");
  3694. if(topQuery->queryID != qid)
  3695. {
  3696. auto currentQuery = queries.getQuery(qid);
  3697. if(currentQuery != nullptr && currentQuery->endsByPlayerAnswer())
  3698. currentQuery->setReply(answer);
  3699. COMPLAIN_RET("This player top query has different ID!"); //topQuery->queryID != qid
  3700. }
  3701. COMPLAIN_RET_FALSE_IF(!topQuery->endsByPlayerAnswer(), "This query cannot be ended by player's answer!");
  3702. topQuery->setReply(answer);
  3703. queries.popQuery(topQuery);
  3704. return true;
  3705. }
  3706. static EndAction end_action;
  3707. void CGameHandler::updateGateState()
  3708. {
  3709. // GATE_BRIDGE - leftmost tile, located over moat
  3710. // GATE_OUTER - central tile, mostly covered by gate image
  3711. // GATE_INNER - rightmost tile, inside the walls
  3712. // GATE_OUTER or GATE_INNER:
  3713. // - if defender moves unit on these tiles, bridge will open
  3714. // - if there is a creature (dead or alive) on these tiles, bridge will always remain open
  3715. // - blocked to attacker if bridge is closed
  3716. // GATE_BRIDGE
  3717. // - if there is a unit or corpse here, bridge can't open (and can't close in fortress)
  3718. // - if Force Field is cast here, bridge can't open (but can close, in any town)
  3719. // - deals moat damage to attacker if bridge is closed (fortress only)
  3720. bool hasForceFieldOnBridge = !battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), true).empty();
  3721. bool hasStackAtGateInner = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_INNER), false) != nullptr;
  3722. bool hasStackAtGateOuter = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_OUTER), false) != nullptr;
  3723. bool hasStackAtGateBridge = gs->curB->battleGetUnitByPos(BattleHex(ESiegeHex::GATE_BRIDGE), false) != nullptr;
  3724. bool hasWideMoat = vstd::contains_if(battleGetAllObstaclesOnPos(BattleHex(ESiegeHex::GATE_BRIDGE), false), [](const std::shared_ptr<const CObstacleInstance> & obst)
  3725. {
  3726. return obst->obstacleType == CObstacleInstance::MOAT;
  3727. });
  3728. BattleUpdateGateState db;
  3729. db.state = gs->curB->si.gateState;
  3730. if (gs->curB->si.wallState[EWallPart::GATE] == EWallState::DESTROYED)
  3731. {
  3732. db.state = EGateState::DESTROYED;
  3733. }
  3734. else if (db.state == EGateState::OPENED)
  3735. {
  3736. bool hasStackOnLongBridge = hasStackAtGateBridge && hasWideMoat;
  3737. bool gateCanClose = !hasStackAtGateInner && !hasStackAtGateOuter && !hasStackOnLongBridge;
  3738. if (gateCanClose)
  3739. db.state = EGateState::CLOSED;
  3740. else
  3741. db.state = EGateState::OPENED;
  3742. }
  3743. else // CLOSED or BLOCKED
  3744. {
  3745. bool gateBlocked = hasForceFieldOnBridge || hasStackAtGateBridge;
  3746. if (gateBlocked)
  3747. db.state = EGateState::BLOCKED;
  3748. else
  3749. db.state = EGateState::CLOSED;
  3750. }
  3751. if (db.state != gs->curB->si.gateState)
  3752. sendAndApply(&db);
  3753. }
  3754. bool CGameHandler::makeBattleAction(BattleAction &ba)
  3755. {
  3756. bool ok = true;
  3757. battle::Target target = ba.getTarget(gs->curB);
  3758. const CStack * stack = battleGetStackByID(ba.stackNumber); //may be nullptr if action is not about stack
  3759. const bool isAboutActiveStack = stack && (ba.stackNumber == gs->curB->getActiveStackID());
  3760. logGlobal->trace("Making action: %s", ba.toString());
  3761. switch(ba.actionType)
  3762. {
  3763. case EActionType::WALK: //walk
  3764. case EActionType::DEFEND: //defend
  3765. case EActionType::WAIT: //wait
  3766. case EActionType::WALK_AND_ATTACK: //walk or attack
  3767. case EActionType::SHOOT: //shoot
  3768. case EActionType::CATAPULT: //catapult
  3769. case EActionType::STACK_HEAL: //healing with First Aid Tent
  3770. case EActionType::MONSTER_SPELL:
  3771. if (!stack)
  3772. {
  3773. complain("No such stack!");
  3774. return false;
  3775. }
  3776. if (!stack->alive())
  3777. {
  3778. complain("This stack is dead: " + stack->nodeName());
  3779. return false;
  3780. }
  3781. if (battleTacticDist())
  3782. {
  3783. if (stack && stack->unitSide() != battleGetTacticsSide())
  3784. {
  3785. complain("This is not a stack of side that has tactics!");
  3786. return false;
  3787. }
  3788. }
  3789. else if (!isAboutActiveStack)
  3790. {
  3791. complain("Action has to be about active stack!");
  3792. return false;
  3793. }
  3794. }
  3795. auto wrapAction = [this](BattleAction &ba)
  3796. {
  3797. StartAction startAction(ba);
  3798. sendAndApply(&startAction);
  3799. return vstd::makeScopeGuard([&]()
  3800. {
  3801. sendAndApply(&end_action);
  3802. });
  3803. };
  3804. switch(ba.actionType)
  3805. {
  3806. case EActionType::END_TACTIC_PHASE: //wait
  3807. case EActionType::BAD_MORALE:
  3808. case EActionType::NO_ACTION:
  3809. {
  3810. auto wrapper = wrapAction(ba);
  3811. break;
  3812. }
  3813. case EActionType::WALK:
  3814. {
  3815. auto wrapper = wrapAction(ba);
  3816. if(target.size() < 1)
  3817. {
  3818. complain("Destination required for move action.");
  3819. ok = false;
  3820. break;
  3821. }
  3822. int walkedTiles = moveStack(ba.stackNumber, target.at(0).hexValue); //move
  3823. if (!walkedTiles)
  3824. complain("Stack failed movement!");
  3825. break;
  3826. }
  3827. case EActionType::DEFEND:
  3828. {
  3829. //defensive stance, TODO: filter out spell boosts from bonus (stone skin etc.)
  3830. SetStackEffect sse;
  3831. Bonus defenseBonusToAdd(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 20, -1, PrimarySkill::DEFENSE, BonusValueType::PERCENT_TO_ALL);
  3832. Bonus bonus2(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, stack->valOfBonuses(BonusType::DEFENSIVE_STANCE),
  3833. -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  3834. Bonus alternativeWeakCreatureBonus(BonusDuration::STACK_GETS_TURN, BonusType::PRIMARY_SKILL, BonusSource::OTHER, 1, -1, PrimarySkill::DEFENSE, BonusValueType::ADDITIVE_VALUE);
  3835. BonusList defence = *stack->getBonuses(Selector::typeSubtype(BonusType::PRIMARY_SKILL, PrimarySkill::DEFENSE));
  3836. int oldDefenceValue = defence.totalValue();
  3837. defence.push_back(std::make_shared<Bonus>(defenseBonusToAdd));
  3838. defence.push_back(std::make_shared<Bonus>(bonus2));
  3839. int difference = defence.totalValue() - oldDefenceValue;
  3840. std::vector<Bonus> buffer;
  3841. if(difference == 0) //give replacement bonus for creatures not reaching 5 defense points (20% of def becomes 0)
  3842. {
  3843. difference = 1;
  3844. buffer.push_back(alternativeWeakCreatureBonus);
  3845. }
  3846. else
  3847. {
  3848. buffer.push_back(defenseBonusToAdd);
  3849. }
  3850. buffer.push_back(bonus2);
  3851. sse.toUpdate.push_back(std::make_pair(ba.stackNumber, buffer));
  3852. sendAndApply(&sse);
  3853. BattleLogMessage message;
  3854. MetaString text;
  3855. stack->addText(text, EMetaText::GENERAL_TXT, 120);
  3856. stack->addNameReplacement(text);
  3857. text.replaceNumber(difference);
  3858. message.lines.push_back(text);
  3859. sendAndApply(&message);
  3860. //don't break - we share code with next case
  3861. }
  3862. [[fallthrough]];
  3863. case EActionType::WAIT:
  3864. {
  3865. auto wrapper = wrapAction(ba);
  3866. break;
  3867. }
  3868. case EActionType::RETREAT: //retreat/flee
  3869. {
  3870. if (!gs->curB->battleCanFlee(gs->curB->sides.at(ba.side).color))
  3871. complain("Cannot retreat!");
  3872. else
  3873. setBattleResult(BattleResult::ESCAPE, !ba.side); //surrendering side loses
  3874. break;
  3875. }
  3876. case EActionType::SURRENDER:
  3877. {
  3878. PlayerColor player = gs->curB->sides.at(ba.side).color;
  3879. int cost = gs->curB->battleGetSurrenderCost(player);
  3880. if (cost < 0)
  3881. complain("Cannot surrender!");
  3882. else if (getResource(player, EGameResID::GOLD) < cost)
  3883. complain("Not enough gold to surrender!");
  3884. else
  3885. {
  3886. giveResource(player, EGameResID::GOLD, -cost);
  3887. setBattleResult(BattleResult::SURRENDER, !ba.side); //surrendering side loses
  3888. }
  3889. break;
  3890. }
  3891. case EActionType::WALK_AND_ATTACK: //walk or attack
  3892. {
  3893. auto wrapper = wrapAction(ba);
  3894. if(!stack)
  3895. {
  3896. complain("No attacker");
  3897. ok = false;
  3898. break;
  3899. }
  3900. if(target.size() < 2)
  3901. {
  3902. complain("Two destinations required for attack action.");
  3903. ok = false;
  3904. break;
  3905. }
  3906. BattleHex attackPos = target.at(0).hexValue;
  3907. BattleHex destinationTile = target.at(1).hexValue;
  3908. const CStack * destinationStack = gs->curB->battleGetStackByPos(destinationTile, true);
  3909. if(!destinationStack)
  3910. {
  3911. complain("Invalid target to attack");
  3912. ok = false;
  3913. break;
  3914. }
  3915. BattleHex startingPos = stack->getPosition();
  3916. int distance = moveStack(ba.stackNumber, attackPos);
  3917. logGlobal->trace("%s will attack %s", stack->nodeName(), destinationStack->nodeName());
  3918. if(stack->getPosition() != attackPos
  3919. && !(stack->doubleWide() && (stack->getPosition() == attackPos.cloneInDirection(stack->destShiftDir(), false)))
  3920. )
  3921. {
  3922. // we were not able to reach destination tile, nor occupy specified hex
  3923. // abort attack attempt, but treat this case as legal - we may have stepped onto a quicksands/mine
  3924. break;
  3925. }
  3926. if(destinationStack && stack->unitId() == destinationStack->unitId()) //we should just move, it will be handled by following check
  3927. {
  3928. destinationStack = nullptr;
  3929. }
  3930. if(!destinationStack)
  3931. {
  3932. complain("Unit can not attack itself");
  3933. ok = false;
  3934. break;
  3935. }
  3936. if(!CStack::isMeleeAttackPossible(stack, destinationStack))
  3937. {
  3938. complain("Attack cannot be performed!");
  3939. ok = false;
  3940. break;
  3941. }
  3942. //attack
  3943. int totalAttacks = stack->totalAttacks.getMeleeValue();
  3944. //TODO: move to CUnitState
  3945. const auto * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  3946. if(attackingHero)
  3947. {
  3948. totalAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  3949. }
  3950. const bool firstStrike = destinationStack->hasBonusOfType(BonusType::FIRST_STRIKE);
  3951. const bool retaliation = destinationStack->ableToRetaliate();
  3952. for (int i = 0; i < totalAttacks; ++i)
  3953. {
  3954. //first strike
  3955. if(i == 0 && firstStrike && retaliation)
  3956. {
  3957. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  3958. }
  3959. //move can cause death, eg. by walking into the moat, first strike can cause death or paralysis/petrification
  3960. if(stack->alive() && !stack->hasBonusOfType(BonusType::NOT_ACTIVE) && destinationStack->alive())
  3961. {
  3962. makeAttack(stack, destinationStack, (i ? 0 : distance), destinationTile, i==0, false, false);//no distance travelled on second attack
  3963. }
  3964. //counterattack
  3965. //we check retaliation twice, so if it unblocked during attack it will work only on next attack
  3966. if(stack->alive()
  3967. && !stack->hasBonusOfType(BonusType::BLOCKS_RETALIATION)
  3968. && (i == 0 && !firstStrike)
  3969. && retaliation && destinationStack->ableToRetaliate())
  3970. {
  3971. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, false, true);
  3972. }
  3973. }
  3974. //return
  3975. if(stack->hasBonusOfType(BonusType::RETURN_AFTER_STRIKE)
  3976. && target.size() == 3
  3977. && startingPos != stack->getPosition()
  3978. && startingPos == target.at(2).hexValue
  3979. && stack->alive())
  3980. {
  3981. moveStack(ba.stackNumber, startingPos);
  3982. //NOTE: curStack->unitId() == ba.stackNumber (rev 1431)
  3983. }
  3984. break;
  3985. }
  3986. case EActionType::SHOOT:
  3987. {
  3988. if(target.size() < 1)
  3989. {
  3990. complain("Destination required for shot action.");
  3991. ok = false;
  3992. break;
  3993. }
  3994. auto destination = target.at(0).hexValue;
  3995. const CStack * destinationStack = gs->curB->battleGetStackByPos(destination);
  3996. if (!gs->curB->battleCanShoot(stack, destination))
  3997. {
  3998. complain("Cannot shoot!");
  3999. break;
  4000. }
  4001. if (!destinationStack)
  4002. {
  4003. complain("No target to shoot!");
  4004. break;
  4005. }
  4006. auto wrapper = wrapAction(ba);
  4007. makeAttack(stack, destinationStack, 0, destination, true, true, false);
  4008. //ranged counterattack
  4009. if (destinationStack->hasBonusOfType(BonusType::RANGED_RETALIATION)
  4010. && !stack->hasBonusOfType(BonusType::BLOCKS_RANGED_RETALIATION)
  4011. && destinationStack->ableToRetaliate()
  4012. && gs->curB->battleCanShoot(destinationStack, stack->getPosition())
  4013. && stack->alive()) //attacker may have died (fire shield)
  4014. {
  4015. makeAttack(destinationStack, stack, 0, stack->getPosition(), true, true, true);
  4016. }
  4017. //allow more than one additional attack
  4018. int totalRangedAttacks = stack->totalAttacks.getRangedValue();
  4019. //TODO: move to CUnitState
  4020. const auto * attackingHero = gs->curB->battleGetFightingHero(ba.side);
  4021. if(attackingHero)
  4022. {
  4023. totalRangedAttacks += attackingHero->valOfBonuses(BonusType::HERO_GRANTS_ATTACKS, stack->creatureIndex());
  4024. }
  4025. for(int i = 1; i < totalRangedAttacks; ++i)
  4026. {
  4027. if(
  4028. stack->alive()
  4029. && destinationStack->alive()
  4030. && stack->shots.canUse()
  4031. )
  4032. {
  4033. makeAttack(stack, destinationStack, 0, destination, false, true, false);
  4034. }
  4035. }
  4036. break;
  4037. }
  4038. case EActionType::CATAPULT:
  4039. {
  4040. auto wrapper = wrapAction(ba);
  4041. const CStack * shooter = gs->curB->battleGetStackByID(ba.stackNumber);
  4042. std::shared_ptr<const Bonus> catapultAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::CATAPULT));
  4043. if(!catapultAbility || catapultAbility->subtype < 0)
  4044. {
  4045. complain("We do not know how to shoot :P");
  4046. }
  4047. else
  4048. {
  4049. const CSpell * spell = SpellID(catapultAbility->subtype).toSpell();
  4050. spells::BattleCast parameters(gs->curB, shooter, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can shot infinitely by catapult
  4051. auto shotLevel = stack->valOfBonuses(Selector::typeSubtype(BonusType::CATAPULT_EXTRA_SHOTS, catapultAbility->subtype));
  4052. parameters.setSpellLevel(shotLevel);
  4053. parameters.cast(spellEnv, target);
  4054. }
  4055. //finish by scope guard
  4056. break;
  4057. }
  4058. case EActionType::STACK_HEAL: //healing with First Aid Tent
  4059. {
  4060. auto wrapper = wrapAction(ba);
  4061. const CStack * healer = gs->curB->battleGetStackByID(ba.stackNumber);
  4062. if(target.size() < 1)
  4063. {
  4064. complain("Destination required for heal action.");
  4065. ok = false;
  4066. break;
  4067. }
  4068. const battle::Unit * destStack = nullptr;
  4069. std::shared_ptr<const Bonus> healerAbility = stack->getBonusLocalFirst(Selector::type()(BonusType::HEALER));
  4070. if(target.at(0).unitValue)
  4071. destStack = target.at(0).unitValue;
  4072. else
  4073. destStack = gs->curB->battleGetUnitByPos(target.at(0).hexValue);
  4074. if(healer == nullptr || destStack == nullptr || !healerAbility || healerAbility->subtype < 0)
  4075. {
  4076. complain("There is either no healer, no destination, or healer cannot heal :P");
  4077. }
  4078. else
  4079. {
  4080. const CSpell * spell = SpellID(healerAbility->subtype).toSpell();
  4081. spells::BattleCast parameters(gs->curB, healer, spells::Mode::SPELL_LIKE_ATTACK, spell); //We can heal infinitely by first aid tent
  4082. auto dest = battle::Destination(destStack, target.at(0).hexValue);
  4083. parameters.setSpellLevel(0);
  4084. parameters.cast(spellEnv, {dest});
  4085. }
  4086. break;
  4087. }
  4088. case EActionType::MONSTER_SPELL:
  4089. {
  4090. auto wrapper = wrapAction(ba);
  4091. const CStack * stack = gs->curB->battleGetStackByID(ba.stackNumber);
  4092. SpellID spellID = SpellID(ba.actionSubtype);
  4093. std::shared_ptr<const Bonus> randSpellcaster = stack->getBonus(Selector::type()(BonusType::RANDOM_SPELLCASTER));
  4094. std::shared_ptr<const Bonus> spellcaster = stack->getBonus(Selector::typeSubtype(BonusType::SPELLCASTER, spellID));
  4095. //TODO special bonus for genies ability
  4096. if (randSpellcaster && battleGetRandomStackSpell(getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_AIMED) < 0)
  4097. spellID = battleGetRandomStackSpell(getRandomGenerator(), stack, CBattleInfoCallback::RANDOM_GENIE);
  4098. if (spellID < 0)
  4099. complain("That stack can't cast spells!");
  4100. else
  4101. {
  4102. const CSpell * spell = SpellID(spellID).toSpell();
  4103. spells::BattleCast parameters(gs->curB, stack, spells::Mode::CREATURE_ACTIVE, spell);
  4104. int32_t spellLvl = 0;
  4105. if(spellcaster)
  4106. vstd::amax(spellLvl, spellcaster->val);
  4107. if(randSpellcaster)
  4108. vstd::amax(spellLvl, randSpellcaster->val);
  4109. parameters.setSpellLevel(spellLvl);
  4110. parameters.cast(spellEnv, target);
  4111. }
  4112. break;
  4113. }
  4114. }
  4115. if(ba.actionType == EActionType::WAIT || ba.actionType == EActionType::DEFEND
  4116. || ba.actionType == EActionType::SHOOT || ba.actionType == EActionType::MONSTER_SPELL)
  4117. handleObstacleTriggersForUnit(*spellEnv, *stack);
  4118. if(ba.stackNumber == gs->curB->activeStack || battleResult.get()) //active stack has moved or battle has finished
  4119. battleMadeAction.setn(true);
  4120. return ok;
  4121. }
  4122. bool CGameHandler::makeCustomAction(BattleAction & ba)
  4123. {
  4124. switch(ba.actionType)
  4125. {
  4126. case EActionType::HERO_SPELL:
  4127. {
  4128. COMPLAIN_RET_FALSE_IF(ba.side > 1, "Side must be 0 or 1!");
  4129. const CGHeroInstance *h = gs->curB->battleGetFightingHero(ba.side);
  4130. COMPLAIN_RET_FALSE_IF((!h), "Wrong caster!");
  4131. const CSpell * s = SpellID(ba.actionSubtype).toSpell();
  4132. if (!s)
  4133. {
  4134. logGlobal->error("Wrong spell id (%d)!", ba.actionSubtype);
  4135. return false;
  4136. }
  4137. spells::BattleCast parameters(gs->curB, h, spells::Mode::HERO, s);
  4138. spells::detail::ProblemImpl problem;
  4139. auto m = s->battleMechanics(&parameters);
  4140. if(!m->canBeCast(problem))//todo: should we check aimed cast?
  4141. {
  4142. logGlobal->warn("Spell cannot be cast!");
  4143. std::vector<std::string> texts;
  4144. problem.getAll(texts);
  4145. for(auto s : texts)
  4146. logGlobal->warn(s);
  4147. return false;
  4148. }
  4149. StartAction start_action(ba);
  4150. sendAndApply(&start_action); //start spell casting
  4151. parameters.cast(spellEnv, ba.getTarget(gs->curB));
  4152. sendAndApply(&end_action);
  4153. if (!gs->curB->battleGetStackByID(gs->curB->activeStack))
  4154. {
  4155. battleMadeAction.setn(true);
  4156. }
  4157. checkBattleStateChanges();
  4158. if (battleResult.get())
  4159. {
  4160. battleMadeAction.setn(true);
  4161. //battle will be ended by startBattle function
  4162. //endBattle(gs->curB->tile, gs->curB->heroes[0], gs->curB->heroes[1]);
  4163. }
  4164. return true;
  4165. }
  4166. }
  4167. return false;
  4168. }
  4169. void CGameHandler::stackEnchantedTrigger(const CStack * st)
  4170. {
  4171. auto bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTED)));
  4172. for(auto b : bl)
  4173. {
  4174. const CSpell * sp = SpellID(b->subtype).toSpell();
  4175. if(!sp)
  4176. continue;
  4177. const int32_t val = bl.valOfBonuses(Selector::typeSubtype(b->type, b->subtype));
  4178. const int32_t level = ((val > 3) ? (val - 3) : val);
  4179. spells::BattleCast battleCast(gs->curB, st, spells::Mode::PASSIVE, sp);
  4180. //this makes effect accumulate for at most 50 turns by default, but effect may be permanent and last till the end of battle
  4181. battleCast.setEffectDuration(50);
  4182. battleCast.setSpellLevel(level);
  4183. spells::Target target;
  4184. if(val > 3)
  4185. {
  4186. for(auto s : gs->curB->battleGetAllStacks())
  4187. if(battleMatchOwner(st, s, true) && s->isValidTarget()) //all allied
  4188. target.emplace_back(s);
  4189. }
  4190. else
  4191. {
  4192. target.emplace_back(st);
  4193. }
  4194. battleCast.applyEffects(spellEnv, target, false, true);
  4195. }
  4196. }
  4197. void CGameHandler::stackTurnTrigger(const CStack *st)
  4198. {
  4199. BattleTriggerEffect bte;
  4200. bte.stackID = st->unitId();
  4201. bte.effect = -1;
  4202. bte.val = 0;
  4203. bte.additionalInfo = 0;
  4204. if (st->alive())
  4205. {
  4206. //unbind
  4207. if (st->hasBonus(Selector::type()(BonusType::BIND_EFFECT)))
  4208. {
  4209. bool unbind = true;
  4210. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::BIND_EFFECT)));
  4211. auto adjacent = gs->curB->battleAdjacentUnits(st);
  4212. for (auto b : bl)
  4213. {
  4214. if(b->additionalInfo != CAddInfo::NONE)
  4215. {
  4216. const CStack * stack = gs->curB->battleGetStackByID(b->additionalInfo[0]); //binding stack must be alive and adjacent
  4217. if(stack)
  4218. {
  4219. if(vstd::contains(adjacent, stack)) //binding stack is still present
  4220. unbind = false;
  4221. }
  4222. }
  4223. else
  4224. {
  4225. unbind = false;
  4226. }
  4227. }
  4228. if (unbind)
  4229. {
  4230. BattleSetStackProperty ssp;
  4231. ssp.which = BattleSetStackProperty::UNBIND;
  4232. ssp.stackID = st->unitId();
  4233. sendAndApply(&ssp);
  4234. }
  4235. }
  4236. if (st->hasBonusOfType(BonusType::POISON))
  4237. {
  4238. std::shared_ptr<const Bonus> b = st->getBonusLocalFirst(Selector::source(BonusSource::SPELL_EFFECT, SpellID::POISON).And(Selector::type()(BonusType::STACK_HEALTH)));
  4239. if (b) //TODO: what if not?...
  4240. {
  4241. bte.val = std::max (b->val - 10, -(st->valOfBonuses(BonusType::POISON)));
  4242. if (bte.val < b->val) //(negative) poison effect increases - update it
  4243. {
  4244. bte.effect = vstd::to_underlying(BonusType::POISON);
  4245. sendAndApply(&bte);
  4246. }
  4247. }
  4248. }
  4249. if(st->hasBonusOfType(BonusType::MANA_DRAIN) && !st->drainedMana)
  4250. {
  4251. const PlayerColor opponent = gs->curB->otherPlayer(gs->curB->battleGetOwner(st));
  4252. const CGHeroInstance * opponentHero = gs->curB->getHero(opponent);
  4253. if(opponentHero)
  4254. {
  4255. ui32 manaDrained = st->valOfBonuses(BonusType::MANA_DRAIN);
  4256. vstd::amin(manaDrained, opponentHero->mana);
  4257. if(manaDrained)
  4258. {
  4259. bte.effect = vstd::to_underlying(BonusType::MANA_DRAIN);
  4260. bte.val = manaDrained;
  4261. bte.additionalInfo = opponentHero->id.getNum(); //for sanity
  4262. sendAndApply(&bte);
  4263. }
  4264. }
  4265. }
  4266. if (st->isLiving() && !st->hasBonusOfType(BonusType::FEARLESS))
  4267. {
  4268. bool fearsomeCreature = false;
  4269. for (CStack * stack : gs->curB->stacks)
  4270. {
  4271. if (battleMatchOwner(st, stack) && stack->alive() && stack->hasBonusOfType(BonusType::FEAR))
  4272. {
  4273. fearsomeCreature = true;
  4274. break;
  4275. }
  4276. }
  4277. if (fearsomeCreature)
  4278. {
  4279. if (getRandomGenerator().nextInt(99) < 10) //fixed 10%
  4280. {
  4281. bte.effect = vstd::to_underlying(BonusType::FEAR);
  4282. sendAndApply(&bte);
  4283. }
  4284. }
  4285. }
  4286. BonusList bl = *(st->getBonuses(Selector::type()(BonusType::ENCHANTER)));
  4287. int side = gs->curB->whatSide(st->unitOwner());
  4288. if(st->canCast() && gs->curB->battleGetEnchanterCounter(side) == 0)
  4289. {
  4290. bool cast = false;
  4291. while(!bl.empty() && !cast)
  4292. {
  4293. auto bonus = *RandomGeneratorUtil::nextItem(bl, getRandomGenerator());
  4294. auto spellID = SpellID(bonus->subtype);
  4295. const CSpell * spell = SpellID(spellID).toSpell();
  4296. bl.remove_if([&bonus](const Bonus * b)
  4297. {
  4298. return b == bonus.get();
  4299. });
  4300. spells::BattleCast parameters(gs->curB, st, spells::Mode::ENCHANTER, spell);
  4301. parameters.setSpellLevel(bonus->val);
  4302. parameters.massive = true;
  4303. parameters.smart = true;
  4304. //todo: recheck effect level
  4305. if(parameters.castIfPossible(spellEnv, spells::Target(1, spells::Destination())))
  4306. {
  4307. cast = true;
  4308. int cooldown = bonus->additionalInfo[0];
  4309. BattleSetStackProperty ssp;
  4310. ssp.which = BattleSetStackProperty::ENCHANTER_COUNTER;
  4311. ssp.absolute = false;
  4312. ssp.val = cooldown;
  4313. ssp.stackID = st->unitId();
  4314. sendAndApply(&ssp);
  4315. }
  4316. }
  4317. }
  4318. }
  4319. }
  4320. void CGameHandler::handleTimeEvents()
  4321. {
  4322. gs->map->events.sort(evntCmp);
  4323. while(gs->map->events.size() && gs->map->events.front().firstOccurence+1 == gs->day)
  4324. {
  4325. CMapEvent ev = gs->map->events.front();
  4326. for (int player = 0; player < PlayerColor::PLAYER_LIMIT_I; player++)
  4327. {
  4328. auto color = PlayerColor(player);
  4329. const PlayerState * pinfo = getPlayerState(color, false); //do not output error if player does not exist
  4330. if (pinfo //player exists
  4331. && (ev.players & 1<<player) //event is enabled to this player
  4332. && ((ev.computerAffected && !pinfo->human)
  4333. || (ev.humanAffected && pinfo->human)
  4334. )
  4335. )
  4336. {
  4337. //give resources
  4338. giveResources(color, ev.resources);
  4339. //prepare dialog
  4340. InfoWindow iw;
  4341. iw.player = color;
  4342. iw.text.appendRawString(ev.message);
  4343. for (int i=0; i<ev.resources.size(); i++)
  4344. {
  4345. if (ev.resources[i]) //if resource is changed, we add it to the dialog
  4346. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,ev.resources[i],0);
  4347. }
  4348. sendAndApply(&iw); //show dialog
  4349. }
  4350. } //PLAYERS LOOP
  4351. if (ev.nextOccurence)
  4352. {
  4353. gs->map->events.pop_front();
  4354. ev.firstOccurence += ev.nextOccurence;
  4355. auto it = gs->map->events.begin();
  4356. while(it != gs->map->events.end() && it->earlierThanOrEqual(ev))
  4357. it++;
  4358. gs->map->events.insert(it, ev);
  4359. }
  4360. else
  4361. {
  4362. gs->map->events.pop_front();
  4363. }
  4364. }
  4365. //TODO send only if changed
  4366. UpdateMapEvents ume;
  4367. ume.events = gs->map->events;
  4368. sendAndApply(&ume);
  4369. }
  4370. void CGameHandler::handleTownEvents(CGTownInstance * town, NewTurn &n)
  4371. {
  4372. town->events.sort(evntCmp);
  4373. while(town->events.size() && town->events.front().firstOccurence == gs->day)
  4374. {
  4375. PlayerColor player = town->tempOwner;
  4376. CCastleEvent ev = town->events.front();
  4377. const PlayerState * pinfo = getPlayerState(player, false);
  4378. if (pinfo //player exists
  4379. && (ev.players & 1<<player.getNum()) //event is enabled to this player
  4380. && ((ev.computerAffected && !pinfo->human)
  4381. || (ev.humanAffected && pinfo->human)))
  4382. {
  4383. // dialog
  4384. InfoWindow iw;
  4385. iw.player = player;
  4386. iw.text.appendRawString(ev.message);
  4387. if (ev.resources.nonZero())
  4388. {
  4389. TResources was = n.res[player];
  4390. n.res[player] += ev.resources;
  4391. n.res[player].amax(0);
  4392. for (int i=0; i<ev.resources.size(); i++)
  4393. if (ev.resources[i] && pinfo->resources[i] != n.res.at(player)[i]) //if resource had changed, we add it to the dialog
  4394. iw.components.emplace_back(Component::EComponentType::RESOURCE,i,n.res.at(player)[i]-was[i],0);
  4395. }
  4396. for (auto & i : ev.buildings)
  4397. {
  4398. if (!town->hasBuilt(i))
  4399. {
  4400. buildStructure(town->id, i, true);
  4401. iw.components.emplace_back(Component::EComponentType::BUILDING, town->subID, i, 0);
  4402. }
  4403. }
  4404. if (!ev.creatures.empty() && !vstd::contains(n.cres, town->id))
  4405. {
  4406. n.cres[town->id].tid = town->id;
  4407. n.cres[town->id].creatures = town->creatures;
  4408. }
  4409. auto & sac = n.cres[town->id];
  4410. for (si32 i=0;i<ev.creatures.size();i++) //creature growths
  4411. {
  4412. if (!town->creatures.at(i).second.empty() && ev.creatures.at(i) > 0)//there is dwelling
  4413. {
  4414. sac.creatures[i].first += ev.creatures.at(i);
  4415. iw.components.emplace_back(Component::EComponentType::CREATURE,
  4416. town->creatures.at(i).second.back(), ev.creatures.at(i), 0);
  4417. }
  4418. }
  4419. sendAndApply(&iw); //show dialog
  4420. }
  4421. if (ev.nextOccurence)
  4422. {
  4423. town->events.pop_front();
  4424. ev.firstOccurence += ev.nextOccurence;
  4425. auto it = town->events.begin();
  4426. while(it != town->events.end() && it->earlierThanOrEqual(ev))
  4427. it++;
  4428. town->events.insert(it, ev);
  4429. }
  4430. else
  4431. {
  4432. town->events.pop_front();
  4433. }
  4434. }
  4435. //TODO send only if changed
  4436. UpdateCastleEvents uce;
  4437. uce.town = town->id;
  4438. uce.events = town->events;
  4439. sendAndApply(&uce);
  4440. }
  4441. bool CGameHandler::complain(const std::string &problem)
  4442. {
  4443. playerMessages->broadcastSystemMessage("Server encountered a problem: " + problem);
  4444. logGlobal->error(problem);
  4445. return true;
  4446. }
  4447. void CGameHandler::showGarrisonDialog(ObjectInstanceID upobj, ObjectInstanceID hid, bool removableUnits)
  4448. {
  4449. //PlayerColor player = getOwner(hid);
  4450. auto upperArmy = dynamic_cast<const CArmedInstance*>(getObj(upobj));
  4451. auto lowerArmy = dynamic_cast<const CArmedInstance*>(getObj(hid));
  4452. assert(lowerArmy);
  4453. assert(upperArmy);
  4454. auto garrisonQuery = std::make_shared<CGarrisonDialogQuery>(this, upperArmy, lowerArmy);
  4455. queries.addQuery(garrisonQuery);
  4456. GarrisonDialog gd;
  4457. gd.hid = hid;
  4458. gd.objid = upobj;
  4459. gd.removableUnits = removableUnits;
  4460. gd.queryID = garrisonQuery->queryID;
  4461. sendAndApply(&gd);
  4462. }
  4463. void CGameHandler::showThievesGuildWindow(PlayerColor player, ObjectInstanceID requestingObjId)
  4464. {
  4465. OpenWindow ow;
  4466. ow.window = EOpenWindowMode::THIEVES_GUILD;
  4467. ow.id1 = player.getNum();
  4468. ow.id2 = requestingObjId.getNum();
  4469. sendAndApply(&ow);
  4470. }
  4471. bool CGameHandler::isAllowedExchange(ObjectInstanceID id1, ObjectInstanceID id2)
  4472. {
  4473. if (id1 == id2)
  4474. return true;
  4475. const CGObjectInstance *o1 = getObj(id1), *o2 = getObj(id2);
  4476. if (!o1 || !o2)
  4477. return true; //arranging stacks within an object should be always allowed
  4478. if (o1 && o2)
  4479. {
  4480. if (o1->ID == Obj::TOWN)
  4481. {
  4482. const CGTownInstance *t = static_cast<const CGTownInstance*>(o1);
  4483. if (t->visitingHero == o2 || t->garrisonHero == o2)
  4484. return true;
  4485. }
  4486. if (o2->ID == Obj::TOWN)
  4487. {
  4488. const CGTownInstance *t = static_cast<const CGTownInstance*>(o2);
  4489. if (t->visitingHero == o1 || t->garrisonHero == o1)
  4490. return true;
  4491. }
  4492. if (o1->ID == Obj::HERO && o2->ID == Obj::HERO)
  4493. {
  4494. const CGHeroInstance *h1 = static_cast<const CGHeroInstance*>(o1);
  4495. const CGHeroInstance *h2 = static_cast<const CGHeroInstance*>(o2);
  4496. // two heroes in same town (garrisoned and visiting)
  4497. if (h1->visitedTown != nullptr && h2->visitedTown != nullptr && h1->visitedTown == h2->visitedTown)
  4498. return true;
  4499. }
  4500. //Ongoing garrison exchange - usually picking from top garison (from o1 to o2), but who knows
  4501. auto dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o1->tempOwner));
  4502. if (!dialog)
  4503. {
  4504. dialog = std::dynamic_pointer_cast<CGarrisonDialogQuery>(queries.topQuery(o2->tempOwner));
  4505. }
  4506. if (dialog)
  4507. {
  4508. auto topArmy = dialog->exchangingArmies.at(0);
  4509. auto bottomArmy = dialog->exchangingArmies.at(1);
  4510. if ((topArmy == o1 && bottomArmy == o2) || (bottomArmy == o1 && topArmy == o2))
  4511. return true;
  4512. }
  4513. }
  4514. return false;
  4515. }
  4516. void CGameHandler::objectVisited(const CGObjectInstance * obj, const CGHeroInstance * h)
  4517. {
  4518. using events::ObjectVisitStarted;
  4519. logGlobal->debug("%s visits %s (%d:%d)", h->nodeName(), obj->getObjectName(), obj->ID, obj->subID);
  4520. std::shared_ptr<CObjectVisitQuery> visitQuery;
  4521. auto startVisit = [&](ObjectVisitStarted & event)
  4522. {
  4523. auto visitedObject = obj;
  4524. if(obj->ID == Obj::HERO)
  4525. {
  4526. auto visitedHero = static_cast<const CGHeroInstance *>(obj);
  4527. const auto visitedTown = visitedHero->visitedTown;
  4528. if(visitedTown)
  4529. {
  4530. const bool isEnemy = visitedHero->getOwner() != h->getOwner();
  4531. if(isEnemy && !visitedTown->isBattleOutsideTown(visitedHero))
  4532. visitedObject = visitedTown;
  4533. }
  4534. }
  4535. visitQuery = std::make_shared<CObjectVisitQuery>(this, visitedObject, h, visitedObject->visitablePos());
  4536. queries.addQuery(visitQuery); //TODO real visit pos
  4537. HeroVisit hv;
  4538. hv.objId = obj->id;
  4539. hv.heroId = h->id;
  4540. hv.player = h->tempOwner;
  4541. hv.starting = true;
  4542. sendAndApply(&hv);
  4543. obj->onHeroVisit(h);
  4544. };
  4545. ObjectVisitStarted::defaultExecute(serverEventBus.get(), startVisit, h->tempOwner, h->id, obj->id);
  4546. if(visitQuery)
  4547. queries.popIfTop(visitQuery); //visit ends here if no queries were created
  4548. }
  4549. void CGameHandler::objectVisitEnded(const CObjectVisitQuery & query)
  4550. {
  4551. using events::ObjectVisitEnded;
  4552. logGlobal->debug("%s visit ends.\n", query.visitingHero->nodeName());
  4553. auto endVisit = [&](ObjectVisitEnded & event)
  4554. {
  4555. HeroVisit hv;
  4556. hv.player = event.getPlayer();
  4557. hv.heroId = event.getHero();
  4558. hv.starting = false;
  4559. sendAndApply(&hv);
  4560. };
  4561. //TODO: ObjectVisitEnded should also have id of visited object,
  4562. //but this requires object being deleted only by `removeAfterVisit()` but not `removeObject()`
  4563. ObjectVisitEnded::defaultExecute(serverEventBus.get(), endVisit, query.players.front(), query.visitingHero->id);
  4564. }
  4565. bool CGameHandler::buildBoat(ObjectInstanceID objid, PlayerColor playerID)
  4566. {
  4567. const IShipyard *obj = IShipyard::castFrom(getObj(objid));
  4568. if (obj->shipyardStatus() != IBoatGenerator::GOOD)
  4569. {
  4570. complain("Cannot build boat in this shipyard!");
  4571. return false;
  4572. }
  4573. TResources boatCost;
  4574. obj->getBoatCost(boatCost);
  4575. TResources aviable = getPlayerState(playerID)->resources;
  4576. if (!aviable.canAfford(boatCost))
  4577. {
  4578. complain("Not enough resources to build a boat!");
  4579. return false;
  4580. }
  4581. int3 tile = obj->bestLocation();
  4582. if (!gs->map->isInTheMap(tile))
  4583. {
  4584. complain("Cannot find appropriate tile for a boat!");
  4585. return false;
  4586. }
  4587. giveResources(playerID, -boatCost);
  4588. createObject(tile, Obj::BOAT, obj->getBoatType().getNum());
  4589. return true;
  4590. }
  4591. void CGameHandler::engageIntoBattle(PlayerColor player)
  4592. {
  4593. //notify interfaces
  4594. PlayerBlocked pb;
  4595. pb.player = player;
  4596. pb.reason = PlayerBlocked::UPCOMING_BATTLE;
  4597. pb.startOrEnd = PlayerBlocked::BLOCKADE_STARTED;
  4598. sendAndApply(&pb);
  4599. }
  4600. void CGameHandler::checkVictoryLossConditions(const std::set<PlayerColor> & playerColors)
  4601. {
  4602. for (auto playerColor : playerColors)
  4603. {
  4604. if (getPlayerState(playerColor, false))
  4605. checkVictoryLossConditionsForPlayer(playerColor);
  4606. }
  4607. }
  4608. void CGameHandler::checkVictoryLossConditionsForAll()
  4609. {
  4610. std::set<PlayerColor> playerColors;
  4611. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; ++i)
  4612. {
  4613. playerColors.insert(PlayerColor(i));
  4614. }
  4615. checkVictoryLossConditions(playerColors);
  4616. }
  4617. void CGameHandler::checkVictoryLossConditionsForPlayer(PlayerColor player)
  4618. {
  4619. const PlayerState * p = getPlayerState(player);
  4620. if(!p || p->status != EPlayerStatus::INGAME) return;
  4621. auto victoryLossCheckResult = gs->checkForVictoryAndLoss(player);
  4622. if (victoryLossCheckResult.victory() || victoryLossCheckResult.loss())
  4623. {
  4624. InfoWindow iw;
  4625. getVictoryLossMessage(player, victoryLossCheckResult, iw);
  4626. sendAndApply(&iw);
  4627. PlayerEndsGame peg;
  4628. peg.player = player;
  4629. peg.victoryLossCheckResult = victoryLossCheckResult;
  4630. sendAndApply(&peg);
  4631. if (victoryLossCheckResult.victory())
  4632. {
  4633. //one player won -> all enemies lost
  4634. for (auto i = gs->players.cbegin(); i!=gs->players.cend(); i++)
  4635. {
  4636. if (i->first != player && getPlayerState(i->first)->status == EPlayerStatus::INGAME)
  4637. {
  4638. peg.player = i->first;
  4639. peg.victoryLossCheckResult = getPlayerRelations(player, i->first) == PlayerRelations::ALLIES ?
  4640. victoryLossCheckResult : victoryLossCheckResult.invert(); // ally of winner
  4641. InfoWindow iw;
  4642. getVictoryLossMessage(player, peg.victoryLossCheckResult, iw);
  4643. iw.player = i->first;
  4644. sendAndApply(&iw);
  4645. sendAndApply(&peg);
  4646. }
  4647. }
  4648. if(p->human)
  4649. {
  4650. lobby->state = EServerState::GAMEPLAY_ENDED;
  4651. }
  4652. }
  4653. else
  4654. {
  4655. //copy heroes vector to avoid iterator invalidation as removal change PlayerState
  4656. auto hlp = p->heroes;
  4657. for (auto h : hlp) //eliminate heroes
  4658. {
  4659. if (h.get())
  4660. removeObject(h);
  4661. }
  4662. //player lost -> all his objects become unflagged (neutral)
  4663. for (auto obj : gs->map->objects) //unflag objs
  4664. {
  4665. if (obj.get() && obj->tempOwner == player)
  4666. setOwner(obj, PlayerColor::NEUTRAL);
  4667. }
  4668. //eliminating one player may cause victory of another:
  4669. std::set<PlayerColor> playerColors;
  4670. //do not copy player state (CBonusSystemNode) by value
  4671. for (auto &p : gs->players) //players may have different colors, iterate over players and not integers
  4672. {
  4673. if (p.first != player)
  4674. playerColors.insert(p.first);
  4675. }
  4676. //notify all players
  4677. for (auto pc : playerColors)
  4678. {
  4679. if (getPlayerState(pc)->status == EPlayerStatus::INGAME)
  4680. {
  4681. InfoWindow iw;
  4682. getVictoryLossMessage(player, victoryLossCheckResult.invert(), iw);
  4683. iw.player = pc;
  4684. sendAndApply(&iw);
  4685. }
  4686. }
  4687. checkVictoryLossConditions(playerColors);
  4688. }
  4689. auto playerInfo = getPlayerState(gs->currentPlayer, false);
  4690. // If we are called before the actual game start, there might be no current player
  4691. if (playerInfo && playerInfo->status != EPlayerStatus::INGAME)
  4692. {
  4693. // If player making turn has lost his turn must be over as well
  4694. states.setFlag(gs->currentPlayer, &PlayerStatus::makingTurn, false);
  4695. }
  4696. }
  4697. }
  4698. void CGameHandler::getVictoryLossMessage(PlayerColor player, const EVictoryLossCheckResult & victoryLossCheckResult, InfoWindow & out) const
  4699. {
  4700. out.player = player;
  4701. out.text = victoryLossCheckResult.messageToSelf;
  4702. out.text.replaceLocalString(EMetaText::COLOR, player.getNum());
  4703. out.components.emplace_back(Component::EComponentType::FLAG, player.getNum(), 0, 0);
  4704. }
  4705. bool CGameHandler::dig(const CGHeroInstance *h)
  4706. {
  4707. if (h->diggingStatus() != EDiggingStatus::CAN_DIG) //checks for terrain and movement
  4708. COMPLAIN_RETF("Hero cannot dig (error code %d)!", h->diggingStatus());
  4709. createObject(h->visitablePos(), Obj::HOLE, 0 );
  4710. //take MPs
  4711. SetMovePoints smp;
  4712. smp.hid = h->id;
  4713. smp.val = 0;
  4714. sendAndApply(&smp);
  4715. InfoWindow iw;
  4716. iw.type = EInfoWindowMode::AUTO;
  4717. iw.player = h->tempOwner;
  4718. if (gs->map->grailPos == h->visitablePos())
  4719. {
  4720. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 58); //"Congratulations! After spending many hours digging here, your hero has uncovered the "
  4721. iw.text.appendLocalString(EMetaText::ART_NAMES, ArtifactID::GRAIL);
  4722. iw.soundID = soundBase::ULTIMATEARTIFACT;
  4723. giveHeroNewArtifact(h, VLC->arth->objects[ArtifactID::GRAIL], ArtifactPosition::FIRST_AVAILABLE); //give grail
  4724. sendAndApply(&iw);
  4725. iw.soundID = soundBase::invalid;
  4726. iw.components.emplace_back(Component::EComponentType::ARTIFACT, ArtifactID::GRAIL, 0, 0);
  4727. iw.text.clear();
  4728. iw.text.appendLocalString(EMetaText::ART_DESCR, ArtifactID::GRAIL);
  4729. sendAndApply(&iw);
  4730. }
  4731. else
  4732. {
  4733. iw.text.appendLocalString(EMetaText::GENERAL_TXT, 59); //"Nothing here. \n Where could it be?"
  4734. iw.soundID = soundBase::Dig;
  4735. sendAndApply(&iw);
  4736. }
  4737. return true;
  4738. }
  4739. void CGameHandler::attackCasting(bool ranged, BonusType attackMode, const battle::Unit * attacker, const battle::Unit * defender)
  4740. {
  4741. if(attacker->hasBonusOfType(attackMode))
  4742. {
  4743. std::set<SpellID> spellsToCast;
  4744. TConstBonusListPtr spells = attacker->getBonuses(Selector::type()(attackMode));
  4745. for(const auto & sf : *spells)
  4746. {
  4747. spellsToCast.insert(SpellID(sf->subtype));
  4748. }
  4749. for(SpellID spellID : spellsToCast)
  4750. {
  4751. bool castMe = false;
  4752. if(!defender->alive())
  4753. {
  4754. logGlobal->debug("attackCasting: all attacked creatures have been killed");
  4755. return;
  4756. }
  4757. int32_t spellLevel = 0;
  4758. TConstBonusListPtr spellsByType = attacker->getBonuses(Selector::typeSubtype(attackMode, spellID));
  4759. for(const auto & sf : *spellsByType)
  4760. {
  4761. int meleeRanged;
  4762. if(sf->additionalInfo.size() < 2)
  4763. {
  4764. // legacy format
  4765. vstd::amax(spellLevel, sf->additionalInfo[0] % 1000);
  4766. meleeRanged = sf->additionalInfo[0] / 1000;
  4767. }
  4768. else
  4769. {
  4770. vstd::amax(spellLevel, sf->additionalInfo[0]);
  4771. meleeRanged = sf->additionalInfo[1];
  4772. }
  4773. if (meleeRanged == 0 || (meleeRanged == 1 && ranged) || (meleeRanged == 2 && !ranged))
  4774. castMe = true;
  4775. }
  4776. int chance = attacker->valOfBonuses((Selector::typeSubtype(attackMode, spellID)));
  4777. vstd::amin(chance, 100);
  4778. const CSpell * spell = SpellID(spellID).toSpell();
  4779. spells::AbilityCaster caster(attacker, spellLevel);
  4780. spells::Target target;
  4781. target.emplace_back(defender);
  4782. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  4783. auto m = spell->battleMechanics(&parameters);
  4784. spells::detail::ProblemImpl ignored;
  4785. if(!m->canBeCastAt(target, ignored))
  4786. continue;
  4787. //check if spell should be cast (probability handling)
  4788. if(getRandomGenerator().nextInt(99) >= chance)
  4789. continue;
  4790. //casting
  4791. if(castMe)
  4792. {
  4793. parameters.cast(spellEnv, target);
  4794. }
  4795. }
  4796. }
  4797. }
  4798. void CGameHandler::handleAttackBeforeCasting(bool ranged, const CStack * attacker, const CStack * defender)
  4799. {
  4800. attackCasting(ranged, BonusType::SPELL_BEFORE_ATTACK, attacker, defender); //no death stare / acid breath needed?
  4801. }
  4802. void CGameHandler::handleAfterAttackCasting(bool ranged, const CStack * attacker, const CStack * defender)
  4803. {
  4804. if(!attacker->alive() || !defender->alive()) // can be already dead
  4805. return;
  4806. attackCasting(ranged, BonusType::SPELL_AFTER_ATTACK, attacker, defender);
  4807. if(!defender->alive())
  4808. {
  4809. //don't try death stare or acid breath on dead stack (crash!)
  4810. return;
  4811. }
  4812. if(attacker->hasBonusOfType(BonusType::DEATH_STARE))
  4813. {
  4814. // mechanics of Death Stare as in H3:
  4815. // each gorgon have 10% chance to kill (counted separately in H3) -> binomial distribution
  4816. //original formula x = min(x, (gorgons_count + 9)/10);
  4817. double chanceToKill = attacker->valOfBonuses(BonusType::DEATH_STARE, 0) / 100.0f;
  4818. vstd::amin(chanceToKill, 1); //cap at 100%
  4819. std::binomial_distribution<> distribution(attacker->getCount(), chanceToKill);
  4820. int staredCreatures = distribution(getRandomGenerator().getStdGenerator());
  4821. double cap = 1 / std::max(chanceToKill, (double)(0.01));//don't divide by 0
  4822. int maxToKill = static_cast<int>((attacker->getCount() + cap - 1) / cap); //not much more than chance * count
  4823. vstd::amin(staredCreatures, maxToKill);
  4824. staredCreatures += (attacker->level() * attacker->valOfBonuses(BonusType::DEATH_STARE, 1)) / defender->level();
  4825. if(staredCreatures)
  4826. {
  4827. //TODO: death stare was not originally available for multiple-hex attacks, but...
  4828. const CSpell * spell = SpellID(SpellID::DEATH_STARE).toSpell();
  4829. spells::AbilityCaster caster(attacker, 0);
  4830. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  4831. spells::Target target;
  4832. target.emplace_back(defender);
  4833. parameters.setEffectValue(staredCreatures);
  4834. parameters.cast(spellEnv, target);
  4835. }
  4836. }
  4837. if(!defender->alive())
  4838. return;
  4839. int64_t acidDamage = 0;
  4840. TConstBonusListPtr acidBreath = attacker->getBonuses(Selector::type()(BonusType::ACID_BREATH));
  4841. for(const auto & b : *acidBreath)
  4842. {
  4843. if(b->additionalInfo[0] > getRandomGenerator().nextInt(99))
  4844. acidDamage += b->val;
  4845. }
  4846. if(acidDamage > 0)
  4847. {
  4848. const CSpell * spell = SpellID(SpellID::ACID_BREATH_DAMAGE).toSpell();
  4849. spells::AbilityCaster caster(attacker, 0);
  4850. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  4851. spells::Target target;
  4852. target.emplace_back(defender);
  4853. parameters.setEffectValue(acidDamage * attacker->getCount());
  4854. parameters.cast(spellEnv, target);
  4855. }
  4856. if(!defender->alive())
  4857. return;
  4858. if(attacker->hasBonusOfType(BonusType::TRANSMUTATION) && defender->isLiving()) //transmutation mechanics, similar to WoG werewolf ability
  4859. {
  4860. double chanceToTrigger = attacker->valOfBonuses(BonusType::TRANSMUTATION) / 100.0f;
  4861. vstd::amin(chanceToTrigger, 1); //cap at 100%
  4862. if(getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  4863. return;
  4864. int bonusAdditionalInfo = attacker->getBonus(Selector::type()(BonusType::TRANSMUTATION))->additionalInfo[0];
  4865. if(defender->unitType()->getId() == bonusAdditionalInfo ||
  4866. (bonusAdditionalInfo == CAddInfo::NONE && defender->unitType()->getId() == attacker->unitType()->getId()))
  4867. return;
  4868. battle::UnitInfo resurrectInfo;
  4869. resurrectInfo.id = gs->curB->battleNextUnitId();
  4870. resurrectInfo.summoned = false;
  4871. resurrectInfo.position = defender->getPosition();
  4872. resurrectInfo.side = defender->unitSide();
  4873. if(bonusAdditionalInfo != CAddInfo::NONE)
  4874. resurrectInfo.type = CreatureID(bonusAdditionalInfo);
  4875. else
  4876. resurrectInfo.type = attacker->creatureId();
  4877. if(attacker->hasBonusOfType((BonusType::TRANSMUTATION), 0))
  4878. resurrectInfo.count = std::max((defender->getCount() * defender->getMaxHealth()) / resurrectInfo.type.toCreature()->getMaxHealth(), 1u);
  4879. else if (attacker->hasBonusOfType((BonusType::TRANSMUTATION), 1))
  4880. resurrectInfo.count = defender->getCount();
  4881. else
  4882. return; //wrong subtype
  4883. BattleUnitsChanged addUnits;
  4884. addUnits.changedStacks.emplace_back(resurrectInfo.id, UnitChanges::EOperation::ADD);
  4885. resurrectInfo.save(addUnits.changedStacks.back().data);
  4886. BattleUnitsChanged removeUnits;
  4887. removeUnits.changedStacks.emplace_back(defender->unitId(), UnitChanges::EOperation::REMOVE);
  4888. sendAndApply(&removeUnits);
  4889. sendAndApply(&addUnits);
  4890. }
  4891. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0) || attacker->hasBonusOfType(BonusType::DESTRUCTION, 1))
  4892. {
  4893. double chanceToTrigger = 0;
  4894. int amountToDie = 0;
  4895. if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 0)) //killing by percentage
  4896. {
  4897. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 0) / 100.0f;
  4898. int percentageToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(0)))->additionalInfo[0];
  4899. amountToDie = static_cast<int>(defender->getCount() * percentageToDie * 0.01f);
  4900. }
  4901. else if(attacker->hasBonusOfType(BonusType::DESTRUCTION, 1)) //killing by count
  4902. {
  4903. chanceToTrigger = attacker->valOfBonuses(BonusType::DESTRUCTION, 1) / 100.0f;
  4904. amountToDie = attacker->getBonus(Selector::type()(BonusType::DESTRUCTION).And(Selector::subtype()(1)))->additionalInfo[0];
  4905. }
  4906. vstd::amin(chanceToTrigger, 1); //cap trigger chance at 100%
  4907. if(getRandomGenerator().getDoubleRange(0, 1)() > chanceToTrigger)
  4908. return;
  4909. BattleStackAttacked bsa;
  4910. bsa.attackerID = -1;
  4911. bsa.stackAttacked = defender->unitId();
  4912. bsa.damageAmount = amountToDie * defender->getMaxHealth();
  4913. bsa.flags = BattleStackAttacked::SPELL_EFFECT;
  4914. bsa.spellID = SpellID::SLAYER;
  4915. defender->prepareAttacked(bsa, getRandomGenerator());
  4916. StacksInjured si;
  4917. si.stacks.push_back(bsa);
  4918. sendAndApply(&si);
  4919. sendGenericKilledLog(defender, bsa.killedAmount, false);
  4920. }
  4921. }
  4922. void CGameHandler::visitObjectOnTile(const TerrainTile &t, const CGHeroInstance * h)
  4923. {
  4924. if (!t.visitableObjects.empty())
  4925. {
  4926. //to prevent self-visiting heroes on space press
  4927. if (t.visitableObjects.back() != h)
  4928. objectVisited(t.visitableObjects.back(), h);
  4929. else if (t.visitableObjects.size() > 1)
  4930. objectVisited(*(t.visitableObjects.end()-2),h);
  4931. }
  4932. }
  4933. bool CGameHandler::sacrificeCreatures(const IMarket * market, const CGHeroInstance * hero, const std::vector<SlotID> & slot, const std::vector<ui32> & count)
  4934. {
  4935. if (!hero)
  4936. COMPLAIN_RET("You need hero to sacrifice creature!");
  4937. int expSum = 0;
  4938. auto finish = [this, &hero, &expSum]()
  4939. {
  4940. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  4941. };
  4942. for(int i = 0; i < slot.size(); ++i)
  4943. {
  4944. int oldCount = hero->getStackCount(slot[i]);
  4945. if(oldCount < (int)count[i])
  4946. {
  4947. finish();
  4948. COMPLAIN_RET("Not enough creatures to sacrifice!")
  4949. }
  4950. else if(oldCount == count[i] && hero->stacksCount() == 1 && hero->needsLastStack())
  4951. {
  4952. finish();
  4953. COMPLAIN_RET("Cannot sacrifice last creature!");
  4954. }
  4955. int crid = hero->getStack(slot[i]).type->getId();
  4956. changeStackCount(StackLocation(hero, slot[i]), -(TQuantity)count[i]);
  4957. int dump, exp;
  4958. market->getOffer(crid, 0, dump, exp, EMarketMode::CREATURE_EXP);
  4959. exp *= count[i];
  4960. expSum += exp;
  4961. }
  4962. finish();
  4963. return true;
  4964. }
  4965. bool CGameHandler::sacrificeArtifact(const IMarket * m, const CGHeroInstance * hero, const std::vector<ArtifactPosition> & slot)
  4966. {
  4967. if (!hero)
  4968. COMPLAIN_RET("You need hero to sacrifice artifact!");
  4969. int expSum = 0;
  4970. auto finish = [this, &hero, &expSum]()
  4971. {
  4972. changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(expSum));
  4973. };
  4974. for(int i = 0; i < slot.size(); ++i)
  4975. {
  4976. ArtifactLocation al(hero, slot[i]);
  4977. const CArtifactInstance * a = al.getArt();
  4978. if(!a)
  4979. {
  4980. finish();
  4981. COMPLAIN_RET("Cannot find artifact to sacrifice!");
  4982. }
  4983. const CArtifactInstance * art = hero->getArt(slot[i]);
  4984. if(!art)
  4985. {
  4986. finish();
  4987. COMPLAIN_RET("No artifact at position to sacrifice!");
  4988. }
  4989. si32 typId = art->artType->getId();
  4990. int dmp, expToGive;
  4991. m->getOffer(typId, 0, dmp, expToGive, EMarketMode::ARTIFACT_EXP);
  4992. expSum += expToGive;
  4993. removeArtifact(al);
  4994. }
  4995. finish();
  4996. return true;
  4997. }
  4998. void CGameHandler::makeStackDoNothing(const CStack * next)
  4999. {
  5000. BattleAction doNothing;
  5001. doNothing.actionType = EActionType::NO_ACTION;
  5002. doNothing.side = next->unitSide();
  5003. doNothing.stackNumber = next->unitId();
  5004. makeAutomaticAction(next, doNothing);
  5005. }
  5006. bool CGameHandler::insertNewStack(const StackLocation &sl, const CCreature *c, TQuantity count)
  5007. {
  5008. if (sl.army->hasStackAtSlot(sl.slot))
  5009. COMPLAIN_RET("Slot is already taken!");
  5010. if (!sl.slot.validSlot())
  5011. COMPLAIN_RET("Cannot insert stack to that slot!");
  5012. InsertNewStack ins;
  5013. ins.army = sl.army->id;
  5014. ins.slot = sl.slot;
  5015. ins.type = c->getId();
  5016. ins.count = count;
  5017. sendAndApply(&ins);
  5018. return true;
  5019. }
  5020. bool CGameHandler::eraseStack(const StackLocation &sl, bool forceRemoval)
  5021. {
  5022. if (!sl.army->hasStackAtSlot(sl.slot))
  5023. COMPLAIN_RET("Cannot find a stack to erase");
  5024. if (sl.army->stacksCount() == 1 //from the last stack
  5025. && sl.army->needsLastStack() //that must be left
  5026. && !forceRemoval) //ignore above conditions if we are forcing removal
  5027. {
  5028. COMPLAIN_RET("Cannot erase the last stack!");
  5029. }
  5030. EraseStack es;
  5031. es.army = sl.army->id;
  5032. es.slot = sl.slot;
  5033. sendAndApply(&es);
  5034. return true;
  5035. }
  5036. bool CGameHandler::changeStackCount(const StackLocation &sl, TQuantity count, bool absoluteValue)
  5037. {
  5038. TQuantity currentCount = sl.army->getStackCount(sl.slot);
  5039. if ((absoluteValue && count < 0)
  5040. || (!absoluteValue && -count > currentCount))
  5041. {
  5042. COMPLAIN_RET("Cannot take more stacks than present!");
  5043. }
  5044. if ((currentCount == -count && !absoluteValue)
  5045. || (!count && absoluteValue))
  5046. {
  5047. eraseStack(sl);
  5048. }
  5049. else
  5050. {
  5051. ChangeStackCount csc;
  5052. csc.army = sl.army->id;
  5053. csc.slot = sl.slot;
  5054. csc.count = count;
  5055. csc.absoluteValue = absoluteValue;
  5056. sendAndApply(&csc);
  5057. }
  5058. return true;
  5059. }
  5060. bool CGameHandler::addToSlot(const StackLocation &sl, const CCreature *c, TQuantity count)
  5061. {
  5062. const CCreature *slotC = sl.army->getCreature(sl.slot);
  5063. if (!slotC) //slot is empty
  5064. insertNewStack(sl, c, count);
  5065. else if (c == slotC)
  5066. changeStackCount(sl, count);
  5067. else
  5068. {
  5069. COMPLAIN_RET("Cannot add " + c->getNamePluralTranslated() + " to slot " + boost::lexical_cast<std::string>(sl.slot) + "!");
  5070. }
  5071. return true;
  5072. }
  5073. void CGameHandler::tryJoiningArmy(const CArmedInstance *src, const CArmedInstance *dst, bool removeObjWhenFinished, bool allowMerging)
  5074. {
  5075. if (removeObjWhenFinished)
  5076. removeAfterVisit(src);
  5077. if (!src->canBeMergedWith(*dst, allowMerging))
  5078. {
  5079. if (allowMerging) //do that, add all matching creatures.
  5080. {
  5081. bool cont = true;
  5082. while (cont)
  5083. {
  5084. for (auto i = src->stacks.begin(); i != src->stacks.end(); i++)//while there are unmoved creatures
  5085. {
  5086. SlotID pos = dst->getSlotFor(i->second->type);
  5087. if (pos.validSlot())
  5088. {
  5089. moveStack(StackLocation(src, i->first), StackLocation(dst, pos));
  5090. cont = true;
  5091. break; //or iterator crashes
  5092. }
  5093. cont = false;
  5094. }
  5095. }
  5096. }
  5097. showGarrisonDialog(src->id, dst->id, true); //show garrison window and optionally remove ourselves from map when player ends
  5098. }
  5099. else //merge
  5100. {
  5101. moveArmy(src, dst, allowMerging);
  5102. }
  5103. }
  5104. bool CGameHandler::moveStack(const StackLocation &src, const StackLocation &dst, TQuantity count)
  5105. {
  5106. if (!src.army->hasStackAtSlot(src.slot))
  5107. COMPLAIN_RET("No stack to move!");
  5108. if (dst.army->hasStackAtSlot(dst.slot) && dst.army->getCreature(dst.slot) != src.army->getCreature(src.slot))
  5109. COMPLAIN_RET("Cannot move: stack of different type at destination pos!");
  5110. if (!dst.slot.validSlot())
  5111. COMPLAIN_RET("Cannot move stack to that slot!");
  5112. if (count == -1)
  5113. {
  5114. count = src.army->getStackCount(src.slot);
  5115. }
  5116. if (src.army != dst.army //moving away
  5117. && count == src.army->getStackCount(src.slot) //all creatures
  5118. && src.army->stacksCount() == 1 //from the last stack
  5119. && src.army->needsLastStack()) //that must be left
  5120. {
  5121. COMPLAIN_RET("Cannot move away the last creature!");
  5122. }
  5123. RebalanceStacks rs;
  5124. rs.srcArmy = src.army->id;
  5125. rs.dstArmy = dst.army->id;
  5126. rs.srcSlot = src.slot;
  5127. rs.dstSlot = dst.slot;
  5128. rs.count = count;
  5129. sendAndApply(&rs);
  5130. return true;
  5131. }
  5132. void CGameHandler::castSpell(const spells::Caster * caster, SpellID spellID, const int3 &pos)
  5133. {
  5134. const CSpell * s = spellID.toSpell();
  5135. if(!s)
  5136. return;
  5137. AdventureSpellCastParameters p;
  5138. p.caster = caster;
  5139. p.pos = pos;
  5140. s->adventureCast(spellEnv, p);
  5141. }
  5142. bool CGameHandler::swapStacks(const StackLocation & sl1, const StackLocation & sl2)
  5143. {
  5144. if(!sl1.army->hasStackAtSlot(sl1.slot))
  5145. {
  5146. return moveStack(sl2, sl1);
  5147. }
  5148. else if(!sl2.army->hasStackAtSlot(sl2.slot))
  5149. {
  5150. return moveStack(sl1, sl2);
  5151. }
  5152. else
  5153. {
  5154. SwapStacks ss;
  5155. ss.srcArmy = sl1.army->id;
  5156. ss.dstArmy = sl2.army->id;
  5157. ss.srcSlot = sl1.slot;
  5158. ss.dstSlot = sl2.slot;
  5159. sendAndApply(&ss);
  5160. return true;
  5161. }
  5162. }
  5163. void CGameHandler::runBattle()
  5164. {
  5165. setBattle(gs->curB);
  5166. assert(gs->curB);
  5167. //TODO: pre-tactic stuff, call scripts etc.
  5168. //Moat should be initialized here, because only here we can use spellcasting
  5169. if (gs->curB->town && gs->curB->town->fortLevel() >= CGTownInstance::CITADEL)
  5170. {
  5171. const auto * h = gs->curB->battleGetFightingHero(BattleSide::DEFENDER);
  5172. const auto * actualCaster = h ? static_cast<const spells::Caster*>(h) : nullptr;
  5173. auto moatCaster = spells::SilentCaster(gs->curB->getSidePlayer(BattleSide::DEFENDER), actualCaster);
  5174. auto cast = spells::BattleCast(gs->curB, &moatCaster, spells::Mode::PASSIVE, gs->curB->town->town->moatAbility.toSpell());
  5175. auto target = spells::Target();
  5176. cast.cast(spellEnv, target);
  5177. }
  5178. //tactic round
  5179. {
  5180. while ((lobby->state != EServerState::SHUTDOWN) && gs->curB->tacticDistance && !battleResult.get())
  5181. boost::this_thread::sleep(boost::posix_time::milliseconds(50));
  5182. }
  5183. //initial stacks appearance triggers, e.g. built-in bonus spells
  5184. auto initialStacks = gs->curB->stacks; //use temporary variable to outclude summoned stacks added to gs->curB->stacks from processing
  5185. for (CStack * stack : initialStacks)
  5186. {
  5187. if (stack->hasBonusOfType(BonusType::SUMMON_GUARDIANS))
  5188. {
  5189. std::shared_ptr<const Bonus> summonInfo = stack->getBonus(Selector::type()(BonusType::SUMMON_GUARDIANS));
  5190. auto accessibility = getAccesibility();
  5191. CreatureID creatureData = CreatureID(summonInfo->subtype);
  5192. std::vector<BattleHex> targetHexes;
  5193. const bool targetIsBig = stack->unitType()->isDoubleWide(); //target = creature to guard
  5194. const bool guardianIsBig = creatureData.toCreature()->isDoubleWide();
  5195. /*Chosen idea for two hex units was to cover all possible surrounding hexes of target unit with as small number of stacks as possible.
  5196. For one-hex targets there are four guardians - front, back and one per side (up + down).
  5197. Two-hex targets are wider and the difference is there are two guardians per side to cover 3 hexes + extra hex in the front
  5198. Additionally, there are special cases for starting positions etc., where guardians would be outside of battlefield if spawned normally*/
  5199. if (!guardianIsBig)
  5200. targetHexes = stack->getSurroundingHexes();
  5201. else
  5202. summonGuardiansHelper(targetHexes, stack->getPosition(), stack->unitSide(), targetIsBig);
  5203. for(auto hex : targetHexes)
  5204. {
  5205. if(accessibility.accessible(hex, guardianIsBig, stack->unitSide())) //without this multiple creatures can occupy one hex
  5206. {
  5207. battle::UnitInfo info;
  5208. info.id = gs->curB->battleNextUnitId();
  5209. info.count = std::max(1, (int)(stack->getCount() * 0.01 * summonInfo->val));
  5210. info.type = creatureData;
  5211. info.side = stack->unitSide();
  5212. info.position = hex;
  5213. info.summoned = true;
  5214. BattleUnitsChanged pack;
  5215. pack.changedStacks.emplace_back(info.id, UnitChanges::EOperation::ADD);
  5216. info.save(pack.changedStacks.back().data);
  5217. sendAndApply(&pack);
  5218. }
  5219. }
  5220. }
  5221. stackEnchantedTrigger(stack);
  5222. }
  5223. //spells opening battle
  5224. for (int i = 0; i < 2; ++i)
  5225. {
  5226. auto h = gs->curB->battleGetFightingHero(i);
  5227. if (h)
  5228. {
  5229. TConstBonusListPtr bl = h->getBonuses(Selector::type()(BonusType::OPENING_BATTLE_SPELL));
  5230. for (auto b : *bl)
  5231. {
  5232. spells::BonusCaster caster(h, b);
  5233. const CSpell * spell = SpellID(b->subtype).toSpell();
  5234. spells::BattleCast parameters(gs->curB, &caster, spells::Mode::PASSIVE, spell);
  5235. parameters.setSpellLevel(3);
  5236. parameters.setEffectDuration(b->val);
  5237. parameters.massive = true;
  5238. parameters.castIfPossible(spellEnv, spells::Target());
  5239. }
  5240. }
  5241. }
  5242. // it is possible that due to opening spells one side was eliminated -> check for end of battle
  5243. checkBattleStateChanges();
  5244. bool firstRound = true;//FIXME: why first round is -1?
  5245. //main loop
  5246. while ((lobby->state != EServerState::SHUTDOWN) && !battleResult.get()) //till the end of the battle ;]
  5247. {
  5248. BattleNextRound bnr;
  5249. bnr.round = gs->curB->round + 1;
  5250. logGlobal->debug("Round %d", bnr.round);
  5251. sendAndApply(&bnr);
  5252. auto obstacles = gs->curB->obstacles; //we copy container, because we're going to modify it
  5253. for (auto &obstPtr : obstacles)
  5254. {
  5255. if (const SpellCreatedObstacle *sco = dynamic_cast<const SpellCreatedObstacle *>(obstPtr.get()))
  5256. if (sco->turnsRemaining == 0)
  5257. removeObstacle(*obstPtr);
  5258. }
  5259. const BattleInfo & curB = *gs->curB;
  5260. for(auto stack : curB.stacks)
  5261. {
  5262. if(stack->alive() && !firstRound)
  5263. stackEnchantedTrigger(stack);
  5264. }
  5265. //stack loop
  5266. auto getNextStack = [this]() -> const CStack *
  5267. {
  5268. if(battleResult.get())
  5269. return nullptr;
  5270. std::vector<battle::Units> q;
  5271. gs->curB->battleGetTurnOrder(q, 1, 0, -1); //todo: get rid of "turn -1"
  5272. if(!q.empty())
  5273. {
  5274. if(!q.front().empty())
  5275. {
  5276. auto next = q.front().front();
  5277. const auto stack = dynamic_cast<const CStack *>(next);
  5278. // regeneration takes place before everything else but only during first turn attempt in each round
  5279. // also works under blind and similar effects
  5280. if(stack && stack->alive() && !stack->waiting)
  5281. {
  5282. BattleTriggerEffect bte;
  5283. bte.stackID = stack->unitId();
  5284. bte.effect = vstd::to_underlying(BonusType::HP_REGENERATION);
  5285. const int32_t lostHealth = stack->getMaxHealth() - stack->getFirstHPleft();
  5286. if(stack->hasBonusOfType(BonusType::HP_REGENERATION))
  5287. bte.val = std::min(lostHealth, stack->valOfBonuses(BonusType::HP_REGENERATION));
  5288. if(bte.val) // anything to heal
  5289. sendAndApply(&bte);
  5290. }
  5291. if(next->willMove())
  5292. return stack;
  5293. }
  5294. }
  5295. return nullptr;
  5296. };
  5297. const CStack * next = nullptr;
  5298. while((lobby->state != EServerState::SHUTDOWN) && (next = getNextStack()))
  5299. {
  5300. BattleUnitsChanged removeGhosts;
  5301. for(auto stack : curB.stacks)
  5302. {
  5303. if(stack->ghostPending)
  5304. removeGhosts.changedStacks.emplace_back(stack->unitId(), UnitChanges::EOperation::REMOVE);
  5305. }
  5306. if(!removeGhosts.changedStacks.empty())
  5307. sendAndApply(&removeGhosts);
  5308. // check for bad morale => freeze
  5309. int nextStackMorale = next->moraleVal();
  5310. if(!next->hadMorale && !next->waited() && nextStackMorale < 0)
  5311. {
  5312. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_BAD_MORALE_DICE);
  5313. size_t diceIndex = std::min<size_t>(diceSize.size()-1, -nextStackMorale);
  5314. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  5315. {
  5316. //unit loses its turn - empty freeze action
  5317. BattleAction ba;
  5318. ba.actionType = EActionType::BAD_MORALE;
  5319. ba.side = next->unitSide();
  5320. ba.stackNumber = next->unitId();
  5321. makeAutomaticAction(next, ba);
  5322. continue;
  5323. }
  5324. }
  5325. if (next->hasBonusOfType(BonusType::ATTACKS_NEAREST_CREATURE)) //while in berserk
  5326. {
  5327. logGlobal->trace("Handle Berserk effect");
  5328. std::pair<const battle::Unit *, BattleHex> attackInfo = curB.getNearestStack(next);
  5329. if (attackInfo.first != nullptr)
  5330. {
  5331. BattleAction attack;
  5332. attack.actionType = EActionType::WALK_AND_ATTACK;
  5333. attack.side = next->unitSide();
  5334. attack.stackNumber = next->unitId();
  5335. attack.aimToHex(attackInfo.second);
  5336. attack.aimToUnit(attackInfo.first);
  5337. makeAutomaticAction(next, attack);
  5338. logGlobal->trace("Attacked nearest target %s", attackInfo.first->getDescription());
  5339. }
  5340. else
  5341. {
  5342. makeStackDoNothing(next);
  5343. logGlobal->trace("No target found");
  5344. }
  5345. continue;
  5346. }
  5347. const CGHeroInstance * curOwner = battleGetOwnerHero(next);
  5348. const int stackCreatureId = next->unitType()->getId();
  5349. if ((stackCreatureId == CreatureID::ARROW_TOWERS || stackCreatureId == CreatureID::BALLISTA)
  5350. && (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, stackCreatureId)))
  5351. {
  5352. BattleAction attack;
  5353. attack.actionType = EActionType::SHOOT;
  5354. attack.side = next->unitSide();
  5355. attack.stackNumber = next->unitId();
  5356. //TODO: select target by priority
  5357. const battle::Unit * target = nullptr;
  5358. for(auto & elem : gs->curB->stacks)
  5359. {
  5360. if(elem->unitType()->getId() != CreatureID::CATAPULT
  5361. && elem->unitOwner() != next->unitOwner()
  5362. && elem->isValidTarget()
  5363. && gs->curB->battleCanShoot(next, elem->getPosition()))
  5364. {
  5365. target = elem;
  5366. break;
  5367. }
  5368. }
  5369. if(target == nullptr)
  5370. {
  5371. makeStackDoNothing(next);
  5372. }
  5373. else
  5374. {
  5375. attack.aimToUnit(target);
  5376. makeAutomaticAction(next, attack);
  5377. }
  5378. continue;
  5379. }
  5380. if (next->unitType()->getId() == CreatureID::CATAPULT)
  5381. {
  5382. const auto & attackableBattleHexes = curB.getAttackableBattleHexes();
  5383. if (attackableBattleHexes.empty())
  5384. {
  5385. makeStackDoNothing(next);
  5386. continue;
  5387. }
  5388. if (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::CATAPULT))
  5389. {
  5390. BattleAction attack;
  5391. attack.actionType = EActionType::CATAPULT;
  5392. attack.side = next->unitSide();
  5393. attack.stackNumber = next->unitId();
  5394. makeAutomaticAction(next, attack);
  5395. continue;
  5396. }
  5397. }
  5398. if (next->unitType()->getId() == CreatureID::FIRST_AID_TENT)
  5399. {
  5400. TStacks possibleStacks = battleGetStacksIf([=](const CStack * s)
  5401. {
  5402. return s->unitOwner() == next->unitOwner() && s->canBeHealed();
  5403. });
  5404. if (!possibleStacks.size())
  5405. {
  5406. makeStackDoNothing(next);
  5407. continue;
  5408. }
  5409. if (!curOwner || getRandomGenerator().nextInt(99) >= curOwner->valOfBonuses(BonusType::MANUAL_CONTROL, CreatureID::FIRST_AID_TENT))
  5410. {
  5411. RandomGeneratorUtil::randomShuffle(possibleStacks, getRandomGenerator());
  5412. const CStack * toBeHealed = possibleStacks.front();
  5413. BattleAction heal;
  5414. heal.actionType = EActionType::STACK_HEAL;
  5415. heal.aimToUnit(toBeHealed);
  5416. heal.side = next->unitSide();
  5417. heal.stackNumber = next->unitId();
  5418. makeAutomaticAction(next, heal);
  5419. continue;
  5420. }
  5421. }
  5422. int numberOfAsks = 1;
  5423. bool breakOuter = false;
  5424. do
  5425. {//ask interface and wait for answer
  5426. if (!battleResult.get())
  5427. {
  5428. stackTurnTrigger(next); //various effects
  5429. if(next->fear)
  5430. {
  5431. makeStackDoNothing(next); //end immediately if stack was affected by fear
  5432. }
  5433. else
  5434. {
  5435. logGlobal->trace("Activating %s", next->nodeName());
  5436. auto nextId = next->unitId();
  5437. BattleSetActiveStack sas;
  5438. sas.stack = nextId;
  5439. sendAndApply(&sas);
  5440. auto actionWasMade = [&]() -> bool
  5441. {
  5442. if (battleMadeAction.data)//active stack has made its action
  5443. return true;
  5444. if (battleResult.get())// battle is finished
  5445. return true;
  5446. if (next == nullptr)//active stack was been removed
  5447. return true;
  5448. return !next->alive();//active stack is dead
  5449. };
  5450. boost::unique_lock<boost::mutex> lock(battleMadeAction.mx);
  5451. battleMadeAction.data = false;
  5452. while ((lobby->state != EServerState::SHUTDOWN) && !actionWasMade())
  5453. {
  5454. battleMadeAction.cond.wait(lock);
  5455. if (battleGetStackByID(nextId, false) != next)
  5456. next = nullptr; //it may be removed, while we wait
  5457. }
  5458. }
  5459. }
  5460. if (battleResult.get()) //don't touch it, battle could be finished while waiting got action
  5461. {
  5462. breakOuter = true;
  5463. break;
  5464. }
  5465. //we're after action, all results applied
  5466. checkBattleStateChanges(); //check if this action ended the battle
  5467. if(next != nullptr)
  5468. {
  5469. //check for good morale
  5470. nextStackMorale = next->moraleVal();
  5471. if( !battleResult.get()
  5472. && !next->hadMorale
  5473. && !next->defending
  5474. && !next->waited()
  5475. && !next->fear
  5476. && next->alive()
  5477. && nextStackMorale > 0)
  5478. {
  5479. auto diceSize = VLC->settings()->getVector(EGameSettings::COMBAT_GOOD_MORALE_DICE);
  5480. size_t diceIndex = std::min<size_t>(diceSize.size()-1, nextStackMorale);
  5481. if(diceSize.size() > 0 && getRandomGenerator().nextInt(1, diceSize[diceIndex]) == 1)
  5482. {
  5483. BattleTriggerEffect bte;
  5484. bte.stackID = next->unitId();
  5485. bte.effect = vstd::to_underlying(BonusType::MORALE);
  5486. bte.val = 1;
  5487. bte.additionalInfo = 0;
  5488. sendAndApply(&bte); //play animation
  5489. ++numberOfAsks; //move this stack once more
  5490. }
  5491. }
  5492. }
  5493. --numberOfAsks;
  5494. } while (numberOfAsks > 0);
  5495. if (breakOuter)
  5496. {
  5497. break;
  5498. }
  5499. }
  5500. firstRound = false;
  5501. }
  5502. if (lobby->state != EServerState::SHUTDOWN)
  5503. endBattle(gs->curB->tile, gs->curB->battleGetFightingHero(0), gs->curB->battleGetFightingHero(1));
  5504. }
  5505. bool CGameHandler::makeAutomaticAction(const CStack *stack, BattleAction &ba)
  5506. {
  5507. BattleSetActiveStack bsa;
  5508. bsa.stack = stack->unitId();
  5509. bsa.askPlayerInterface = false;
  5510. sendAndApply(&bsa);
  5511. bool ret = makeBattleAction(ba);
  5512. checkBattleStateChanges();
  5513. return ret;
  5514. }
  5515. bool CGameHandler::giveHeroArtifact(const CGHeroInstance * h, const CArtifactInstance * a, ArtifactPosition pos)
  5516. {
  5517. assert(a->artType);
  5518. ArtifactLocation al(h, ArtifactPosition::PRE_FIRST);
  5519. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  5520. {
  5521. al.slot = ArtifactUtils::getArtAnyPosition(h, a->getTypeId());
  5522. }
  5523. else if(ArtifactUtils::isSlotBackpack(pos))
  5524. {
  5525. al.slot = ArtifactUtils::getArtBackpackPosition(h, a->getTypeId());
  5526. }
  5527. else
  5528. {
  5529. al.slot = pos;
  5530. }
  5531. if(a->canBePutAt(al))
  5532. putArtifact(al, a);
  5533. else
  5534. return false;
  5535. return true;
  5536. }
  5537. void CGameHandler::putArtifact(const ArtifactLocation &al, const CArtifactInstance *a)
  5538. {
  5539. PutArtifact pa;
  5540. pa.art = a;
  5541. pa.al = al;
  5542. sendAndApply(&pa);
  5543. }
  5544. bool CGameHandler::giveHeroNewArtifact(const CGHeroInstance * h, const CArtifact * artType, ArtifactPosition pos)
  5545. {
  5546. assert(artType);
  5547. if(pos == ArtifactPosition::FIRST_AVAILABLE)
  5548. {
  5549. if(!artType->canBePutAt(h, ArtifactUtils::getArtAnyPosition(h, artType->getId())))
  5550. COMPLAIN_RET("Cannot put artifact in that slot!");
  5551. }
  5552. else if(ArtifactUtils::isSlotBackpack(pos))
  5553. {
  5554. if(!artType->canBePutAt(h, ArtifactUtils::getArtBackpackPosition(h, artType->getId())))
  5555. COMPLAIN_RET("Cannot put artifact in that slot!");
  5556. }
  5557. else
  5558. {
  5559. COMPLAIN_RET_FALSE_IF(!artType->canBePutAt(h, pos, false), "Cannot put artifact in that slot!");
  5560. }
  5561. auto * newArtInst = new CArtifactInstance();
  5562. newArtInst->artType = artType; // *NOT* via settype -> all bonus-related stuff must be done by NewArtifact apply
  5563. NewArtifact na;
  5564. na.art = newArtInst;
  5565. sendAndApply(&na); // -> updates newArtInst!!!
  5566. if(giveHeroArtifact(h, newArtInst, pos))
  5567. return true;
  5568. else
  5569. return false;
  5570. }
  5571. void CGameHandler::setBattleResult(BattleResult::EResult resultType, int victoriusSide)
  5572. {
  5573. boost::unique_lock<boost::mutex> guard(battleResult.mx);
  5574. if (battleResult.data)
  5575. {
  5576. complain((boost::format("The battle result has been already set (to %d, asked to %d)")
  5577. % battleResult.data->result % resultType).str());
  5578. return;
  5579. }
  5580. auto br = new BattleResult();
  5581. br->result = resultType;
  5582. br->winner = victoriusSide; //surrendering side loses
  5583. gs->curB->calculateCasualties(br->casualties);
  5584. battleResult.data = br;
  5585. }
  5586. void CGameHandler::spawnWanderingMonsters(CreatureID creatureID)
  5587. {
  5588. std::vector<int3>::iterator tile;
  5589. std::vector<int3> tiles;
  5590. getFreeTiles(tiles);
  5591. ui32 amount = (ui32)tiles.size() / 200; //Chance is 0.5% for each tile
  5592. RandomGeneratorUtil::randomShuffle(tiles, getRandomGenerator());
  5593. logGlobal->trace("Spawning wandering monsters. Found %d free tiles. Creature type: %d", tiles.size(), creatureID.num);
  5594. const CCreature *cre = VLC->creh->objects.at(creatureID);
  5595. for (int i = 0; i < (int)amount; ++i)
  5596. {
  5597. tile = tiles.begin();
  5598. logGlobal->trace("\tSpawning monster at %s", tile->toString());
  5599. {
  5600. auto count = cre->getRandomAmount(std::rand);
  5601. createObject(*tile, Obj::MONSTER, creatureID);
  5602. auto monsterId = getTopObj(*tile)->id;
  5603. setObjProperty(monsterId, ObjProperty::MONSTER_COUNT, count);
  5604. setObjProperty(monsterId, ObjProperty::MONSTER_POWER, (si64)1000*count);
  5605. }
  5606. tiles.erase(tile); //not use it again
  5607. }
  5608. }
  5609. void CGameHandler::removeObstacle(const CObstacleInstance & obstacle)
  5610. {
  5611. BattleObstaclesChanged obsRem;
  5612. obsRem.changes.emplace_back(obstacle.uniqueID, ObstacleChanges::EOperation::REMOVE);
  5613. sendAndApply(&obsRem);
  5614. }
  5615. void CGameHandler::synchronizeArtifactHandlerLists()
  5616. {
  5617. UpdateArtHandlerLists uahl;
  5618. uahl.treasures = VLC->arth->treasures;
  5619. uahl.minors = VLC->arth->minors;
  5620. uahl.majors = VLC->arth->majors;
  5621. uahl.relics = VLC->arth->relics;
  5622. sendAndApply(&uahl);
  5623. }
  5624. bool CGameHandler::isValidObject(const CGObjectInstance *obj) const
  5625. {
  5626. return vstd::contains(gs->map->objects, obj);
  5627. }
  5628. bool CGameHandler::isBlockedByQueries(const CPack *pack, PlayerColor player)
  5629. {
  5630. if (!strcmp(typeid(*pack).name(), typeid(PlayerMessage).name()))
  5631. return false;
  5632. auto query = queries.topQuery(player);
  5633. if (query && query->blocksPack(pack))
  5634. {
  5635. complain(boost::str(boost::format(
  5636. "\r\n| Player \"%s\" has to answer queries before attempting any further actions.\r\n| Top Query: \"%s\"\r\n")
  5637. % boost::to_upper_copy<std::string>(player.getStr())
  5638. % query->toString()
  5639. ));
  5640. return true;
  5641. }
  5642. return false;
  5643. }
  5644. void CGameHandler::removeAfterVisit(const CGObjectInstance *object)
  5645. {
  5646. //If the object is being visited, there must be a matching query
  5647. for (const auto &query : queries.allQueries())
  5648. {
  5649. if (auto someVistQuery = std::dynamic_pointer_cast<CObjectVisitQuery>(query))
  5650. {
  5651. if (someVistQuery->visitedObject == object)
  5652. {
  5653. someVistQuery->removeObjectAfterVisit = true;
  5654. return;
  5655. }
  5656. }
  5657. }
  5658. //If we haven't returned so far, there is no query and no visit, call was wrong
  5659. assert("This function needs to be called during the object visit!");
  5660. }
  5661. void CGameHandler::changeFogOfWar(int3 center, ui32 radius, PlayerColor player, bool hide)
  5662. {
  5663. std::unordered_set<int3> tiles;
  5664. getTilesInRange(tiles, center, radius, player, hide? -1 : 1);
  5665. if (hide)
  5666. {
  5667. std::unordered_set<int3> observedTiles; //do not hide tiles observed by heroes. May lead to disastrous AI problems
  5668. auto p = getPlayerState(player);
  5669. for (auto h : p->heroes)
  5670. {
  5671. getTilesInRange(observedTiles, h->getSightCenter(), h->getSightRadius(), h->tempOwner, -1);
  5672. }
  5673. for (auto t : p->towns)
  5674. {
  5675. getTilesInRange(observedTiles, t->getSightCenter(), t->getSightRadius(), t->tempOwner, -1);
  5676. }
  5677. for (auto tile : observedTiles)
  5678. vstd::erase_if_present (tiles, tile);
  5679. }
  5680. changeFogOfWar(tiles, player, hide);
  5681. }
  5682. void CGameHandler::changeFogOfWar(std::unordered_set<int3> &tiles, PlayerColor player, bool hide)
  5683. {
  5684. FoWChange fow;
  5685. fow.tiles = tiles;
  5686. fow.player = player;
  5687. fow.mode = hide? 0 : 1;
  5688. sendAndApply(&fow);
  5689. }
  5690. bool CGameHandler::isVisitCoveredByAnotherQuery(const CGObjectInstance *obj, const CGHeroInstance *hero)
  5691. {
  5692. if (auto topQuery = queries.topQuery(hero->getOwner()))
  5693. if (auto visit = std::dynamic_pointer_cast<const CObjectVisitQuery>(topQuery))
  5694. return !(visit->visitedObject == obj && visit->visitingHero == hero);
  5695. return true;
  5696. }
  5697. void CGameHandler::setObjProperty(ObjectInstanceID objid, int prop, si64 val)
  5698. {
  5699. SetObjectProperty sob;
  5700. sob.id = objid;
  5701. sob.what = prop;
  5702. sob.val = static_cast<ui32>(val);
  5703. sendAndApply(&sob);
  5704. }
  5705. void CGameHandler::showInfoDialog(InfoWindow * iw)
  5706. {
  5707. sendAndApply(iw);
  5708. }
  5709. void CGameHandler::showInfoDialog(const std::string & msg, PlayerColor player)
  5710. {
  5711. InfoWindow iw;
  5712. iw.player = player;
  5713. iw.text.appendRawString(msg);
  5714. showInfoDialog(&iw);
  5715. }
  5716. CasualtiesAfterBattle::CasualtiesAfterBattle(const SideInBattle & battleSide, const BattleInfo * bat):
  5717. army(battleSide.armyObject)
  5718. {
  5719. heroWithDeadCommander = ObjectInstanceID();
  5720. PlayerColor color = battleSide.color;
  5721. for(CStack * st : bat->stacks)
  5722. {
  5723. if(st->summoned) //don't take into account temporary summoned stacks
  5724. continue;
  5725. if(st->unitOwner() != color) //remove only our stacks
  5726. continue;
  5727. logGlobal->debug("Calculating casualties for %s", st->nodeName());
  5728. st->health.takeResurrected();
  5729. if(st->unitSlot() == SlotID::ARROW_TOWERS_SLOT)
  5730. {
  5731. logGlobal->debug("Ignored arrow towers stack.");
  5732. }
  5733. else if(st->unitSlot() == SlotID::WAR_MACHINES_SLOT)
  5734. {
  5735. auto warMachine = st->unitType()->warMachine;
  5736. if(warMachine == ArtifactID::NONE)
  5737. {
  5738. logGlobal->error("Invalid creature in war machine virtual slot. Stack: %s", st->nodeName());
  5739. }
  5740. //catapult artifact remain even if "creature" killed in siege
  5741. else if(warMachine != ArtifactID::CATAPULT && st->getCount() <= 0)
  5742. {
  5743. logGlobal->debug("War machine has been destroyed");
  5744. auto hero = dynamic_ptr_cast<CGHeroInstance> (army);
  5745. if (hero)
  5746. removedWarMachines.push_back (ArtifactLocation(hero, hero->getArtPos(warMachine, true)));
  5747. else
  5748. logGlobal->error("War machine in army without hero");
  5749. }
  5750. }
  5751. else if(st->unitSlot() == SlotID::SUMMONED_SLOT_PLACEHOLDER)
  5752. {
  5753. if(st->alive() && st->getCount() > 0)
  5754. {
  5755. logGlobal->debug("Permanently summoned %d units.", st->getCount());
  5756. const CreatureID summonedType = st->creatureId();
  5757. summoned[summonedType] += st->getCount();
  5758. }
  5759. }
  5760. else if(st->unitSlot() == SlotID::COMMANDER_SLOT_PLACEHOLDER)
  5761. {
  5762. if (nullptr == st->base)
  5763. {
  5764. logGlobal->error("Stack with no base in commander slot. Stack: %s", st->nodeName());
  5765. }
  5766. else
  5767. {
  5768. auto c = dynamic_cast <const CCommanderInstance *>(st->base);
  5769. if(c)
  5770. {
  5771. auto h = dynamic_cast <const CGHeroInstance *>(army);
  5772. if(h && h->commander == c && (st->getCount() == 0 || !st->alive()))
  5773. {
  5774. logGlobal->debug("Commander is dead.");
  5775. heroWithDeadCommander = army->id; //TODO: unify commander handling
  5776. }
  5777. }
  5778. else
  5779. logGlobal->error("Stack with invalid instance in commander slot. Stack: %s", st->nodeName());
  5780. }
  5781. }
  5782. else if(st->base && !army->slotEmpty(st->unitSlot()))
  5783. {
  5784. logGlobal->debug("Count: %d; base count: %d", st->getCount(), army->getStackCount(st->unitSlot()));
  5785. if(st->getCount() == 0 || !st->alive())
  5786. {
  5787. logGlobal->debug("Stack has been destroyed.");
  5788. StackLocation sl(army, st->unitSlot());
  5789. newStackCounts.push_back(TStackAndItsNewCount(sl, 0));
  5790. }
  5791. else if(st->getCount() < army->getStackCount(st->unitSlot()))
  5792. {
  5793. logGlobal->debug("Stack lost %d units.", army->getStackCount(st->unitSlot()) - st->getCount());
  5794. StackLocation sl(army, st->unitSlot());
  5795. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  5796. }
  5797. else if(st->getCount() > army->getStackCount(st->unitSlot()))
  5798. {
  5799. logGlobal->debug("Stack gained %d units.", st->getCount() - army->getStackCount(st->unitSlot()));
  5800. StackLocation sl(army, st->unitSlot());
  5801. newStackCounts.push_back(TStackAndItsNewCount(sl, st->getCount()));
  5802. }
  5803. }
  5804. else
  5805. {
  5806. logGlobal->warn("Unable to process stack: %s", st->nodeName());
  5807. }
  5808. }
  5809. }
  5810. void CasualtiesAfterBattle::updateArmy(CGameHandler *gh)
  5811. {
  5812. for (TStackAndItsNewCount &ncount : newStackCounts)
  5813. {
  5814. if (ncount.second > 0)
  5815. gh->changeStackCount(ncount.first, ncount.second, true);
  5816. else
  5817. gh->eraseStack(ncount.first, true);
  5818. }
  5819. for (auto summoned_iter : summoned)
  5820. {
  5821. SlotID slot = army->getSlotFor(summoned_iter.first);
  5822. if (slot.validSlot())
  5823. {
  5824. StackLocation location(army, slot);
  5825. gh->addToSlot(location, summoned_iter.first.toCreature(), summoned_iter.second);
  5826. }
  5827. else
  5828. {
  5829. //even if it will be possible to summon anything permanently it should be checked for free slot
  5830. //necromancy is handled separately
  5831. gh->complain("No free slot to put summoned creature");
  5832. }
  5833. }
  5834. for (auto al : removedWarMachines)
  5835. {
  5836. gh->removeArtifact(al);
  5837. }
  5838. if (heroWithDeadCommander != ObjectInstanceID())
  5839. {
  5840. SetCommanderProperty scp;
  5841. scp.heroid = heroWithDeadCommander;
  5842. scp.which = SetCommanderProperty::ALIVE;
  5843. scp.amount = 0;
  5844. gh->sendAndApply(&scp);
  5845. }
  5846. }
  5847. CGameHandler::FinishingBattleHelper::FinishingBattleHelper(std::shared_ptr<const CBattleQuery> Query, int RemainingBattleQueriesCount)
  5848. {
  5849. assert(Query->result);
  5850. assert(Query->bi);
  5851. auto &result = *Query->result;
  5852. auto &info = *Query->bi;
  5853. winnerHero = result.winner != 0 ? info.sides[1].hero : info.sides[0].hero;
  5854. loserHero = result.winner != 0 ? info.sides[0].hero : info.sides[1].hero;
  5855. victor = info.sides[result.winner].color;
  5856. loser = info.sides[!result.winner].color;
  5857. winnerSide = result.winner;
  5858. remainingBattleQueriesCount = RemainingBattleQueriesCount;
  5859. }
  5860. CGameHandler::FinishingBattleHelper::FinishingBattleHelper()
  5861. {
  5862. winnerHero = loserHero = nullptr;
  5863. winnerSide = 0;
  5864. remainingBattleQueriesCount = 0;
  5865. }
  5866. CRandomGenerator & CGameHandler::getRandomGenerator()
  5867. {
  5868. return CRandomGenerator::getDefault();
  5869. }
  5870. #if SCRIPTING_ENABLED
  5871. scripting::Pool * CGameHandler::getGlobalContextPool() const
  5872. {
  5873. return serverScripts.get();
  5874. }
  5875. scripting::Pool * CGameHandler::getContextPool() const
  5876. {
  5877. return serverScripts.get();
  5878. }
  5879. #endif
  5880. void CGameHandler::createObject(const int3 & visitablePosition, Obj type, int32_t subtype)
  5881. {
  5882. NewObject no;
  5883. no.ID = type;
  5884. no.subID= subtype;
  5885. no.targetPos = visitablePosition;
  5886. sendAndApply(&no);
  5887. }
  5888. void CGameHandler::deserializationFix()
  5889. {
  5890. //FIXME: pointer to GameHandler itself can't be deserialized at the moment since GameHandler is top-level entity in serialization
  5891. // restore any places that requires such pointer manually
  5892. heroPool->gameHandler = this;
  5893. playerMessages->gameHandler = this;
  5894. }