CGameHandler.cpp 206 KB

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