CGameHandler.cpp 169 KB

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