CGameHandler.cpp 192 KB

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