CGameHandler.cpp 198 KB

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