CGameHandler.cpp 191 KB

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