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