CGameHandler.cpp 171 KB

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