CGameHandler.cpp 199 KB

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