CGameHandler.cpp 221 KB

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