CGameHandler.cpp 177 KB

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