CGameHandler.cpp 196 KB

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