CGameHandler.cpp 225 KB

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