CGameHandler.cpp 189 KB

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