CGameHandler.cpp 221 KB

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