CObjectHandler.cpp 202 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603
  1. /*
  2. * CObjectHandler.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "CObjectHandler.h"
  12. #include "CDefObjInfoHandler.h"
  13. #include "CGeneralTextHandler.h"
  14. #include "CDefObjInfoHandler.h"
  15. #include "CHeroHandler.h"
  16. #include "CSpellHandler.h"
  17. #include "CModHandler.h"
  18. #include "../client/CSoundBase.h"
  19. #include "CTownHandler.h"
  20. #include "CCreatureHandler.h"
  21. #include "VCMI_Lib.h"
  22. #include "IGameCallback.h"
  23. #include "CGameState.h"
  24. #include "NetPacks.h"
  25. #include "StartInfo.h"
  26. #include "mapping/CMap.h"
  27. #include <SDL_stdinc.h>
  28. #include "CBuildingHandler.h"
  29. #include "JsonNode.h"
  30. #include "filesystem/Filesystem.h"
  31. using namespace boost::assign;
  32. std::map<Obj, std::map<int, std::vector<ObjectInstanceID> > > CGTeleport::objs;
  33. std::vector<std::pair<ObjectInstanceID, ObjectInstanceID> > CGTeleport::gates;
  34. IGameCallback * IObjectInterface::cb = nullptr;
  35. extern std::minstd_rand ran;
  36. std::map <PlayerColor, std::set <ui8> > CGKeys::playerKeyMap;
  37. std::map <si32, std::vector<ObjectInstanceID> > CGMagi::eyelist;
  38. ui8 CGObelisk::obeliskCount; //how many obelisks are on map
  39. std::map<TeamID, ui8> CGObelisk::visited; //map: team_id => how many obelisks has been visited
  40. std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
  41. std::vector<int> CGTownInstance::universitySkills;
  42. ///helpers
  43. static void openWindow(const OpenWindow::EWindow type, const int id1, const int id2 = -1)
  44. {
  45. OpenWindow ow;
  46. ow.window = type;
  47. ow.id1 = id1;
  48. ow.id2 = id2;
  49. IObjectInterface::cb->sendAndApply(&ow);
  50. }
  51. static void showInfoDialog(const PlayerColor playerID, const ui32 txtID, const ui16 soundID)
  52. {
  53. InfoWindow iw;
  54. iw.soundID = soundID;
  55. iw.player = playerID;
  56. iw.text.addTxt(MetaString::ADVOB_TXT,txtID);
  57. IObjectInterface::cb->sendAndApply(&iw);
  58. }
  59. /*static void showInfoDialog(const ObjectInstanceID heroID, const ui32 txtID, const ui16 soundID)
  60. {
  61. const PlayerColor playerID = IObjectInterface::cb->getOwner(heroID);
  62. showInfoDialog(playerID,txtID,soundID);
  63. }*/
  64. static void showInfoDialog(const CGHeroInstance* h, const ui32 txtID, const ui16 soundID)
  65. {
  66. const PlayerColor playerID = h->getOwner();
  67. showInfoDialog(playerID,txtID,soundID);
  68. }
  69. static std::string & visitedTxt(const bool visited)
  70. {
  71. int id = visited ? 352 : 353;
  72. return VLC->generaltexth->allTexts[id];
  73. }
  74. ///IObjectInterface
  75. void IObjectInterface::onHeroVisit(const CGHeroInstance * h) const
  76. {}
  77. void IObjectInterface::onHeroLeave(const CGHeroInstance * h) const
  78. {}
  79. void IObjectInterface::newTurn () const
  80. {}
  81. IObjectInterface::~IObjectInterface()
  82. {}
  83. IObjectInterface::IObjectInterface()
  84. {}
  85. void IObjectInterface::initObj()
  86. {}
  87. void IObjectInterface::setProperty( ui8 what, ui32 val )
  88. {}
  89. bool IObjectInterface::wasVisited (PlayerColor player) const
  90. {
  91. return false;
  92. }
  93. bool IObjectInterface::wasVisited (const CGHeroInstance * h) const
  94. {
  95. return false;
  96. }
  97. void IObjectInterface::postInit()
  98. {}
  99. void IObjectInterface::preInit()
  100. {}
  101. void IObjectInterface::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  102. {
  103. }
  104. void IObjectInterface::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  105. {
  106. }
  107. void IObjectInterface::garrisonDialogClosed(const CGHeroInstance *hero) const
  108. {
  109. }
  110. void IObjectInterface::heroLevelUpDone(const CGHeroInstance *hero) const
  111. {
  112. }
  113. void CPlayersVisited::setPropertyDer( ui8 what, ui32 val )
  114. {
  115. if(what == 10)
  116. players.insert(PlayerColor(val));
  117. }
  118. bool CPlayersVisited::wasVisited( PlayerColor player ) const
  119. {
  120. return vstd::contains(players,player);
  121. }
  122. bool CPlayersVisited::wasVisited( TeamID team ) const
  123. {
  124. for(auto i : players)
  125. {
  126. if(cb->getPlayer(i)->team == team)
  127. return true;
  128. }
  129. return false;
  130. }
  131. // Bank helper. Find the creature ID and their number, and store the
  132. // result in storage (either guards or reward creatures).
  133. static void readCreatures(const JsonNode &creature, std::vector< std::pair <CreatureID, ui32> > &storage)
  134. {
  135. std::pair<CreatureID, si32> creInfo = std::make_pair(CreatureID::NONE, 0);
  136. //TODO: replace numeric id's with mod-friendly string id's
  137. creInfo.second = creature["number"].Float();
  138. creInfo.first = CreatureID((si32)creature["id"].Float());
  139. storage.push_back(creInfo);
  140. }
  141. // Bank helper. Process a bank level.
  142. static void readBankLevel(const JsonNode &level, BankConfig &bc)
  143. {
  144. int idx;
  145. bc.chance = level["chance"].Float();
  146. for(const JsonNode &creature : level["guards"].Vector())
  147. {
  148. readCreatures(creature, bc.guards);
  149. }
  150. bc.upgradeChance = level["upgrade_chance"].Float();
  151. bc.combatValue = level["combat_value"].Float();
  152. bc.resources = Res::ResourceSet(level["reward_resources"]);
  153. for(const JsonNode &creature : level["reward_creatures"].Vector())
  154. {
  155. readCreatures(creature, bc.creatures);
  156. }
  157. bc.artifacts.resize(4);
  158. idx = 0;
  159. for(const JsonNode &artifact : level["reward_artifacts"].Vector())
  160. {
  161. bc.artifacts[idx] = artifact.Float();
  162. idx ++;
  163. }
  164. bc.value = level["value"].Float();
  165. bc.rewardDifficulty = level["profitability"].Float();
  166. bc.easiest = level["easiest"].Float();
  167. }
  168. CObjectHandler::CObjectHandler()
  169. {
  170. logGlobal->traceStream() << "\t\tReading cregens ";
  171. const JsonNode config(ResourceID("config/dwellings.json"));
  172. for(const JsonNode &dwelling : config["dwellings"].Vector())
  173. {
  174. cregens[dwelling["dwelling"].Float()] = CreatureID((si32)dwelling["creature"].Float());
  175. }
  176. logGlobal->traceStream() << "\t\tDone loading cregens!";
  177. logGlobal->traceStream() << "\t\tReading resources prices ";
  178. const JsonNode config2(ResourceID("config/resources.json"));
  179. for(const JsonNode &price : config2["resources_prices"].Vector())
  180. {
  181. resVals.push_back(price.Float());
  182. }
  183. logGlobal->traceStream() << "\t\tDone loading resource prices!";
  184. logGlobal->traceStream() << "\t\tReading banks configs";
  185. const JsonNode config3(ResourceID("config/bankconfig.json"));
  186. int bank_num = 0;
  187. for(const JsonNode &bank : config3["banks"].Vector())
  188. {
  189. creBanksNames[bank_num] = bank["name"].String();
  190. int level_num = 0;
  191. for(const JsonNode &level : bank["levels"].Vector())
  192. {
  193. banksInfo[bank_num].push_back(new BankConfig);
  194. BankConfig &bc = *banksInfo[bank_num].back();
  195. bc.level = level_num;
  196. readBankLevel(level, bc);
  197. level_num ++;
  198. }
  199. bank_num ++;
  200. }
  201. logGlobal->traceStream() << "\t\tDone loading banks configs";
  202. }
  203. CObjectHandler::~CObjectHandler()
  204. {
  205. for(auto & mapEntry : banksInfo)
  206. {
  207. for(auto & vecEntry : mapEntry.second)
  208. {
  209. vecEntry.dellNull();
  210. }
  211. }
  212. }
  213. int CObjectHandler::bankObjToIndex (const CGObjectInstance * obj)
  214. {
  215. switch (obj->ID) //find appriopriate key
  216. {
  217. case Obj::CREATURE_BANK:
  218. return obj->subID;
  219. case Obj::DERELICT_SHIP:
  220. return 8;
  221. case Obj::DRAGON_UTOPIA:
  222. return 10;
  223. case Obj::CRYPT:
  224. return 9;
  225. case Obj::SHIPWRECK:
  226. return 7;
  227. case Obj::PYRAMID:
  228. return 21;
  229. default:
  230. logGlobal->warnStream() << "Unrecognized Bank indetifier!";
  231. return 0;
  232. }
  233. }
  234. PlayerColor CGObjectInstance::getOwner() const
  235. {
  236. //if (state)
  237. // return state->owner;
  238. //else
  239. return tempOwner; //won't have owner
  240. }
  241. CGObjectInstance::CGObjectInstance():
  242. pos(-1,-1,-1),
  243. ID(Obj::NO_OBJ),
  244. subID(-1),
  245. tempOwner(PlayerColor::UNFLAGGABLE),
  246. blockVisit(false)
  247. {
  248. }
  249. CGObjectInstance::~CGObjectInstance()
  250. {
  251. //if (state)
  252. // delete state;
  253. //state=nullptr;
  254. }
  255. const std::string & CGObjectInstance::getHoverText() const
  256. {
  257. return hoverName;
  258. }
  259. void CGObjectInstance::setOwner(PlayerColor ow)
  260. {
  261. //if (state)
  262. // state->owner = ow;
  263. //else
  264. tempOwner = ow;
  265. }
  266. int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
  267. {
  268. return appearance.getWidth();
  269. }
  270. int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
  271. {
  272. return appearance.getHeight();
  273. }
  274. bool CGObjectInstance::visitableAt(int x, int y) const //returns true if object is visitable at location (x, y) form left top tile of image (x, y in tiles)
  275. {
  276. return appearance.isVisitableAt(pos.x - x, pos.y - y);
  277. }
  278. bool CGObjectInstance::blockingAt(int x, int y) const
  279. {
  280. return appearance.isBlockedAt(pos.x - x, pos.y - y);
  281. }
  282. bool CGObjectInstance::coveringAt(int x, int y) const
  283. {
  284. return appearance.isVisibleAt(pos.x - x, pos.y - y);
  285. }
  286. std::set<int3> CGObjectInstance::getBlockedPos() const
  287. {
  288. std::set<int3> ret;
  289. for(int w=0; w<getWidth(); ++w)
  290. {
  291. for(int h=0; h<getHeight(); ++h)
  292. {
  293. if (appearance.isBlockedAt(w, h))
  294. ret.insert(int3(pos.x - w, pos.y - h, pos.z));
  295. }
  296. }
  297. return ret;
  298. }
  299. bool CGObjectInstance::operator<(const CGObjectInstance & cmp) const //screen printing priority comparing
  300. {
  301. if (appearance.printPriority != cmp.appearance.printPriority)
  302. return appearance.printPriority > cmp.appearance.printPriority;
  303. if(pos.y != cmp.pos.y)
  304. return pos.y < cmp.pos.y;
  305. if(cmp.ID==Obj::HERO && ID!=Obj::HERO)
  306. return true;
  307. if(cmp.ID!=Obj::HERO && ID==Obj::HERO)
  308. return false;
  309. if(!isVisitable() && cmp.isVisitable())
  310. return true;
  311. if(!cmp.isVisitable() && isVisitable())
  312. return false;
  313. if(this->pos.x<cmp.pos.x)
  314. return true;
  315. return false;
  316. }
  317. void CGObjectInstance::initObj()
  318. {
  319. switch(ID)
  320. {
  321. case Obj::TAVERN:
  322. blockVisit = true;
  323. break;
  324. }
  325. }
  326. void CGObjectInstance::setProperty( ui8 what, ui32 val )
  327. {
  328. switch(what)
  329. {
  330. case ObjProperty::OWNER:
  331. tempOwner = PlayerColor(val);
  332. break;
  333. case ObjProperty::BLOCKVIS:
  334. blockVisit = val;
  335. break;
  336. case ObjProperty::ID:
  337. ID = Obj(val);
  338. break;
  339. case ObjProperty::SUBID:
  340. subID = val;
  341. break;
  342. }
  343. setPropertyDer(what, val);
  344. }
  345. void CGObjectInstance::setPropertyDer( ui8 what, ui32 val )
  346. {}
  347. int3 CGObjectInstance::getSightCenter() const
  348. {
  349. //return vistiable tile if possible
  350. for(int i=0; i < 8; i++)
  351. for(int j=0; j < 6; j++)
  352. if(visitableAt(i,j))
  353. return(pos + int3(i-7, j-5, 0));
  354. return pos;
  355. }
  356. int CGObjectInstance::getSightRadious() const
  357. {
  358. return 3;
  359. }
  360. void CGObjectInstance::getSightTiles(std::unordered_set<int3, ShashInt3> &tiles) const //returns reference to the set
  361. {
  362. cb->getTilesInRange(tiles, getSightCenter(), getSightRadious(), tempOwner, 1);
  363. }
  364. void CGObjectInstance::hideTiles(PlayerColor ourplayer, int radius) const
  365. {
  366. for (auto i = cb->gameState()->teams.begin(); i != cb->gameState()->teams.end(); i++)
  367. {
  368. if ( !vstd::contains(i->second.players, ourplayer ))//another team
  369. {
  370. for (auto & elem : i->second.players)
  371. if ( cb->getPlayer(elem)->status == EPlayerStatus::INGAME )//seek for living player (if any)
  372. {
  373. FoWChange fw;
  374. fw.mode = 0;
  375. fw.player = elem;
  376. cb->getTilesInRange (fw.tiles, pos, radius, (elem), -1);
  377. cb->sendAndApply (&fw);
  378. break;
  379. }
  380. }
  381. }
  382. }
  383. int3 CGObjectInstance::getVisitableOffset() const
  384. {
  385. for(int y = 0; y < appearance.getHeight(); y++)
  386. for (int x = 0; x < appearance.getWidth(); x++)
  387. if (appearance.isVisitableAt(x, y))
  388. return int3(x,y,0);
  389. logGlobal->warnStream() << "Warning: getVisitableOffset called on non-visitable obj!";
  390. return int3(0,0,0);
  391. }
  392. void CGObjectInstance::getNameVis( std::string &hname ) const
  393. {
  394. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  395. hname = VLC->generaltexth->names[ID];
  396. if(h)
  397. {
  398. const bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  399. hname + " " + visitedTxt(visited);
  400. }
  401. }
  402. void CGObjectInstance::giveDummyBonus(ObjectInstanceID heroID, ui8 duration) const
  403. {
  404. GiveBonus gbonus;
  405. gbonus.bonus.type = Bonus::NONE;
  406. gbonus.id = heroID.getNum();
  407. gbonus.bonus.duration = duration;
  408. gbonus.bonus.source = Bonus::OBJECT;
  409. gbonus.bonus.sid = ID;
  410. cb->giveHeroBonus(&gbonus);
  411. }
  412. void CGObjectInstance::onHeroVisit( const CGHeroInstance * h ) const
  413. {
  414. switch(ID)
  415. {
  416. case Obj::HILL_FORT:
  417. {
  418. openWindow(OpenWindow::HILL_FORT_WINDOW,id.getNum(),h->id.getNum());
  419. }
  420. break;
  421. case Obj::SANCTUARY:
  422. {
  423. //You enter the sanctuary and immediately feel as if a great weight has been lifted off your shoulders. You feel safe here.
  424. showInfoDialog(h,114,soundBase::GETPROTECTION);
  425. }
  426. break;
  427. case Obj::TAVERN:
  428. {
  429. openWindow(OpenWindow::TAVERN_WINDOW,h->id.getNum(),id.getNum());
  430. }
  431. break;
  432. }
  433. }
  434. ui8 CGObjectInstance::getPassableness() const
  435. {
  436. return 0;
  437. }
  438. int3 CGObjectInstance::visitablePos() const
  439. {
  440. return pos - getVisitableOffset();
  441. }
  442. bool CGObjectInstance::isVisitable() const
  443. {
  444. return appearance.isVisitable();
  445. }
  446. bool CGObjectInstance::passableFor(PlayerColor color) const
  447. {
  448. return getPassableness() & 1<<color.getNum();
  449. }
  450. CGObjectInstanceBySubIdFinder::CGObjectInstanceBySubIdFinder(CGObjectInstance * obj) : obj(obj)
  451. {
  452. }
  453. bool CGObjectInstanceBySubIdFinder::operator()(CGObjectInstance * obj) const
  454. {
  455. return this->obj->subID == obj->subID;
  456. }
  457. static int lowestSpeed(const CGHeroInstance * chi)
  458. {
  459. if(!chi->Slots().size())
  460. {
  461. logGlobal->errorStream() << "Error! Hero " << chi->id.getNum() << " ("<<chi->name<<") has no army!";
  462. return 20;
  463. }
  464. auto i = chi->Slots().begin();
  465. //TODO? should speed modifiers (eg from artifacts) affect hero movement?
  466. int ret = (i++)->second->valOfBonuses(Bonus::STACKS_SPEED);
  467. for (;i!=chi->Slots().end();i++)
  468. {
  469. ret = std::min(ret, i->second->valOfBonuses(Bonus::STACKS_SPEED));
  470. }
  471. return ret;
  472. }
  473. ui32 CGHeroInstance::getTileCost(const TerrainTile &dest, const TerrainTile &from) const
  474. {
  475. //base move cost
  476. unsigned ret = 100;
  477. //if there is road both on dest and src tiles - use road movement cost
  478. if(dest.roadType != ERoadType::NO_ROAD && from.roadType != ERoadType::NO_ROAD)
  479. {
  480. int road = std::min(dest.roadType,from.roadType); //used road ID
  481. switch(road)
  482. {
  483. case ERoadType::DIRT_ROAD:
  484. ret = 75;
  485. break;
  486. case ERoadType::GRAVEL_ROAD:
  487. ret = 65;
  488. break;
  489. case ERoadType::COBBLESTONE_ROAD:
  490. ret = 50;
  491. break;
  492. default:
  493. logGlobal->errorStream() << "Unknown road type: " << road << "... Something wrong!";
  494. break;
  495. }
  496. }
  497. else
  498. {
  499. //FIXME: in H3 presence of Nomad in army will remove terrain penalty for sand. Bonus not implemented in VCMI
  500. // NOTE: in H3 neutral stacks will ignore terrain penalty only if placed as topmost stack(s) in hero army.
  501. // This is clearly bug in H3 however intended behaviour is not clear.
  502. // Current VCMI behaviour will ignore neutrals in calculations so army in VCMI
  503. // will always have best penalty without any influence from player-defined stacks order
  504. bool nativeArmy = true;
  505. for(auto stack : stacks)
  506. {
  507. int nativeTerrain = VLC->townh->factions[stack.second->type->faction]->nativeTerrain;
  508. if (nativeTerrain != -1 && nativeTerrain != from.terType)
  509. {
  510. nativeArmy = false;
  511. break;
  512. }
  513. }
  514. if (!nativeArmy)
  515. ret = VLC->heroh->terrCosts[from.terType];
  516. }
  517. return ret;
  518. }
  519. int3 CGHeroInstance::convertPosition(int3 src, bool toh3m) //toh3m=true: manifest->h3m; toh3m=false: h3m->manifest
  520. {
  521. if (toh3m)
  522. {
  523. src.x+=1;
  524. return src;
  525. }
  526. else
  527. {
  528. src.x-=1;
  529. return src;
  530. }
  531. }
  532. int3 CGHeroInstance::getPosition(bool h3m) const //h3m=true - returns position of hero object; h3m=false - returns position of hero 'manifestation'
  533. {
  534. if (h3m)
  535. {
  536. return pos;
  537. }
  538. else
  539. {
  540. return convertPosition(pos,false);
  541. }
  542. }
  543. bool CGHeroInstance::canWalkOnSea() const
  544. {
  545. return hasBonusOfType(Bonus::FLYING_MOVEMENT) || hasBonusOfType(Bonus::WATER_WALKING);
  546. }
  547. ui8 CGHeroInstance::getSecSkillLevel(SecondarySkill skill) const
  548. {
  549. for(auto & elem : secSkills)
  550. if(elem.first == skill)
  551. return elem.second;
  552. return 0;
  553. }
  554. void CGHeroInstance::setSecSkillLevel(SecondarySkill which, int val, bool abs)
  555. {
  556. if(getSecSkillLevel(which) == 0)
  557. {
  558. secSkills.push_back(std::pair<SecondarySkill,ui8>(which, val));
  559. updateSkill(which, val);
  560. }
  561. else
  562. {
  563. for (auto & elem : secSkills)
  564. {
  565. if(elem.first == which)
  566. {
  567. if(abs)
  568. elem.second = val;
  569. else
  570. elem.second += val;
  571. if(elem.second > 3) //workaround to avoid crashes when same sec skill is given more than once
  572. {
  573. logGlobal->warnStream() << "Warning: Skill " << which << " increased over limit! Decreasing to Expert.";
  574. elem.second = 3;
  575. }
  576. updateSkill(which, elem.second); //when we know final value
  577. }
  578. }
  579. }
  580. }
  581. bool CGHeroInstance::canLearnSkill() const
  582. {
  583. return secSkills.size() < GameConstants::SKILL_PER_HERO;
  584. }
  585. int CGHeroInstance::maxMovePoints(bool onLand) const
  586. {
  587. int base;
  588. if(onLand)
  589. {
  590. // used function is f(x) = 66.6x + 1300, rounded to second digit, where x is lowest speed in army
  591. static const int baseSpeed = 1300; // base speed from creature with 0 speed
  592. int armySpeed = lowestSpeed(this) * 20 / 3;
  593. base = armySpeed * 10 + baseSpeed; // separate *10 is intentional to receive same rounding as in h3
  594. vstd::abetween(base, 1500, 2000); // base speed is limited by these values
  595. }
  596. else
  597. {
  598. base = 1500; //on water base movement is always 1500 (speed of army doesn't matter)
  599. }
  600. const Bonus::BonusType bt = onLand ? Bonus::LAND_MOVEMENT : Bonus::SEA_MOVEMENT;
  601. const int bonus = valOfBonuses(Bonus::MOVEMENT) + valOfBonuses(bt);
  602. const int subtype = onLand ? SecondarySkill::LOGISTICS : SecondarySkill::NAVIGATION;
  603. const double modifier = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, subtype) / 100.0;
  604. return int(base* (1+modifier)) + bonus;
  605. }
  606. CGHeroInstance::CGHeroInstance()
  607. : IBoatGenerator(this)
  608. {
  609. setNodeType(HERO);
  610. ID = Obj::HERO;
  611. tacticFormationEnabled = inTownGarrison = false;
  612. mana = movement = portrait = level = -1;
  613. isStanding = true;
  614. moveDir = 4;
  615. exp = 0xffffffff;
  616. visitedTown = nullptr;
  617. type = nullptr;
  618. boat = nullptr;
  619. commander = nullptr;
  620. sex = 0xff;
  621. secSkills.push_back(std::make_pair(SecondarySkill::DEFAULT, -1));
  622. }
  623. void CGHeroInstance::initHero(HeroTypeID SUBID)
  624. {
  625. subID = SUBID.getNum();
  626. initHero();
  627. }
  628. void CGHeroInstance::initHero()
  629. {
  630. assert(validTypes(true));
  631. if(!type)
  632. type = VLC->heroh->heroes[subID];
  633. if (ID == Obj::HERO)
  634. appearance = VLC->dobjinfo->pickCandidates(Obj::HERO, type->heroClass->id).front();
  635. if(!vstd::contains(spells, SpellID::PRESET)) //hero starts with a spell
  636. {
  637. for(auto spellID : type->spells)
  638. spells.insert(spellID);
  639. }
  640. else //remove placeholder
  641. spells -= SpellID::PRESET;
  642. if(!getArt(ArtifactPosition::MACH4) && !getArt(ArtifactPosition::SPELLBOOK) && type->haveSpellBook) //no catapult means we haven't read pre-existent set -> use default rules for spellbook
  643. putArtifact(ArtifactPosition::SPELLBOOK, CArtifactInstance::createNewArtifactInstance(0));
  644. if(!getArt(ArtifactPosition::MACH4))
  645. putArtifact(ArtifactPosition::MACH4, CArtifactInstance::createNewArtifactInstance(3)); //everyone has a catapult
  646. if(portrait < 0 || portrait == 255)
  647. portrait = type->imageIndex;
  648. if(!hasBonus(Selector::sourceType(Bonus::HERO_BASE_SKILL)))
  649. {
  650. for(int g=0; g<GameConstants::PRIMARY_SKILLS; ++g)
  651. {
  652. pushPrimSkill(static_cast<PrimarySkill::PrimarySkill>(g), type->heroClass->primarySkillInitial[g]);
  653. }
  654. }
  655. if(secSkills.size() == 1 && secSkills[0] == std::pair<SecondarySkill,ui8>(SecondarySkill::DEFAULT, -1)) //set secondary skills to default
  656. secSkills = type->secSkillsInit;
  657. if (!name.length())
  658. name = type->name;
  659. if (sex == 0xFF)//sex is default
  660. sex = type->sex;
  661. setFormation(false);
  662. if (!stacksCount()) //standard army//initial army
  663. {
  664. initArmy();
  665. }
  666. assert(validTypes());
  667. if (exp == 0xffffffff)
  668. {
  669. initExp();
  670. }
  671. else if (ID != Obj::PRISON)
  672. {
  673. level = VLC->heroh->level(exp);
  674. }
  675. else //warp hero at the beginning of next turn
  676. {
  677. level = 1;
  678. }
  679. if (VLC->modh->modules.COMMANDERS && !commander)
  680. {
  681. commander = new CCommanderInstance(type->heroClass->commander->idNumber);
  682. commander->setArmyObj (castToArmyObj()); //TODO: separate function for setting commanders
  683. commander->giveStackExp (exp); //after our exp is set
  684. }
  685. if (mana < 0)
  686. mana = manaLimit();
  687. }
  688. void CGHeroInstance::initArmy(IArmyDescriptor *dst /*= nullptr*/)
  689. {
  690. if(!dst)
  691. dst = this;
  692. int howManyStacks = 0; //how many stacks will hero receives <1 - 3>
  693. int pom = ran()%100;
  694. int warMachinesGiven = 0;
  695. if(pom < 9)
  696. howManyStacks = 1;
  697. else if(pom < 79)
  698. howManyStacks = 2;
  699. else
  700. howManyStacks = 3;
  701. vstd::amin(howManyStacks, type->initialArmy.size());
  702. for(int stackNo=0; stackNo < howManyStacks; stackNo++)
  703. {
  704. auto & stack = type->initialArmy[stackNo];
  705. int range = stack.maxAmount - stack.minAmount;
  706. int count = ran()%(range+1) + stack.minAmount;
  707. if(stack.creature >= CreatureID::CATAPULT &&
  708. stack.creature <= CreatureID::ARROW_TOWERS) //war machine
  709. {
  710. warMachinesGiven++;
  711. if(dst != this)
  712. continue;
  713. int slot = -1;
  714. ArtifactID aid = ArtifactID::NONE;
  715. switch (stack.creature)
  716. {
  717. case CreatureID::CATAPULT:
  718. slot = ArtifactPosition::MACH4;
  719. aid = ArtifactID::CATAPULT;
  720. break;
  721. default:
  722. aid = CArtHandler::creatureToMachineID(stack.creature);
  723. slot = 9 + aid;
  724. break;
  725. }
  726. auto convSlot = ArtifactPosition(slot);
  727. if(!getArt(convSlot))
  728. putArtifact(convSlot, CArtifactInstance::createNewArtifactInstance(aid));
  729. else
  730. logGlobal->warnStream() << "Hero " << name << " already has artifact at " << slot << ", omitting giving " << aid;
  731. }
  732. else
  733. dst->setCreature(SlotID(stackNo-warMachinesGiven), stack.creature, count);
  734. }
  735. }
  736. CGHeroInstance::~CGHeroInstance()
  737. {
  738. commander.dellNull();
  739. }
  740. bool CGHeroInstance::needsLastStack() const
  741. {
  742. return true;
  743. }
  744. void CGHeroInstance::onHeroVisit(const CGHeroInstance * h) const
  745. {
  746. if(h == this) return; //exclude potential self-visiting
  747. if (ID == Obj::HERO)
  748. {
  749. if( cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner)) //our or ally hero
  750. {
  751. //exchange
  752. cb->heroExchange(h->id, id);
  753. }
  754. else //battle
  755. {
  756. if(visitedTown) //we're in town
  757. visitedTown->onHeroVisit(h); //town will handle attacking
  758. else
  759. cb->startBattleI(h, this);
  760. }
  761. }
  762. else if(ID == Obj::PRISON)
  763. {
  764. int txt_id;
  765. if(cb->getHeroCount(h->tempOwner,false) < GameConstants::MAX_HEROES_PER_PLAYER) //free hero slot
  766. {
  767. cb->changeObjPos(id,pos+int3(1,0,0),0);
  768. //update hero parameters
  769. SetMovePoints smp;
  770. smp.hid = id;
  771. smp.val = maxMovePoints (true); //TODO: hota prison on water?
  772. cb->setMovePoints (&smp);
  773. cb->setManaPoints (id, manaLimit());
  774. cb->setObjProperty(id, ObjProperty::ID, Obj::HERO); //set ID to 34
  775. cb->giveHero(id,h->tempOwner); //recreates def and adds hero to player
  776. txt_id = 102;
  777. }
  778. else //already 8 wandering heroes
  779. {
  780. txt_id = 103;
  781. }
  782. showInfoDialog(h,txt_id,soundBase::ROGUE);
  783. }
  784. }
  785. const std::string & CGHeroInstance::getHoverText() const
  786. {
  787. if(ID != Obj::PRISON)
  788. {
  789. hoverName = VLC->generaltexth->allTexts[15];
  790. boost::algorithm::replace_first(hoverName,"%s",name);
  791. boost::algorithm::replace_first(hoverName,"%s", type->heroClass->name);
  792. return hoverName;
  793. }
  794. else
  795. hoverName = VLC->generaltexth->names[ID];
  796. return hoverName;
  797. }
  798. const std::string & CGHeroInstance::getBiography() const
  799. {
  800. if (biography.length())
  801. return biography;
  802. return type->biography;
  803. }
  804. ui8 CGHeroInstance::maxlevelsToMagicSchool() const
  805. {
  806. return type->heroClass->isMagicHero() ? 3 : 4;
  807. }
  808. ui8 CGHeroInstance::maxlevelsToWisdom() const
  809. {
  810. return type->heroClass->isMagicHero() ? 3 : 6;
  811. }
  812. void CGHeroInstance::SecondarySkillsInfo::resetMagicSchoolCounter()
  813. {
  814. magicSchoolCounter = 1;
  815. }
  816. void CGHeroInstance::SecondarySkillsInfo::resetWisdomCounter()
  817. {
  818. wisdomCounter = 1;
  819. }
  820. void CGHeroInstance::initObj()
  821. {
  822. blockVisit = true;
  823. auto hs = new HeroSpecial();
  824. hs->setNodeType(CBonusSystemNode::specialty);
  825. attachTo(hs); //do we ever need to detach it?
  826. if(!type)
  827. initHero(); //TODO: set up everything for prison before specialties are configured
  828. skillsInfo.distribution.seed(rand());
  829. skillsInfo.resetMagicSchoolCounter();
  830. skillsInfo.resetWisdomCounter();
  831. for(const auto &spec : type->spec) //TODO: unfity with bonus system
  832. {
  833. auto bonus = new Bonus();
  834. bonus->val = spec.val;
  835. bonus->sid = id.getNum(); //from the hero, specialty has no unique id
  836. bonus->duration = Bonus::PERMANENT;
  837. bonus->source = Bonus::HERO_SPECIAL;
  838. switch (spec.type)
  839. {
  840. case 1:// creature specialty
  841. {
  842. hs->growsWithLevel = true;
  843. const CCreature &specCreature = *VLC->creh->creatures[spec.additionalinfo]; //creature in which we have specialty
  844. //int creLevel = specCreature.level;
  845. //if(!creLevel)
  846. //{
  847. // if(spec.additionalinfo == 146)
  848. // creLevel = 5; //treat ballista as 5-level
  849. // else
  850. // {
  851. // logGlobal->warnStream() << "Warning: unknown level of " << specCreature.namePl;
  852. // continue;
  853. // }
  854. //}
  855. //bonus->additionalInfo = spec.additionalinfo; //creature id, should not be used again - this works only with limiter
  856. bonus->limiter.reset(new CCreatureTypeLimiter (specCreature, true)); //with upgrades
  857. bonus->type = Bonus::PRIMARY_SKILL;
  858. bonus->valType = Bonus::ADDITIVE_VALUE;
  859. bonus->subtype = PrimarySkill::ATTACK;
  860. hs->addNewBonus(bonus);
  861. bonus = new Bonus(*bonus);
  862. bonus->subtype = PrimarySkill::DEFENSE;
  863. hs->addNewBonus(bonus);
  864. //values will be calculated later
  865. bonus = new Bonus(*bonus);
  866. bonus->type = Bonus::STACKS_SPEED;
  867. bonus->val = 1; //+1 speed
  868. hs->addNewBonus(bonus);
  869. }
  870. break;
  871. case 2://secondary skill
  872. hs->growsWithLevel = true;
  873. bonus->type = Bonus::SPECIAL_SECONDARY_SKILL; //needs to be recalculated with level, based on this value
  874. bonus->valType = Bonus::BASE_NUMBER; // to receive nonzero value
  875. bonus->subtype = spec.subtype; //skill id
  876. bonus->val = spec.val; //value per level, in percent
  877. hs->addNewBonus(bonus);
  878. bonus = new Bonus(*bonus);
  879. switch (spec.additionalinfo)
  880. {
  881. case 0: //normal
  882. bonus->valType = Bonus::PERCENT_TO_BASE;
  883. break;
  884. case 1: //when it's navigation or there's no 'base' at all
  885. bonus->valType = Bonus::PERCENT_TO_ALL;
  886. break;
  887. }
  888. bonus->type = Bonus::SECONDARY_SKILL_PREMY; //value will be calculated later
  889. hs->addNewBonus(bonus);
  890. break;
  891. case 3://spell damage bonus, level dependent but calculated elsewhere
  892. bonus->type = Bonus::SPECIAL_SPELL_LEV;
  893. bonus->subtype = spec.subtype;
  894. hs->addNewBonus(bonus);
  895. break;
  896. case 4://creature stat boost
  897. switch (spec.subtype)
  898. {
  899. case 1://attack
  900. bonus->type = Bonus::PRIMARY_SKILL;
  901. bonus->subtype = PrimarySkill::ATTACK;
  902. break;
  903. case 2://defense
  904. bonus->type = Bonus::PRIMARY_SKILL;
  905. bonus->subtype = PrimarySkill::DEFENSE;
  906. break;
  907. case 3:
  908. bonus->type = Bonus::CREATURE_DAMAGE;
  909. bonus->subtype = 0; //both min and max
  910. break;
  911. case 4://hp
  912. bonus->type = Bonus::STACK_HEALTH;
  913. break;
  914. case 5:
  915. bonus->type = Bonus::STACKS_SPEED;
  916. break;
  917. default:
  918. continue;
  919. }
  920. bonus->additionalInfo = spec.additionalinfo; //creature id
  921. bonus->valType = Bonus::ADDITIVE_VALUE;
  922. bonus->limiter.reset(new CCreatureTypeLimiter (*VLC->creh->creatures[spec.additionalinfo], true));
  923. hs->addNewBonus(bonus);
  924. break;
  925. case 5://spell damage bonus in percent
  926. bonus->type = Bonus::SPECIFIC_SPELL_DAMAGE;
  927. bonus->valType = Bonus::BASE_NUMBER; // current spell system is screwed
  928. bonus->subtype = spec.subtype; //spell id
  929. hs->addNewBonus(bonus);
  930. break;
  931. case 6://damage bonus for bless (Adela)
  932. bonus->type = Bonus::SPECIAL_BLESS_DAMAGE;
  933. bonus->subtype = spec.subtype; //spell id if you ever wanted to use it otherwise
  934. bonus->additionalInfo = spec.additionalinfo; //damage factor
  935. hs->addNewBonus(bonus);
  936. break;
  937. case 7://maxed mastery for spell
  938. bonus->type = Bonus::MAXED_SPELL;
  939. bonus->subtype = spec.subtype; //spell i
  940. hs->addNewBonus(bonus);
  941. break;
  942. case 8://peculiar spells - enchantments
  943. bonus->type = Bonus::SPECIAL_PECULIAR_ENCHANT;
  944. bonus->subtype = spec.subtype; //spell id
  945. bonus->additionalInfo = spec.additionalinfo;//0, 1 for Coronius
  946. hs->addNewBonus(bonus);
  947. break;
  948. case 9://upgrade creatures
  949. {
  950. const auto &creatures = VLC->creh->creatures;
  951. bonus->type = Bonus::SPECIAL_UPGRADE;
  952. bonus->subtype = spec.subtype; //base id
  953. bonus->additionalInfo = spec.additionalinfo; //target id
  954. hs->addNewBonus(bonus);
  955. bonus = new Bonus(*bonus);
  956. for(auto cre_id : creatures[spec.subtype]->upgrades)
  957. {
  958. bonus->subtype = cre_id; //propagate for regular upgrades of base creature
  959. hs->addNewBonus(bonus);
  960. bonus = new Bonus(*bonus);
  961. }
  962. vstd::clear_pointer(bonus);
  963. break;
  964. }
  965. case 10://resource generation
  966. bonus->type = Bonus::GENERATE_RESOURCE;
  967. bonus->subtype = spec.subtype;
  968. hs->addNewBonus(bonus);
  969. break;
  970. case 11://starting skill with mastery (Adrienne)
  971. setSecSkillLevel(SecondarySkill(spec.val), spec.additionalinfo, true);
  972. break;
  973. case 12://army speed
  974. bonus->type = Bonus::STACKS_SPEED;
  975. hs->addNewBonus(bonus);
  976. break;
  977. case 13://Dragon bonuses (Mutare)
  978. bonus->type = Bonus::PRIMARY_SKILL;
  979. bonus->valType = Bonus::ADDITIVE_VALUE;
  980. switch (spec.subtype)
  981. {
  982. case 1:
  983. bonus->subtype = PrimarySkill::ATTACK;
  984. break;
  985. case 2:
  986. bonus->subtype = PrimarySkill::DEFENSE;
  987. break;
  988. }
  989. bonus->limiter.reset(new HasAnotherBonusLimiter(Bonus::DRAGON_NATURE));
  990. hs->addNewBonus(bonus);
  991. break;
  992. default:
  993. logGlobal->warnStream() << "Unexpected hero specialty " << type;
  994. }
  995. }
  996. specialty.push_back(hs); //will it work?
  997. for (auto hs2 : type->specialty) //copy active (probably growing) bonuses from hero prootype to hero object
  998. {
  999. auto hs = new HeroSpecial();
  1000. attachTo(hs); //do we ever need to detach it?
  1001. hs->setNodeType(CBonusSystemNode::specialty);
  1002. for (auto bonus : hs2.bonuses)
  1003. {
  1004. hs->addNewBonus (bonus);
  1005. }
  1006. hs->growsWithLevel = hs2.growsWithLevel;
  1007. specialty.push_back(hs); //will it work?
  1008. }
  1009. //initialize bonuses
  1010. recreateSecondarySkillsBonuses();
  1011. Updatespecialty();
  1012. mana = manaLimit(); //after all bonuses are taken into account, make sure this line is the last one
  1013. type->name = name;
  1014. }
  1015. void CGHeroInstance::Updatespecialty() //TODO: calculate special value of bonuses on-the-fly?
  1016. {
  1017. for (auto hs : specialty)
  1018. {
  1019. if (hs->growsWithLevel)
  1020. {
  1021. //const auto &creatures = VLC->creh->creatures;
  1022. for(Bonus * b : hs->getBonusList())
  1023. {
  1024. switch (b->type)
  1025. {
  1026. case Bonus::SECONDARY_SKILL_PREMY:
  1027. b->val = (hs->valOfBonuses(Bonus::SPECIAL_SECONDARY_SKILL, b->subtype) * level);
  1028. break; //use only hero skills as bonuses to avoid feedback loop
  1029. case Bonus::PRIMARY_SKILL: //for creatures, that is
  1030. {
  1031. const CCreature * cre = nullptr;
  1032. int creLevel = 0;
  1033. if (auto creatureLimiter = std::dynamic_pointer_cast<CCreatureTypeLimiter>(b->limiter)) //TODO: more general eveluation of bonuses?
  1034. {
  1035. cre = creatureLimiter->creature;
  1036. creLevel = cre->level;
  1037. if (!creLevel)
  1038. {
  1039. creLevel = 5; //treat ballista as tier 5
  1040. }
  1041. }
  1042. else //no creature found, can't calculate value
  1043. {
  1044. logGlobal->warnStream() << "Primary skill specialty growth supported only with creature type limiters";
  1045. break;
  1046. }
  1047. double primSkillModifier = (int)(level / creLevel) / 20.0;
  1048. int param;
  1049. switch (b->subtype)
  1050. {
  1051. case PrimarySkill::ATTACK:
  1052. param = cre->Attack();
  1053. break;
  1054. case PrimarySkill::DEFENSE:
  1055. param = cre->Defense();
  1056. break;
  1057. default:
  1058. continue;
  1059. }
  1060. b->val = ceil(param * (1 + primSkillModifier)) - param; //yep, overcomplicated but matches original
  1061. break;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. }
  1067. }
  1068. void CGHeroInstance::recreateSecondarySkillsBonuses()
  1069. {
  1070. auto secondarySkillsBonuses = getBonuses(Selector::sourceType(Bonus::SECONDARY_SKILL));
  1071. for(auto bonus : *secondarySkillsBonuses)
  1072. removeBonus(bonus);
  1073. for(auto skill_info : secSkills)
  1074. updateSkill(SecondarySkill(skill_info.first), skill_info.second);
  1075. }
  1076. void CGHeroInstance::updateSkill(SecondarySkill which, int val)
  1077. {
  1078. if(which == SecondarySkill::LEADERSHIP || which == SecondarySkill::LUCK)
  1079. { //luck-> VLC->generaltexth->arraytxt[73+luckSkill]; VLC->generaltexth->arraytxt[104+moraleSkill]
  1080. bool luck = which == SecondarySkill::LUCK;
  1081. Bonus::BonusType type[] = {Bonus::MORALE, Bonus::LUCK};
  1082. Bonus *b = getBonusLocalFirst(Selector::type(type[luck]).And(Selector::sourceType(Bonus::SECONDARY_SKILL)));
  1083. if(!b)
  1084. {
  1085. b = new Bonus(Bonus::PERMANENT, type[luck], Bonus::SECONDARY_SKILL, +val, which, which, Bonus::BASE_NUMBER);
  1086. addNewBonus(b);
  1087. }
  1088. else
  1089. b->val = +val;
  1090. }
  1091. else if(which == SecondarySkill::DIPLOMACY) //surrender discount: 20% per level
  1092. {
  1093. if(Bonus *b = getBonusLocalFirst(Selector::type(Bonus::SURRENDER_DISCOUNT).And(Selector::sourceType(Bonus::SECONDARY_SKILL))))
  1094. b->val = +val;
  1095. else
  1096. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::SURRENDER_DISCOUNT, Bonus::SECONDARY_SKILL, val * 20, which));
  1097. }
  1098. int skillVal = 0;
  1099. switch (which)
  1100. {
  1101. case SecondarySkill::ARCHERY:
  1102. switch (val)
  1103. {
  1104. case 1:
  1105. skillVal = 10; break;
  1106. case 2:
  1107. skillVal = 25; break;
  1108. case 3:
  1109. skillVal = 50; break;
  1110. }
  1111. break;
  1112. case SecondarySkill::LOGISTICS:
  1113. skillVal = 10 * val; break;
  1114. case SecondarySkill::NAVIGATION:
  1115. skillVal = 50 * val; break;
  1116. case SecondarySkill::MYSTICISM:
  1117. skillVal = val; break;
  1118. case SecondarySkill::EAGLE_EYE:
  1119. skillVal = 30 + 10 * val; break;
  1120. case SecondarySkill::NECROMANCY:
  1121. skillVal = 10 * val; break;
  1122. case SecondarySkill::LEARNING:
  1123. skillVal = 5 * val; break;
  1124. case SecondarySkill::OFFENCE:
  1125. skillVal = 10 * val; break;
  1126. case SecondarySkill::ARMORER:
  1127. skillVal = 5 * val; break;
  1128. case SecondarySkill::INTELLIGENCE:
  1129. skillVal = 25 << (val-1); break;
  1130. case SecondarySkill::SORCERY:
  1131. skillVal = 5 * val; break;
  1132. case SecondarySkill::RESISTANCE:
  1133. skillVal = 5 << (val-1); break;
  1134. case SecondarySkill::FIRST_AID:
  1135. skillVal = 25 + 25*val; break;
  1136. case SecondarySkill::ESTATES:
  1137. skillVal = 125 << (val-1); break;
  1138. }
  1139. Bonus::ValueType skillValType = skillVal ? Bonus::BASE_NUMBER : Bonus::INDEPENDENT_MIN;
  1140. if(Bonus * b = getBonusList().getFirst(Selector::typeSubtype(Bonus::SECONDARY_SKILL_PREMY, which)
  1141. .And(Selector::sourceType(Bonus::SECONDARY_SKILL)))) //only local hero bonus
  1142. {
  1143. b->val = skillVal;
  1144. b->valType = skillValType;
  1145. }
  1146. else
  1147. {
  1148. auto bonus = new Bonus(Bonus::PERMANENT, Bonus::SECONDARY_SKILL_PREMY, Bonus::SECONDARY_SKILL, skillVal, id.getNum(), which, skillValType);
  1149. bonus->source = Bonus::SECONDARY_SKILL;
  1150. addNewBonus(bonus);
  1151. }
  1152. }
  1153. void CGHeroInstance::setPropertyDer( ui8 what, ui32 val )
  1154. {
  1155. if(what == ObjProperty::PRIMARY_STACK_COUNT)
  1156. setStackCount(SlotID(0), val);
  1157. }
  1158. double CGHeroInstance::getFightingStrength() const
  1159. {
  1160. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::ATTACK)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::DEFENSE)));
  1161. }
  1162. double CGHeroInstance::getMagicStrength() const
  1163. {
  1164. return sqrt((1.0 + 0.05*getPrimSkillLevel(PrimarySkill::KNOWLEDGE)) * (1.0 + 0.05*getPrimSkillLevel(PrimarySkill::SPELL_POWER)));
  1165. }
  1166. double CGHeroInstance::getHeroStrength() const
  1167. {
  1168. return sqrt(pow(getFightingStrength(), 2.0) * pow(getMagicStrength(), 2.0));
  1169. }
  1170. ui64 CGHeroInstance::getTotalStrength() const
  1171. {
  1172. double ret = getFightingStrength() * getArmyStrength();
  1173. return (ui64) ret;
  1174. }
  1175. TExpType CGHeroInstance::calculateXp(TExpType exp) const
  1176. {
  1177. return exp * (100 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::LEARNING))/100.0;
  1178. }
  1179. ui8 CGHeroInstance::getSpellSchoolLevel(const CSpell * spell, int *outSelectedSchool) const
  1180. {
  1181. si16 skill = -1; //skill level
  1182. #define TRY_SCHOOL(schoolName, schoolMechanicsId, schoolOutId) \
  1183. if(spell-> schoolName) \
  1184. { \
  1185. int thisSchool = std::max<int>(getSecSkillLevel( \
  1186. SecondarySkill(14 + (schoolMechanicsId))), \
  1187. valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 1 << (schoolMechanicsId))); \
  1188. if(thisSchool > skill) \
  1189. { \
  1190. skill = thisSchool; \
  1191. if(outSelectedSchool) \
  1192. *outSelectedSchool = schoolOutId; \
  1193. } \
  1194. }
  1195. TRY_SCHOOL(fire, 0, 1)
  1196. TRY_SCHOOL(air, 1, 0)
  1197. TRY_SCHOOL(water, 2, 2)
  1198. TRY_SCHOOL(earth, 3, 3)
  1199. #undef TRY_SCHOOL
  1200. vstd::amax(skill, valOfBonuses(Bonus::MAGIC_SCHOOL_SKILL, 0)); //any school bonus
  1201. vstd::amax(skill, valOfBonuses(Bonus::SPELL, spell->id.toEnum())); //given by artifact or other effect
  1202. if (hasBonusOfType(Bonus::MAXED_SPELL, spell->id))//hero specialty (Daremyth, Melodia)
  1203. skill = 3;
  1204. assert(skill >= 0 && skill <= 3);
  1205. return skill;
  1206. }
  1207. bool CGHeroInstance::canCastThisSpell(const CSpell * spell) const
  1208. {
  1209. if(!getArt(ArtifactPosition::SPELLBOOK)) //if hero has no spellbook
  1210. return false;
  1211. if(vstd::contains(spells, spell->id) //hero has this spell in spellbook
  1212. || (spell->air && hasBonusOfType(Bonus::AIR_SPELLS)) // this is air spell and hero can cast all air spells
  1213. || (spell->fire && hasBonusOfType(Bonus::FIRE_SPELLS)) // this is fire spell and hero can cast all fire spells
  1214. || (spell->water && hasBonusOfType(Bonus::WATER_SPELLS)) // this is water spell and hero can cast all water spells
  1215. || (spell->earth && hasBonusOfType(Bonus::EARTH_SPELLS)) // this is earth spell and hero can cast all earth spells
  1216. || hasBonusOfType(Bonus::SPELL, spell->id)
  1217. || hasBonusOfType(Bonus::SPELLS_OF_LEVEL, spell->level)
  1218. )
  1219. return true;
  1220. return false;
  1221. }
  1222. /**
  1223. * Calculates what creatures and how many to be raised from a battle.
  1224. * @param battleResult The results of the battle.
  1225. * @return Returns a pair with the first value indicating the ID of the creature
  1226. * type and second value the amount. Both values are returned as -1 if necromancy
  1227. * could not be applied.
  1228. */
  1229. CStackBasicDescriptor CGHeroInstance::calculateNecromancy (const BattleResult &battleResult) const
  1230. {
  1231. const ui8 necromancyLevel = getSecSkillLevel(SecondarySkill::NECROMANCY);
  1232. // Hero knows necromancy or has Necromancer Cloak
  1233. if (necromancyLevel > 0 || hasBonusOfType(Bonus::IMPROVED_NECROMANCY))
  1234. {
  1235. double necromancySkill = valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::NECROMANCY)/100.0;
  1236. vstd::amin(necromancySkill, 1.0); //it's impossible to raise more creatures than all...
  1237. const std::map<ui32,si32> &casualties = battleResult.casualties[!battleResult.winner];
  1238. ui32 raisedUnits = 0;
  1239. // Figure out what to raise and how many.
  1240. const CreatureID creatureTypes[] = {CreatureID::SKELETON, CreatureID::WALKING_DEAD, CreatureID::WIGHTS, CreatureID::LICHES};
  1241. const bool improvedNecromancy = hasBonusOfType(Bonus::IMPROVED_NECROMANCY);
  1242. const CCreature *raisedUnitType = VLC->creh->creatures[creatureTypes[improvedNecromancy ? necromancyLevel : 0]];
  1243. const ui32 raisedUnitHP = raisedUnitType->valOfBonuses(Bonus::STACK_HEALTH);
  1244. //calculate creatures raised from each defeated stack
  1245. for (auto & casualtie : casualties)
  1246. {
  1247. // Get lost enemy hit points convertible to units.
  1248. CCreature * c = VLC->creh->creatures[casualtie.first];
  1249. const ui32 raisedHP = c->valOfBonuses(Bonus::STACK_HEALTH) * casualtie.second * necromancySkill;
  1250. raisedUnits += std::min<ui32>(raisedHP / raisedUnitHP, casualtie.second * necromancySkill); //limit to % of HP and % of original stack count
  1251. }
  1252. // Make room for new units.
  1253. SlotID slot = getSlotFor(raisedUnitType->idNumber);
  1254. if (slot == SlotID())
  1255. {
  1256. // If there's no room for unit, try it's upgraded version 2/3rds the size.
  1257. raisedUnitType = VLC->creh->creatures[*raisedUnitType->upgrades.begin()];
  1258. raisedUnits = (raisedUnits*2)/3;
  1259. slot = getSlotFor(raisedUnitType->idNumber);
  1260. }
  1261. if (raisedUnits <= 0)
  1262. raisedUnits = 1;
  1263. return CStackBasicDescriptor(raisedUnitType->idNumber, raisedUnits);
  1264. }
  1265. return CStackBasicDescriptor();
  1266. }
  1267. /**
  1268. * Show the necromancy dialog with information about units raised.
  1269. * @param raisedStack Pair where the first element represents ID of the raised creature
  1270. * and the second element the amount.
  1271. */
  1272. void CGHeroInstance::showNecromancyDialog(const CStackBasicDescriptor &raisedStack) const
  1273. {
  1274. InfoWindow iw;
  1275. iw.soundID = soundBase::pickup01 + ran() % 7;
  1276. iw.player = tempOwner;
  1277. iw.components.push_back(Component(raisedStack));
  1278. if (raisedStack.count > 1) // Practicing the dark arts of necromancy, ... (plural)
  1279. {
  1280. iw.text.addTxt(MetaString::GENERAL_TXT, 145);
  1281. iw.text.addReplacement(raisedStack.count);
  1282. }
  1283. else // Practicing the dark arts of necromancy, ... (singular)
  1284. {
  1285. iw.text.addTxt(MetaString::GENERAL_TXT, 146);
  1286. }
  1287. iw.text.addReplacement(raisedStack);
  1288. cb->showInfoDialog(&iw);
  1289. }
  1290. int3 CGHeroInstance::getSightCenter() const
  1291. {
  1292. return getPosition(false);
  1293. }
  1294. int CGHeroInstance::getSightRadious() const
  1295. {
  1296. return 5 + getSecSkillLevel(SecondarySkill::SCOUTING) + valOfBonuses(Bonus::SIGHT_RADIOUS); //default + scouting
  1297. }
  1298. si32 CGHeroInstance::manaRegain() const
  1299. {
  1300. if (hasBonusOfType(Bonus::FULL_MANA_REGENERATION))
  1301. return manaLimit();
  1302. return 1 + valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, 8) + valOfBonuses(Bonus::MANA_REGENERATION); //1 + Mysticism level
  1303. }
  1304. // /**
  1305. // * Places an artifact in hero's backpack. If it's a big artifact equips it
  1306. // * or discards it if it cannot be equipped.
  1307. // */
  1308. // void CGHeroInstance::giveArtifact (ui32 aid) //use only for fixed artifacts
  1309. // {
  1310. // CArtifact * const artifact = VLC->arth->artifacts[aid]; //pointer to constant object
  1311. // CArtifactInstance *ai = CArtifactInstance::createNewArtifactInstance(artifact);
  1312. // ai->putAt(this, ai->firstAvailableSlot(this));
  1313. // }
  1314. int CGHeroInstance::getBoatType() const
  1315. {
  1316. switch(type->heroClass->getAlignment())
  1317. {
  1318. case EAlignment::GOOD:
  1319. return 1;
  1320. case EAlignment::EVIL:
  1321. return 0;
  1322. case EAlignment::NEUTRAL:
  1323. return 2;
  1324. default:
  1325. throw std::runtime_error("Wrong alignment!");
  1326. }
  1327. }
  1328. void CGHeroInstance::getOutOffsets(std::vector<int3> &offsets) const
  1329. {
  1330. static int3 dirs[] = { int3(0,1,0),int3(0,-1,0),int3(-1,0,0),int3(+1,0,0), int3(1,1,0),int3(-1,1,0),int3(1,-1,0),int3(-1,-1,0) };
  1331. for (auto & dir : dirs)
  1332. offsets += dir;
  1333. }
  1334. int CGHeroInstance::getSpellCost(const CSpell *sp) const
  1335. {
  1336. return sp->costs[getSpellSchoolLevel(sp)];
  1337. }
  1338. void CGHeroInstance::pushPrimSkill( PrimarySkill::PrimarySkill which, int val )
  1339. {
  1340. assert(!hasBonus(Selector::typeSubtype(Bonus::PRIMARY_SKILL, which)
  1341. .And(Selector::sourceType(Bonus::HERO_BASE_SKILL))));
  1342. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::PRIMARY_SKILL, Bonus::HERO_BASE_SKILL, val, id.getNum(), which));
  1343. }
  1344. EAlignment::EAlignment CGHeroInstance::getAlignment() const
  1345. {
  1346. return type->heroClass->getAlignment();
  1347. }
  1348. void CGHeroInstance::initExp()
  1349. {
  1350. exp=40+ (ran()) % 50;
  1351. level = 1;
  1352. }
  1353. std::string CGHeroInstance::nodeName() const
  1354. {
  1355. return "Hero " + name;
  1356. }
  1357. void CGHeroInstance::putArtifact(ArtifactPosition pos, CArtifactInstance *art)
  1358. {
  1359. assert(!getArt(pos));
  1360. art->putAt(ArtifactLocation(this, pos));
  1361. }
  1362. void CGHeroInstance::putInBackpack(CArtifactInstance *art)
  1363. {
  1364. putArtifact(art->firstBackpackSlot(this), art);
  1365. }
  1366. bool CGHeroInstance::hasSpellbook() const
  1367. {
  1368. return getArt(ArtifactPosition::SPELLBOOK);
  1369. }
  1370. void CGHeroInstance::deserializationFix()
  1371. {
  1372. artDeserializationFix(this);
  1373. for (auto hs : specialty)
  1374. {
  1375. attachTo (hs);
  1376. }
  1377. }
  1378. CBonusSystemNode * CGHeroInstance::whereShouldBeAttached(CGameState *gs)
  1379. {
  1380. if(visitedTown)
  1381. {
  1382. if(inTownGarrison)
  1383. return visitedTown;
  1384. else
  1385. return &visitedTown->townAndVis;
  1386. }
  1387. else
  1388. return CArmedInstance::whereShouldBeAttached(gs);
  1389. }
  1390. int CGHeroInstance::movementPointsAfterEmbark(int MPsBefore, int basicCost, bool disembark /*= false*/) const
  1391. {
  1392. if(hasBonusOfType(Bonus::FREE_SHIP_BOARDING))
  1393. return (MPsBefore - basicCost) * static_cast<double>(maxMovePoints(disembark)) / maxMovePoints(!disembark);
  1394. return 0; //take all MPs otherwise
  1395. }
  1396. CGHeroInstance::ECanDig CGHeroInstance::diggingStatus() const
  1397. {
  1398. if(movement < maxMovePoints(true))
  1399. return LACK_OF_MOVEMENT;
  1400. else if(cb->getTile(getPosition(false))->terType == ETerrainType::WATER)
  1401. return WRONG_TERRAIN;
  1402. else
  1403. {
  1404. const TerrainTile *t = cb->getTile(getPosition());
  1405. //TODO look for hole
  1406. //CGI->mh->getTerrainDescr(h->getPosition(false), hlp, false);
  1407. if(/*hlp.length() || */t->blockingObjects.size() > 1)
  1408. return TILE_OCCUPIED;
  1409. else
  1410. return CAN_DIG;
  1411. }
  1412. }
  1413. ArtBearer::ArtBearer CGHeroInstance::bearerType() const
  1414. {
  1415. return ArtBearer::HERO;
  1416. }
  1417. std::vector<SecondarySkill> CGHeroInstance::levelUpProposedSkills() const
  1418. {
  1419. std::vector<SecondarySkill> obligatorySkills; //hero is offered magic school or wisdom if possible
  1420. if (!skillsInfo.wisdomCounter)
  1421. {
  1422. if (cb->isAllowed(2, SecondarySkill::WISDOM) && !getSecSkillLevel(SecondarySkill::WISDOM))
  1423. obligatorySkills.push_back(SecondarySkill::WISDOM);
  1424. }
  1425. if (!skillsInfo.magicSchoolCounter)
  1426. {
  1427. std::vector<SecondarySkill> ss;
  1428. ss += SecondarySkill::FIRE_MAGIC, SecondarySkill::AIR_MAGIC, SecondarySkill::WATER_MAGIC, SecondarySkill::EARTH_MAGIC;
  1429. auto rng = [=](ui32 val) mutable -> ui32
  1430. {
  1431. return skillsInfo.distribution() % val; //must be determined
  1432. };
  1433. std::random_shuffle(ss.begin(), ss.end(), rng);
  1434. for (auto skill : ss)
  1435. {
  1436. if (cb->isAllowed(2, skill) && !getSecSkillLevel(skill)) //only schools hero doesn't know yet
  1437. {
  1438. obligatorySkills.push_back(skill);
  1439. break; //only one
  1440. }
  1441. }
  1442. }
  1443. std::vector<SecondarySkill> skills;
  1444. //picking sec. skills for choice
  1445. std::set<SecondarySkill> basicAndAdv, expert, none;
  1446. for(int i=0;i<GameConstants::SKILL_QUANTITY;i++)
  1447. if (cb->isAllowed(2,i))
  1448. none.insert(SecondarySkill(i));
  1449. for(auto & elem : secSkills)
  1450. {
  1451. if(elem.second < SecSkillLevel::EXPERT)
  1452. basicAndAdv.insert(elem.first);
  1453. else
  1454. expert.insert(elem.first);
  1455. none.erase(elem.first);
  1456. }
  1457. for (auto s : obligatorySkills) //don't duplicate them
  1458. {
  1459. none.erase (s);
  1460. basicAndAdv.erase (s);
  1461. expert.erase (s);
  1462. }
  1463. //first offered skill:
  1464. // 1) give obligatory skill
  1465. // 2) give any other new skill
  1466. // 3) upgrade existing
  1467. if (canLearnSkill() && obligatorySkills.size() > 0)
  1468. {
  1469. skills.push_back (obligatorySkills[0]);
  1470. }
  1471. else if(none.size() && canLearnSkill()) //hero have free skill slot
  1472. {
  1473. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.distribution)); //new skill
  1474. none.erase(skills.back());
  1475. }
  1476. else if(!basicAndAdv.empty())
  1477. {
  1478. skills.push_back(type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.distribution)); //upgrade existing
  1479. basicAndAdv.erase(skills.back());
  1480. }
  1481. //second offered skill:
  1482. //1) upgrade existing
  1483. //2) give obligatory skill
  1484. //3) give any other new skill
  1485. if(!basicAndAdv.empty())
  1486. {
  1487. SecondarySkill s = type->heroClass->chooseSecSkill(basicAndAdv, skillsInfo.distribution);//upgrade existing
  1488. skills.push_back(s);
  1489. basicAndAdv.erase(s);
  1490. }
  1491. else if (canLearnSkill() && obligatorySkills.size() > 1)
  1492. {
  1493. skills.push_back (obligatorySkills[1]);
  1494. }
  1495. else if(none.size() && canLearnSkill())
  1496. {
  1497. skills.push_back(type->heroClass->chooseSecSkill(none, skillsInfo.distribution)); //give new skill
  1498. none.erase(skills.back());
  1499. }
  1500. return skills;
  1501. }
  1502. bool CGHeroInstance::gainsLevel() const
  1503. {
  1504. return exp >= VLC->heroh->reqExp(level+1);
  1505. }
  1506. void CGDwelling::initObj()
  1507. {
  1508. switch(ID)
  1509. {
  1510. case Obj::CREATURE_GENERATOR1:
  1511. {
  1512. CreatureID crid = VLC->objh->cregens[subID];
  1513. const CCreature *crs = VLC->creh->creatures[crid];
  1514. creatures.resize(1);
  1515. creatures[0].second.push_back(crid);
  1516. if (subID >= VLC->generaltexth->creGens.size()) //very messy workaround
  1517. {
  1518. auto & dwellingNames = VLC->townh->factions[crs->faction]->town->dwellingNames;
  1519. assert (dwellingNames.size() > crs->level - 1);
  1520. hoverName = dwellingNames[crs->level - 1];
  1521. }
  1522. else
  1523. hoverName = VLC->generaltexth->creGens[subID];
  1524. if(crs->level > 4)
  1525. putStack(SlotID(0), new CStackInstance(crs, (crs->growth) * 3));
  1526. if (getOwner() != PlayerColor::NEUTRAL)
  1527. cb->gameState()->players[getOwner()].dwellings.push_back (this);
  1528. }
  1529. break;
  1530. case Obj::CREATURE_GENERATOR4:
  1531. creatures.resize(4);
  1532. if(subID == 1) //Golem Factory
  1533. {
  1534. creatures[0].second.push_back(CreatureID::STONE_GOLEM);
  1535. creatures[1].second.push_back(CreatureID::IRON_GOLEM);
  1536. creatures[2].second.push_back(CreatureID::GOLD_GOLEM);
  1537. creatures[3].second.push_back(CreatureID::DIAMOND_GOLEM);
  1538. //guards
  1539. putStack(SlotID(0), new CStackInstance(CreatureID::GOLD_GOLEM, 9));
  1540. putStack(SlotID(1), new CStackInstance(CreatureID::DIAMOND_GOLEM, 6));
  1541. }
  1542. else if(subID == 0) // Elemental Conflux
  1543. {
  1544. creatures[0].second.push_back(CreatureID::AIR_ELEMENTAL);
  1545. creatures[1].second.push_back(CreatureID::FIRE_ELEMENTAL);
  1546. creatures[2].second.push_back(CreatureID::EARTH_ELEMENTAL);
  1547. creatures[3].second.push_back(CreatureID::WATER_ELEMENTAL);
  1548. //guards
  1549. putStack(SlotID(0), new CStackInstance(CreatureID::EARTH_ELEMENTAL, 12));
  1550. }
  1551. else
  1552. {
  1553. assert(0);
  1554. }
  1555. hoverName = VLC->generaltexth->creGens4[subID];
  1556. break;
  1557. case Obj::REFUGEE_CAMP:
  1558. //is handled within newturn func
  1559. break;
  1560. case Obj::WAR_MACHINE_FACTORY:
  1561. creatures.resize(3);
  1562. creatures[0].second.push_back(CreatureID::BALLISTA);
  1563. creatures[1].second.push_back(CreatureID::FIRST_AID_TENT);
  1564. creatures[2].second.push_back(CreatureID::AMMO_CART);
  1565. break;
  1566. default:
  1567. assert(0);
  1568. break;
  1569. }
  1570. }
  1571. void CGDwelling::setProperty(ui8 what, ui32 val)
  1572. {
  1573. switch (what)
  1574. {
  1575. case ObjProperty::OWNER: //change owner
  1576. if (ID == Obj::CREATURE_GENERATOR1) //single generators
  1577. {
  1578. if (tempOwner != PlayerColor::NEUTRAL)
  1579. {
  1580. std::vector<ConstTransitivePtr<CGDwelling> >* dwellings = &cb->gameState()->players[tempOwner].dwellings;
  1581. dwellings->erase (std::find(dwellings->begin(), dwellings->end(), this));
  1582. }
  1583. if (PlayerColor(val) != PlayerColor::NEUTRAL) //can new owner be neutral?
  1584. cb->gameState()->players[PlayerColor(val)].dwellings.push_back (this);
  1585. }
  1586. break;
  1587. case ObjProperty::AVAILABLE_CREATURE:
  1588. creatures.resize(1);
  1589. creatures[0].second.resize(1);
  1590. creatures[0].second[0] = CreatureID(val);
  1591. break;
  1592. }
  1593. CGObjectInstance::setProperty(what,val);
  1594. }
  1595. void CGDwelling::onHeroVisit( const CGHeroInstance * h ) const
  1596. {
  1597. if(ID == Obj::REFUGEE_CAMP && !creatures[0].first) //Refugee Camp, no available cres
  1598. {
  1599. InfoWindow iw;
  1600. iw.player = h->tempOwner;
  1601. iw.text.addTxt(MetaString::ADVOB_TXT, 44); //{%s} \n\n The camp is deserted. Perhaps you should try next week.
  1602. iw.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1603. cb->sendAndApply(&iw);
  1604. return;
  1605. }
  1606. PlayerRelations::PlayerRelations relations = cb->gameState()->getPlayerRelations( h->tempOwner, tempOwner );
  1607. if ( relations == PlayerRelations::ALLIES )
  1608. return;//do not allow recruiting or capturing
  1609. if( !relations && stacksCount() > 0) //object is guarded, owned by enemy
  1610. {
  1611. BlockingDialog bd(true,false);
  1612. bd.player = h->tempOwner;
  1613. bd.text.addTxt(MetaString::GENERAL_TXT, 421); //Much to your dismay, the %s is guarded by %s %s. Do you wish to fight the guards?
  1614. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1615. bd.text.addReplacement(MetaString::ARRAY_TXT, 176 + Slots().begin()->second->getQuantityID()*3);
  1616. bd.text.addReplacement(*Slots().begin()->second);
  1617. cb->showBlockingDialog(&bd);
  1618. return;
  1619. }
  1620. if(!relations && ID != Obj::WAR_MACHINE_FACTORY)
  1621. {
  1622. cb->setOwner(this, h->tempOwner);
  1623. }
  1624. BlockingDialog bd (true,false);
  1625. bd.player = h->tempOwner;
  1626. if(ID == Obj::CREATURE_GENERATOR1 || ID == Obj::CREATURE_GENERATOR4)
  1627. {
  1628. bd.text.addTxt(MetaString::ADVOB_TXT, ID == Obj::CREATURE_GENERATOR1 ? 35 : 36); //{%s} Would you like to recruit %s? / {%s} Would you like to recruit %s, %s, %s, or %s?
  1629. bd.text.addReplacement(ID == Obj::CREATURE_GENERATOR1 ? MetaString::CREGENS : MetaString::CREGENS4, subID);
  1630. for(auto & elem : creatures)
  1631. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  1632. }
  1633. else if(ID == Obj::REFUGEE_CAMP)
  1634. {
  1635. bd.text.addTxt(MetaString::ADVOB_TXT, 35); //{%s} Would you like to recruit %s?
  1636. bd.text.addReplacement(MetaString::OBJ_NAMES, ID);
  1637. for(auto & elem : creatures)
  1638. bd.text.addReplacement(MetaString::CRE_PL_NAMES, elem.second[0]);
  1639. }
  1640. else if(ID == Obj::WAR_MACHINE_FACTORY)
  1641. bd.text.addTxt(MetaString::ADVOB_TXT, 157); //{War Machine Factory} Would you like to purchase War Machines?
  1642. else
  1643. throw std::runtime_error("Illegal dwelling!");
  1644. cb->showBlockingDialog(&bd);
  1645. }
  1646. void CGDwelling::newTurn() const
  1647. {
  1648. if(cb->getDate(Date::DAY_OF_WEEK) != 1) //not first day of week
  1649. return;
  1650. //town growths and War Machines Factories are handled separately
  1651. if(ID == Obj::TOWN || ID == Obj::WAR_MACHINE_FACTORY)
  1652. return;
  1653. if(ID == Obj::REFUGEE_CAMP) //if it's a refugee camp, we need to pick an available creature
  1654. {
  1655. cb->setObjProperty(id, ObjProperty::AVAILABLE_CREATURE, VLC->creh->pickRandomMonster());
  1656. }
  1657. bool change = false;
  1658. SetAvailableCreatures sac;
  1659. sac.creatures = creatures;
  1660. sac.tid = id;
  1661. for (size_t i = 0; i < creatures.size(); i++)
  1662. {
  1663. if(creatures[i].second.size())
  1664. {
  1665. CCreature *cre = VLC->creh->creatures[creatures[i].second[0]];
  1666. TQuantity amount = cre->growth * (1 + cre->valOfBonuses(Bonus::CREATURE_GROWTH_PERCENT)/100) + cre->valOfBonuses(Bonus::CREATURE_GROWTH);
  1667. if (VLC->modh->settings.DWELLINGS_ACCUMULATE_CREATURES && ID != Obj::REFUGEE_CAMP) //camp should not try to accumulate different kinds of creatures
  1668. sac.creatures[i].first += amount;
  1669. else
  1670. sac.creatures[i].first = amount;
  1671. change = true;
  1672. }
  1673. }
  1674. if(change)
  1675. cb->sendAndApply(&sac);
  1676. }
  1677. void CGDwelling::heroAcceptsCreatures( const CGHeroInstance *h) const
  1678. {
  1679. CreatureID crid = creatures[0].second[0];
  1680. CCreature *crs = VLC->creh->creatures[crid];
  1681. TQuantity count = creatures[0].first;
  1682. if(crs->level == 1 && ID != Obj::REFUGEE_CAMP) //first level - creatures are for free
  1683. {
  1684. if(count) //there are available creatures
  1685. {
  1686. SlotID slot = h->getSlotFor(crid);
  1687. if(!slot.validSlot()) //no available slot
  1688. {
  1689. InfoWindow iw;
  1690. iw.player = h->tempOwner;
  1691. iw.text.addTxt(MetaString::GENERAL_TXT, 425);//The %s would join your hero, but there aren't enough provisions to support them.
  1692. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1693. cb->showInfoDialog(&iw);
  1694. }
  1695. else //give creatures
  1696. {
  1697. SetAvailableCreatures sac;
  1698. sac.tid = id;
  1699. sac.creatures = creatures;
  1700. sac.creatures[0].first = 0;
  1701. InfoWindow iw;
  1702. iw.player = h->tempOwner;
  1703. iw.text.addTxt(MetaString::GENERAL_TXT, 423); //%d %s join your army.
  1704. iw.text.addReplacement(count);
  1705. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1706. cb->showInfoDialog(&iw);
  1707. cb->sendAndApply(&sac);
  1708. cb->addToSlot(StackLocation(h, slot), crs, count);
  1709. }
  1710. }
  1711. else //there no creatures
  1712. {
  1713. InfoWindow iw;
  1714. iw.text.addTxt(MetaString::GENERAL_TXT, 422); //There are no %s here to recruit.
  1715. iw.text.addReplacement(MetaString::CRE_PL_NAMES, crid);
  1716. iw.player = h->tempOwner;
  1717. cb->sendAndApply(&iw);
  1718. }
  1719. }
  1720. else
  1721. {
  1722. if(ID == Obj::WAR_MACHINE_FACTORY) //pick available War Machines
  1723. {
  1724. //there is 1 war machine available to recruit if hero doesn't have one
  1725. SetAvailableCreatures sac;
  1726. sac.tid = id;
  1727. sac.creatures = creatures;
  1728. sac.creatures[0].first = !h->getArt(ArtifactPosition::MACH1); //ballista
  1729. sac.creatures[1].first = !h->getArt(ArtifactPosition::MACH3); //first aid tent
  1730. sac.creatures[2].first = !h->getArt(ArtifactPosition::MACH2); //ammo cart
  1731. cb->sendAndApply(&sac);
  1732. }
  1733. OpenWindow ow;
  1734. ow.id1 = id.getNum();
  1735. ow.id2 = h->id.getNum();
  1736. ow.window = (ID == Obj::CREATURE_GENERATOR1 || ID == Obj::REFUGEE_CAMP)
  1737. ? OpenWindow::RECRUITMENT_FIRST
  1738. : OpenWindow::RECRUITMENT_ALL;
  1739. cb->sendAndApply(&ow);
  1740. }
  1741. }
  1742. void CGDwelling::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  1743. {
  1744. if (result.winner == 0)
  1745. {
  1746. onHeroVisit(hero);
  1747. }
  1748. }
  1749. void CGDwelling::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  1750. {
  1751. auto relations = cb->getPlayerRelations(getOwner(), hero->getOwner());
  1752. if(stacksCount() > 0 && relations == PlayerRelations::ENEMIES) //guards present
  1753. {
  1754. if(answer)
  1755. cb->startBattleI(hero, this);
  1756. }
  1757. else if(answer)
  1758. {
  1759. heroAcceptsCreatures(hero);
  1760. }
  1761. }
  1762. int CGTownInstance::getSightRadious() const //returns sight distance
  1763. {
  1764. if (subID == ETownType::TOWER)
  1765. {
  1766. if (hasBuilt(BuildingID::GRAIL)) //skyship
  1767. return -1; //entire map
  1768. if (hasBuilt(BuildingID::LOOKOUT_TOWER)) //lookout tower
  1769. return 20;
  1770. }
  1771. return 5;
  1772. }
  1773. void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
  1774. {
  1775. ///this is freakin' overcomplicated solution
  1776. switch (what)
  1777. {
  1778. case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
  1779. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, visitingHero->id.getNum());
  1780. break;
  1781. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  1782. bonusingBuildings[val]->setProperty (ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
  1783. break;
  1784. case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
  1785. bonusingBuildings[val]->setProperty (ObjProperty::VISITORS, garrisonHero->id.getNum());
  1786. break;
  1787. case ObjProperty::BONUS_VALUE_FIRST:
  1788. bonusValue.first = val;
  1789. break;
  1790. case ObjProperty::BONUS_VALUE_SECOND:
  1791. bonusValue.second = val;
  1792. break;
  1793. }
  1794. }
  1795. CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
  1796. {
  1797. if (hasBuilt(BuildingID::CASTLE))
  1798. return CASTLE;
  1799. if (hasBuilt(BuildingID::CITADEL))
  1800. return CITADEL;
  1801. if (hasBuilt(BuildingID::FORT))
  1802. return FORT;
  1803. return NONE;
  1804. }
  1805. int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
  1806. {
  1807. if (hasBuilt(BuildingID::CAPITOL))
  1808. return 3;
  1809. if (hasBuilt(BuildingID::CITY_HALL))
  1810. return 2;
  1811. if (hasBuilt(BuildingID::TOWN_HALL))
  1812. return 1;
  1813. if (hasBuilt(BuildingID::VILLAGE_HALL))
  1814. return 0;
  1815. return -1;
  1816. }
  1817. int CGTownInstance::mageGuildLevel() const
  1818. {
  1819. if (hasBuilt(BuildingID::MAGES_GUILD_5))
  1820. return 5;
  1821. if (hasBuilt(BuildingID::MAGES_GUILD_4))
  1822. return 4;
  1823. if (hasBuilt(BuildingID::MAGES_GUILD_3))
  1824. return 3;
  1825. if (hasBuilt(BuildingID::MAGES_GUILD_2))
  1826. return 2;
  1827. if (hasBuilt(BuildingID::MAGES_GUILD_1))
  1828. return 1;
  1829. return 0;
  1830. }
  1831. int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
  1832. {
  1833. return town->hordeLvl.at(HID);
  1834. }
  1835. int CGTownInstance::creatureGrowth(const int & level) const
  1836. {
  1837. return getGrowthInfo(level).totalGrowth();
  1838. }
  1839. GrowthInfo CGTownInstance::getGrowthInfo(int level) const
  1840. {
  1841. GrowthInfo ret;
  1842. if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
  1843. return ret;
  1844. if (creatures[level].second.empty())
  1845. return ret; //no dwelling
  1846. const CCreature *creature = VLC->creh->creatures[creatures[level].second.back()];
  1847. const int base = creature->growth;
  1848. int castleBonus = 0;
  1849. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[590], base));// \n\nBasic growth %d"
  1850. if (hasBuilt(BuildingID::CASTLE))
  1851. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CASTLE, castleBonus = base));
  1852. else if (hasBuilt(BuildingID::CITADEL))
  1853. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::CITADEL, castleBonus = base / 2));
  1854. if(town->hordeLvl.at(0) == level)//horde 1
  1855. if(hasBuilt(BuildingID::HORDE_1))
  1856. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_1, creature->hordeGrowth));
  1857. if(town->hordeLvl.at(1) == level)//horde 2
  1858. if(hasBuilt(BuildingID::HORDE_2))
  1859. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::HORDE_2, creature->hordeGrowth));
  1860. int dwellingBonus = 0;
  1861. if(const PlayerState *p = cb->getPlayer(tempOwner, false))
  1862. {
  1863. for(const CGDwelling *dwelling : p->dwellings)
  1864. if(vstd::contains(creatures[level].second, dwelling->creatures[0].second[0]))
  1865. dwellingBonus++;
  1866. }
  1867. if(dwellingBonus)
  1868. ret.entries.push_back(GrowthInfo::Entry(VLC->generaltexth->allTexts[591], dwellingBonus));// \nExternal dwellings %+d
  1869. //other *-of-legion-like bonuses (%d to growth cumulative with grail)
  1870. TBonusListPtr bonuses = getBonuses(Selector::type(Bonus::CREATURE_GROWTH).And(Selector::subtype(level)));
  1871. for(const Bonus *b : *bonuses)
  1872. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val));
  1873. //statue-of-legion-like bonus: % to base+castle
  1874. TBonusListPtr bonuses2 = getBonuses(Selector::type(Bonus::CREATURE_GROWTH_PERCENT));
  1875. for(const Bonus *b : *bonuses2)
  1876. ret.entries.push_back(GrowthInfo::Entry(b->Description() + " %+d", b->val * (base + castleBonus) / 100));
  1877. if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
  1878. ret.entries.push_back(GrowthInfo::Entry(subID, BuildingID::GRAIL, ret.totalGrowth() / 2));
  1879. return ret;
  1880. }
  1881. int CGTownInstance::dailyIncome() const
  1882. {
  1883. int ret = 0;
  1884. if (hasBuilt(BuildingID::GRAIL))
  1885. ret+=5000;
  1886. if (hasBuilt(BuildingID::CAPITOL))
  1887. ret+=4000;
  1888. else if (hasBuilt(BuildingID::CITY_HALL))
  1889. ret+=2000;
  1890. else if (hasBuilt(BuildingID::TOWN_HALL))
  1891. ret+=1000;
  1892. else if (hasBuilt(BuildingID::VILLAGE_HALL))
  1893. ret+=500;
  1894. return ret;
  1895. }
  1896. bool CGTownInstance::hasFort() const
  1897. {
  1898. return hasBuilt(BuildingID::FORT);
  1899. }
  1900. bool CGTownInstance::hasCapitol() const
  1901. {
  1902. return hasBuilt(BuildingID::CAPITOL);
  1903. }
  1904. CGTownInstance::CGTownInstance()
  1905. :IShipyard(this), IMarket(this), town(nullptr), builded(0), destroyed(0), identifier(0), alignment(0xff)
  1906. {
  1907. }
  1908. CGTownInstance::~CGTownInstance()
  1909. {
  1910. for (auto & elem : bonusingBuildings)
  1911. delete elem;
  1912. }
  1913. int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
  1914. {
  1915. if(checkGuild && mageGuildLevel() < level)
  1916. return 0;
  1917. int ret = 6 - level; //how many spells are available at this level
  1918. if (hasBuilt(BuildingID::LIBRARY, ETownType::TOWER))
  1919. ret++;
  1920. return ret;
  1921. }
  1922. bool CGTownInstance::needsLastStack() const
  1923. {
  1924. if(garrisonHero)
  1925. return true;
  1926. else return false;
  1927. }
  1928. void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
  1929. {
  1930. if( !cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ))//if this is enemy
  1931. {
  1932. if(armedGarrison() || visitingHero)
  1933. {
  1934. const CGHeroInstance *defendingHero = nullptr;
  1935. const CArmedInstance *defendingArmy = this;
  1936. if(visitingHero)
  1937. defendingHero = visitingHero;
  1938. else if(garrisonHero)
  1939. defendingHero = garrisonHero;
  1940. if(defendingHero)
  1941. defendingArmy = defendingHero;
  1942. bool outsideTown = (defendingHero == visitingHero && garrisonHero);
  1943. //TODO
  1944. //"borrowing" army from garrison to visiting hero
  1945. cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (outsideTown ? nullptr : this));
  1946. }
  1947. else
  1948. {
  1949. cb->setOwner(this, h->tempOwner);
  1950. removeCapitols(h->getOwner());
  1951. cb->heroVisitCastle(this, h);
  1952. }
  1953. }
  1954. else if(h->visitablePos() == visitablePos())
  1955. {
  1956. if (h->commander && !h->commander->alive) //rise commander. TODO: interactive script
  1957. {
  1958. SetCommanderProperty scp;
  1959. scp.heroid = h->id;
  1960. scp.which = SetCommanderProperty::ALIVE;
  1961. scp.amount = 1;
  1962. cb->sendAndApply (&scp);
  1963. }
  1964. cb->heroVisitCastle(this, h);
  1965. }
  1966. else
  1967. {
  1968. logGlobal->errorStream() << h->name << " visits allied town of " << name << " from different pos?";
  1969. }
  1970. }
  1971. void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
  1972. {
  1973. cb->stopHeroVisitCastle(this, h);
  1974. }
  1975. void CGTownInstance::initObj()
  1976. ///initialize town structures
  1977. {
  1978. blockVisit = true;
  1979. hoverName = name + ", " + town->faction->name;
  1980. if (subID == ETownType::DUNGEON)
  1981. creatures.resize(GameConstants::CREATURES_PER_TOWN+1);//extra dwelling for Dungeon
  1982. else
  1983. creatures.resize(GameConstants::CREATURES_PER_TOWN);
  1984. for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
  1985. {
  1986. BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST).advance(level);
  1987. int upgradeNum = 0;
  1988. for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
  1989. {
  1990. if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
  1991. creatures[level].second.push_back(town->creatures[level][upgradeNum]);
  1992. }
  1993. }
  1994. switch (subID)
  1995. { //add new visitable objects
  1996. case 0:
  1997. bonusingBuildings.push_back (new COPWBonus(BuildingID::STABLES, this));
  1998. break;
  1999. case 5:
  2000. bonusingBuildings.push_back (new COPWBonus(BuildingID::MANA_VORTEX, this));
  2001. //fallthrough
  2002. case 2: case 3: case 6:
  2003. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_4, this));
  2004. break;
  2005. case 7:
  2006. bonusingBuildings.push_back (new CTownBonus(BuildingID::SPECIAL_1, this));
  2007. break;
  2008. }
  2009. //add special bonuses from buildings
  2010. recreateBuildingsBonuses();
  2011. }
  2012. void CGTownInstance::newTurn() const
  2013. {
  2014. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
  2015. {
  2016. //give resources for Rampart, Mystic Pond
  2017. if (hasBuilt(BuildingID::MYSTIC_POND, ETownType::RAMPART)
  2018. && cb->getDate(Date::DAY) != 1 && (tempOwner < PlayerColor::PLAYER_LIMIT))
  2019. {
  2020. int resID = rand()%4+2;//bonus to random rare resource
  2021. resID = (resID==2)?1:resID;
  2022. int resVal = rand()%4+1;//with size 1..4
  2023. cb->giveResource(tempOwner, static_cast<Res::ERes>(resID), resVal);
  2024. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
  2025. cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
  2026. }
  2027. if ( subID == ETownType::DUNGEON )
  2028. for (auto & elem : bonusingBuildings)
  2029. {
  2030. if ((elem)->ID == BuildingID::MANA_VORTEX)
  2031. cb->setObjProperty (id, ObjProperty::STRUCTURE_CLEAR_VISITORS, (elem)->id); //reset visitors for Mana Vortex
  2032. }
  2033. if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
  2034. {
  2035. std::vector<SlotID> nativeCrits; //slots
  2036. for (auto & elem : Slots())
  2037. {
  2038. if (elem.second->type->faction == subID) //native
  2039. {
  2040. nativeCrits.push_back(elem.first); //collect matching slots
  2041. }
  2042. }
  2043. if (nativeCrits.size())
  2044. {
  2045. SlotID pos = nativeCrits[rand() % nativeCrits.size()];
  2046. StackLocation sl(this, pos);
  2047. const CCreature *c = getCreature(pos);
  2048. if (rand()%100 < 90 || c->upgrades.empty()) //increase number if no upgrade available
  2049. {
  2050. cb->changeStackCount(sl, c->growth);
  2051. }
  2052. else //upgrade
  2053. {
  2054. cb->changeStackType(sl, VLC->creh->creatures[*c->upgrades.begin()]);
  2055. }
  2056. }
  2057. if ((stacksCount() < GameConstants::ARMY_SIZE && rand()%100 < 25) || Slots().empty()) //add new stack
  2058. {
  2059. int i = rand() % std::min (GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH)<<1);
  2060. if (!town->creatures[i].empty())
  2061. {
  2062. CreatureID c = town->creatures[i][0];
  2063. SlotID n;
  2064. TQuantity count = creatureGrowth(i);
  2065. if (!count) // no dwelling
  2066. count = VLC->creh->creatures[c]->growth;
  2067. {//no lower tiers or above current month
  2068. if ((n = getSlotFor(c)).validSlot())
  2069. {
  2070. StackLocation sl(this, n);
  2071. if (slotEmpty(n))
  2072. cb->insertNewStack(sl, VLC->creh->creatures[c], count);
  2073. else //add to existing
  2074. cb->changeStackCount(sl, count);
  2075. }
  2076. }
  2077. }
  2078. }
  2079. }
  2080. }
  2081. }
  2082. int3 CGTownInstance::getSightCenter() const
  2083. {
  2084. return pos - int3(2,0,0);
  2085. }
  2086. ui8 CGTownInstance::getPassableness() const
  2087. {
  2088. if (!armedGarrison())//empty castle - anyone can visit
  2089. return GameConstants::ALL_PLAYERS;
  2090. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  2091. return 0;
  2092. ui8 mask = 0;
  2093. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  2094. for(PlayerColor it : ts->players)
  2095. mask |= 1<<it.getNum();//allies - add to possible visitors
  2096. return mask;
  2097. }
  2098. void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
  2099. {
  2100. offsets += int3(-1,2,0), int3(-3,2,0);
  2101. }
  2102. void CGTownInstance::removeCapitols (PlayerColor owner) const
  2103. {
  2104. if (hasCapitol()) // search if there's an older capitol
  2105. {
  2106. PlayerState* state = cb->gameState()->getPlayer (owner); //get all towns owned by player
  2107. for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
  2108. {
  2109. if (*i != this && (*i)->hasCapitol())
  2110. {
  2111. RazeStructures rs;
  2112. rs.tid = id;
  2113. rs.bid.insert(BuildingID::CAPITOL);
  2114. rs.destroyed = destroyed;
  2115. cb->sendAndApply(&rs);
  2116. return;
  2117. }
  2118. }
  2119. }
  2120. }
  2121. int CGTownInstance::getBoatType() const
  2122. {
  2123. switch (town->faction->alignment)
  2124. {
  2125. case EAlignment::EVIL : return 0;
  2126. case EAlignment::GOOD : return 1;
  2127. case EAlignment::NEUTRAL : return 2;
  2128. }
  2129. assert(0);
  2130. return -1;
  2131. }
  2132. int CGTownInstance::getMarketEfficiency() const
  2133. {
  2134. if (!hasBuilt(BuildingID::MARKETPLACE))
  2135. return 0;
  2136. const PlayerState *p = cb->getPlayer(tempOwner);
  2137. assert(p);
  2138. int marketCount = 0;
  2139. for(const CGTownInstance *t : p->towns)
  2140. if(t->hasBuilt(BuildingID::MARKETPLACE))
  2141. marketCount++;
  2142. return marketCount;
  2143. }
  2144. bool CGTownInstance::allowsTrade(EMarketMode::EMarketMode mode) const
  2145. {
  2146. switch(mode)
  2147. {
  2148. case EMarketMode::RESOURCE_RESOURCE:
  2149. case EMarketMode::RESOURCE_PLAYER:
  2150. return hasBuilt(BuildingID::MARKETPLACE);
  2151. case EMarketMode::ARTIFACT_RESOURCE:
  2152. case EMarketMode::RESOURCE_ARTIFACT:
  2153. return hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::TOWER)
  2154. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::DUNGEON)
  2155. || hasBuilt(BuildingID::ARTIFACT_MERCHANT, ETownType::CONFLUX);
  2156. case EMarketMode::CREATURE_RESOURCE:
  2157. return hasBuilt(BuildingID::FREELANCERS_GUILD, ETownType::STRONGHOLD);
  2158. case EMarketMode::CREATURE_UNDEAD:
  2159. return hasBuilt(BuildingID::SKELETON_TRANSFORMER, ETownType::NECROPOLIS);
  2160. case EMarketMode::RESOURCE_SKILL:
  2161. return hasBuilt(BuildingID::MAGIC_UNIVERSITY, ETownType::CONFLUX);
  2162. default:
  2163. assert(0);
  2164. return false;
  2165. }
  2166. }
  2167. std::vector<int> CGTownInstance::availableItemsIds(EMarketMode::EMarketMode mode) const
  2168. {
  2169. if(mode == EMarketMode::RESOURCE_ARTIFACT)
  2170. {
  2171. std::vector<int> ret;
  2172. for(const CArtifact *a : merchantArtifacts)
  2173. if(a)
  2174. ret.push_back(a->id);
  2175. else
  2176. ret.push_back(-1);
  2177. return ret;
  2178. }
  2179. else if ( mode == EMarketMode::RESOURCE_SKILL )
  2180. {
  2181. return universitySkills;
  2182. }
  2183. else
  2184. return IMarket::availableItemsIds(mode);
  2185. }
  2186. void CGTownInstance::updateAppearance()
  2187. {
  2188. if (!hasFort())
  2189. appearance.animationFile = town->clientInfo.advMapVillage;
  2190. else if(hasCapitol())
  2191. appearance.animationFile = town->clientInfo.advMapCapitol;
  2192. else
  2193. appearance.animationFile = town->clientInfo.advMapCastle;
  2194. }
  2195. std::string CGTownInstance::nodeName() const
  2196. {
  2197. return "Town (" + (town ? town->faction->name : "unknown") + ") of " + name;
  2198. }
  2199. void CGTownInstance::deserializationFix()
  2200. {
  2201. attachTo(&townAndVis);
  2202. //Hero is already handled by CGameState::attachArmedObjects
  2203. // if(visitingHero)
  2204. // visitingHero->attachTo(&townAndVis);
  2205. // if(garrisonHero)
  2206. // garrisonHero->attachTo(this);
  2207. }
  2208. void CGTownInstance::updateMoraleBonusFromArmy()
  2209. {
  2210. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  2211. if(!b)
  2212. {
  2213. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  2214. addNewBonus(b);
  2215. }
  2216. if (garrisonHero)
  2217. b->val = 0;
  2218. else
  2219. CArmedInstance::updateMoraleBonusFromArmy();
  2220. }
  2221. void CGTownInstance::recreateBuildingsBonuses()
  2222. {
  2223. static TPropagatorPtr playerProp(new CPropagatorNodeType(PLAYER));
  2224. BonusList bl;
  2225. getExportedBonusList().getBonuses(bl, Selector::sourceType(Bonus::TOWN_STRUCTURE));
  2226. for(Bonus *b : bl)
  2227. removeBonus(b);
  2228. //tricky! -> checks tavern only if no bratherhood of sword or not a castle
  2229. if(subID != ETownType::CASTLE || !addBonusIfBuilt(BuildingID::BROTHERHOOD, Bonus::MORALE, +2))
  2230. addBonusIfBuilt(BuildingID::TAVERN, Bonus::MORALE, +1);
  2231. if(subID == ETownType::CASTLE) //castle
  2232. {
  2233. addBonusIfBuilt(BuildingID::LIGHTHOUSE, Bonus::SEA_MOVEMENT, +500, playerProp);
  2234. addBonusIfBuilt(BuildingID::GRAIL, Bonus::MORALE, +2, playerProp); //colossus
  2235. }
  2236. else if(subID == ETownType::RAMPART) //rampart
  2237. {
  2238. addBonusIfBuilt(BuildingID::FOUNTAIN_OF_FORTUNE, Bonus::LUCK, +2); //fountain of fortune
  2239. addBonusIfBuilt(BuildingID::GRAIL, Bonus::LUCK, +2, playerProp); //guardian spirit
  2240. }
  2241. else if(subID == ETownType::TOWER) //tower
  2242. {
  2243. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +15, PrimarySkill::KNOWLEDGE); //grail
  2244. }
  2245. else if(subID == ETownType::INFERNO) //Inferno
  2246. {
  2247. addBonusIfBuilt(BuildingID::STORMCLOUDS, Bonus::PRIMARY_SKILL, +2, PrimarySkill::SPELL_POWER); //Brimstone Clouds
  2248. }
  2249. else if(subID == ETownType::NECROPOLIS) //necropolis
  2250. {
  2251. addBonusIfBuilt(BuildingID::COVER_OF_DARKNESS, Bonus::DARKNESS, +20);
  2252. addBonusIfBuilt(BuildingID::NECROMANCY_AMPLIFIER, Bonus::SECONDARY_SKILL_PREMY, +10, playerProp, SecondarySkill::NECROMANCY); //necromancy amplifier
  2253. addBonusIfBuilt(BuildingID::GRAIL, Bonus::SECONDARY_SKILL_PREMY, +20, playerProp, SecondarySkill::NECROMANCY); //Soul prison
  2254. }
  2255. else if(subID == ETownType::DUNGEON) //Dungeon
  2256. {
  2257. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +12, PrimarySkill::SPELL_POWER); //grail
  2258. }
  2259. else if(subID == ETownType::STRONGHOLD) //Stronghold
  2260. {
  2261. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +20, PrimarySkill::ATTACK); //grail
  2262. }
  2263. else if(subID == ETownType::FORTRESS) //Fortress
  2264. {
  2265. addBonusIfBuilt(BuildingID::GLYPHS_OF_FEAR, Bonus::PRIMARY_SKILL, +2, PrimarySkill::DEFENSE); //Glyphs of Fear
  2266. addBonusIfBuilt(BuildingID::BLOOD_OBELISK, Bonus::PRIMARY_SKILL, +2, PrimarySkill::ATTACK); //Blood Obelisk
  2267. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::ATTACK); //grail
  2268. addBonusIfBuilt(BuildingID::GRAIL, Bonus::PRIMARY_SKILL, +10, PrimarySkill::DEFENSE); //grail
  2269. }
  2270. else if(subID == ETownType::CONFLUX)
  2271. {
  2272. }
  2273. }
  2274. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, int subtype /*= -1*/)
  2275. {
  2276. static auto emptyPropagator = TPropagatorPtr();
  2277. return addBonusIfBuilt(building, type, val, emptyPropagator, subtype);
  2278. }
  2279. bool CGTownInstance::addBonusIfBuilt(BuildingID building, Bonus::BonusType type, int val, TPropagatorPtr & prop, int subtype /*= -1*/)
  2280. {
  2281. if(hasBuilt(building))
  2282. {
  2283. std::ostringstream descr;
  2284. descr << town->buildings.at(building)->Name() << " ";
  2285. if(val > 0)
  2286. descr << "+";
  2287. else if(val < 0)
  2288. descr << "-";
  2289. descr << val;
  2290. Bonus *b = new Bonus(Bonus::PERMANENT, type, Bonus::TOWN_STRUCTURE, val, building, descr.str(), subtype);
  2291. if(prop)
  2292. b->addPropagator(prop);
  2293. addNewBonus(b);
  2294. return true;
  2295. }
  2296. return false;
  2297. }
  2298. void CGTownInstance::setVisitingHero(CGHeroInstance *h)
  2299. {
  2300. assert(!!visitingHero == !h);
  2301. if(h)
  2302. {
  2303. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2304. assert(p);
  2305. h->detachFrom(p);
  2306. h->attachTo(&townAndVis);
  2307. visitingHero = h;
  2308. h->visitedTown = this;
  2309. h->inTownGarrison = false;
  2310. }
  2311. else
  2312. {
  2313. PlayerState *p = cb->gameState()->getPlayer(visitingHero->tempOwner);
  2314. visitingHero->visitedTown = nullptr;
  2315. visitingHero->detachFrom(&townAndVis);
  2316. visitingHero->attachTo(p);
  2317. visitingHero = nullptr;
  2318. }
  2319. }
  2320. void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
  2321. {
  2322. assert(!!garrisonHero == !h);
  2323. if(h)
  2324. {
  2325. PlayerState *p = cb->gameState()->getPlayer(h->tempOwner);
  2326. assert(p);
  2327. h->detachFrom(p);
  2328. h->attachTo(this);
  2329. garrisonHero = h;
  2330. h->visitedTown = this;
  2331. h->inTownGarrison = true;
  2332. }
  2333. else
  2334. {
  2335. PlayerState *p = cb->gameState()->getPlayer(garrisonHero->tempOwner);
  2336. garrisonHero->visitedTown = nullptr;
  2337. garrisonHero->inTownGarrison = false;
  2338. garrisonHero->detachFrom(this);
  2339. garrisonHero->attachTo(p);
  2340. garrisonHero = nullptr;
  2341. }
  2342. updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
  2343. }
  2344. bool CGTownInstance::armedGarrison() const
  2345. {
  2346. return stacksCount() || garrisonHero;
  2347. }
  2348. int CGTownInstance::getTownLevel() const
  2349. {
  2350. // count all buildings that are not upgrades
  2351. return boost::range::count_if(builtBuildings, [&](const BuildingID & build)
  2352. {
  2353. return town->buildings.at(build) && town->buildings.at(build)->upgrade == -1;
  2354. });
  2355. }
  2356. CBonusSystemNode * CGTownInstance::whatShouldBeAttached()
  2357. {
  2358. return &townAndVis;
  2359. }
  2360. const CArmedInstance * CGTownInstance::getUpperArmy() const
  2361. {
  2362. if(garrisonHero)
  2363. return garrisonHero;
  2364. return this;
  2365. }
  2366. bool CGTownInstance::hasBuilt(BuildingID buildingID, int townID) const
  2367. {
  2368. if (townID == town->faction->index || townID == ETownType::ANY)
  2369. return hasBuilt(buildingID);
  2370. return false;
  2371. }
  2372. bool CGTownInstance::hasBuilt(BuildingID buildingID) const
  2373. {
  2374. return vstd::contains(builtBuildings, buildingID);
  2375. }
  2376. void CGTownInstance::addHeroToStructureVisitors( const CGHeroInstance *h, si32 structureInstanceID ) const
  2377. {
  2378. if(visitingHero == h)
  2379. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
  2380. else if(garrisonHero == h)
  2381. cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
  2382. else
  2383. {
  2384. //should never ever happen
  2385. logGlobal->errorStream() << "Cannot add hero " << h->name << " to visitors of structure #" << structureInstanceID;
  2386. assert(0);
  2387. }
  2388. }
  2389. void CGTownInstance::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  2390. {
  2391. if(result.winner == 0)
  2392. {
  2393. removeCapitols(hero->getOwner());
  2394. cb->setOwner (this, hero->tempOwner); //give control after checkout is done
  2395. FoWChange fw;
  2396. fw.player = hero->tempOwner;
  2397. fw.mode = 1;
  2398. getSightTiles (fw.tiles); //update visibility for castle structures
  2399. cb->sendAndApply (&fw);
  2400. }
  2401. }
  2402. bool CGVisitableOPH::wasVisited (const CGHeroInstance * h) const
  2403. {
  2404. return vstd::contains(visitors, h->id);
  2405. }
  2406. void CGVisitableOPH::onHeroVisit( const CGHeroInstance * h ) const
  2407. {
  2408. if(!vstd::contains(visitors, h->id))
  2409. {
  2410. onNAHeroVisit (h, false);
  2411. switch(ID)
  2412. {
  2413. case Obj::TREE_OF_KNOWLEDGE:
  2414. case Obj::ARENA:
  2415. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2416. case Obj::SCHOOL_OF_MAGIC:
  2417. case Obj::SCHOOL_OF_WAR:
  2418. break;
  2419. default:
  2420. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2421. break;
  2422. }
  2423. }
  2424. else
  2425. {
  2426. onNAHeroVisit(h, true);
  2427. }
  2428. }
  2429. void CGVisitableOPH::initObj()
  2430. {
  2431. if(ID==Obj::TREE_OF_KNOWLEDGE)
  2432. {
  2433. switch (ran() % 3)
  2434. {
  2435. case 1:
  2436. treePrice[Res::GOLD] = 2000;
  2437. break;
  2438. case 2:
  2439. treePrice[Res::GEMS] = 10;
  2440. break;
  2441. default:
  2442. break;
  2443. }
  2444. }
  2445. }
  2446. void CGVisitableOPH::treeSelected (const CGHeroInstance * h, ui32 result) const
  2447. {
  2448. if(result) //player agreed to give res for exp
  2449. {
  2450. si64 expToGive = VLC->heroh->reqExp(h->level+1) - VLC->heroh->reqExp(h->level);;
  2451. cb->giveResources (h->getOwner(), -treePrice);
  2452. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, expToGive);
  2453. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2454. }
  2455. }
  2456. void CGVisitableOPH::onNAHeroVisit (const CGHeroInstance * h, bool alreadyVisited) const
  2457. {
  2458. Component::EComponentType c_id = Component::PRIM_SKILL; //most used here
  2459. int subid=0, ot=0, sound = 0;
  2460. TExpType val=1;
  2461. switch(ID)
  2462. {
  2463. case Obj::ARENA:
  2464. sound = soundBase::NOMAD;
  2465. ot = 0;
  2466. break;
  2467. case Obj::MERCENARY_CAMP:
  2468. sound = soundBase::NOMAD;
  2469. subid=PrimarySkill::ATTACK;
  2470. ot=80;
  2471. break;
  2472. case Obj::MARLETTO_TOWER:
  2473. sound = soundBase::NOMAD;
  2474. subid=PrimarySkill::DEFENSE;
  2475. ot=39;
  2476. break;
  2477. case Obj::STAR_AXIS:
  2478. sound = soundBase::gazebo;
  2479. subid=PrimarySkill::SPELL_POWER;
  2480. ot=100;
  2481. break;
  2482. case Obj::GARDEN_OF_REVELATION:
  2483. sound = soundBase::GETPROTECTION;
  2484. subid=PrimarySkill::KNOWLEDGE;
  2485. ot=59;
  2486. break;
  2487. case Obj::LEARNING_STONE:
  2488. sound = soundBase::gazebo;
  2489. c_id=Component::EXPERIENCE;
  2490. ot=143;
  2491. val=1000;
  2492. break;
  2493. case Obj::TREE_OF_KNOWLEDGE:
  2494. sound = soundBase::gazebo;
  2495. c_id = Component::EXPERIENCE;
  2496. subid = 1;
  2497. ot = 147;
  2498. val = 1;
  2499. break;
  2500. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2501. sound = soundBase::gazebo;
  2502. ot = 66;
  2503. break;
  2504. case Obj::SCHOOL_OF_MAGIC:
  2505. sound = soundBase::faerie;
  2506. ot = 71;
  2507. break;
  2508. case Obj::SCHOOL_OF_WAR:
  2509. c_id=Component::PRIM_SKILL;
  2510. sound = soundBase::MILITARY;
  2511. ot = 158;
  2512. break;
  2513. }
  2514. if (!alreadyVisited)
  2515. {
  2516. switch (ID)
  2517. {
  2518. case Obj::ARENA:
  2519. {
  2520. BlockingDialog sd(false,true);
  2521. sd.soundID = sound;
  2522. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2523. sd.components.push_back(Component(c_id, PrimarySkill::ATTACK, 2, 0));
  2524. sd.components.push_back(Component(c_id, PrimarySkill::DEFENSE, 2, 0));
  2525. sd.player = h->getOwner();
  2526. cb->showBlockingDialog(&sd);
  2527. return;
  2528. }
  2529. case Obj::MERCENARY_CAMP:
  2530. case Obj::MARLETTO_TOWER:
  2531. case Obj::STAR_AXIS:
  2532. case Obj::GARDEN_OF_REVELATION:
  2533. {
  2534. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(subid), val);
  2535. InfoWindow iw;
  2536. iw.soundID = sound;
  2537. iw.components.push_back(Component(c_id, subid, val, 0));
  2538. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2539. iw.player = h->getOwner();
  2540. cb->showInfoDialog(&iw);
  2541. break;
  2542. }
  2543. case Obj::LEARNING_STONE: //give exp
  2544. {
  2545. val = h->calculateXp(val);
  2546. InfoWindow iw;
  2547. iw.soundID = sound;
  2548. iw.components.push_back (Component(c_id,subid,val,0));
  2549. iw.player = h->getOwner();
  2550. iw.text.addTxt(MetaString::ADVOB_TXT,ot);
  2551. cb->showInfoDialog(&iw);
  2552. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, val);
  2553. break;
  2554. }
  2555. case Obj::TREE_OF_KNOWLEDGE:
  2556. {
  2557. val = VLC->heroh->reqExp (h->level + val) - VLC->heroh->reqExp(h->level);
  2558. if(!treePrice.nonZero())
  2559. {
  2560. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2561. InfoWindow iw;
  2562. iw.soundID = sound;
  2563. iw.components.push_back (Component(c_id,subid,1,0));
  2564. iw.player = h->getOwner();
  2565. iw.text.addTxt (MetaString::ADVOB_TXT,148);
  2566. cb->showInfoDialog (&iw);
  2567. cb->changePrimSkill (h, PrimarySkill::EXPERIENCE, val);
  2568. break;
  2569. }
  2570. else
  2571. {
  2572. if(treePrice[Res::GOLD] > 0)
  2573. ot = 149;
  2574. else
  2575. ot = 151;
  2576. if(!cb->getPlayer(h->tempOwner)->resources.canAfford(treePrice)) //not enough resources
  2577. {
  2578. ot++;
  2579. showInfoDialog(h,ot,sound);
  2580. return;
  2581. }
  2582. BlockingDialog sd (true, false);
  2583. sd.soundID = sound;
  2584. sd.player = h->getOwner();
  2585. sd.text.addTxt (MetaString::ADVOB_TXT,ot);
  2586. sd.addResourceComponents (treePrice);
  2587. cb->showBlockingDialog (&sd);
  2588. }
  2589. break;
  2590. }
  2591. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2592. {
  2593. int txt_id = 66;
  2594. if(h->level < 10 - 2*h->getSecSkillLevel(SecondarySkill::DIPLOMACY)) //not enough level
  2595. {
  2596. txt_id += 2;
  2597. }
  2598. else
  2599. {
  2600. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2601. cb->changePrimSkill (h, PrimarySkill::ATTACK, 2);
  2602. cb->changePrimSkill (h, PrimarySkill::DEFENSE, 2);
  2603. cb->changePrimSkill (h, PrimarySkill::KNOWLEDGE, 2);
  2604. cb->changePrimSkill (h, PrimarySkill::SPELL_POWER, 2);
  2605. }
  2606. showInfoDialog(h,txt_id,sound);
  2607. break;
  2608. }
  2609. case Obj::SCHOOL_OF_MAGIC:
  2610. case Obj::SCHOOL_OF_WAR:
  2611. {
  2612. int skill = (ID==Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2613. if (cb->getResource (h->getOwner(), Res::GOLD) < 1000) //not enough resources
  2614. {
  2615. showInfoDialog (h->getOwner(), ot+2, sound);
  2616. }
  2617. else
  2618. {
  2619. BlockingDialog sd(true,true);
  2620. sd.soundID = sound;
  2621. sd.player = h->getOwner();
  2622. sd.text.addTxt(MetaString::ADVOB_TXT,ot);
  2623. sd.components.push_back(Component(c_id, skill, +1, 0));
  2624. sd.components.push_back(Component(c_id, skill+1, +1, 0));
  2625. cb->showBlockingDialog(&sd);
  2626. }
  2627. }
  2628. break;
  2629. }
  2630. }
  2631. else
  2632. {
  2633. ot++;
  2634. showInfoDialog (h->getOwner(),ot,sound);
  2635. }
  2636. }
  2637. const std::string & CGVisitableOPH::getHoverText() const
  2638. {
  2639. int pom = -1;
  2640. switch(ID)
  2641. {
  2642. case Obj::ARENA:
  2643. pom = -1;
  2644. break;
  2645. case Obj::MERCENARY_CAMP:
  2646. pom = 8;
  2647. break;
  2648. case Obj::MARLETTO_TOWER:
  2649. pom = 7;
  2650. break;
  2651. case Obj::STAR_AXIS:
  2652. pom = 11;
  2653. break;
  2654. case Obj::GARDEN_OF_REVELATION:
  2655. pom = 4;
  2656. break;
  2657. case Obj::LEARNING_STONE:
  2658. pom = 5;
  2659. break;
  2660. case Obj::TREE_OF_KNOWLEDGE:
  2661. pom = 18;
  2662. break;
  2663. case Obj::LIBRARY_OF_ENLIGHTENMENT:
  2664. break;
  2665. case Obj::SCHOOL_OF_MAGIC:
  2666. pom = 9;
  2667. break;
  2668. case Obj::SCHOOL_OF_WAR:
  2669. pom = 10;
  2670. break;
  2671. default:
  2672. throw std::runtime_error("Wrong CGVisitableOPH object ID!\n");
  2673. }
  2674. hoverName = VLC->generaltexth->names[ID];
  2675. if(pom >= 0)
  2676. hoverName += ("\n" + VLC->generaltexth->xtrainfo[pom]);
  2677. const CGHeroInstance *h = cb->getSelectedHero (cb->getCurrentPlayer());
  2678. if(h)
  2679. {
  2680. hoverName += "\n\n";
  2681. bool visited = vstd::contains (visitors, h->id);
  2682. hoverName += visitedTxt (visited);
  2683. }
  2684. return hoverName;
  2685. }
  2686. void CGVisitableOPH::arenaSelected(const CGHeroInstance * h, int primSkill ) const
  2687. {
  2688. cb->setObjProperty(id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2689. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(primSkill-1), 2);
  2690. }
  2691. void CGVisitableOPH::setPropertyDer( ui8 what, ui32 val )
  2692. {
  2693. if(what == ObjProperty::VISITORS)
  2694. visitors.insert(ObjectInstanceID(val));
  2695. }
  2696. void CGVisitableOPH::schoolSelected(const CGHeroInstance * h, ui32 which) const
  2697. {
  2698. if(!which) //player refused to pay
  2699. return;
  2700. int base = (ID == Obj::SCHOOL_OF_MAGIC ? 2 : 0);
  2701. cb->setObjProperty (id, ObjProperty::VISITORS, h->id.getNum()); //add to the visitors
  2702. cb->giveResource (h->getOwner(),Res::GOLD,-1000); //take 1000 gold
  2703. cb->changePrimSkill (h, static_cast<PrimarySkill::PrimarySkill>(base + which-1), +1); //give appropriate skill
  2704. }
  2705. void CGVisitableOPH::blockingDialogAnswered(const CGHeroInstance *h, ui32 answer) const
  2706. {
  2707. switch (ID)
  2708. {
  2709. case Obj::ARENA:
  2710. arenaSelected(h, answer);
  2711. break;
  2712. case Obj::TREE_OF_KNOWLEDGE:
  2713. treeSelected(h, answer);
  2714. break;
  2715. case Obj::SCHOOL_OF_MAGIC:
  2716. case Obj::SCHOOL_OF_WAR:
  2717. schoolSelected(h, answer);
  2718. break;
  2719. default:
  2720. assert(0);
  2721. break;
  2722. }
  2723. }
  2724. COPWBonus::COPWBonus (BuildingID index, CGTownInstance *TOWN)
  2725. {
  2726. ID = index;
  2727. town = TOWN;
  2728. id = town->bonusingBuildings.size();
  2729. }
  2730. void COPWBonus::setProperty(ui8 what, ui32 val)
  2731. {
  2732. switch (what)
  2733. {
  2734. case ObjProperty::VISITORS:
  2735. visitors.insert(val);
  2736. break;
  2737. case ObjProperty::STRUCTURE_CLEAR_VISITORS:
  2738. visitors.clear();
  2739. break;
  2740. }
  2741. }
  2742. void COPWBonus::onHeroVisit (const CGHeroInstance * h) const
  2743. {
  2744. ObjectInstanceID heroID = h->id;
  2745. if (town->hasBuilt(ID))
  2746. {
  2747. InfoWindow iw;
  2748. iw.player = h->tempOwner;
  2749. switch (town->subID)
  2750. {
  2751. case ETownType::CASTLE: //Stables
  2752. if (!h->hasBonusFrom(Bonus::OBJECT, Obj::STABLES)) //does not stack with advMap Stables
  2753. {
  2754. GiveBonus gb;
  2755. gb.bonus = Bonus(Bonus::ONE_WEEK, Bonus::LAND_MOVEMENT, Bonus::OBJECT, 600, 94, VLC->generaltexth->arraytxt[100]);
  2756. gb.id = heroID.getNum();
  2757. cb->giveHeroBonus(&gb);
  2758. iw.text << VLC->generaltexth->allTexts[580];
  2759. cb->showInfoDialog(&iw);
  2760. }
  2761. break;
  2762. case ETownType::DUNGEON: //Mana Vortex
  2763. if (visitors.empty() && h->mana <= h->manaLimit() * 2)
  2764. {
  2765. cb->setManaPoints (heroID, 2 * h->manaLimit());
  2766. //TODO: investigate line below
  2767. //cb->setObjProperty (town->id, ObjProperty::VISITED, true);
  2768. iw.text << VLC->generaltexth->allTexts[579];
  2769. cb->showInfoDialog(&iw);
  2770. town->addHeroToStructureVisitors(h, id);
  2771. }
  2772. break;
  2773. }
  2774. }
  2775. }
  2776. CTownBonus::CTownBonus (BuildingID index, CGTownInstance *TOWN)
  2777. {
  2778. ID = index;
  2779. town = TOWN;
  2780. id = town->bonusingBuildings.size();
  2781. }
  2782. void CTownBonus::setProperty (ui8 what, ui32 val)
  2783. {
  2784. if(what == ObjProperty::VISITORS)
  2785. visitors.insert(ObjectInstanceID(val));
  2786. }
  2787. void CTownBonus::onHeroVisit (const CGHeroInstance * h) const
  2788. {
  2789. ObjectInstanceID heroID = h->id;
  2790. if (town->hasBuilt(ID) && visitors.find(heroID) == visitors.end())
  2791. {
  2792. InfoWindow iw;
  2793. PrimarySkill::PrimarySkill what = PrimarySkill::ATTACK;
  2794. int val=0, mid=0;
  2795. switch (ID)
  2796. {
  2797. case BuildingID::SPECIAL_4:
  2798. switch(town->subID)
  2799. {
  2800. case ETownType::TOWER: //wall
  2801. what = PrimarySkill::KNOWLEDGE;
  2802. val = 1;
  2803. mid = 581;
  2804. iw.components.push_back (Component(Component::PRIM_SKILL, 3, 1, 0));
  2805. break;
  2806. case ETownType::INFERNO: //order of fire
  2807. what = PrimarySkill::SPELL_POWER;
  2808. val = 1;
  2809. mid = 582;
  2810. iw.components.push_back (Component(Component::PRIM_SKILL, 2, 1, 0));
  2811. break;
  2812. case ETownType::STRONGHOLD://hall of Valhalla
  2813. what = PrimarySkill::ATTACK;
  2814. val = 1;
  2815. mid = 584;
  2816. iw.components.push_back (Component(Component::PRIM_SKILL, 0, 1, 0));
  2817. break;
  2818. case ETownType::DUNGEON://academy of battle scholars
  2819. what = PrimarySkill::EXPERIENCE;
  2820. val = h->calculateXp(1000);
  2821. mid = 583;
  2822. iw.components.push_back (Component(Component::EXPERIENCE, 0, val, 0));
  2823. break;
  2824. }
  2825. break;
  2826. case BuildingID::SPECIAL_1:
  2827. switch(town->subID)
  2828. {
  2829. case ETownType::FORTRESS: //cage of warlords
  2830. what = PrimarySkill::DEFENSE;
  2831. val = 1;
  2832. mid = 585;
  2833. iw.components.push_back (Component(Component::PRIM_SKILL, 1, 1, 0));
  2834. break;
  2835. }
  2836. break;
  2837. }
  2838. assert(mid);
  2839. iw.player = cb->getOwner(heroID);
  2840. iw.text << VLC->generaltexth->allTexts[mid];
  2841. cb->showInfoDialog(&iw);
  2842. cb->changePrimSkill (cb->getHero(heroID), what, val);
  2843. town->addHeroToStructureVisitors(h, id);
  2844. }
  2845. }
  2846. const std::string & CGCreature::getHoverText() const
  2847. {
  2848. if(stacks.empty())
  2849. {
  2850. static const std::string errorValue("!!!INVALID_STACK!!!");
  2851. //should not happen...
  2852. logGlobal->errorStream() << "Invalid stack at tile " << pos << ": subID=" << subID << "; id=" << id;
  2853. return errorValue; // references to temporary are illegal - use pre-constructed string
  2854. }
  2855. MetaString ms;
  2856. int pom = stacks.begin()->second->getQuantityID();
  2857. pom = 172 + 3*pom;
  2858. ms.addTxt(MetaString::ARRAY_TXT,pom);
  2859. ms << " " ;
  2860. ms.addTxt(MetaString::CRE_PL_NAMES,subID);
  2861. ms.toString(hoverName);
  2862. if(const CGHeroInstance *selHero = cb->getSelectedHero(cb->getCurrentPlayer()))
  2863. {
  2864. const JsonNode & texts = VLC->generaltexth->localizedTexts["adventureMap"]["monsterThreat"];
  2865. hoverName += texts["title"].String();
  2866. int choice;
  2867. double ratio = ((double)getArmyStrength() / selHero->getTotalStrength());
  2868. if (ratio < 0.1) choice = 0;
  2869. else if (ratio < 0.25) choice = 1;
  2870. else if (ratio < 0.6) choice = 2;
  2871. else if (ratio < 0.9) choice = 3;
  2872. else if (ratio < 1.1) choice = 4;
  2873. else if (ratio < 1.3) choice = 5;
  2874. else if (ratio < 1.8) choice = 6;
  2875. else if (ratio < 2.5) choice = 7;
  2876. else if (ratio < 4) choice = 8;
  2877. else if (ratio < 8) choice = 9;
  2878. else if (ratio < 20) choice = 10;
  2879. else choice = 11;
  2880. hoverName += texts["levels"].Vector()[choice].String();
  2881. }
  2882. return hoverName;
  2883. }
  2884. void CGCreature::onHeroVisit( const CGHeroInstance * h ) const
  2885. {
  2886. int action = takenAction(h);
  2887. switch( action ) //decide what we do...
  2888. {
  2889. case FIGHT:
  2890. fight(h);
  2891. break;
  2892. case FLEE: //flee
  2893. {
  2894. flee(h);
  2895. break;
  2896. }
  2897. case JOIN_FOR_FREE: //join for free
  2898. {
  2899. BlockingDialog ynd(true,false);
  2900. ynd.player = h->tempOwner;
  2901. ynd.text.addTxt(MetaString::ADVOB_TXT, 86);
  2902. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  2903. cb->showBlockingDialog(&ynd);
  2904. break;
  2905. }
  2906. default: //join for gold
  2907. {
  2908. assert(action > 0);
  2909. //ask if player agrees to pay gold
  2910. BlockingDialog ynd(true,false);
  2911. ynd.player = h->tempOwner;
  2912. std::string tmp = VLC->generaltexth->advobtxt[90];
  2913. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(getStackCount(SlotID(0))));
  2914. boost::algorithm::replace_first(tmp,"%d",boost::lexical_cast<std::string>(action));
  2915. boost::algorithm::replace_first(tmp,"%s",VLC->creh->creatures[subID]->namePl);
  2916. ynd.text << tmp;
  2917. cb->showBlockingDialog(&ynd);
  2918. break;
  2919. }
  2920. }
  2921. }
  2922. void CGCreature::initObj()
  2923. {
  2924. blockVisit = true;
  2925. switch(character)
  2926. {
  2927. case 0:
  2928. character = -4;
  2929. break;
  2930. case 1:
  2931. character = 1 + ran()%7;
  2932. break;
  2933. case 2:
  2934. character = 1 + ran()%10;
  2935. break;
  2936. case 3:
  2937. character = 4 + ran()%7;
  2938. break;
  2939. case 4:
  2940. character = 10;
  2941. break;
  2942. }
  2943. stacks[SlotID(0)]->setType(CreatureID(subID));
  2944. TQuantity &amount = stacks[SlotID(0)]->count;
  2945. CCreature &c = *VLC->creh->creatures[subID];
  2946. if(!amount)
  2947. {
  2948. if(c.ammMax == c.ammMin)
  2949. amount = c.ammMax;
  2950. else
  2951. amount = c.ammMin + (ran() % (c.ammMax - c.ammMin));
  2952. if(!amount) //armies with 0 creatures are illegal
  2953. {
  2954. logGlobal->warnStream() << "Problem: stack " << nodeName() << " cannot have 0 creatures. Check properties of " << c.nodeName();
  2955. amount = 1;
  2956. }
  2957. }
  2958. formation.randomFormation = rand();
  2959. temppower = stacks[SlotID(0)]->count * 1000;
  2960. refusedJoining = false;
  2961. }
  2962. void CGCreature::newTurn() const
  2963. {//Works only for stacks of single type of size up to 2 millions
  2964. if (stacks.begin()->second->count < VLC->modh->settings.CREEP_SIZE && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  2965. {
  2966. ui32 power = temppower * (100 + VLC->modh->settings.WEEKLY_GROWTH)/100;
  2967. cb->setObjProperty(id, ObjProperty::MONSTER_COUNT, std::min (power/1000 , (ui32)VLC->modh->settings.CREEP_SIZE)); //set new amount
  2968. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  2969. }
  2970. if (VLC->modh->modules.STACK_EXP)
  2971. cb->setObjProperty(id, ObjProperty::MONSTER_EXP, VLC->modh->settings.NEUTRAL_STACK_EXP); //for testing purpose
  2972. }
  2973. void CGCreature::setPropertyDer(ui8 what, ui32 val)
  2974. {
  2975. switch (what)
  2976. {
  2977. case ObjProperty::MONSTER_COUNT:
  2978. stacks[SlotID(0)]->count = val;
  2979. break;
  2980. case ObjProperty::MONSTER_POWER:
  2981. temppower = val;
  2982. break;
  2983. case ObjProperty::MONSTER_EXP:
  2984. giveStackExp(val);
  2985. break;
  2986. case ObjProperty::MONSTER_RESTORE_TYPE:
  2987. formation.basicType = val;
  2988. break;
  2989. case ObjProperty::MONSTER_REFUSED_JOIN:
  2990. refusedJoining = val;
  2991. break;
  2992. }
  2993. }
  2994. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  2995. {
  2996. //calculate relative strength of hero and creatures armies
  2997. double relStrength = double(h->getTotalStrength()) / getArmyStrength();
  2998. int powerFactor;
  2999. if(relStrength >= 7)
  3000. powerFactor = 11;
  3001. else if(relStrength >= 1)
  3002. powerFactor = (int)(2*(relStrength-1));
  3003. else if(relStrength >= 0.5)
  3004. powerFactor = -1;
  3005. else if(relStrength >= 0.333)
  3006. powerFactor = -2;
  3007. else
  3008. powerFactor = -3;
  3009. std::set<CreatureID> myKindCres; //what creatures are the same kind as we
  3010. const CCreature * myCreature = VLC->creh->creatures[subID];
  3011. myKindCres.insert(myCreature->idNumber); //we
  3012. myKindCres.insert(myCreature->upgrades.begin(), myCreature->upgrades.end()); //our upgrades
  3013. for(ConstTransitivePtr<CCreature> &crea : VLC->creh->creatures)
  3014. {
  3015. if(vstd::contains(crea->upgrades, myCreature->idNumber)) //it's our base creatures
  3016. myKindCres.insert(crea->idNumber);
  3017. }
  3018. int count = 0, //how many creatures of similar kind has hero
  3019. totalCount = 0;
  3020. for (auto & elem : h->Slots())
  3021. {
  3022. if(vstd::contains(myKindCres,elem.second->type->idNumber))
  3023. count += elem.second->count;
  3024. totalCount += elem.second->count;
  3025. }
  3026. int sympathy = 0; // 0 if hero have no similar creatures
  3027. if(count)
  3028. sympathy++; // 1 - if hero have at least 1 similar creature
  3029. if(count*2 > totalCount)
  3030. sympathy++; // 2 - hero have similar creatures more that 50%
  3031. int charisma = powerFactor + h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy;
  3032. if(charisma < character) //creatures will fight
  3033. return -2;
  3034. if (allowJoin)
  3035. {
  3036. if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) + sympathy + 1 >= character)
  3037. return 0; //join for free
  3038. else if(h->getSecSkillLevel(SecondarySkill::DIPLOMACY) * 2 + sympathy + 1 >= character)
  3039. return VLC->creh->creatures[subID]->cost[6] * getStackCount(SlotID(0)); //join for gold
  3040. }
  3041. //we are still here - creatures have not joined hero, flee or fight
  3042. if (charisma > character)
  3043. return -1; //flee
  3044. else
  3045. return -2; //fight
  3046. }
  3047. void CGCreature::fleeDecision(const CGHeroInstance *h, ui32 pursue) const
  3048. {
  3049. if(refusedJoining)
  3050. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  3051. if(pursue)
  3052. {
  3053. fight(h);
  3054. }
  3055. else
  3056. {
  3057. cb->removeObject(this);
  3058. }
  3059. }
  3060. void CGCreature::joinDecision(const CGHeroInstance *h, int cost, ui32 accept) const
  3061. {
  3062. if(!accept)
  3063. {
  3064. if(takenAction(h,false) == -1) //they flee
  3065. {
  3066. cb->setObjProperty(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  3067. flee(h);
  3068. }
  3069. else //they fight
  3070. {
  3071. showInfoDialog(h,87,0);//Insulted by your refusal of their offer, the monsters attack!
  3072. fight(h);
  3073. }
  3074. }
  3075. else //accepted
  3076. {
  3077. if (cb->getResource(h->tempOwner, Res::GOLD) < cost) //player don't have enough gold!
  3078. {
  3079. InfoWindow iw;
  3080. iw.player = h->tempOwner;
  3081. iw.text << std::pair<ui8,ui32>(1,29); //You don't have enough gold
  3082. cb->showInfoDialog(&iw);
  3083. //act as if player refused
  3084. joinDecision(h,cost,false);
  3085. return;
  3086. }
  3087. //take gold
  3088. if(cost)
  3089. cb->giveResource(h->tempOwner,Res::GOLD,-cost);
  3090. cb->tryJoiningArmy(this, h, true, true);
  3091. }
  3092. }
  3093. void CGCreature::fight( const CGHeroInstance *h ) const
  3094. {
  3095. //split stacks
  3096. //TODO: multiple creature types in a stack?
  3097. int basicType = stacks.begin()->second->type->idNumber;
  3098. cb->setObjProperty(id, ObjProperty::MONSTER_RESTORE_TYPE, basicType); //store info about creature stack
  3099. double relativePower = static_cast<double>(h->getTotalStrength()) / getArmyStrength();
  3100. int stacksCount;
  3101. //TODO: number depends on tile type
  3102. if (relativePower < 0.5)
  3103. {
  3104. stacksCount = 7;
  3105. }
  3106. else if (relativePower < 0.67)
  3107. {
  3108. stacksCount = 7;
  3109. }
  3110. else if (relativePower < 1)
  3111. {
  3112. stacksCount = 6;
  3113. }
  3114. else if (relativePower < 1.5)
  3115. {
  3116. stacksCount = 5;
  3117. }
  3118. else if (relativePower < 2)
  3119. {
  3120. stacksCount = 4;
  3121. }
  3122. else
  3123. {
  3124. stacksCount = 3;
  3125. }
  3126. SlotID sourceSlot = stacks.begin()->first;
  3127. SlotID destSlot;
  3128. for (int stacksLeft = stacksCount; stacksLeft > 1; --stacksLeft)
  3129. {
  3130. int stackSize = stacks.begin()->second->count / stacksLeft;
  3131. if (stackSize)
  3132. {
  3133. if ((destSlot = getFreeSlot()).validSlot())
  3134. cb->moveStack(StackLocation(this, sourceSlot), StackLocation(this, destSlot), stackSize);
  3135. else
  3136. {
  3137. logGlobal->warnStream() <<"Warning! Not enough empty slots to split stack!";
  3138. break;
  3139. }
  3140. }
  3141. else break;
  3142. }
  3143. if (stacksCount > 1)
  3144. {
  3145. if (formation.randomFormation % 100 < 50) //upgrade
  3146. {
  3147. SlotID slotId = SlotID(stacks.size() / 2);
  3148. if(ui32 upgradesSize = getStack(slotId).type->upgrades.size())
  3149. {
  3150. auto it = getStack(slotId).type->upgrades.cbegin(); //pick random in case there are more
  3151. std::advance (it, rand() % upgradesSize);
  3152. cb->changeStackType(StackLocation(this, slotId), VLC->creh->creatures[*it]);
  3153. }
  3154. }
  3155. }
  3156. cb->startBattleI(h, this);
  3157. }
  3158. void CGCreature::flee( const CGHeroInstance * h ) const
  3159. {
  3160. BlockingDialog ynd(true,false);
  3161. ynd.player = h->tempOwner;
  3162. ynd.text.addTxt(MetaString::ADVOB_TXT,91);
  3163. ynd.text.addReplacement(MetaString::CRE_PL_NAMES, subID);
  3164. cb->showBlockingDialog(&ynd);
  3165. }
  3166. void CGCreature::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3167. {
  3168. if(result.winner==0)
  3169. {
  3170. cb->removeObject(this);
  3171. }
  3172. else
  3173. {
  3174. //int killedAmount=0;
  3175. //for(std::set<std::pair<ui32,si32> >::iterator i=result->casualties[1].begin(); i!=result->casualties[1].end(); i++)
  3176. // if(i->first == subID)
  3177. // killedAmount += i->second;
  3178. //cb->setAmount(id, slots.find(0)->second.second - killedAmount);
  3179. /*
  3180. MetaString ms;
  3181. int pom = slots.find(0)->second.getQuantityID();
  3182. pom = 174 + 3*pom + 1;
  3183. ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,subID);
  3184. cb->setHoverName(id,&ms);
  3185. cb->setObjProperty(id, 11, slots.begin()->second.count * 1000);
  3186. */
  3187. //merge stacks into one
  3188. TSlots::const_iterator i;
  3189. CCreature * cre = VLC->creh->creatures[formation.basicType];
  3190. for (i = stacks.begin(); i != stacks.end(); i++)
  3191. {
  3192. if (cre->isMyUpgrade(i->second->type))
  3193. {
  3194. cb->changeStackType (StackLocation(this, i->first), cre); //un-upgrade creatures
  3195. }
  3196. }
  3197. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  3198. if(!hasStackAtSlot(SlotID(0)))
  3199. cb->moveStack(StackLocation(this, stacks.begin()->first), StackLocation(this, SlotID(0)), stacks.begin()->second->count);
  3200. while (stacks.size() > 1) //hopefully that's enough
  3201. {
  3202. // TODO it's either overcomplicated (if we assume there'll be only one stack) or buggy (if we allow multiple stacks... but that'll also cause troubles elsewhere)
  3203. i = stacks.end();
  3204. i--;
  3205. SlotID slot = getSlotFor(i->second->type);
  3206. if (slot == i->first) //no reason to move stack to its own slot
  3207. break;
  3208. else
  3209. cb->moveStack (StackLocation(this, i->first), StackLocation(this, slot), i->second->count);
  3210. }
  3211. cb->setObjProperty(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->count * 1000); //remember casualties
  3212. }
  3213. }
  3214. void CGCreature::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3215. {
  3216. auto action = takenAction(hero);
  3217. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  3218. joinDecision(hero, action, answer);
  3219. else if(action != FIGHT)
  3220. fleeDecision(hero, answer);
  3221. else
  3222. assert(0);
  3223. }
  3224. void CGMine::onHeroVisit( const CGHeroInstance * h ) const
  3225. {
  3226. int relations = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  3227. if(relations == 2) //we're visiting our mine
  3228. {
  3229. cb->showGarrisonDialog(id,h->id,true);
  3230. return;
  3231. }
  3232. else if (relations == 1)//ally
  3233. return;
  3234. if(stacksCount()) //Mine is guarded
  3235. {
  3236. BlockingDialog ynd(true,false);
  3237. ynd.player = h->tempOwner;
  3238. ynd.text.addTxt(MetaString::ADVOB_TXT, subID == 7 ? 84 : 187);
  3239. cb->showBlockingDialog(&ynd);
  3240. return;
  3241. }
  3242. flagMine(h->tempOwner);
  3243. }
  3244. void CGMine::newTurn() const
  3245. {
  3246. if(cb->getDate() == 1)
  3247. return;
  3248. if (tempOwner == PlayerColor::NEUTRAL)
  3249. return;
  3250. cb->giveResource(tempOwner, producedResource, producedQuantity);
  3251. }
  3252. void CGMine::initObj()
  3253. {
  3254. if(subID >= 7) //Abandoned Mine
  3255. {
  3256. //set guardians
  3257. int howManyTroglodytes = 100 + ran()%100;
  3258. auto troglodytes = new CStackInstance(CreatureID::TROGLODYTES, howManyTroglodytes);
  3259. putStack(SlotID(0), troglodytes);
  3260. //after map reading tempOwner placeholds bitmask for allowed resources
  3261. std::vector<Res::ERes> possibleResources;
  3262. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  3263. if(tempOwner.getNum() & 1<<i) //NOTE: reuse of tempOwner
  3264. possibleResources.push_back(static_cast<Res::ERes>(i));
  3265. assert(possibleResources.size());
  3266. producedResource = possibleResources[ran()%possibleResources.size()];
  3267. tempOwner = PlayerColor::NEUTRAL;
  3268. hoverName = VLC->generaltexth->mines[7].first + "\n" + VLC->generaltexth->allTexts[202] + " " + troglodytes->getQuantityTXT(false) + " " + troglodytes->type->namePl;
  3269. }
  3270. else
  3271. {
  3272. producedResource = static_cast<Res::ERes>(subID);
  3273. MetaString ms;
  3274. ms << std::pair<ui8,ui32>(9,producedResource);
  3275. if(tempOwner >= PlayerColor::PLAYER_LIMIT)
  3276. tempOwner = PlayerColor::NEUTRAL;
  3277. else
  3278. ms << " (" << std::pair<ui8,ui32>(6,23+tempOwner.getNum()) << ")";
  3279. ms.toString(hoverName);
  3280. }
  3281. producedQuantity = defaultResProduction();
  3282. }
  3283. void CGMine::flagMine(PlayerColor player) const
  3284. {
  3285. assert(tempOwner != player);
  3286. cb->setOwner(this, player); //not ours? flag it!
  3287. MetaString ms;
  3288. ms << std::pair<ui8,ui32>(9,subID) << "\n(" << std::pair<ui8,ui32>(6,23+player.getNum()) << ")";
  3289. if(subID == 7)
  3290. {
  3291. ms << "(%s)";
  3292. ms.addReplacement(MetaString::RES_NAMES, producedResource);
  3293. }
  3294. cb->setHoverName(this,&ms);
  3295. InfoWindow iw;
  3296. iw.soundID = soundBase::FLAGMINE;
  3297. iw.text.addTxt(MetaString::MINE_EVNTS,producedResource); //not use subID, abandoned mines uses default mine texts
  3298. iw.player = player;
  3299. iw.components.push_back(Component(Component::RESOURCE,producedResource,producedQuantity,-1));
  3300. cb->showInfoDialog(&iw);
  3301. }
  3302. ui32 CGMine::defaultResProduction()
  3303. {
  3304. switch(producedResource)
  3305. {
  3306. case Res::WOOD:
  3307. case Res::ORE:
  3308. return 2;
  3309. case Res::GOLD:
  3310. return 1000;
  3311. default:
  3312. return 1;
  3313. }
  3314. }
  3315. void CGMine::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3316. {
  3317. if(result.winner == 0) //attacker won
  3318. {
  3319. if(subID == 7)
  3320. {
  3321. showInfoDialog(hero->tempOwner, 85, 0);
  3322. }
  3323. flagMine(hero->tempOwner);
  3324. }
  3325. }
  3326. void CGMine::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3327. {
  3328. if(answer)
  3329. cb->startBattleI(hero, this);
  3330. }
  3331. void CGResource::initObj()
  3332. {
  3333. blockVisit = true;
  3334. hoverName = VLC->generaltexth->restypes[subID];
  3335. if(!amount)
  3336. {
  3337. switch(subID)
  3338. {
  3339. case 6:
  3340. amount = 500 + (ran()%6)*100;
  3341. break;
  3342. case 0: case 2:
  3343. amount = 6 + (ran()%5);
  3344. break;
  3345. default:
  3346. amount = 3 + (ran()%3);
  3347. break;
  3348. }
  3349. }
  3350. }
  3351. void CGResource::onHeroVisit( const CGHeroInstance * h ) const
  3352. {
  3353. if(stacksCount())
  3354. {
  3355. if(message.size())
  3356. {
  3357. BlockingDialog ynd(true,false);
  3358. ynd.player = h->getOwner();
  3359. ynd.text << message;
  3360. cb->showBlockingDialog(&ynd);
  3361. }
  3362. else
  3363. {
  3364. blockingDialogAnswered(h, true); //behave as if player accepted battle
  3365. }
  3366. }
  3367. else
  3368. {
  3369. if(message.length())
  3370. {
  3371. InfoWindow iw;
  3372. iw.player = h->tempOwner;
  3373. iw.text << message;
  3374. cb->showInfoDialog(&iw);
  3375. }
  3376. collectRes(h->getOwner());
  3377. }
  3378. }
  3379. void CGResource::collectRes( PlayerColor player ) const
  3380. {
  3381. cb->giveResource(player, static_cast<Res::ERes>(subID), amount);
  3382. ShowInInfobox sii;
  3383. sii.player = player;
  3384. sii.c = Component(Component::RESOURCE,subID,amount,0);
  3385. sii.text.addTxt(MetaString::ADVOB_TXT,113);
  3386. sii.text.addReplacement(MetaString::RES_NAMES, subID);
  3387. cb->showCompInfo(&sii);
  3388. cb->removeObject(this);
  3389. }
  3390. void CGResource::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3391. {
  3392. if(result.winner == 0) //attacker won
  3393. collectRes(hero->getOwner());
  3394. }
  3395. void CGResource::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3396. {
  3397. if(answer)
  3398. cb->startBattleI(hero, this);
  3399. }
  3400. void CGVisitableOPW::newTurn() const
  3401. {
  3402. if (cb->getDate(Date::DAY_OF_WEEK) == 1) //first day of week = 1
  3403. {
  3404. cb->setObjProperty(id, ObjProperty::VISITED, false);
  3405. MetaString ms; //set text to "not visited"
  3406. ms << std::pair<ui8,ui32>(3,ID) << " " << std::pair<ui8,ui32>(1,353);
  3407. cb->setHoverName(this,&ms);
  3408. }
  3409. }
  3410. bool CGVisitableOPW::wasVisited(PlayerColor player) const
  3411. {
  3412. return visited; //TODO: other players should see object as unvisited
  3413. }
  3414. void CGVisitableOPW::onHeroVisit( const CGHeroInstance * h ) const
  3415. {
  3416. int mid=0, sound = 0;
  3417. switch (ID)
  3418. {
  3419. case Obj::MYSTICAL_GARDEN:
  3420. sound = soundBase::experience;
  3421. mid = 92;
  3422. break;
  3423. case Obj::WINDMILL:
  3424. sound = soundBase::GENIE;
  3425. mid = 170;
  3426. break;
  3427. case Obj::WATER_WHEEL:
  3428. sound = soundBase::GENIE;
  3429. mid = 164;
  3430. break;
  3431. default:
  3432. assert(0);
  3433. }
  3434. if (visited)
  3435. {
  3436. if (ID!=Obj::WINDMILL)
  3437. mid++;
  3438. else
  3439. mid--;
  3440. showInfoDialog(h,mid,sound);
  3441. }
  3442. else
  3443. {
  3444. Component::EComponentType type = Component::RESOURCE;
  3445. Res::ERes sub=Res::WOOD;
  3446. int val=0;
  3447. switch (ID)
  3448. {
  3449. case Obj::MYSTICAL_GARDEN:
  3450. if (rand()%2)
  3451. {
  3452. sub = Res::GEMS;
  3453. val = 5;
  3454. }
  3455. else
  3456. {
  3457. sub = Res::GOLD;
  3458. val = 500;
  3459. }
  3460. break;
  3461. case Obj::WINDMILL:
  3462. mid = 170;
  3463. sub = static_cast<Res::ERes>((rand() % 5) + 1);
  3464. val = (rand() % 4) + 3;
  3465. break;
  3466. case Obj::WATER_WHEEL:
  3467. mid = 164;
  3468. sub = Res::GOLD;
  3469. if(cb->getDate(Date::DAY)<8)
  3470. val = 500;
  3471. else
  3472. val = 1000;
  3473. }
  3474. cb->giveResource(h->tempOwner, sub, val);
  3475. InfoWindow iw;
  3476. iw.soundID = sound;
  3477. iw.player = h->tempOwner;
  3478. iw.components.push_back(Component(type,sub,val,0));
  3479. iw.text.addTxt(MetaString::ADVOB_TXT,mid);
  3480. cb->showInfoDialog(&iw);
  3481. cb->setObjProperty(id, ObjProperty::VISITED, true);
  3482. MetaString ms; //set text to "visited"
  3483. ms.addTxt(MetaString::OBJ_NAMES,ID); ms << " "; ms.addTxt(MetaString::GENERAL_TXT,352);
  3484. cb->setHoverName(this,&ms);
  3485. }
  3486. }
  3487. void CGVisitableOPW::setPropertyDer( ui8 what, ui32 val )
  3488. {
  3489. if(what == ObjProperty::VISITED)
  3490. visited = val;
  3491. }
  3492. void CGTeleport::onHeroVisit( const CGHeroInstance * h ) const
  3493. {
  3494. ObjectInstanceID destinationid;
  3495. switch(ID)
  3496. {
  3497. case Obj::MONOLITH1: //one way - find corresponding exit monolith
  3498. if(vstd::contains(objs,Obj::MONOLITH2) && vstd::contains(objs[Obj::MONOLITH2],subID) && objs[Obj::MONOLITH2][subID].size())
  3499. destinationid = objs[Obj::MONOLITH2][subID][rand()%objs[Obj::MONOLITH2][subID].size()];
  3500. else
  3501. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3502. break;
  3503. case Obj::MONOLITH3://two way monolith - pick any other one
  3504. case Obj::WHIRLPOOL: //Whirlpool
  3505. if(vstd::contains(objs,ID) && vstd::contains(objs[ID],subID) && objs[ID][subID].size()>1)
  3506. {
  3507. while ((destinationid = objs[ID][subID][rand()%objs[ID][subID].size()]) == id); //choose another exit
  3508. if (ID == Obj::WHIRLPOOL)
  3509. {
  3510. if (!h->hasBonusOfType(Bonus::WHIRLPOOL_PROTECTION))
  3511. {
  3512. if (h->Slots().size() > 1 || h->Slots().begin()->second->count > 1)
  3513. { //we can't remove last unit
  3514. SlotID targetstack = h->Slots().begin()->first; //slot numbers may vary
  3515. for(auto i = h->Slots().rbegin(); i != h->Slots().rend(); i++)
  3516. {
  3517. if (h->getPower(targetstack) > h->getPower(i->first))
  3518. {
  3519. targetstack = (i->first);
  3520. }
  3521. }
  3522. TQuantity countToTake = h->getStackCount(targetstack) * 0.5;
  3523. vstd::amax(countToTake, 1);
  3524. InfoWindow iw;
  3525. iw.player = h->tempOwner;
  3526. iw.text.addTxt (MetaString::ADVOB_TXT, 168);
  3527. iw.components.push_back (Component(CStackBasicDescriptor(h->getCreature(targetstack), countToTake)));
  3528. cb->showInfoDialog(&iw);
  3529. cb->changeStackCount(StackLocation(h, targetstack), -countToTake);
  3530. }
  3531. }
  3532. }
  3533. }
  3534. else
  3535. logGlobal->warnStream() << "Cannot find corresponding exit monolith for "<< id;
  3536. break;
  3537. case Obj::SUBTERRANEAN_GATE: //find nearest subterranean gate on the other level
  3538. {
  3539. destinationid = getMatchingGate(id);
  3540. if(destinationid == ObjectInstanceID()) //no exit
  3541. {
  3542. showInfoDialog(h,153,0);//Just inside the entrance you find a large pile of rubble blocking the tunnel. You leave discouraged.
  3543. }
  3544. break;
  3545. }
  3546. }
  3547. if(destinationid == ObjectInstanceID())
  3548. {
  3549. logGlobal->warnStream() << "Cannot find exit... (obj at " << pos << ") :( ";
  3550. return;
  3551. }
  3552. if (ID == Obj::WHIRLPOOL)
  3553. {
  3554. std::set<int3> tiles = cb->getObj(destinationid)->getBlockedPos();
  3555. auto it = tiles.begin();
  3556. std::advance (it, rand() % tiles.size()); //picking random element of set is tiring
  3557. cb->moveHero (h->id, *it + int3(1,0,0), true);
  3558. }
  3559. else
  3560. cb->moveHero (h->id,CGHeroInstance::convertPosition(cb->getObj(destinationid)->pos,true) - getVisitableOffset(), true);
  3561. }
  3562. void CGTeleport::initObj()
  3563. {
  3564. int si = subID;
  3565. switch (ID)
  3566. {
  3567. case Obj::SUBTERRANEAN_GATE://ignore subterranean gates subid
  3568. case Obj::WHIRLPOOL:
  3569. {
  3570. si = 0;
  3571. break;
  3572. }
  3573. default:
  3574. break;
  3575. }
  3576. objs[ID][si].push_back(id);
  3577. }
  3578. void CGTeleport::postInit() //matches subterranean gates into pairs
  3579. {
  3580. //split on underground and surface gates
  3581. std::vector<const CGObjectInstance *> gatesSplit[2]; //surface and underground gates
  3582. for(auto & elem : objs[Obj::SUBTERRANEAN_GATE][0])
  3583. {
  3584. const CGObjectInstance *hlp = cb->getObj(elem);
  3585. gatesSplit[hlp->pos.z].push_back(hlp);
  3586. }
  3587. //sort by position
  3588. std::sort(gatesSplit[0].begin(), gatesSplit[0].end(), [](const CGObjectInstance * a, const CGObjectInstance * b)
  3589. {
  3590. return a->pos < b->pos;
  3591. });
  3592. for(size_t i = 0; i < gatesSplit[0].size(); i++)
  3593. {
  3594. const CGObjectInstance *cur = gatesSplit[0][i];
  3595. //find nearest underground exit
  3596. std::pair<int,double> best(-1,150000); //pair<pos_in_vector, distance>
  3597. for(int j = 0; j < gatesSplit[1].size(); j++)
  3598. {
  3599. const CGObjectInstance *checked = gatesSplit[1][j];
  3600. if(!checked)
  3601. continue;
  3602. double hlp = checked->pos.dist2d(cur->pos);
  3603. if(hlp < best.second)
  3604. {
  3605. best.first = j;
  3606. best.second = hlp;
  3607. }
  3608. }
  3609. if(best.first >= 0) //found pair
  3610. {
  3611. gates.push_back(std::make_pair(cur->id, gatesSplit[1][best.first]->id));
  3612. gatesSplit[1][best.first] = nullptr;
  3613. }
  3614. else
  3615. {
  3616. gates.push_back(std::make_pair(cur->id, ObjectInstanceID()));
  3617. }
  3618. }
  3619. objs.erase(Obj::SUBTERRANEAN_GATE);
  3620. }
  3621. ObjectInstanceID CGTeleport::getMatchingGate(ObjectInstanceID id)
  3622. {
  3623. for(auto & gate : gates)
  3624. {
  3625. if(gate.first == id)
  3626. return gate.second;
  3627. if(gate.second == id)
  3628. return gate.first;
  3629. }
  3630. return ObjectInstanceID();
  3631. }
  3632. void CGArtifact::initObj()
  3633. {
  3634. blockVisit = true;
  3635. if(ID == Obj::ARTIFACT)
  3636. {
  3637. hoverName = VLC->arth->artifacts[subID]->Name();
  3638. if(!storedArtifact->artType)
  3639. storedArtifact->setType(VLC->arth->artifacts[subID]);
  3640. }
  3641. if(ID == Obj::SPELL_SCROLL)
  3642. subID = 1;
  3643. assert(storedArtifact->artType);
  3644. assert(storedArtifact->getParentNodes().size());
  3645. //assert(storedArtifact->artType->id == subID); //this does not stop desync
  3646. }
  3647. void CGArtifact::onHeroVisit( const CGHeroInstance * h ) const
  3648. {
  3649. if(!stacksCount())
  3650. {
  3651. InfoWindow iw;
  3652. iw.player = h->tempOwner;
  3653. switch(ID)
  3654. {
  3655. case Obj::ARTIFACT:
  3656. {
  3657. iw.soundID = soundBase::treasure; //play sound only for non-scroll arts
  3658. iw.components.push_back(Component(Component::ARTIFACT,subID,0,0));
  3659. if(message.length())
  3660. iw.text << message;
  3661. else
  3662. {
  3663. if (VLC->arth->artifacts[subID]->EventText().size())
  3664. iw.text << std::pair<ui8, ui32> (MetaString::ART_EVNTS, subID);
  3665. else //fix for mod artifacts with no event text
  3666. {
  3667. iw.text.addTxt (MetaString::ADVOB_TXT, 183); //% has found treasure
  3668. iw.text.addReplacement (h->name);
  3669. }
  3670. }
  3671. }
  3672. break;
  3673. case Obj::SPELL_SCROLL:
  3674. {
  3675. int spellID = storedArtifact->getGivenSpellID();
  3676. iw.components.push_back (Component(Component::SPELL, spellID,0,0));
  3677. iw.text.addTxt (MetaString::ADVOB_TXT,135);
  3678. iw.text.addReplacement(MetaString::SPELL_NAME, spellID);
  3679. }
  3680. break;
  3681. }
  3682. cb->showInfoDialog(&iw);
  3683. pick(h);
  3684. }
  3685. else
  3686. {
  3687. if(message.size())
  3688. {
  3689. BlockingDialog ynd(true,false);
  3690. ynd.player = h->getOwner();
  3691. ynd.text << message;
  3692. cb->showBlockingDialog(&ynd);
  3693. }
  3694. else
  3695. {
  3696. blockingDialogAnswered(h, true);
  3697. }
  3698. }
  3699. }
  3700. void CGArtifact::pick(const CGHeroInstance * h) const
  3701. {
  3702. cb->giveHeroArtifact(h, storedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  3703. cb->removeObject(this);
  3704. }
  3705. void CGArtifact::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  3706. {
  3707. if(result.winner == 0) //attacker won
  3708. pick(hero);
  3709. }
  3710. void CGArtifact::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3711. {
  3712. if(answer)
  3713. cb->startBattleI(hero, this);
  3714. }
  3715. void CGPickable::initObj()
  3716. {
  3717. blockVisit = true;
  3718. switch(ID)
  3719. {
  3720. case Obj::CAMPFIRE:
  3721. val2 = (ran()%3) + 4; //4 - 6
  3722. val1 = val2 * 100;
  3723. type = ran()%6; //given resource
  3724. break;
  3725. case Obj::FLOTSAM:
  3726. switch(type = ran()%4)
  3727. {
  3728. case 0:
  3729. val1 = val2 = 0;
  3730. break;
  3731. case 1:
  3732. val1 = 5;
  3733. val2 = 0;
  3734. break;
  3735. case 2:
  3736. val1 = 5;
  3737. val2 = 200;
  3738. break;
  3739. case 3:
  3740. val1 = 10;
  3741. val2 = 500;
  3742. break;
  3743. }
  3744. break;
  3745. case Obj::SEA_CHEST:
  3746. {
  3747. int hlp = ran()%100;
  3748. if(hlp < 20)
  3749. {
  3750. val1 = 0;
  3751. type = 0;
  3752. }
  3753. else if(hlp < 90)
  3754. {
  3755. val1 = 1500;
  3756. type = 2;
  3757. }
  3758. else
  3759. {
  3760. val1 = 1000;
  3761. val2 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3762. type = 1;
  3763. }
  3764. }
  3765. break;
  3766. case Obj::SHIPWRECK_SURVIVOR:
  3767. {
  3768. int hlp = ran()%100;
  3769. if(hlp < 55)
  3770. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3771. else if(hlp < 75)
  3772. val1 = cb->getRandomArt (CArtifact::ART_MINOR);
  3773. else if(hlp < 95)
  3774. val1 = cb->getRandomArt (CArtifact::ART_MAJOR);
  3775. else
  3776. val1 = cb->getRandomArt (CArtifact::ART_RELIC);
  3777. }
  3778. break;
  3779. case Obj::TREASURE_CHEST:
  3780. {
  3781. int hlp = ran()%100;
  3782. if(hlp >= 95)
  3783. {
  3784. type = 1;
  3785. val1 = cb->getRandomArt (CArtifact::ART_TREASURE);
  3786. return;
  3787. }
  3788. else if (hlp >= 65)
  3789. {
  3790. val1 = 2000;
  3791. }
  3792. else if(hlp >= 33)
  3793. {
  3794. val1 = 1500;
  3795. }
  3796. else
  3797. {
  3798. val1 = 1000;
  3799. }
  3800. val2 = val1 - 500;
  3801. type = 0;
  3802. break;
  3803. }
  3804. }
  3805. }
  3806. void CGPickable::onHeroVisit( const CGHeroInstance * h ) const
  3807. {
  3808. switch(ID)
  3809. {
  3810. case Obj::CAMPFIRE:
  3811. {
  3812. cb->giveResource(h->tempOwner,static_cast<Res::ERes>(type),val2); //non-gold resource
  3813. cb->giveResource(h->tempOwner,Res::GOLD,val1);//gold
  3814. InfoWindow iw;
  3815. iw.soundID = soundBase::experience;
  3816. iw.player = h->tempOwner;
  3817. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3818. iw.components.push_back(Component(Component::RESOURCE,type,val2,0));
  3819. iw.text.addTxt(MetaString::ADVOB_TXT,23);
  3820. cb->showInfoDialog(&iw);
  3821. break;
  3822. }
  3823. case Obj::FLOTSAM:
  3824. {
  3825. cb->giveResource(h->tempOwner,Res::WOOD,val1); //wood
  3826. cb->giveResource(h->tempOwner,Res::GOLD,val2);//gold
  3827. InfoWindow iw;
  3828. iw.soundID = soundBase::GENIE;
  3829. iw.player = h->tempOwner;
  3830. if(val1)
  3831. iw.components.push_back(Component(Component::RESOURCE,Res::WOOD,val1,0));
  3832. if(val2)
  3833. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val2,0));
  3834. iw.text.addTxt(MetaString::ADVOB_TXT, 51+type);
  3835. cb->showInfoDialog(&iw);
  3836. break;
  3837. }
  3838. case Obj::SEA_CHEST:
  3839. {
  3840. InfoWindow iw;
  3841. iw.soundID = soundBase::chest;
  3842. iw.player = h->tempOwner;
  3843. iw.text.addTxt(MetaString::ADVOB_TXT, 116 + type);
  3844. if(val1) //there is gold
  3845. {
  3846. iw.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3847. cb->giveResource(h->tempOwner,Res::GOLD,val1);
  3848. }
  3849. if(type == 1) //art
  3850. {
  3851. //TODO: what if no space in backpack?
  3852. iw.components.push_back(Component(Component::ARTIFACT, val2, 1, 0));
  3853. iw.text.addReplacement(MetaString::ART_NAMES, val2);
  3854. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val2],ArtifactPosition::FIRST_AVAILABLE);
  3855. }
  3856. cb->showInfoDialog(&iw);
  3857. break;
  3858. }
  3859. case Obj::SHIPWRECK_SURVIVOR:
  3860. {
  3861. InfoWindow iw;
  3862. iw.soundID = soundBase::experience;
  3863. iw.player = h->tempOwner;
  3864. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3865. iw.text.addTxt(MetaString::ADVOB_TXT, 125);
  3866. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3867. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3868. cb->showInfoDialog(&iw);
  3869. break;
  3870. }
  3871. case Obj::TREASURE_CHEST:
  3872. {
  3873. if (subID) //not OH3 treasure chest
  3874. {
  3875. logGlobal->warnStream() << "Not supported WoG treasure chest!";
  3876. return;
  3877. }
  3878. if(type) //there is an artifact
  3879. {
  3880. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[val1],ArtifactPosition::FIRST_AVAILABLE);
  3881. InfoWindow iw;
  3882. iw.soundID = soundBase::treasure;
  3883. iw.player = h->tempOwner;
  3884. iw.components.push_back(Component(Component::ARTIFACT,val1,1,0));
  3885. iw.text.addTxt(MetaString::ADVOB_TXT,145);
  3886. iw.text.addReplacement(MetaString::ART_NAMES, val1);
  3887. cb->showInfoDialog(&iw);
  3888. break;
  3889. }
  3890. else
  3891. {
  3892. BlockingDialog sd(false,true);
  3893. sd.player = h->tempOwner;
  3894. sd.text.addTxt(MetaString::ADVOB_TXT,146);
  3895. sd.components.push_back(Component(Component::RESOURCE,Res::GOLD,val1,0));
  3896. TExpType expVal = h->calculateXp(val2);
  3897. sd.components.push_back(Component(Component::EXPERIENCE,0,expVal, 0));
  3898. sd.soundID = soundBase::chest;
  3899. cb->showBlockingDialog(&sd);
  3900. return;
  3901. }
  3902. }
  3903. }
  3904. cb->removeObject(this);
  3905. }
  3906. void CGPickable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  3907. {
  3908. switch(answer)
  3909. {
  3910. case 1: //player pick gold
  3911. cb->giveResource(hero->tempOwner, Res::GOLD, val1);
  3912. break;
  3913. case 2: //player pick exp
  3914. cb->changePrimSkill(hero, PrimarySkill::EXPERIENCE, hero->calculateXp(val2));
  3915. break;
  3916. default:
  3917. throw std::runtime_error("Unhandled treasure choice");
  3918. }
  3919. cb->removeObject(this);
  3920. }
  3921. bool CQuest::checkQuest (const CGHeroInstance * h) const
  3922. {
  3923. switch (missionType)
  3924. {
  3925. case MISSION_NONE:
  3926. return true;
  3927. case MISSION_LEVEL:
  3928. if (m13489val <= h->level)
  3929. return true;
  3930. return false;
  3931. case MISSION_PRIMARY_STAT:
  3932. for (int i = 0; i < GameConstants::PRIMARY_SKILLS; ++i)
  3933. {
  3934. if (h->getPrimSkillLevel(static_cast<PrimarySkill::PrimarySkill>(i)) < m2stats[i])
  3935. return false;
  3936. }
  3937. return true;
  3938. case MISSION_KILL_HERO:
  3939. case MISSION_KILL_CREATURE:
  3940. if (!h->cb->getObjByQuestIdentifier(m13489val))
  3941. return true;
  3942. return false;
  3943. case MISSION_ART:
  3944. for (auto & elem : m5arts)
  3945. {
  3946. if (h->hasArt(elem))
  3947. continue;
  3948. return false; //if the artifact was not found
  3949. }
  3950. return true;
  3951. case MISSION_ARMY:
  3952. {
  3953. std::vector<CStackBasicDescriptor>::const_iterator cre;
  3954. TSlots::const_iterator it;
  3955. ui32 count;
  3956. for (cre = m6creatures.begin(); cre != m6creatures.end(); ++cre)
  3957. {
  3958. for (count = 0, it = h->Slots().begin(); it != h->Slots().end(); ++it)
  3959. {
  3960. if (it->second->type == cre->type)
  3961. count += it->second->count;
  3962. }
  3963. if (count < cre->count) //not enough creatures of this kind
  3964. return false;
  3965. }
  3966. }
  3967. return true;
  3968. case MISSION_RESOURCES:
  3969. for (Res::ERes i = Res::WOOD; i <= Res::GOLD; vstd::advance(i, +1)) //including Mithril ?
  3970. { //Quest has no direct access to callback
  3971. if (h->cb->getResource (h->tempOwner, i) < m7resources[i])
  3972. return false;
  3973. }
  3974. return true;
  3975. case MISSION_HERO:
  3976. if (m13489val == h->type->ID.getNum())
  3977. return true;
  3978. return false;
  3979. case MISSION_PLAYER:
  3980. if (m13489val == h->getOwner().getNum())
  3981. return true;
  3982. return false;
  3983. default:
  3984. return false;
  3985. }
  3986. }
  3987. void CQuest::getVisitText (MetaString &iwText, std::vector<Component> &components, bool isCustom, bool firstVisit, const CGHeroInstance * h) const
  3988. {
  3989. std::string text;
  3990. bool failRequirements = (h ? !checkQuest(h) : true);
  3991. if (firstVisit)
  3992. {
  3993. isCustom = isCustomFirst;
  3994. iwText << (text = firstVisitText);
  3995. }
  3996. else if (failRequirements)
  3997. {
  3998. isCustom = isCustomNext;
  3999. iwText << (text = nextVisitText);
  4000. }
  4001. switch (missionType)
  4002. {
  4003. case MISSION_LEVEL:
  4004. components.push_back(Component (Component::EXPERIENCE, 0, m13489val, 0));
  4005. if (!isCustom)
  4006. iwText.addReplacement(m13489val);
  4007. break;
  4008. case MISSION_PRIMARY_STAT:
  4009. {
  4010. MetaString loot;
  4011. for (int i = 0; i < 4; ++i)
  4012. {
  4013. if (m2stats[i])
  4014. {
  4015. components.push_back(Component (Component::PRIM_SKILL, i, m2stats[i], 0));
  4016. loot << "%d %s";
  4017. loot.addReplacement(m2stats[i]);
  4018. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4019. }
  4020. }
  4021. if (!isCustom)
  4022. iwText.addReplacement(loot.buildList());
  4023. }
  4024. break;
  4025. case MISSION_KILL_HERO:
  4026. components.push_back(Component(Component::HERO_PORTRAIT, heroPortrait, 0, 0));
  4027. if (!isCustom)
  4028. addReplacements(iwText, text);
  4029. break;
  4030. case MISSION_HERO:
  4031. //FIXME: portrait may not match hero, if custom portrait was set in map editor
  4032. components.push_back(Component (Component::HERO_PORTRAIT, VLC->heroh->heroes[m13489val]->imageIndex, 0, 0));
  4033. if (!isCustom)
  4034. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4035. break;
  4036. case MISSION_KILL_CREATURE:
  4037. {
  4038. components.push_back(Component(stackToKill));
  4039. if (!isCustom)
  4040. {
  4041. addReplacements(iwText, text);
  4042. }
  4043. }
  4044. break;
  4045. case MISSION_ART:
  4046. {
  4047. MetaString loot;
  4048. for (auto & elem : m5arts)
  4049. {
  4050. components.push_back(Component (Component::ARTIFACT, elem, 0, 0));
  4051. loot << "%s";
  4052. loot.addReplacement(MetaString::ART_NAMES, elem);
  4053. }
  4054. if (!isCustom)
  4055. iwText.addReplacement(loot.buildList());
  4056. }
  4057. break;
  4058. case MISSION_ARMY:
  4059. {
  4060. MetaString loot;
  4061. for (auto & elem : m6creatures)
  4062. {
  4063. components.push_back(Component(elem));
  4064. loot << "%s";
  4065. loot.addReplacement(elem);
  4066. }
  4067. if (!isCustom)
  4068. iwText.addReplacement(loot.buildList());
  4069. }
  4070. break;
  4071. case MISSION_RESOURCES:
  4072. {
  4073. MetaString loot;
  4074. for (int i = 0; i < 7; ++i)
  4075. {
  4076. if (m7resources[i])
  4077. {
  4078. components.push_back(Component (Component::RESOURCE, i, m7resources[i], 0));
  4079. loot << "%d %s";
  4080. loot.addReplacement(m7resources[i]);
  4081. loot.addReplacement(MetaString::RES_NAMES, i);
  4082. }
  4083. }
  4084. if (!isCustom)
  4085. iwText.addReplacement(loot.buildList());
  4086. }
  4087. break;
  4088. case MISSION_PLAYER:
  4089. components.push_back(Component (Component::FLAG, m13489val, 0, 0));
  4090. if (!isCustom)
  4091. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4092. break;
  4093. }
  4094. }
  4095. void CQuest::getRolloverText (MetaString &ms, bool onHover) const
  4096. {
  4097. if (onHover)
  4098. ms << "\n\n";
  4099. ms << VLC->generaltexth->quests[missionType-1][onHover ? 3 : 4][textOption];
  4100. switch (missionType)
  4101. {
  4102. case MISSION_LEVEL:
  4103. ms.addReplacement(m13489val);
  4104. break;
  4105. case MISSION_PRIMARY_STAT:
  4106. {
  4107. MetaString loot;
  4108. for (int i = 0; i < 4; ++i)
  4109. {
  4110. if (m2stats[i])
  4111. {
  4112. loot << "%d %s";
  4113. loot.addReplacement(m2stats[i]);
  4114. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4115. }
  4116. }
  4117. ms.addReplacement(loot.buildList());
  4118. }
  4119. break;
  4120. case MISSION_KILL_HERO:
  4121. ms.addReplacement(heroName);
  4122. break;
  4123. case MISSION_KILL_CREATURE:
  4124. ms.addReplacement(stackToKill);
  4125. break;
  4126. case MISSION_ART:
  4127. {
  4128. MetaString loot;
  4129. for (auto & elem : m5arts)
  4130. {
  4131. loot << "%s";
  4132. loot.addReplacement(MetaString::ART_NAMES, elem);
  4133. }
  4134. ms.addReplacement(loot.buildList());
  4135. }
  4136. break;
  4137. case MISSION_ARMY:
  4138. {
  4139. MetaString loot;
  4140. for (auto & elem : m6creatures)
  4141. {
  4142. loot << "%s";
  4143. loot.addReplacement(elem);
  4144. }
  4145. ms.addReplacement(loot.buildList());
  4146. }
  4147. break;
  4148. case MISSION_RESOURCES:
  4149. {
  4150. MetaString loot;
  4151. for (int i = 0; i < 7; ++i)
  4152. {
  4153. if (m7resources[i])
  4154. {
  4155. loot << "%d %s";
  4156. loot.addReplacement(m7resources[i]);
  4157. loot.addReplacement(MetaString::RES_NAMES, i);
  4158. }
  4159. }
  4160. ms.addReplacement(loot.buildList());
  4161. }
  4162. break;
  4163. case MISSION_HERO:
  4164. ms.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4165. break;
  4166. case MISSION_PLAYER:
  4167. ms.addReplacement(VLC->generaltexth->colors[m13489val]);
  4168. break;
  4169. default:
  4170. break;
  4171. }
  4172. }
  4173. void CQuest::getCompletionText (MetaString &iwText, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4174. {
  4175. iwText << completedText;
  4176. switch (missionType)
  4177. {
  4178. case CQuest::MISSION_LEVEL:
  4179. if (!isCustomComplete)
  4180. iwText.addReplacement(m13489val);
  4181. break;
  4182. case CQuest::MISSION_PRIMARY_STAT:
  4183. if (vstd::contains (completedText,'%')) //there's one case when there's nothing to replace
  4184. {
  4185. MetaString loot;
  4186. for (int i = 0; i < 4; ++i)
  4187. {
  4188. if (m2stats[i])
  4189. {
  4190. loot << "%d %s";
  4191. loot.addReplacement(m2stats[i]);
  4192. loot.addReplacement(VLC->generaltexth->primarySkillNames[i]);
  4193. }
  4194. }
  4195. if (!isCustomComplete)
  4196. iwText.addReplacement(loot.buildList());
  4197. }
  4198. break;
  4199. case CQuest::MISSION_ART:
  4200. {
  4201. MetaString loot;
  4202. for (auto & elem : m5arts)
  4203. {
  4204. loot << "%s";
  4205. loot.addReplacement(MetaString::ART_NAMES, elem);
  4206. }
  4207. if (!isCustomComplete)
  4208. iwText.addReplacement(loot.buildList());
  4209. }
  4210. break;
  4211. case CQuest::MISSION_ARMY:
  4212. {
  4213. MetaString loot;
  4214. for (auto & elem : m6creatures)
  4215. {
  4216. loot << "%s";
  4217. loot.addReplacement(elem);
  4218. }
  4219. if (!isCustomComplete)
  4220. iwText.addReplacement(loot.buildList());
  4221. }
  4222. break;
  4223. case CQuest::MISSION_RESOURCES:
  4224. {
  4225. MetaString loot;
  4226. for (int i = 0; i < 7; ++i)
  4227. {
  4228. if (m7resources[i])
  4229. {
  4230. loot << "%d %s";
  4231. loot.addReplacement(m7resources[i]);
  4232. loot.addReplacement(MetaString::RES_NAMES, i);
  4233. }
  4234. }
  4235. if (!isCustomComplete)
  4236. iwText.addReplacement(loot.buildList());
  4237. }
  4238. break;
  4239. case MISSION_KILL_HERO:
  4240. case MISSION_KILL_CREATURE:
  4241. if (!isCustomComplete)
  4242. addReplacements(iwText, completedText);
  4243. break;
  4244. case MISSION_HERO:
  4245. if (!isCustomComplete)
  4246. iwText.addReplacement(VLC->heroh->heroes[m13489val]->name);
  4247. break;
  4248. case MISSION_PLAYER:
  4249. if (!isCustomComplete)
  4250. iwText.addReplacement(VLC->generaltexth->colors[m13489val]);
  4251. break;
  4252. }
  4253. }
  4254. void CGSeerHut::setObjToKill()
  4255. {
  4256. if (quest->missionType == CQuest::MISSION_KILL_CREATURE)
  4257. {
  4258. quest->stackToKill = getCreatureToKill(false)->getStack(SlotID(0)); //FIXME: stacks tend to dissapear (desync?) on server :?
  4259. assert(quest->stackToKill.type);
  4260. quest->stackToKill.count = 0; //no count in info window
  4261. quest->stackDirection = checkDirection();
  4262. }
  4263. else if (quest->missionType == CQuest::MISSION_KILL_HERO)
  4264. {
  4265. quest->heroName = getHeroToKill(false)->name;
  4266. quest->heroPortrait = getHeroToKill(false)->portrait;
  4267. }
  4268. }
  4269. void CGSeerHut::init()
  4270. {
  4271. seerName = VLC->generaltexth->seerNames[ran()%VLC->generaltexth->seerNames.size()];
  4272. quest->textOption = ran() % 3;
  4273. }
  4274. void CGSeerHut::initObj()
  4275. {
  4276. init();
  4277. quest->progress = CQuest::NOT_ACTIVE;
  4278. if (quest->missionType)
  4279. {
  4280. if (!quest->isCustomFirst)
  4281. quest->firstVisitText = VLC->generaltexth->quests[quest->missionType-1][0][quest->textOption];
  4282. if (!quest->isCustomNext)
  4283. quest->nextVisitText = VLC->generaltexth->quests[quest->missionType-1][1][quest->textOption];
  4284. if (!quest->isCustomComplete)
  4285. quest->completedText = VLC->generaltexth->quests[quest->missionType-1][2][quest->textOption];
  4286. }
  4287. else
  4288. {
  4289. quest->progress = CQuest::COMPLETE;
  4290. quest->firstVisitText = VLC->generaltexth->seerEmpty[quest->textOption];
  4291. }
  4292. }
  4293. void CGSeerHut::getRolloverText (MetaString &text, bool onHover) const
  4294. {
  4295. quest->getRolloverText (text, onHover);//TODO: simplify?
  4296. if (!onHover)
  4297. text.addReplacement(seerName);
  4298. }
  4299. const std::string & CGSeerHut::getHoverText() const
  4300. {
  4301. switch (ID)
  4302. {
  4303. case Obj::SEER_HUT:
  4304. if (quest->progress != CQuest::NOT_ACTIVE)
  4305. {
  4306. hoverName = VLC->generaltexth->allTexts[347];
  4307. boost::algorithm::replace_first(hoverName,"%s", seerName);
  4308. }
  4309. else //just seer hut
  4310. hoverName = VLC->generaltexth->names[ID];
  4311. break;
  4312. case Obj::QUEST_GUARD:
  4313. hoverName = VLC->generaltexth->names[ID];
  4314. break;
  4315. default:
  4316. logGlobal->debugStream() << "unrecognized quest object";
  4317. }
  4318. if (quest->progress & quest->missionType) //rollover when the quest is active
  4319. {
  4320. MetaString ms;
  4321. getRolloverText (ms, true);
  4322. hoverName += ms.toString();
  4323. }
  4324. return hoverName;
  4325. }
  4326. void CQuest::addReplacements(MetaString &out, const std::string &base) const
  4327. {
  4328. switch(missionType)
  4329. {
  4330. case MISSION_KILL_CREATURE:
  4331. out.addReplacement(stackToKill);
  4332. if (std::count(base.begin(), base.end(), '%') == 2) //say where is placed monster
  4333. {
  4334. out.addReplacement(VLC->generaltexth->arraytxt[147+stackDirection]);
  4335. }
  4336. break;
  4337. case MISSION_KILL_HERO:
  4338. out.addReplacement(heroName);
  4339. break;
  4340. }
  4341. }
  4342. bool IQuestObject::checkQuest(const CGHeroInstance* h) const
  4343. {
  4344. return quest->checkQuest(h);
  4345. }
  4346. void IQuestObject::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  4347. {
  4348. quest->getVisitText (text,components, isCustom, FirstVisit, h);
  4349. }
  4350. void CGSeerHut::getCompletionText(MetaString &text, std::vector<Component> &components, bool isCustom, const CGHeroInstance * h) const
  4351. {
  4352. quest->getCompletionText (text, components, isCustom, h);
  4353. switch (rewardType)
  4354. {
  4355. case EXPERIENCE: components.push_back(Component (Component::EXPERIENCE, 0, h->calculateXp(rVal), 0));
  4356. break;
  4357. case MANA_POINTS: components.push_back(Component (Component::PRIM_SKILL, 5, rVal, 0));
  4358. break;
  4359. case MORALE_BONUS: components.push_back(Component (Component::MORALE, 0, rVal, 0));
  4360. break;
  4361. case LUCK_BONUS: components.push_back(Component (Component::LUCK, 0, rVal, 0));
  4362. break;
  4363. case RESOURCES: components.push_back(Component (Component::RESOURCE, rID, rVal, 0));
  4364. break;
  4365. case PRIMARY_SKILL: components.push_back(Component (Component::PRIM_SKILL, rID, rVal, 0));
  4366. break;
  4367. case SECONDARY_SKILL: components.push_back(Component (Component::SEC_SKILL, rID, rVal, 0));
  4368. break;
  4369. case ARTIFACT: components.push_back(Component (Component::ARTIFACT, rID, 0, 0));
  4370. break;
  4371. case SPELL: components.push_back(Component (Component::SPELL, rID, 0, 0));
  4372. break;
  4373. case CREATURE: components.push_back(Component (Component::CREATURE, rID, rVal, 0));
  4374. break;
  4375. }
  4376. }
  4377. void CGSeerHut::setPropertyDer (ui8 what, ui32 val)
  4378. {
  4379. switch (what)
  4380. {
  4381. case 10:
  4382. quest->progress = static_cast<CQuest::Eprogress>(val);
  4383. break;
  4384. }
  4385. }
  4386. void CGSeerHut::newTurn() const
  4387. {
  4388. if (quest->lastDay >= 0 && quest->lastDay < cb->getDate()-1) //time is up
  4389. {
  4390. cb->setObjProperty (id, 10, CQuest::COMPLETE);
  4391. }
  4392. }
  4393. void CGSeerHut::onHeroVisit( const CGHeroInstance * h ) const
  4394. {
  4395. InfoWindow iw;
  4396. iw.player = h->getOwner();
  4397. if (quest->progress < CQuest::COMPLETE)
  4398. {
  4399. bool firstVisit = !quest->progress;
  4400. bool failRequirements = !checkQuest(h);
  4401. bool isCustom=false;
  4402. if (firstVisit)
  4403. {
  4404. isCustom = quest->isCustomFirst;
  4405. cb->setObjProperty (id, 10, CQuest::IN_PROGRESS);
  4406. AddQuest aq;
  4407. aq.quest = QuestInfo (quest, this, visitablePos());
  4408. aq.player = h->tempOwner;
  4409. cb->sendAndApply (&aq); //TODO: merge with setObjProperty?
  4410. }
  4411. else if (failRequirements)
  4412. {
  4413. isCustom = quest->isCustomNext;
  4414. }
  4415. if (firstVisit || failRequirements)
  4416. {
  4417. getVisitText (iw.text, iw.components, isCustom, firstVisit, h);
  4418. cb->showInfoDialog(&iw);
  4419. }
  4420. if (!failRequirements) // propose completion, also on first visit
  4421. {
  4422. BlockingDialog bd (true, false);
  4423. bd.player = h->getOwner();
  4424. bd.soundID = soundBase::QUEST;
  4425. getCompletionText (bd.text, bd.components, isCustom, h);
  4426. cb->showBlockingDialog (&bd);
  4427. return;
  4428. }
  4429. }
  4430. else
  4431. {
  4432. iw.text << VLC->generaltexth->seerEmpty[quest->textOption];
  4433. if (ID == Obj::SEER_HUT)
  4434. iw.text.addReplacement(seerName);
  4435. cb->showInfoDialog(&iw);
  4436. }
  4437. }
  4438. int CGSeerHut::checkDirection() const
  4439. {
  4440. int3 cord = getCreatureToKill()->pos;
  4441. if ((double)cord.x/(double)cb->getMapSize().x < 0.34) //north
  4442. {
  4443. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //northwest
  4444. return 8;
  4445. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //north
  4446. return 1;
  4447. else //northeast
  4448. return 2;
  4449. }
  4450. else if ((double)cord.x/(double)cb->getMapSize().x < 0.67) //horizontal
  4451. {
  4452. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //west
  4453. return 7;
  4454. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //central
  4455. return 9;
  4456. else //east
  4457. return 3;
  4458. }
  4459. else //south
  4460. {
  4461. if ((double)cord.y/(double)cb->getMapSize().y < 0.34) //southwest
  4462. return 6;
  4463. else if ((double)cord.y/(double)cb->getMapSize().y < 0.67) //south
  4464. return 5;
  4465. else //southeast
  4466. return 4;
  4467. }
  4468. }
  4469. void CGSeerHut::finishQuest(const CGHeroInstance * h, ui32 accept) const
  4470. {
  4471. if (accept)
  4472. {
  4473. switch (quest->missionType)
  4474. {
  4475. case CQuest::MISSION_ART:
  4476. for (auto & elem : quest->m5arts)
  4477. {
  4478. cb->removeArtifact(ArtifactLocation(h, h->getArtPos(elem, false)));
  4479. }
  4480. break;
  4481. case CQuest::MISSION_ARMY:
  4482. cb->takeCreatures(h->id, quest->m6creatures);
  4483. break;
  4484. case CQuest::MISSION_RESOURCES:
  4485. for (int i = 0; i < 7; ++i)
  4486. {
  4487. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(i), -quest->m7resources[i]);
  4488. }
  4489. break;
  4490. default:
  4491. break;
  4492. }
  4493. cb->setObjProperty (id, 10, CQuest::COMPLETE); //mission complete
  4494. completeQuest(h); //make sure to remove QuestGuard at the very end
  4495. }
  4496. }
  4497. void CGSeerHut::completeQuest (const CGHeroInstance * h) const //reward
  4498. {
  4499. switch (rewardType)
  4500. {
  4501. case EXPERIENCE:
  4502. {
  4503. TExpType expVal = h->calculateXp(rVal);
  4504. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  4505. break;
  4506. }
  4507. case MANA_POINTS:
  4508. {
  4509. cb->setManaPoints(h->id, h->mana+rVal);
  4510. break;
  4511. }
  4512. case MORALE_BONUS: case LUCK_BONUS:
  4513. {
  4514. Bonus hb(Bonus::ONE_WEEK, (rewardType == 3 ? Bonus::MORALE : Bonus::LUCK),
  4515. Bonus::OBJECT, rVal, h->id.getNum(), "", -1);
  4516. GiveBonus gb;
  4517. gb.id = h->id.getNum();
  4518. gb.bonus = hb;
  4519. cb->giveHeroBonus(&gb);
  4520. }
  4521. break;
  4522. case RESOURCES:
  4523. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(rID), rVal);
  4524. break;
  4525. case PRIMARY_SKILL:
  4526. cb->changePrimSkill(h, static_cast<PrimarySkill::PrimarySkill>(rID), rVal, false);
  4527. break;
  4528. case SECONDARY_SKILL:
  4529. cb->changeSecSkill(h, SecondarySkill(rID), rVal, false);
  4530. break;
  4531. case ARTIFACT:
  4532. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[rID],ArtifactPosition::FIRST_AVAILABLE);
  4533. break;
  4534. case SPELL:
  4535. {
  4536. std::set<SpellID> spell;
  4537. spell.insert (SpellID(rID));
  4538. cb->changeSpells(h, true, spell);
  4539. }
  4540. break;
  4541. case CREATURE:
  4542. {
  4543. CCreatureSet creatures;
  4544. creatures.setCreature(SlotID(0), CreatureID(rID), rVal);
  4545. cb->giveCreatures(this, h, creatures, false);
  4546. }
  4547. break;
  4548. default:
  4549. break;
  4550. }
  4551. }
  4552. const CGHeroInstance * CGSeerHut::getHeroToKill(bool allowNull) const
  4553. {
  4554. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4555. if(allowNull && !o)
  4556. return nullptr;
  4557. assert(o && (o->ID == Obj::HERO || o->ID == Obj::PRISON));
  4558. return static_cast<const CGHeroInstance*>(o);
  4559. }
  4560. const CGCreature * CGSeerHut::getCreatureToKill(bool allowNull) const
  4561. {
  4562. const CGObjectInstance *o = cb->getObjByQuestIdentifier(quest->m13489val);
  4563. if(allowNull && !o)
  4564. return nullptr;
  4565. assert(o && o->ID == Obj::MONSTER);
  4566. return static_cast<const CGCreature*>(o);
  4567. }
  4568. void CGSeerHut::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  4569. {
  4570. finishQuest(hero, answer);
  4571. }
  4572. void CGQuestGuard::init()
  4573. {
  4574. blockVisit = true;
  4575. quest->textOption = (ran() % 3) + 3; //3-5
  4576. }
  4577. void CGQuestGuard::completeQuest(const CGHeroInstance *h) const
  4578. {
  4579. cb->removeObject(this);
  4580. }
  4581. void CGWitchHut::initObj()
  4582. {
  4583. ability = allowedAbilities[ran()%allowedAbilities.size()];
  4584. }
  4585. void CGWitchHut::onHeroVisit( const CGHeroInstance * h ) const
  4586. {
  4587. InfoWindow iw;
  4588. iw.soundID = soundBase::gazebo;
  4589. iw.player = h->getOwner();
  4590. if(!wasVisited(h->tempOwner))
  4591. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  4592. ui32 txt_id;
  4593. if(h->getSecSkillLevel(SecondarySkill(ability))) //you already know this skill
  4594. {
  4595. txt_id =172;
  4596. }
  4597. else if(!h->canLearnSkill()) //already all skills slots used
  4598. {
  4599. txt_id = 173;
  4600. }
  4601. else //give sec skill
  4602. {
  4603. iw.components.push_back(Component(Component::SEC_SKILL, ability, 1, 0));
  4604. txt_id = 171;
  4605. cb->changeSecSkill(h, SecondarySkill(ability), 1, true);
  4606. }
  4607. iw.text.addTxt(MetaString::ADVOB_TXT,txt_id);
  4608. iw.text.addReplacement(MetaString::SEC_SKILL_NAME, ability);
  4609. cb->showInfoDialog(&iw);
  4610. }
  4611. const std::string & CGWitchHut::getHoverText() const
  4612. {
  4613. hoverName = VLC->generaltexth->names[ID];
  4614. if(wasVisited(cb->getLocalPlayer()))
  4615. {
  4616. hoverName += "\n" + VLC->generaltexth->allTexts[356]; // + (learn %s)
  4617. boost::algorithm::replace_first(hoverName,"%s",VLC->generaltexth->skillName[ability]);
  4618. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4619. if(h && h->getSecSkillLevel(SecondarySkill(ability))) //hero knows that ability
  4620. hoverName += "\n\n" + VLC->generaltexth->allTexts[357]; // (Already learned)
  4621. }
  4622. return hoverName;
  4623. }
  4624. bool CGBonusingObject::wasVisited (const CGHeroInstance * h) const
  4625. {
  4626. return h->hasBonusFrom(Bonus::OBJECT, ID);
  4627. }
  4628. void CGBonusingObject::onHeroVisit( const CGHeroInstance * h ) const
  4629. {
  4630. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4631. int messageID=0;
  4632. int bonusMove = 0;
  4633. ui32 descr_id = 0;
  4634. InfoWindow iw;
  4635. iw.player = h->tempOwner;
  4636. GiveBonus gbonus;
  4637. gbonus.id = h->id.getNum();
  4638. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  4639. gbonus.bonus.source = Bonus::OBJECT;
  4640. gbonus.bonus.sid = ID;
  4641. bool second = false;
  4642. Bonus secondBonus;
  4643. switch(ID)
  4644. {
  4645. case Obj::BUOY:
  4646. messageID = 21;
  4647. iw.soundID = soundBase::MORALE;
  4648. gbonus.bonus.type = Bonus::MORALE;
  4649. gbonus.bonus.val = +1;
  4650. descr_id = 94;
  4651. break;
  4652. case Obj::SWAN_POND:
  4653. messageID = 29;
  4654. iw.soundID = soundBase::LUCK;
  4655. gbonus.bonus.type = Bonus::LUCK;
  4656. gbonus.bonus.val = 2;
  4657. descr_id = 67;
  4658. bonusMove = -h->movement;
  4659. break;
  4660. case Obj::FAERIE_RING:
  4661. messageID = 49;
  4662. iw.soundID = soundBase::LUCK;
  4663. gbonus.bonus.type = Bonus::LUCK;
  4664. gbonus.bonus.val = 1;
  4665. descr_id = 71;
  4666. break;
  4667. case Obj::FOUNTAIN_OF_FORTUNE:
  4668. messageID = 55;
  4669. iw.soundID = soundBase::LUCK;
  4670. gbonus.bonus.type = Bonus::LUCK;
  4671. gbonus.bonus.val = rand()%5 - 1;
  4672. descr_id = 69;
  4673. gbonus.bdescr.addReplacement((gbonus.bonus.val<0 ? "-" : "+") + boost::lexical_cast<std::string>(gbonus.bonus.val));
  4674. break;
  4675. case Obj::IDOL_OF_FORTUNE:
  4676. messageID = 62;
  4677. iw.soundID = soundBase::experience;
  4678. gbonus.bonus.val = 1;
  4679. descr_id = 68;
  4680. if(cb->getDate(Date::DAY_OF_WEEK) == 7) //7th day of week
  4681. {
  4682. gbonus.bonus.type = Bonus::MORALE;
  4683. second = true;
  4684. secondBonus = gbonus.bonus;
  4685. secondBonus.type = Bonus::LUCK;
  4686. }
  4687. else
  4688. {
  4689. gbonus.bonus.type = (cb->getDate(Date::DAY_OF_WEEK)%2) ? Bonus::LUCK : Bonus::MORALE;
  4690. }
  4691. break;
  4692. case Obj::MERMAID:
  4693. messageID = 83;
  4694. iw.soundID = soundBase::LUCK;
  4695. gbonus.bonus.type = Bonus::LUCK;
  4696. gbonus.bonus.val = 1;
  4697. descr_id = 72;
  4698. break;
  4699. case Obj::RALLY_FLAG:
  4700. iw.soundID = soundBase::MORALE;
  4701. messageID = 111;
  4702. gbonus.bonus.type = Bonus::MORALE;
  4703. gbonus.bonus.val = 1;
  4704. descr_id = 102;
  4705. second = true;
  4706. secondBonus = gbonus.bonus;
  4707. secondBonus.type = Bonus::LUCK;
  4708. bonusMove = 400;
  4709. break;
  4710. case Obj::OASIS:
  4711. iw.soundID = soundBase::MORALE;
  4712. messageID = 95;
  4713. gbonus.bonus.type = Bonus::MORALE;
  4714. gbonus.bonus.val = 1;
  4715. descr_id = 95;
  4716. bonusMove = 800;
  4717. break;
  4718. case Obj::TEMPLE:
  4719. messageID = 140;
  4720. iw.soundID = soundBase::temple;
  4721. gbonus.bonus.type = Bonus::MORALE;
  4722. if(cb->getDate(Date::DAY_OF_WEEK)==7) //sunday
  4723. {
  4724. gbonus.bonus.val = 2;
  4725. descr_id = 97;
  4726. }
  4727. else
  4728. {
  4729. gbonus.bonus.val = 1;
  4730. descr_id = 96;
  4731. }
  4732. break;
  4733. case Obj::WATERING_HOLE:
  4734. iw.soundID = soundBase::MORALE;
  4735. messageID = 166;
  4736. gbonus.bonus.type = Bonus::MORALE;
  4737. gbonus.bonus.val = 1;
  4738. descr_id = 100;
  4739. bonusMove = 400;
  4740. break;
  4741. case Obj::FOUNTAIN_OF_YOUTH:
  4742. iw.soundID = soundBase::MORALE;
  4743. messageID = 57;
  4744. gbonus.bonus.type = Bonus::MORALE;
  4745. gbonus.bonus.val = 1;
  4746. descr_id = 103;
  4747. bonusMove = 400;
  4748. break;
  4749. case Obj::STABLES:
  4750. iw.soundID = soundBase::STORE;
  4751. bool someUpgradeDone = false;
  4752. for (auto i = h->Slots().begin(); i != h->Slots().end(); ++i)
  4753. {
  4754. if(i->second->type->idNumber == CreatureID::CAVALIER)
  4755. {
  4756. cb->changeStackType(StackLocation(h, i->first), VLC->creh->creatures[CreatureID::CHAMPION]);
  4757. someUpgradeDone = true;
  4758. }
  4759. }
  4760. if (someUpgradeDone)
  4761. {
  4762. messageID = 138;
  4763. iw.components.push_back(Component(Component::CREATURE,11,0,1));
  4764. }
  4765. else
  4766. messageID = 137;
  4767. gbonus.bonus.type = Bonus::LAND_MOVEMENT;
  4768. gbonus.bonus.val = 600;
  4769. bonusMove = 600;
  4770. gbonus.bonus.duration = Bonus::ONE_WEEK;
  4771. //gbonus.bdescr << std::pair<ui8,ui32>(6, 100);
  4772. break;
  4773. }
  4774. if (descr_id != 0)
  4775. gbonus.bdescr.addTxt(MetaString::ARRAY_TXT,descr_id);
  4776. assert(messageID);
  4777. if(visited)
  4778. {
  4779. if(ID==Obj::RALLY_FLAG || ID==Obj::OASIS || ID==Obj::MERMAID || ID==Obj::STABLES)
  4780. messageID--;
  4781. else
  4782. messageID++;
  4783. }
  4784. else
  4785. {
  4786. //TODO: fix if second bonus val != main bonus val
  4787. if(gbonus.bonus.type == Bonus::MORALE || secondBonus.type == Bonus::MORALE)
  4788. iw.components.push_back(Component(Component::MORALE,0,gbonus.bonus.val,0));
  4789. if(gbonus.bonus.type == Bonus::LUCK || secondBonus.type == Bonus::LUCK)
  4790. iw.components.push_back(Component(Component::LUCK,0,gbonus.bonus.val,0));
  4791. cb->giveHeroBonus(&gbonus);
  4792. if(second)
  4793. {
  4794. gbonus.bonus = secondBonus;
  4795. cb->giveHeroBonus(&gbonus);
  4796. }
  4797. if(bonusMove) //swan pond - take all move points, stables - give move point this day
  4798. {
  4799. SetMovePoints smp;
  4800. smp.hid = h->id;
  4801. smp.val = h->movement + bonusMove;
  4802. cb->setMovePoints(&smp);
  4803. }
  4804. }
  4805. iw.text.addTxt(MetaString::ADVOB_TXT,messageID);
  4806. cb->showInfoDialog(&iw);
  4807. }
  4808. const std::string & CGBonusingObject::getHoverText() const
  4809. {
  4810. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  4811. hoverName = VLC->generaltexth->names[ID];
  4812. if(h)
  4813. {
  4814. bool visited = h->hasBonusFrom(Bonus::OBJECT,ID);
  4815. hoverName += " " + visitedTxt(visited);
  4816. }
  4817. return hoverName;
  4818. }
  4819. void CGBonusingObject::initObj()
  4820. {
  4821. if(ID == Obj::BUOY || ID == Obj::MERMAID)
  4822. {
  4823. blockVisit = true;
  4824. }
  4825. }
  4826. void CGMagicSpring::setPropertyDer(ui8 what, ui32 val)
  4827. {
  4828. CGVisitableOPW::setPropertyDer (what, val); //set visitable if applicable
  4829. if (what == ObjProperty::LEFT_VISITED)
  4830. {
  4831. if (visitedTile == RIGHT)
  4832. visited = true; //both field were used, object is not available this week
  4833. else
  4834. visitedTile = LEFT;
  4835. }
  4836. else if (what == ObjProperty::RIGHT_VISITED)
  4837. {
  4838. if (visitedTile == LEFT)
  4839. visited = true;
  4840. else
  4841. visitedTile = RIGHT;
  4842. }
  4843. else if (what == ObjProperty::LEFTRIGHT_CLEAR)
  4844. visitedTile = CLEAR;
  4845. }
  4846. std::vector<int3> CGMagicSpring::getVisitableOffsets() const
  4847. {
  4848. std::vector <int3> visitableTiles;
  4849. for(int y = 0; y < 6; y++)
  4850. for (int x = 0; x < 8; x++) //starting from left
  4851. if (appearance.isVisitableAt(x, y))
  4852. visitableTiles.push_back (int3(x, y , 0));
  4853. return visitableTiles;
  4854. }
  4855. int3 CGMagicSpring::getVisitableOffset() const
  4856. {
  4857. //FIXME: this also shoudl stop AI from passing through already visited spring, is that ok?
  4858. auto visitableTiles = getVisitableOffsets();
  4859. if (visitableTiles.size() < 2)
  4860. {
  4861. logGlobal->warnStream() << "Warning: Magic Spring should have at least two visitable offsets!";
  4862. return int3(-1,-1,-1);
  4863. }
  4864. if (visited)
  4865. return int3(-1,-1,-1);
  4866. else
  4867. {
  4868. if (visitedTile == RIGHT)
  4869. return visitableTiles[0]; //visit teh other one now
  4870. else if (visitedTile == LEFT)
  4871. return visitableTiles[1];
  4872. else
  4873. return visitableTiles[0]; //only left one?
  4874. }
  4875. }
  4876. void CGMagicSpring::onHeroVisit(const CGHeroInstance * h) const
  4877. {
  4878. int messageID;
  4879. if (!visited)
  4880. {
  4881. if (h->mana > h->manaLimit())
  4882. messageID = 76;
  4883. else
  4884. {
  4885. messageID = 74;
  4886. cb->setManaPoints (h->id, 2 * h->manaLimit());//TODO: mark left or right tile visited
  4887. if (visitedTile) //visitng the second tile
  4888. cb->setObjProperty (id, ObjProperty::VISITED, true);
  4889. else
  4890. {
  4891. auto visitableTiles = getVisitableOffsets();
  4892. assert (visitableTiles.size() >= 2);
  4893. if (h->getPosition() == pos - visitableTiles[0])
  4894. cb->setObjProperty (id, ObjProperty::LEFT_VISITED, true);
  4895. else if (h->getPosition() == pos - visitableTiles[1])
  4896. cb->setObjProperty (id, ObjProperty::RIGHT_VISITED, true);
  4897. else
  4898. logGlobal->warnStream() << "Warning: hero is not on any Magic Spring visitable offsets!";
  4899. }
  4900. }
  4901. }
  4902. else
  4903. messageID = 75;
  4904. showInfoDialog(h,messageID,soundBase::GENIE);
  4905. }
  4906. void CGMagicSpring::newTurn() const
  4907. {
  4908. CGVisitableOPW::newTurn();
  4909. if (cb->getDate(Date::DAY_OF_WEEK) == 1)
  4910. {
  4911. cb->setObjProperty(id, ObjProperty::LEFTRIGHT_CLEAR, false);
  4912. }
  4913. }
  4914. const std::string & CGMagicSpring::getHoverText() const
  4915. {
  4916. //TODO: change hover text depending on hovered tile
  4917. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  4918. return hoverName;
  4919. }
  4920. void CGMagicWell::onHeroVisit( const CGHeroInstance * h ) const
  4921. {
  4922. int message;
  4923. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Well today
  4924. {
  4925. message = 78;//"A second drink at the well in one day will not help you."
  4926. }
  4927. else if(h->mana < h->manaLimit())
  4928. {
  4929. giveDummyBonus(h->id);
  4930. cb->setManaPoints(h->id,h->manaLimit());
  4931. message = 77;
  4932. }
  4933. else
  4934. {
  4935. message = 79;
  4936. }
  4937. showInfoDialog(h,message,soundBase::faerie);
  4938. }
  4939. const std::string & CGMagicWell::getHoverText() const
  4940. {
  4941. getNameVis(hoverName);
  4942. return hoverName;
  4943. }
  4944. void CGPandoraBox::initObj()
  4945. {
  4946. blockVisit = (ID==Obj::PANDORAS_BOX); //block only if it's really pandora's box (events also derive from that class)
  4947. hasGuardians = stacks.size();
  4948. }
  4949. void CGPandoraBox::onHeroVisit(const CGHeroInstance * h) const
  4950. {
  4951. BlockingDialog bd (true, false);
  4952. bd.player = h->getOwner();
  4953. bd.soundID = soundBase::QUEST;
  4954. bd.text.addTxt (MetaString::ADVOB_TXT, 14);
  4955. cb->showBlockingDialog (&bd);
  4956. }
  4957. void CGPandoraBox::giveContentsUpToExp(const CGHeroInstance *h) const
  4958. {
  4959. cb->removeAfterVisit(this);
  4960. InfoWindow iw;
  4961. iw.player = h->getOwner();
  4962. bool changesPrimSkill = false;
  4963. for (auto & elem : primskills)
  4964. {
  4965. if(elem)
  4966. {
  4967. changesPrimSkill = true;
  4968. break;
  4969. }
  4970. }
  4971. if(gainedExp || changesPrimSkill || abilities.size())
  4972. {
  4973. TExpType expVal = h->calculateXp(gainedExp);
  4974. //getText(iw,afterBattle,175,h); //wtf?
  4975. iw.text.addTxt(MetaString::ADVOB_TXT, 175); //%s learns something
  4976. iw.text.addReplacement(h->name);
  4977. if(expVal)
  4978. iw.components.push_back(Component(Component::EXPERIENCE,0,expVal,0));
  4979. for(int i=0; i<primskills.size(); i++)
  4980. if(primskills[i])
  4981. iw.components.push_back(Component(Component::PRIM_SKILL,i,primskills[i],0));
  4982. for(int i=0; i<abilities.size(); i++)
  4983. iw.components.push_back(Component(Component::SEC_SKILL,abilities[i],abilityLevels[i],0));
  4984. cb->showInfoDialog(&iw);
  4985. //give sec skills
  4986. for(int i=0; i<abilities.size(); i++)
  4987. {
  4988. int curLev = h->getSecSkillLevel(abilities[i]);
  4989. if( (curLev && curLev < abilityLevels[i]) || (h->canLearnSkill() ))
  4990. {
  4991. cb->changeSecSkill(h,abilities[i],abilityLevels[i],true);
  4992. }
  4993. }
  4994. //give prim skills
  4995. for(int i=0; i<primskills.size(); i++)
  4996. if(primskills[i])
  4997. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(i),primskills[i],false);
  4998. assert(!cb->isVisitCoveredByAnotherQuery(this, h));
  4999. //give exp
  5000. if(expVal)
  5001. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, expVal, false);
  5002. }
  5003. if(!cb->isVisitCoveredByAnotherQuery(this, h))
  5004. giveContentsAfterExp(h);
  5005. //Otherwise continuation occurs via post-level-up callback.
  5006. }
  5007. void CGPandoraBox::giveContentsAfterExp(const CGHeroInstance *h) const
  5008. {
  5009. bool hadGuardians = hasGuardians; //copy, because flag will be emptied after issuing first post-battle message
  5010. std::string msg = message; //in case box is removed in the meantime
  5011. InfoWindow iw;
  5012. iw.player = h->getOwner();
  5013. if(spells.size())
  5014. {
  5015. std::set<SpellID> spellsToGive;
  5016. iw.components.clear();
  5017. if (spells.size() > 1)
  5018. {
  5019. iw.text.addTxt(MetaString::ADVOB_TXT, 188); //%s learns spells
  5020. }
  5021. else
  5022. {
  5023. iw.text.addTxt(MetaString::ADVOB_TXT, 184); //%s learns a spell
  5024. }
  5025. iw.text.addReplacement(h->name);
  5026. std::vector<ConstTransitivePtr<CSpell> > * sp = &VLC->spellh->spells;
  5027. for(auto i=spells.cbegin(); i != spells.cend(); i++)
  5028. {
  5029. if ((*sp)[*i]->level <= h->getSecSkillLevel(SecondarySkill::WISDOM) + 2) //enough wisdom
  5030. {
  5031. iw.components.push_back(Component(Component::SPELL,*i,0,0));
  5032. spellsToGive.insert(*i);
  5033. }
  5034. }
  5035. if(!spellsToGive.empty())
  5036. {
  5037. cb->changeSpells(h,true,spellsToGive);
  5038. cb->showInfoDialog(&iw);
  5039. }
  5040. }
  5041. if(manaDiff)
  5042. {
  5043. getText(iw,hadGuardians,manaDiff,176,177,h);
  5044. iw.components.push_back(Component(Component::PRIM_SKILL,5,manaDiff,0));
  5045. cb->showInfoDialog(&iw);
  5046. cb->setManaPoints(h->id, h->mana + manaDiff);
  5047. }
  5048. if(moraleDiff)
  5049. {
  5050. getText(iw,hadGuardians,moraleDiff,178,179,h);
  5051. iw.components.push_back(Component(Component::MORALE,0,moraleDiff,0));
  5052. cb->showInfoDialog(&iw);
  5053. GiveBonus gb;
  5054. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,moraleDiff,id.getNum(),"");
  5055. gb.id = h->id.getNum();
  5056. cb->giveHeroBonus(&gb);
  5057. }
  5058. if(luckDiff)
  5059. {
  5060. getText(iw,hadGuardians,luckDiff,180,181,h);
  5061. iw.components.push_back(Component(Component::LUCK,0,luckDiff,0));
  5062. cb->showInfoDialog(&iw);
  5063. GiveBonus gb;
  5064. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,luckDiff,id.getNum(),"");
  5065. gb.id = h->id.getNum();
  5066. cb->giveHeroBonus(&gb);
  5067. }
  5068. iw.components.clear();
  5069. iw.text.clear();
  5070. for(int i=0; i<resources.size(); i++)
  5071. {
  5072. if(resources[i] < 0)
  5073. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  5074. }
  5075. if(iw.components.size())
  5076. {
  5077. getText(iw,hadGuardians,182,h);
  5078. cb->showInfoDialog(&iw);
  5079. }
  5080. iw.components.clear();
  5081. iw.text.clear();
  5082. for(int i=0; i<resources.size(); i++)
  5083. {
  5084. if(resources[i] > 0)
  5085. iw.components.push_back(Component(Component::RESOURCE,i,resources[i],0));
  5086. }
  5087. if(iw.components.size())
  5088. {
  5089. getText(iw,hadGuardians,183,h);
  5090. cb->showInfoDialog(&iw);
  5091. }
  5092. iw.components.clear();
  5093. // getText(iw,afterBattle,183,h);
  5094. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure
  5095. iw.text.addReplacement(h->name);
  5096. for(auto & elem : artifacts)
  5097. {
  5098. iw.components.push_back(Component(Component::ARTIFACT,elem,0,0));
  5099. if(iw.components.size() >= 14)
  5100. {
  5101. cb->showInfoDialog(&iw);
  5102. iw.components.clear();
  5103. iw.text.addTxt(MetaString::ADVOB_TXT, 183); //% has found treasure - once more?
  5104. iw.text.addReplacement(h->name);
  5105. }
  5106. }
  5107. if(iw.components.size())
  5108. {
  5109. cb->showInfoDialog(&iw);
  5110. }
  5111. for(int i=0; i<resources.size(); i++)
  5112. if(resources[i])
  5113. cb->giveResource(h->getOwner(),static_cast<Res::ERes>(i),resources[i]);
  5114. for(auto & elem : artifacts)
  5115. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[elem],ArtifactPosition::FIRST_AVAILABLE);
  5116. iw.components.clear();
  5117. iw.text.clear();
  5118. if (creatures.Slots().size())
  5119. { //this part is taken straight from creature bank
  5120. MetaString loot;
  5121. for(auto & elem : creatures.Slots())
  5122. { //build list of joined creatures
  5123. iw.components.push_back(Component(*elem.second));
  5124. loot << "%s";
  5125. loot.addReplacement(*elem.second);
  5126. }
  5127. if (creatures.Slots().size() == 1 && creatures.Slots().begin()->second->count == 1)
  5128. iw.text.addTxt(MetaString::ADVOB_TXT, 185);
  5129. else
  5130. iw.text.addTxt(MetaString::ADVOB_TXT, 186);
  5131. iw.text.addReplacement(loot.buildList());
  5132. iw.text.addReplacement(h->name);
  5133. cb->showInfoDialog(&iw);
  5134. cb->giveCreatures(this, h, creatures, true);
  5135. }
  5136. if(!hasGuardians && msg.size())
  5137. {
  5138. iw.text << msg;
  5139. cb->showInfoDialog(&iw);
  5140. }
  5141. }
  5142. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int text, const CGHeroInstance * h ) const
  5143. {
  5144. if(afterBattle || !message.size())
  5145. {
  5146. iw.text.addTxt(MetaString::ADVOB_TXT,text);//%s has lost treasure.
  5147. iw.text.addReplacement(h->name);
  5148. }
  5149. else
  5150. {
  5151. iw.text << message;
  5152. afterBattle = true;
  5153. }
  5154. }
  5155. void CGPandoraBox::getText( InfoWindow &iw, bool &afterBattle, int val, int negative, int positive, const CGHeroInstance * h ) const
  5156. {
  5157. iw.components.clear();
  5158. iw.text.clear();
  5159. if(afterBattle || !message.size())
  5160. {
  5161. iw.text.addTxt(MetaString::ADVOB_TXT,val < 0 ? negative : positive); //%s's luck takes a turn for the worse / %s's luck increases
  5162. iw.text.addReplacement(h->name);
  5163. }
  5164. else
  5165. {
  5166. iw.text << message;
  5167. afterBattle = true;
  5168. }
  5169. }
  5170. void CGPandoraBox::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5171. {
  5172. if(result.winner)
  5173. return;
  5174. giveContentsUpToExp(hero);
  5175. }
  5176. void CGPandoraBox::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5177. {
  5178. if (answer)
  5179. {
  5180. if (stacksCount() > 0) //if pandora's box is protected by army
  5181. {
  5182. showInfoDialog(hero,16,0);
  5183. cb->startBattleI(hero, this); //grants things after battle
  5184. }
  5185. else if (message.size() == 0 && resources.size() == 0
  5186. && primskills.size() == 0 && abilities.size() == 0
  5187. && abilityLevels.size() == 0 && artifacts.size() == 0
  5188. && spells.size() == 0 && creatures.Slots().size() > 0
  5189. && gainedExp == 0 && manaDiff == 0 && moraleDiff == 0 && luckDiff == 0) //if it gives nothing without battle
  5190. {
  5191. showInfoDialog(hero,15,0);
  5192. cb->removeObject(this);
  5193. }
  5194. else //if it gives something without battle
  5195. {
  5196. giveContentsUpToExp(hero);
  5197. }
  5198. }
  5199. }
  5200. void CGPandoraBox::heroLevelUpDone(const CGHeroInstance *hero) const
  5201. {
  5202. giveContentsAfterExp(hero);
  5203. }
  5204. void CGEvent::onHeroVisit( const CGHeroInstance * h ) const
  5205. {
  5206. if(!(availableFor & (1 << h->tempOwner.getNum())))
  5207. return;
  5208. if(cb->getPlayerSettings(h->tempOwner)->playerID)
  5209. {
  5210. if(humanActivate)
  5211. activated(h);
  5212. }
  5213. else if(computerActivate)
  5214. activated(h);
  5215. }
  5216. void CGEvent::activated( const CGHeroInstance * h ) const
  5217. {
  5218. if(stacksCount() > 0)
  5219. {
  5220. InfoWindow iw;
  5221. iw.player = h->tempOwner;
  5222. if(message.size())
  5223. iw.text << message;
  5224. else
  5225. iw.text.addTxt(MetaString::ADVOB_TXT, 16);
  5226. cb->showInfoDialog(&iw);
  5227. cb->startBattleI(h, this);
  5228. }
  5229. else
  5230. {
  5231. giveContentsUpToExp(h);
  5232. }
  5233. }
  5234. void CGObservatory::onHeroVisit( const CGHeroInstance * h ) const
  5235. {
  5236. InfoWindow iw;
  5237. iw.player = h->tempOwner;
  5238. switch (ID)
  5239. {
  5240. case Obj::REDWOOD_OBSERVATORY:
  5241. case Obj::PILLAR_OF_FIRE:
  5242. {
  5243. iw.soundID = soundBase::LIGHTHOUSE;
  5244. iw.text.addTxt(MetaString::ADVOB_TXT,98 + (ID==Obj::PILLAR_OF_FIRE));
  5245. FoWChange fw;
  5246. fw.player = h->tempOwner;
  5247. fw.mode = 1;
  5248. cb->getTilesInRange (fw.tiles, pos, 20, h->tempOwner, 1);
  5249. cb->sendAndApply (&fw);
  5250. break;
  5251. }
  5252. case Obj::COVER_OF_DARKNESS:
  5253. {
  5254. iw.text.addTxt (MetaString::ADVOB_TXT, 31);
  5255. hideTiles(h->tempOwner, 20);
  5256. break;
  5257. }
  5258. }
  5259. cb->showInfoDialog(&iw);
  5260. }
  5261. void CGShrine::onHeroVisit( const CGHeroInstance * h ) const
  5262. {
  5263. if(spell == SpellID::NONE)
  5264. {
  5265. logGlobal->errorStream() << "Not initialized shrine visited!";
  5266. return;
  5267. }
  5268. if(!wasVisited(h->tempOwner))
  5269. cb->setObjProperty(id, 10, h->tempOwner.getNum());
  5270. InfoWindow iw;
  5271. iw.soundID = soundBase::temple;
  5272. iw.player = h->getOwner();
  5273. iw.text.addTxt(MetaString::ADVOB_TXT,127 + ID - 88);
  5274. iw.text.addTxt(MetaString::SPELL_NAME,spell);
  5275. iw.text << ".";
  5276. if(!h->getArt(ArtifactPosition::SPELLBOOK))
  5277. {
  5278. iw.text.addTxt(MetaString::ADVOB_TXT,131);
  5279. }
  5280. else if(ID == Obj::SHRINE_OF_MAGIC_THOUGHT && !h->getSecSkillLevel(SecondarySkill::WISDOM)) //it's third level spell and hero doesn't have wisdom
  5281. {
  5282. iw.text.addTxt(MetaString::ADVOB_TXT,130);
  5283. }
  5284. else if(vstd::contains(h->spells,spell))//hero already knows the spell
  5285. {
  5286. iw.text.addTxt(MetaString::ADVOB_TXT,174);
  5287. }
  5288. else //give spell
  5289. {
  5290. std::set<SpellID> spells;
  5291. spells.insert(spell);
  5292. cb->changeSpells(h, true, spells);
  5293. iw.components.push_back(Component(Component::SPELL,spell,0,0));
  5294. }
  5295. cb->showInfoDialog(&iw);
  5296. }
  5297. void CGShrine::initObj()
  5298. {
  5299. if(spell == SpellID::NONE) //spell not set
  5300. {
  5301. int level = ID-87;
  5302. std::vector<SpellID> possibilities;
  5303. cb->getAllowedSpells (possibilities, level);
  5304. if(!possibilities.size())
  5305. {
  5306. logGlobal->errorStream() << "Error: cannot init shrine, no allowed spells!";
  5307. return;
  5308. }
  5309. spell = possibilities[ran() % possibilities.size()];
  5310. }
  5311. }
  5312. const std::string & CGShrine::getHoverText() const
  5313. {
  5314. hoverName = VLC->generaltexth->names[ID];
  5315. if(wasVisited(cb->getCurrentPlayer())) //TODO: use local player, not current
  5316. {
  5317. hoverName += "\n" + VLC->generaltexth->allTexts[355]; // + (learn %s)
  5318. boost::algorithm::replace_first(hoverName,"%s", spell.toSpell()->name);
  5319. const CGHeroInstance *h = cb->getSelectedHero(cb->getCurrentPlayer());
  5320. if(h && vstd::contains(h->spells,spell)) //hero knows that ability
  5321. hoverName += "\n\n" + VLC->generaltexth->allTexts[354]; // (Already learned)
  5322. }
  5323. return hoverName;
  5324. }
  5325. void CGSignBottle::initObj()
  5326. {
  5327. //if no text is set than we pick random from the predefined ones
  5328. if(!message.size())
  5329. message = VLC->generaltexth->randsign[ran()%VLC->generaltexth->randsign.size()];
  5330. if(ID == Obj::OCEAN_BOTTLE)
  5331. {
  5332. blockVisit = true;
  5333. }
  5334. }
  5335. void CGSignBottle::onHeroVisit( const CGHeroInstance * h ) const
  5336. {
  5337. InfoWindow iw;
  5338. iw.soundID = soundBase::STORE;
  5339. iw.player = h->getOwner();
  5340. iw.text << message;
  5341. cb->showInfoDialog(&iw);
  5342. if(ID == Obj::OCEAN_BOTTLE)
  5343. cb->removeObject(this);
  5344. }
  5345. //TODO: remove
  5346. //void CGScholar::giveAnyBonus( const CGHeroInstance * h ) const
  5347. //{
  5348. //
  5349. //}
  5350. void CGScholar::onHeroVisit( const CGHeroInstance * h ) const
  5351. {
  5352. EBonusType type = bonusType;
  5353. int bid = bonusID;
  5354. //check if the bonus if applicable, if not - give primary skill (always possible)
  5355. int ssl = h->getSecSkillLevel(SecondarySkill(bid)); //current sec skill level, used if bonusType == 1
  5356. if((type == SECONDARY_SKILL
  5357. && ((ssl == 3) || (!ssl && !h->canLearnSkill()))) ////hero already has expert level in the skill or (don't know skill and doesn't have free slot)
  5358. || (type == SPELL && (!h->getArt(ArtifactPosition::SPELLBOOK) || vstd::contains(h->spells, (ui32) bid)
  5359. || ( SpellID(bid).toSpell()->level > h->getSecSkillLevel(SecondarySkill::WISDOM) + 2)
  5360. ))) //hero doesn't have a spellbook or already knows the spell or doesn't have Wisdom
  5361. {
  5362. type = PRIM_SKILL;
  5363. bid = ran() % GameConstants::PRIMARY_SKILLS;
  5364. }
  5365. InfoWindow iw;
  5366. iw.soundID = soundBase::gazebo;
  5367. iw.player = h->getOwner();
  5368. iw.text.addTxt(MetaString::ADVOB_TXT,115);
  5369. switch (type)
  5370. {
  5371. case PRIM_SKILL:
  5372. cb->changePrimSkill(h,static_cast<PrimarySkill::PrimarySkill>(bid),+1);
  5373. iw.components.push_back(Component(Component::PRIM_SKILL,bid,+1,0));
  5374. break;
  5375. case SECONDARY_SKILL:
  5376. cb->changeSecSkill(h,SecondarySkill(bid),+1);
  5377. iw.components.push_back(Component(Component::SEC_SKILL,bid,ssl+1,0));
  5378. break;
  5379. case SPELL:
  5380. {
  5381. std::set<SpellID> hlp;
  5382. hlp.insert(SpellID(bid));
  5383. cb->changeSpells(h,true,hlp);
  5384. iw.components.push_back(Component(Component::SPELL,bid,0,0));
  5385. }
  5386. break;
  5387. default:
  5388. logGlobal->errorStream() << "Error: wrong bonus type (" << (int)type << ") for Scholar!\n";
  5389. return;
  5390. }
  5391. cb->showInfoDialog(&iw);
  5392. cb->removeObject(this);
  5393. }
  5394. void CGScholar::initObj()
  5395. {
  5396. blockVisit = true;
  5397. if(bonusType == RANDOM)
  5398. {
  5399. bonusType = static_cast<EBonusType>(ran()%3);
  5400. switch(bonusType)
  5401. {
  5402. case PRIM_SKILL:
  5403. bonusID = ran() % GameConstants::PRIMARY_SKILLS;
  5404. break;
  5405. case SECONDARY_SKILL:
  5406. bonusID = ran() % GameConstants::SKILL_QUANTITY;
  5407. break;
  5408. case SPELL:
  5409. std::vector<SpellID> possibilities;
  5410. for (int i = 1; i < 6; ++i)
  5411. cb->getAllowedSpells (possibilities, i);
  5412. bonusID = possibilities[ran() % possibilities.size()];
  5413. break;
  5414. }
  5415. }
  5416. }
  5417. void CGGarrison::onHeroVisit (const CGHeroInstance *h) const
  5418. {
  5419. int ally = cb->gameState()->getPlayerRelations(h->tempOwner, tempOwner);
  5420. if (!ally && stacksCount() > 0) {
  5421. //TODO: Find a way to apply magic garrison effects in battle.
  5422. cb->startBattleI(h, this);
  5423. return;
  5424. }
  5425. //New owner.
  5426. if (!ally)
  5427. cb->setOwner(this, h->tempOwner);
  5428. cb->showGarrisonDialog(id, h->id, removableUnits);
  5429. }
  5430. ui8 CGGarrison::getPassableness() const
  5431. {
  5432. if ( !stacksCount() )//empty - anyone can visit
  5433. return GameConstants::ALL_PLAYERS;
  5434. if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
  5435. return 0;
  5436. ui8 mask = 0;
  5437. TeamState * ts = cb->gameState()->getPlayerTeam(tempOwner);
  5438. for(PlayerColor it : ts->players)
  5439. mask |= 1<<it.getNum(); //allies - add to possible visitors
  5440. return mask;
  5441. }
  5442. void CGGarrison::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5443. {
  5444. if (result.winner == 0)
  5445. onHeroVisit(hero);
  5446. }
  5447. void CGOnceVisitable::onHeroVisit( const CGHeroInstance * h ) const
  5448. {
  5449. int sound = soundBase::sound_todo;
  5450. int txtid;
  5451. switch(ID)
  5452. {
  5453. case Obj::CORPSE:
  5454. txtid = 37;
  5455. sound = soundBase::MYSTERY;
  5456. break;
  5457. case Obj::LEAN_TO:
  5458. sound = soundBase::GENIE;
  5459. txtid = 64;
  5460. break;
  5461. case Obj::WAGON:
  5462. sound = soundBase::GENIE;
  5463. txtid = 154;
  5464. break;
  5465. case Obj::WARRIORS_TOMB:
  5466. {
  5467. //ask if player wants to search the Tomb
  5468. BlockingDialog bd(true, false);
  5469. bd.soundID = soundBase::GRAVEYARD;
  5470. bd.player = h->getOwner();
  5471. bd.text.addTxt(MetaString::ADVOB_TXT,161);
  5472. cb->showBlockingDialog(&bd);
  5473. return;
  5474. }
  5475. default:
  5476. logGlobal->errorStream() << "Error: Unknown object (" << ID <<") treated as CGOnceVisitable!";
  5477. return;
  5478. }
  5479. InfoWindow iw;
  5480. iw.soundID = sound;
  5481. iw.player = h->getOwner();
  5482. if(players.size()) //we have been already visited...
  5483. {
  5484. txtid++;
  5485. if(ID == Obj::WAGON) //wagon has extra text (for finding art) we need to omit
  5486. txtid++;
  5487. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5488. }
  5489. else //first visit - give bonus!
  5490. {
  5491. switch(artOrRes)
  5492. {
  5493. case 0: // first visit but empty
  5494. if (ID == Obj::CORPSE)
  5495. ++txtid;
  5496. else
  5497. txtid+=2;
  5498. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5499. break;
  5500. case 1: //art
  5501. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5502. cb->giveHeroNewArtifact(h, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5503. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5504. if (ID == Obj::CORPSE)
  5505. {
  5506. iw.text << "%s";
  5507. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5508. }
  5509. break;
  5510. case 2: //res
  5511. iw.text.addTxt(MetaString::ADVOB_TXT, txtid);
  5512. iw.components.push_back (Component(Component::RESOURCE, bonusType, bonusVal, 0));
  5513. cb->giveResource(h->getOwner(), static_cast<Res::ERes>(bonusType), bonusVal);
  5514. break;
  5515. }
  5516. if(ID == Obj::WAGON && artOrRes == 1)
  5517. {
  5518. iw.text.localStrings.back().second++;
  5519. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5520. }
  5521. }
  5522. cb->showInfoDialog(&iw);
  5523. cb->setObjProperty(id, 10, h->getOwner().getNum());
  5524. }
  5525. const std::string & CGOnceVisitable::getHoverText() const
  5526. {
  5527. const bool visited = wasVisited(cb->getCurrentPlayer());
  5528. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  5529. return hoverName;
  5530. }
  5531. void CGOnceVisitable::initObj()
  5532. {
  5533. switch(ID)
  5534. {
  5535. case Obj::CORPSE:
  5536. {
  5537. blockVisit = true;
  5538. int hlp = ran()%100;
  5539. if(hlp < 20)
  5540. {
  5541. artOrRes = 1;
  5542. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR | CArtifact::ART_MAJOR);
  5543. }
  5544. else
  5545. {
  5546. artOrRes = 0;
  5547. }
  5548. }
  5549. break;
  5550. case Obj::LEAN_TO:
  5551. {
  5552. artOrRes = 2;
  5553. bonusType = ran()%6; //any basic resource without gold
  5554. bonusVal = ran()%4 + 1;
  5555. }
  5556. break;
  5557. case Obj::WARRIORS_TOMB:
  5558. {
  5559. artOrRes = 1;
  5560. int hlp = ran()%100;
  5561. if(hlp < 30)
  5562. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE);
  5563. else if(hlp < 80)
  5564. bonusType = cb->getRandomArt (CArtifact::ART_MINOR);
  5565. else if(hlp < 95)
  5566. bonusType = cb->getRandomArt (CArtifact::ART_MAJOR);
  5567. else
  5568. bonusType = cb->getRandomArt (CArtifact::ART_RELIC);
  5569. }
  5570. break;
  5571. case Obj::WAGON:
  5572. {
  5573. int hlp = ran()%100;
  5574. if(hlp < 10)
  5575. {
  5576. artOrRes = 0; // nothing... :(
  5577. }
  5578. else if(hlp < 50) //minor or treasure art
  5579. {
  5580. artOrRes = 1;
  5581. bonusType = cb->getRandomArt (CArtifact::ART_TREASURE | CArtifact::ART_MINOR);
  5582. }
  5583. else //2 - 5 of non-gold resource
  5584. {
  5585. artOrRes = 2;
  5586. bonusType = ran()%6;
  5587. bonusVal = ran()%4 + 2;
  5588. }
  5589. }
  5590. break;
  5591. }
  5592. }
  5593. void CGOnceVisitable::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5594. {
  5595. //must have been Tomb
  5596. if(answer)
  5597. {
  5598. InfoWindow iw;
  5599. iw.player = hero->getOwner();
  5600. iw.components.push_back(Component(Component::MORALE,0,-3,0));
  5601. if(players.size()) //we've been already visited, player found nothing
  5602. {
  5603. iw.text.addTxt(MetaString::ADVOB_TXT,163);
  5604. }
  5605. else //first visit - give artifact
  5606. {
  5607. iw.text.addTxt(MetaString::ADVOB_TXT,162);
  5608. iw.components.push_back(Component(Component::ARTIFACT,bonusType,0,0));
  5609. iw.text.addReplacement(MetaString::ART_NAMES, bonusType);
  5610. cb->giveHeroNewArtifact(hero, VLC->arth->artifacts[bonusType],ArtifactPosition::FIRST_AVAILABLE);
  5611. }
  5612. if(!hero->hasBonusFrom(Bonus::OBJECT,ID)) //we don't have modifier from this object yet
  5613. {
  5614. //ruin morale
  5615. GiveBonus gb;
  5616. gb.id = hero->id.getNum();
  5617. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::MORALE,Bonus::OBJECT,-3,id.getNum(),"");
  5618. gb.bdescr.addTxt(MetaString::ARRAY_TXT,104); //Warrior Tomb Visited -3
  5619. cb->giveHeroBonus(&gb);
  5620. }
  5621. cb->showInfoDialog(&iw);
  5622. cb->setObjProperty(id, 10, hero->getOwner().getNum());
  5623. }
  5624. }
  5625. void CBank::initObj()
  5626. {
  5627. index = VLC->objh->bankObjToIndex(this);
  5628. bc = nullptr;
  5629. daycounter = 0;
  5630. multiplier = 1;
  5631. }
  5632. const std::string & CBank::getHoverText() const
  5633. {
  5634. bool visited = (bc == nullptr);
  5635. hoverName = VLC->objh->creBanksNames[index] + " " + visitedTxt(visited);
  5636. return hoverName;
  5637. }
  5638. void CBank::reset(ui16 var1) //prevents desync
  5639. {
  5640. ui8 chance = 0;
  5641. for (auto & elem : VLC->objh->banksInfo[index])
  5642. {
  5643. if (var1 < (chance += elem->chance))
  5644. {
  5645. bc = elem;
  5646. break;
  5647. }
  5648. }
  5649. artifacts.clear();
  5650. }
  5651. void CBank::initialize() const
  5652. {
  5653. cb->setObjProperty (id, ObjProperty::BANK_RESET, ran()); //synchronous reset
  5654. for (ui8 i = 0; i <= 3; i++)
  5655. {
  5656. for (ui8 n = 0; n < bc->artifacts[i]; n++)
  5657. {
  5658. CArtifact::EartClass artClass;
  5659. switch(i)
  5660. {
  5661. case 0: artClass = CArtifact::ART_TREASURE; break;
  5662. case 1: artClass = CArtifact::ART_MINOR; break;
  5663. case 2: artClass = CArtifact::ART_MAJOR; break;
  5664. case 3: artClass = CArtifact::ART_RELIC; break;
  5665. default: assert(0); continue;
  5666. }
  5667. int artID = cb->getArtSync(ran(), artClass, true);
  5668. cb->setObjProperty(id, ObjProperty::BANK_ADD_ARTIFACT, artID);
  5669. }
  5670. }
  5671. cb->setObjProperty (id, ObjProperty::BANK_INIT_ARMY, ran()); //get army
  5672. }
  5673. void CBank::setPropertyDer (ui8 what, ui32 val)
  5674. /// random values are passed as arguments and processed identically on all clients
  5675. {
  5676. switch (what)
  5677. {
  5678. case ObjProperty::BANK_DAYCOUNTER: //daycounter
  5679. if (val == 0)
  5680. daycounter = 1; //yes, 1
  5681. else
  5682. daycounter++;
  5683. break;
  5684. case ObjProperty::BANK_MULTIPLIER: //multiplier, in percent
  5685. multiplier = val / 100.0;
  5686. break;
  5687. case 13: //bank preset
  5688. bc = VLC->objh->banksInfo[index][val];
  5689. break;
  5690. case ObjProperty::BANK_RESET:
  5691. reset (val%100);
  5692. break;
  5693. case ObjProperty::BANK_CLEAR_CONFIG:
  5694. bc = nullptr;
  5695. break;
  5696. case ObjProperty::BANK_CLEAR_ARTIFACTS: //remove rewards from Derelict Ship
  5697. artifacts.clear();
  5698. break;
  5699. case ObjProperty::BANK_INIT_ARMY: //set ArmedInstance army
  5700. {
  5701. int upgraded = 0;
  5702. if (val%100 < bc->upgradeChance) //once again anti-desync
  5703. upgraded = 1;
  5704. switch (bc->guards.size())
  5705. {
  5706. case 1:
  5707. for (int i = 0; i < 4; ++i)
  5708. setCreature (SlotID(i), bc->guards[0].first, bc->guards[0].second / 5 );
  5709. setCreature (SlotID(4), CreatureID(bc->guards[0].first + upgraded), bc->guards[0].second / 5 );
  5710. break;
  5711. case 4:
  5712. {
  5713. if (bc->guards.back().second) //all stacks are present
  5714. {
  5715. for (auto & elem : bc->guards)
  5716. {
  5717. setCreature (SlotID(stacksCount()), elem.first, elem.second);
  5718. }
  5719. }
  5720. else if (bc->guards[2].second)//Wraiths are present, split two stacks in Crypt
  5721. {
  5722. setCreature (SlotID(0), bc->guards[0].first, bc->guards[0].second / 2 );
  5723. setCreature (SlotID(1), bc->guards[1].first, bc->guards[1].second / 2);
  5724. setCreature (SlotID(2), CreatureID(bc->guards[2].first + upgraded), bc->guards[2].second);
  5725. setCreature (SlotID(3), bc->guards[1].first, bc->guards[1].second / 2 );
  5726. setCreature (SlotID(4), bc->guards[0].first, bc->guards[0].second - (bc->guards[0].second / 2) );
  5727. }
  5728. else //split both stacks
  5729. {
  5730. for (int i = 0; i < 3; ++i) //skellies
  5731. setCreature (SlotID(2*i), bc->guards[0].first, bc->guards[0].second / 3);
  5732. for (int i = 0; i < 2; ++i) //zombies
  5733. setCreature (SlotID(2*i+1), bc->guards[1].first, bc->guards[1].second / 2);
  5734. }
  5735. }
  5736. break;
  5737. default:
  5738. logGlobal->warnStream() << "Error: Unexpected army data: " << bc->guards.size() <<" items found";
  5739. return;
  5740. }
  5741. }
  5742. break;
  5743. case ObjProperty::BANK_ADD_ARTIFACT: //add Artifact
  5744. {
  5745. artifacts.push_back (val);
  5746. break;
  5747. }
  5748. }
  5749. }
  5750. void CBank::newTurn() const
  5751. {
  5752. if (bc == nullptr)
  5753. {
  5754. if (cb->getDate() == 1)
  5755. initialize(); //initialize on first day
  5756. else if (daycounter >= 28 && (subID < 13 || subID > 16)) //no reset for Emissaries
  5757. {
  5758. initialize();
  5759. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 0); //daycounter 0
  5760. if (ID == Obj::DERELICT_SHIP && cb->getDate() > 1)
  5761. {
  5762. cb->setObjProperty (id, ObjProperty::BANK_MULTIPLIER, 0);//ugly hack to make derelict ships usable only once
  5763. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_ARTIFACTS, 0);
  5764. }
  5765. }
  5766. else
  5767. cb->setObjProperty (id, ObjProperty::BANK_DAYCOUNTER, 1); //daycounter++
  5768. }
  5769. }
  5770. bool CBank::wasVisited (PlayerColor player) const
  5771. {
  5772. return !bc;
  5773. }
  5774. void CBank::onHeroVisit (const CGHeroInstance * h) const
  5775. {
  5776. if (bc)
  5777. {
  5778. int banktext = 0;
  5779. switch (ID)
  5780. {
  5781. case Obj::CREATURE_BANK:
  5782. banktext = 32;
  5783. break;
  5784. case Obj::DERELICT_SHIP:
  5785. banktext = 41;
  5786. break;
  5787. case Obj::DRAGON_UTOPIA:
  5788. banktext = 47;
  5789. break;
  5790. case Obj::CRYPT:
  5791. banktext = 119;
  5792. break;
  5793. case Obj::SHIPWRECK:
  5794. banktext = 122;
  5795. break;
  5796. }
  5797. BlockingDialog bd (true, false);
  5798. bd.player = h->getOwner();
  5799. bd.soundID = soundBase::ROGUE;
  5800. bd.text.addTxt(MetaString::ADVOB_TXT,banktext);
  5801. if (ID == Obj::CREATURE_BANK)
  5802. bd.text.addReplacement(VLC->objh->creBanksNames[index]);
  5803. cb->showBlockingDialog (&bd);
  5804. }
  5805. else
  5806. {
  5807. InfoWindow iw;
  5808. iw.soundID = soundBase::GRAVEYARD;
  5809. iw.player = h->getOwner();
  5810. if (ID == Obj::CRYPT) //morale penalty for empty Crypt
  5811. {
  5812. GiveBonus gbonus;
  5813. gbonus.id = h->id.getNum();
  5814. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5815. gbonus.bonus.source = Bonus::OBJECT;
  5816. gbonus.bonus.sid = ID;
  5817. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[98];
  5818. gbonus.bonus.type = Bonus::MORALE;
  5819. gbonus.bonus.val = -1;
  5820. cb->giveHeroBonus(&gbonus);
  5821. iw.text << VLC->generaltexth->advobtxt[120];
  5822. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5823. }
  5824. else
  5825. {
  5826. iw.text << VLC->generaltexth->advobtxt[33];
  5827. iw.text.addReplacement(VLC->objh->creBanksNames[index]);
  5828. }
  5829. cb->showInfoDialog(&iw);
  5830. }
  5831. }
  5832. void CBank::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  5833. {
  5834. if (result.winner == 0)
  5835. {
  5836. int textID = -1;
  5837. InfoWindow iw;
  5838. iw.player = hero->getOwner();
  5839. MetaString loot;
  5840. switch (ID)
  5841. {
  5842. case Obj::CREATURE_BANK: case Obj::DRAGON_UTOPIA:
  5843. textID = 34;
  5844. break;
  5845. case Obj::DERELICT_SHIP:
  5846. if (multiplier)
  5847. textID = 43;
  5848. else
  5849. {
  5850. GiveBonus gbonus;
  5851. gbonus.id = hero->id.getNum();
  5852. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5853. gbonus.bonus.source = Bonus::OBJECT;
  5854. gbonus.bonus.sid = ID;
  5855. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[101];
  5856. gbonus.bonus.type = Bonus::MORALE;
  5857. gbonus.bonus.val = -1;
  5858. cb->giveHeroBonus(&gbonus);
  5859. textID = 42;
  5860. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5861. }
  5862. break;
  5863. case Obj::CRYPT:
  5864. if (bc->resources.size() != 0)
  5865. textID = 121;
  5866. else
  5867. {
  5868. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5869. GiveBonus gbonus;
  5870. gbonus.id = hero->id.getNum();
  5871. gbonus.bonus.duration = Bonus::ONE_BATTLE;
  5872. gbonus.bonus.source = Bonus::OBJECT;
  5873. gbonus.bonus.sid = ID;
  5874. gbonus.bdescr << "\n" << VLC->generaltexth->arraytxt[ID];
  5875. gbonus.bonus.type = Bonus::MORALE;
  5876. gbonus.bonus.val = -1;
  5877. cb->giveHeroBonus(&gbonus);
  5878. textID = 120;
  5879. iw.components.push_back (Component (Component::MORALE, 0 , -1, 0));
  5880. }
  5881. break;
  5882. case Obj::SHIPWRECK:
  5883. if (bc->resources.size())
  5884. textID = 124;
  5885. else
  5886. textID = 123;
  5887. break;
  5888. }
  5889. //grant resources
  5890. if (textID != 42) //empty derelict ship gives no cash
  5891. {
  5892. for (int it = 0; it < bc->resources.size(); it++)
  5893. {
  5894. if (bc->resources[it] != 0)
  5895. {
  5896. iw.components.push_back (Component (Component::RESOURCE, it, bc->resources[it], 0));
  5897. loot << "%d %s";
  5898. loot.addReplacement(iw.components.back().val);
  5899. loot.addReplacement(MetaString::RES_NAMES, iw.components.back().subtype);
  5900. cb->giveResource (hero->getOwner(), static_cast<Res::ERes>(it), bc->resources[it]);
  5901. }
  5902. }
  5903. }
  5904. //grant artifacts
  5905. for (auto & elem : artifacts)
  5906. {
  5907. iw.components.push_back (Component (Component::ARTIFACT, elem, 0, 0));
  5908. loot << "%s";
  5909. loot.addReplacement(MetaString::ART_NAMES, elem);
  5910. cb->giveHeroNewArtifact (hero, VLC->arth->artifacts[elem], ArtifactPosition::FIRST_AVAILABLE);
  5911. }
  5912. //display loot
  5913. if (!iw.components.empty())
  5914. {
  5915. iw.text.addTxt (MetaString::ADVOB_TXT, textID);
  5916. if (textID == 34)
  5917. {
  5918. iw.text.addReplacement(MetaString::CRE_PL_NAMES, result.casualties[1].begin()->first);
  5919. iw.text.addReplacement(loot.buildList());
  5920. }
  5921. cb->showInfoDialog(&iw);
  5922. }
  5923. loot.clear();
  5924. iw.components.clear();
  5925. iw.text.clear();
  5926. //grant creatures
  5927. CCreatureSet ourArmy;
  5928. for (auto it = bc->creatures.cbegin(); it != bc->creatures.cend(); it++)
  5929. {
  5930. SlotID slot = ourArmy.getSlotFor(it->first);
  5931. ourArmy.addToSlot(slot, it->first, it->second);
  5932. }
  5933. for (auto & elem : ourArmy.Slots())
  5934. {
  5935. iw.components.push_back(Component(*elem.second));
  5936. loot << "%s";
  5937. loot.addReplacement(*elem.second);
  5938. }
  5939. if (ourArmy.Slots().size())
  5940. {
  5941. if (ourArmy.Slots().size() == 1 && ourArmy.Slots().begin()->second->count == 1)
  5942. iw.text.addTxt (MetaString::ADVOB_TXT, 185);
  5943. else
  5944. iw.text.addTxt (MetaString::ADVOB_TXT, 186);
  5945. iw.text.addReplacement(loot.buildList());
  5946. iw.text.addReplacement(hero->name);
  5947. cb->showInfoDialog(&iw);
  5948. cb->giveCreatures(this, hero, ourArmy, false);
  5949. }
  5950. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0); //bc = nullptr
  5951. }
  5952. }
  5953. void CBank::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  5954. {
  5955. if (answer)
  5956. {
  5957. cb->startBattleI(hero, this, true);
  5958. }
  5959. }
  5960. void CGPyramid::initObj()
  5961. {
  5962. std::vector<SpellID> available;
  5963. cb->getAllowedSpells (available, 5);
  5964. if (available.size())
  5965. {
  5966. bc = VLC->objh->banksInfo[21].front(); //TODO: remove hardcoded value?
  5967. spell = (available[ran()%available.size()]);
  5968. }
  5969. else
  5970. {
  5971. logGlobal->errorStream() <<"No spells available for Pyramid! Object set to empty.";
  5972. }
  5973. setPropertyDer (ObjProperty::BANK_INIT_ARMY,ran()); //set guards at game start
  5974. }
  5975. const std::string & CGPyramid::getHoverText() const
  5976. {
  5977. hoverName = VLC->objh->creBanksNames[21]+ " " + visitedTxt((bc==nullptr));
  5978. return hoverName;
  5979. }
  5980. void CGPyramid::onHeroVisit (const CGHeroInstance * h) const
  5981. {
  5982. if (bc)
  5983. {
  5984. BlockingDialog bd (true, false);
  5985. bd.player = h->getOwner();
  5986. bd.soundID = soundBase::MYSTERY;
  5987. bd.text << VLC->generaltexth->advobtxt[105];
  5988. cb->showBlockingDialog(&bd);
  5989. }
  5990. else
  5991. {
  5992. InfoWindow iw;
  5993. iw.player = h->getOwner();
  5994. iw.text << VLC->generaltexth->advobtxt[107];
  5995. iw.components.push_back (Component (Component::LUCK, 0 , -2, 0));
  5996. GiveBonus gb;
  5997. gb.bonus = Bonus(Bonus::ONE_BATTLE,Bonus::LUCK,Bonus::OBJECT,-2,id.getNum(),VLC->generaltexth->arraytxt[70]);
  5998. gb.id = h->id.getNum();
  5999. cb->giveHeroBonus(&gb);
  6000. cb->showInfoDialog(&iw);
  6001. }
  6002. }
  6003. void CGPyramid::battleFinished(const CGHeroInstance *hero, const BattleResult &result) const
  6004. {
  6005. if (result.winner == 0)
  6006. {
  6007. InfoWindow iw;
  6008. iw.player = hero->getOwner();
  6009. iw.text.addTxt (MetaString::ADVOB_TXT, 106);
  6010. iw.text.addTxt (MetaString::SPELL_NAME, spell);
  6011. if (!hero->getArt(ArtifactPosition::SPELLBOOK))
  6012. iw.text.addTxt (MetaString::ADVOB_TXT, 109); //no spellbook
  6013. else if (hero->getSecSkillLevel(SecondarySkill::WISDOM) < 3)
  6014. iw.text.addTxt (MetaString::ADVOB_TXT, 108); //no expert Wisdom
  6015. else
  6016. {
  6017. std::set<SpellID> spells;
  6018. spells.insert (SpellID(spell));
  6019. cb->changeSpells (hero, true, spells);
  6020. iw.components.push_back(Component (Component::SPELL, spell, 0, 0));
  6021. }
  6022. cb->showInfoDialog(&iw);
  6023. cb->setObjProperty (id, ObjProperty::BANK_CLEAR_CONFIG, 0);
  6024. }
  6025. }
  6026. void CGKeys::setPropertyDer (ui8 what, ui32 val) //101-108 - enable key for player 1-8
  6027. {
  6028. if (what >= 101 && what <= (100 + PlayerColor::PLAYER_LIMIT_I))
  6029. {
  6030. PlayerColor player(what-101);
  6031. playerKeyMap[player].insert((ui8)val);
  6032. }
  6033. else
  6034. logGlobal->errorStream() << boost::format("Unexpected properties requested to set: what=%d, val=%d") % (int)what % val;
  6035. }
  6036. bool CGKeys::wasMyColorVisited (PlayerColor player) const
  6037. {
  6038. if (vstd::contains(playerKeyMap[player], subID)) //creates set if it's not there
  6039. return true;
  6040. else
  6041. return false;
  6042. }
  6043. const std::string& CGKeys::getHoverText() const
  6044. {
  6045. bool visited = wasMyColorVisited (cb->getLocalPlayer());
  6046. hoverName = getName() + "\n" + visitedTxt(visited);
  6047. return hoverName;
  6048. }
  6049. const std::string CGKeys::getName() const
  6050. {
  6051. std::string name;
  6052. name = VLC->generaltexth->tentColors[subID] + " " + VLC->generaltexth->names[ID];
  6053. return name;
  6054. }
  6055. bool CGKeymasterTent::wasVisited (PlayerColor player) const
  6056. {
  6057. return wasMyColorVisited (player);
  6058. }
  6059. void CGKeymasterTent::onHeroVisit( const CGHeroInstance * h ) const
  6060. {
  6061. int txt_id;
  6062. if (!wasMyColorVisited (h->getOwner()) )
  6063. {
  6064. cb->setObjProperty(id, h->tempOwner.getNum()+101, subID);
  6065. txt_id=19;
  6066. }
  6067. else
  6068. txt_id=20;
  6069. showInfoDialog(h,txt_id,soundBase::CAVEHEAD);
  6070. }
  6071. void CGBorderGuard::initObj()
  6072. {
  6073. //ui32 m13489val = subID; //store color as quest info
  6074. blockVisit = true;
  6075. }
  6076. void CGBorderGuard::getVisitText (MetaString &text, std::vector<Component> &components, bool isCustom, bool FirstVisit, const CGHeroInstance * h) const
  6077. {
  6078. text << std::pair<ui8,ui32>(11,18);
  6079. }
  6080. void CGBorderGuard::getRolloverText (MetaString &text, bool onHover) const
  6081. {
  6082. if (!onHover)
  6083. text << VLC->generaltexth->tentColors[subID] << " " << VLC->generaltexth->names[Obj::KEYMASTER];
  6084. }
  6085. bool CGBorderGuard::checkQuest (const CGHeroInstance * h) const
  6086. {
  6087. return wasMyColorVisited (h->tempOwner);
  6088. }
  6089. void CGBorderGuard::onHeroVisit( const CGHeroInstance * h ) const
  6090. {
  6091. if (wasMyColorVisited (h->getOwner()) )
  6092. {
  6093. BlockingDialog bd (true, false);
  6094. bd.player = h->getOwner();
  6095. bd.soundID = soundBase::QUEST;
  6096. bd.text.addTxt (MetaString::ADVOB_TXT, 17);
  6097. cb->showBlockingDialog (&bd);
  6098. }
  6099. else
  6100. {
  6101. showInfoDialog(h,18,soundBase::CAVEHEAD);
  6102. AddQuest aq;
  6103. aq.quest = QuestInfo (quest, this, visitablePos());
  6104. aq.player = h->tempOwner;
  6105. cb->sendAndApply (&aq);
  6106. //TODO: add this quest only once OR check for multiple instances later
  6107. }
  6108. }
  6109. void CGBorderGuard::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6110. {
  6111. if (answer)
  6112. cb->removeObject(this);
  6113. }
  6114. void CGBorderGate::onHeroVisit( const CGHeroInstance * h ) const //TODO: passability
  6115. {
  6116. if (!wasMyColorVisited (h->getOwner()) )
  6117. {
  6118. showInfoDialog(h,18,0);
  6119. AddQuest aq;
  6120. aq.quest = QuestInfo (quest, this, visitablePos());
  6121. aq.player = h->tempOwner;
  6122. cb->sendAndApply (&aq);
  6123. }
  6124. }
  6125. ui8 CGBorderGate::getPassableness() const
  6126. {
  6127. ui8 ret = 0;
  6128. for (int i = 0; i < PlayerColor::PLAYER_LIMIT_I; i++)
  6129. ret |= wasMyColorVisited(PlayerColor(i))<<i;
  6130. return ret;
  6131. }
  6132. void CGMagi::initObj()
  6133. {
  6134. if (ID == Obj::EYE_OF_MAGI)
  6135. {
  6136. blockVisit = true;
  6137. eyelist[subID].push_back(id);
  6138. }
  6139. }
  6140. void CGMagi::onHeroVisit(const CGHeroInstance * h) const
  6141. {
  6142. if (ID == Obj::HUT_OF_MAGI)
  6143. {
  6144. showInfoDialog(h, 61, soundBase::LIGHTHOUSE);
  6145. if (!eyelist[subID].empty())
  6146. {
  6147. CenterView cv;
  6148. cv.player = h->tempOwner;
  6149. cv.focusTime = 2000;
  6150. FoWChange fw;
  6151. fw.player = h->tempOwner;
  6152. fw.mode = 1;
  6153. for(auto it : eyelist[subID])
  6154. {
  6155. const CGObjectInstance *eye = cb->getObj(it);
  6156. cb->getTilesInRange (fw.tiles, eye->pos, 10, h->tempOwner, 1);
  6157. cb->sendAndApply(&fw);
  6158. cv.pos = eye->pos;
  6159. cb->sendAndApply(&cv);
  6160. }
  6161. cv.pos = h->getPosition(false);
  6162. cb->sendAndApply(&cv);
  6163. }
  6164. }
  6165. else if (ID == Obj::EYE_OF_MAGI)
  6166. {
  6167. showInfoDialog(h,48,soundBase::invalid);
  6168. }
  6169. }
  6170. void CGBoat::initObj()
  6171. {
  6172. hero = nullptr;
  6173. }
  6174. void CGSirens::initObj()
  6175. {
  6176. blockVisit = true;
  6177. }
  6178. const std::string & CGSirens::getHoverText() const
  6179. {
  6180. getNameVis(hoverName);
  6181. return hoverName;
  6182. }
  6183. void CGSirens::onHeroVisit( const CGHeroInstance * h ) const
  6184. {
  6185. InfoWindow iw;
  6186. iw.soundID = soundBase::DANGER;
  6187. iw.player = h->tempOwner;
  6188. if(h->hasBonusFrom(Bonus::OBJECT,ID)) //has already visited Sirens
  6189. {
  6190. iw.text.addTxt(MetaString::ADVOB_TXT,133);
  6191. }
  6192. else
  6193. {
  6194. giveDummyBonus(h->id, Bonus::ONE_BATTLE);
  6195. TExpType xp = 0;
  6196. for (auto i = h->Slots().begin(); i != h->Slots().end(); i++)
  6197. {
  6198. TQuantity drown = i->second->count * 0.3;
  6199. if(drown)
  6200. {
  6201. cb->changeStackCount(StackLocation(h, i->first), -drown);
  6202. xp += drown * i->second->type->valOfBonuses(Bonus::STACK_HEALTH);
  6203. }
  6204. }
  6205. if(xp)
  6206. {
  6207. xp = h->calculateXp(xp);
  6208. iw.text.addTxt(MetaString::ADVOB_TXT,132);
  6209. iw.text.addReplacement(xp);
  6210. cb->changePrimSkill(h, PrimarySkill::EXPERIENCE, xp, false);
  6211. }
  6212. else
  6213. {
  6214. iw.text.addTxt(MetaString::ADVOB_TXT,134);
  6215. }
  6216. }
  6217. cb->showInfoDialog(&iw);
  6218. }
  6219. //bool IShipyard::validLocation() const
  6220. //{
  6221. // std::vector<int3> offsets;
  6222. // getOutOffsets(offsets);
  6223. //
  6224. // TerrainTile *tile;
  6225. // for(int i = 0; i < offsets.size(); i++)
  6226. // if((tile = IObjectInterface::cb->getTile(o->pos + offsets[i])) && tile->terType == TerrainTile::water) //tile is in the map and is water
  6227. // return true;
  6228. // return false;
  6229. //}
  6230. int3 IBoatGenerator::bestLocation() const
  6231. {
  6232. std::vector<int3> offsets;
  6233. getOutOffsets(offsets);
  6234. for (auto & offset : offsets)
  6235. {
  6236. if (const TerrainTile *tile = IObjectInterface::cb->getTile(o->pos + offset, false)) //tile is in the map
  6237. {
  6238. if (tile->terType == ETerrainType::WATER && (!tile->blocked || tile->blockingObjects.front()->ID == 8)) //and is water and is not blocked or is blocked by boat
  6239. return o->pos + offset;
  6240. }
  6241. }
  6242. return int3 (-1,-1,-1);
  6243. }
  6244. IBoatGenerator::EGeneratorState IBoatGenerator::shipyardStatus() const
  6245. {
  6246. int3 tile = bestLocation();
  6247. const TerrainTile *t = IObjectInterface::cb->getTile(tile);
  6248. if(!t)
  6249. return TILE_BLOCKED; //no available water
  6250. else if(!t->blockingObjects.size())
  6251. return GOOD; //OK
  6252. else if(t->blockingObjects.front()->ID == Obj::BOAT)
  6253. return BOAT_ALREADY_BUILT; //blocked with boat
  6254. else
  6255. return TILE_BLOCKED; //blocked
  6256. }
  6257. int IBoatGenerator::getBoatType() const
  6258. {
  6259. //We make good ships by default
  6260. return 1;
  6261. }
  6262. IBoatGenerator::IBoatGenerator(const CGObjectInstance *O)
  6263. : o(O)
  6264. {
  6265. }
  6266. void IBoatGenerator::getProblemText(MetaString &out, const CGHeroInstance *visitor) const
  6267. {
  6268. switch(shipyardStatus())
  6269. {
  6270. case BOAT_ALREADY_BUILT:
  6271. out.addTxt(MetaString::GENERAL_TXT, 51);
  6272. break;
  6273. case TILE_BLOCKED:
  6274. if(visitor)
  6275. {
  6276. out.addTxt(MetaString::GENERAL_TXT, 134);
  6277. out.addReplacement(visitor->name);
  6278. }
  6279. else
  6280. out.addTxt(MetaString::ADVOB_TXT, 189);
  6281. break;
  6282. case NO_WATER:
  6283. logGlobal->errorStream() << "Shipyard without water!!! " << o->pos << "\t" << o->id;
  6284. return;
  6285. }
  6286. }
  6287. void IShipyard::getBoatCost( std::vector<si32> &cost ) const
  6288. {
  6289. cost.resize(GameConstants::RESOURCE_QUANTITY);
  6290. cost[Res::WOOD] = 10;
  6291. cost[Res::GOLD] = 1000;
  6292. }
  6293. IShipyard::IShipyard(const CGObjectInstance *O)
  6294. : IBoatGenerator(O)
  6295. {
  6296. }
  6297. IShipyard * IShipyard::castFrom( CGObjectInstance *obj )
  6298. {
  6299. if(!obj)
  6300. return nullptr;
  6301. if(obj->ID == Obj::TOWN)
  6302. {
  6303. return static_cast<CGTownInstance*>(obj);
  6304. }
  6305. else if(obj->ID == Obj::SHIPYARD)
  6306. {
  6307. return static_cast<CGShipyard*>(obj);
  6308. }
  6309. else
  6310. {
  6311. return nullptr;
  6312. }
  6313. }
  6314. const IShipyard * IShipyard::castFrom( const CGObjectInstance *obj )
  6315. {
  6316. return castFrom(const_cast<CGObjectInstance*>(obj));
  6317. }
  6318. CGShipyard::CGShipyard()
  6319. :IShipyard(this)
  6320. {
  6321. }
  6322. void CGShipyard::getOutOffsets( std::vector<int3> &offsets ) const
  6323. {
  6324. // H J L K I
  6325. // A x S x B
  6326. // C E G F D
  6327. offsets += int3(-3,0,0), int3(1,0,0), //AB
  6328. int3(-3,1,0), int3(1,1,0), int3(-2,1,0), int3(0,1,0), int3(-1,1,0), //CDEFG
  6329. int3(-3,-1,0), int3(1,-1,0), int3(-2,-1,0), int3(0,-1,0), int3(-1,-1,0); //HIJKL
  6330. }
  6331. void CGShipyard::onHeroVisit( const CGHeroInstance * h ) const
  6332. {
  6333. if(!cb->gameState()->getPlayerRelations(tempOwner, h->tempOwner))
  6334. cb->setOwner(this, h->tempOwner);
  6335. auto s = shipyardStatus();
  6336. if(s != IBoatGenerator::GOOD)
  6337. {
  6338. InfoWindow iw;
  6339. iw.player = tempOwner;
  6340. getProblemText(iw.text, h);
  6341. cb->showInfoDialog(&iw);
  6342. }
  6343. else
  6344. {
  6345. openWindow(OpenWindow::SHIPYARD_WINDOW,id.getNum(),h->id.getNum());
  6346. }
  6347. }
  6348. void CCartographer::onHeroVisit( const CGHeroInstance * h ) const
  6349. {
  6350. if (!wasVisited (h->getOwner()) ) //if hero has not visited yet this cartographer
  6351. {
  6352. if (cb->getResource(h->tempOwner, Res::GOLD) >= 1000) //if he can afford a map
  6353. {
  6354. //ask if he wants to buy one
  6355. int text=0;
  6356. switch (subID)
  6357. {
  6358. case 0:
  6359. text = 25;
  6360. break;
  6361. case 1:
  6362. text = 26;
  6363. break;
  6364. case 2:
  6365. text = 27;
  6366. break;
  6367. default:
  6368. logGlobal->warnStream() << "Unrecognized subtype of cartographer";
  6369. }
  6370. assert(text);
  6371. BlockingDialog bd (true, false);
  6372. bd.player = h->getOwner();
  6373. bd.soundID = soundBase::LIGHTHOUSE;
  6374. bd.text.addTxt (MetaString::ADVOB_TXT, text);
  6375. cb->showBlockingDialog (&bd);
  6376. }
  6377. else //if he cannot afford
  6378. {
  6379. showInfoDialog(h,28,soundBase::CAVEHEAD);
  6380. }
  6381. }
  6382. else //if he already visited carographer
  6383. {
  6384. showInfoDialog(h,24,soundBase::CAVEHEAD);
  6385. }
  6386. }
  6387. void CCartographer::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
  6388. {
  6389. if (answer) //if hero wants to buy map
  6390. {
  6391. cb->giveResource (hero->tempOwner, Res::GOLD, -1000);
  6392. FoWChange fw;
  6393. fw.mode = 1;
  6394. fw.player = hero->tempOwner;
  6395. //subIDs of different types of cartographers:
  6396. //water = 0; land = 1; underground = 2;
  6397. cb->getAllTiles (fw.tiles, hero->tempOwner, subID - 1, !subID + 1); //reveal appropriate tiles
  6398. cb->sendAndApply (&fw);
  6399. cb->setObjProperty (id, 10, hero->tempOwner.getNum());
  6400. }
  6401. }
  6402. void CGDenOfthieves::onHeroVisit (const CGHeroInstance * h) const
  6403. {
  6404. cb->showThievesGuildWindow(h->tempOwner, id);
  6405. }
  6406. void CGObelisk::onHeroVisit( const CGHeroInstance * h ) const
  6407. {
  6408. InfoWindow iw;
  6409. iw.player = h->tempOwner;
  6410. TeamState *ts = cb->gameState()->getPlayerTeam(h->tempOwner);
  6411. assert(ts);
  6412. TeamID team = ts->id;
  6413. if(!wasVisited(team))
  6414. {
  6415. iw.text.addTxt(MetaString::ADVOB_TXT, 96);
  6416. cb->sendAndApply(&iw);
  6417. cb->setObjProperty(id, 20, h->tempOwner.getNum()); //increment general visited obelisks counter
  6418. openWindow(OpenWindow::PUZZLE_MAP, h->tempOwner.getNum());
  6419. cb->setObjProperty(id, 10, h->tempOwner.getNum()); //mark that particular obelisk as visited
  6420. }
  6421. else
  6422. {
  6423. iw.text.addTxt(MetaString::ADVOB_TXT, 97);
  6424. cb->sendAndApply(&iw);
  6425. }
  6426. }
  6427. void CGObelisk::initObj()
  6428. {
  6429. obeliskCount++;
  6430. }
  6431. const std::string & CGObelisk::getHoverText() const
  6432. {
  6433. bool visited = wasVisited(cb->getLocalPlayer());
  6434. hoverName = VLC->generaltexth->names[ID] + " " + visitedTxt(visited);
  6435. return hoverName;
  6436. }
  6437. void CGObelisk::setPropertyDer( ui8 what, ui32 val )
  6438. {
  6439. CPlayersVisited::setPropertyDer(what, val);
  6440. switch(what)
  6441. {
  6442. case 20:
  6443. assert(val < PlayerColor::PLAYER_LIMIT_I);
  6444. visited[TeamID(val)]++;
  6445. if(visited[TeamID(val)] > obeliskCount)
  6446. {
  6447. logGlobal->errorStream() << "Error: Visited " << visited[TeamID(val)] << "\t\t" << obeliskCount;
  6448. assert(0);
  6449. }
  6450. break;
  6451. }
  6452. }
  6453. void CGLighthouse::onHeroVisit( const CGHeroInstance * h ) const
  6454. {
  6455. if(h->tempOwner != tempOwner)
  6456. {
  6457. PlayerColor oldOwner = tempOwner;
  6458. cb->setOwner(this,h->tempOwner); //not ours? flag it!
  6459. showInfoDialog(h,69,soundBase::LIGHTHOUSE);
  6460. giveBonusTo(h->tempOwner);
  6461. if(oldOwner < PlayerColor::PLAYER_LIMIT) //remove bonus from old owner
  6462. {
  6463. RemoveBonus rb(RemoveBonus::PLAYER);
  6464. rb.whoID = oldOwner.getNum();
  6465. rb.source = Bonus::OBJECT;
  6466. rb.id = id.getNum();
  6467. cb->sendAndApply(&rb);
  6468. }
  6469. }
  6470. }
  6471. void CGLighthouse::initObj()
  6472. {
  6473. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6474. {
  6475. giveBonusTo(tempOwner);
  6476. }
  6477. }
  6478. const std::string & CGLighthouse::getHoverText() const
  6479. {
  6480. hoverName = VLC->generaltexth->names[ID];
  6481. //TODO: owned by %s player
  6482. return hoverName;
  6483. }
  6484. void CGLighthouse::giveBonusTo( PlayerColor player ) const
  6485. {
  6486. GiveBonus gb(GiveBonus::PLAYER);
  6487. gb.bonus.type = Bonus::SEA_MOVEMENT;
  6488. gb.bonus.val = 500;
  6489. gb.id = player.getNum();
  6490. gb.bonus.duration = Bonus::PERMANENT;
  6491. gb.bonus.source = Bonus::OBJECT;
  6492. gb.bonus.sid = id.getNum();
  6493. cb->sendAndApply(&gb);
  6494. }
  6495. void CArmedInstance::randomizeArmy(int type)
  6496. {
  6497. for (auto & elem : stacks)
  6498. {
  6499. int & randID = elem.second->idRand;
  6500. if(randID >= 0)
  6501. {
  6502. int level = randID / 2;
  6503. bool upgrade = randID % 2;
  6504. elem.second->setType(VLC->townh->factions[type]->town->creatures[level][upgrade]);
  6505. randID = -1;
  6506. }
  6507. assert(elem.second->valid(false));
  6508. assert(elem.second->armyObj == this);
  6509. }
  6510. return;
  6511. }
  6512. CArmedInstance::CArmedInstance()
  6513. {
  6514. battle = nullptr;
  6515. }
  6516. //int CArmedInstance::valOfGlobalBonuses(CSelector selector) const
  6517. //{
  6518. //// if (tempOwner != NEUTRAL_PLAYER)
  6519. // return cb->gameState()->players[tempOwner].valOfBonuses(selector);
  6520. //}
  6521. void CArmedInstance::updateMoraleBonusFromArmy()
  6522. {
  6523. if(!validTypes(false)) //object not randomized, don't bother
  6524. return;
  6525. Bonus *b = getBonusList().getFirst(Selector::sourceType(Bonus::ARMY).And(Selector::type(Bonus::MORALE)));
  6526. if(!b)
  6527. {
  6528. b = new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, 0, -1);
  6529. addNewBonus(b);
  6530. }
  6531. //number of alignments and presence of undead
  6532. std::set<TFaction> factions;
  6533. bool hasUndead = false;
  6534. for(auto slot : Slots())
  6535. {
  6536. const CStackInstance * inst = slot.second;
  6537. const CCreature * creature = VLC->creh->creatures[inst->getCreatureID()];
  6538. factions.insert(creature->faction);
  6539. // Check for undead flag instead of faction (undead mummies are neutral)
  6540. hasUndead |= inst->hasBonusOfType(Bonus::UNDEAD);
  6541. }
  6542. size_t factionsInArmy = factions.size(); //town garrison seems to take both sets into account
  6543. // Take Angelic Alliance troop-mixing freedom of non-evil units into account.
  6544. if (hasBonusOfType(Bonus::NONEVIL_ALIGNMENT_MIX))
  6545. {
  6546. size_t mixableFactions = 0;
  6547. for(TFaction f : factions)
  6548. {
  6549. if (VLC->townh->factions[f]->alignment != EAlignment::EVIL)
  6550. mixableFactions++;
  6551. }
  6552. if (mixableFactions > 0)
  6553. factionsInArmy -= mixableFactions - 1;
  6554. }
  6555. if(factionsInArmy == 1)
  6556. {
  6557. b->val = +1;
  6558. b->description = VLC->generaltexth->arraytxt[115]; //All troops of one alignment +1
  6559. }
  6560. else if (!factions.empty()) // no bonus from empty garrison
  6561. {
  6562. b->val = 2 - factionsInArmy;
  6563. b->description = boost::str(boost::format(VLC->generaltexth->arraytxt[114]) % factionsInArmy % b->val); //Troops of %d alignments %d
  6564. }
  6565. boost::algorithm::trim(b->description);
  6566. //-1 modifier for any Undead unit in army
  6567. const ui8 UNDEAD_MODIFIER_ID = -2;
  6568. Bonus *undeadModifier = getBonusList().getFirst(Selector::source(Bonus::ARMY, UNDEAD_MODIFIER_ID));
  6569. if(hasUndead)
  6570. {
  6571. if(!undeadModifier)
  6572. addNewBonus(new Bonus(Bonus::PERMANENT, Bonus::MORALE, Bonus::ARMY, -1, UNDEAD_MODIFIER_ID, VLC->generaltexth->arraytxt[116]));
  6573. }
  6574. else if(undeadModifier)
  6575. removeBonus(undeadModifier);
  6576. }
  6577. void CArmedInstance::armyChanged()
  6578. {
  6579. updateMoraleBonusFromArmy();
  6580. }
  6581. CBonusSystemNode * CArmedInstance::whereShouldBeAttached(CGameState *gs)
  6582. {
  6583. if(tempOwner < PlayerColor::PLAYER_LIMIT)
  6584. return gs->getPlayer(tempOwner);
  6585. else
  6586. return &gs->globalEffects;
  6587. }
  6588. CBonusSystemNode * CArmedInstance::whatShouldBeAttached()
  6589. {
  6590. return this;
  6591. }
  6592. bool IMarket::getOffer(int id1, int id2, int &val1, int &val2, EMarketMode::EMarketMode mode) const
  6593. {
  6594. switch(mode)
  6595. {
  6596. case EMarketMode::RESOURCE_RESOURCE:
  6597. {
  6598. double effectiveness = std::min((getMarketEfficiency() + 1.0) / 20.0, 0.5);
  6599. double r = VLC->objh->resVals[id1], //value of given resource
  6600. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6601. if(r>g) //if given resource is more expensive than wanted
  6602. {
  6603. val2 = ceil(r / g);
  6604. val1 = 1;
  6605. }
  6606. else //if wanted resource is more expensive
  6607. {
  6608. val1 = (g / r) + 0.5;
  6609. val2 = 1;
  6610. }
  6611. }
  6612. break;
  6613. case EMarketMode::CREATURE_RESOURCE:
  6614. {
  6615. const double effectivenessArray[] = {0.0, 0.3, 0.45, 0.50, 0.65, 0.7, 0.85, 0.9, 1.0};
  6616. double effectiveness = effectivenessArray[std::min(getMarketEfficiency(), 8)];
  6617. double r = VLC->creh->creatures[id1]->cost[6], //value of given creature in gold
  6618. g = VLC->objh->resVals[id2] / effectiveness; //value of wanted resource
  6619. if(r>g) //if given resource is more expensive than wanted
  6620. {
  6621. val2 = ceil(r / g);
  6622. val1 = 1;
  6623. }
  6624. else //if wanted resource is more expensive
  6625. {
  6626. val1 = (g / r) + 0.5;
  6627. val2 = 1;
  6628. }
  6629. }
  6630. break;
  6631. case EMarketMode::RESOURCE_PLAYER:
  6632. val1 = 1;
  6633. val2 = 1;
  6634. break;
  6635. case EMarketMode::RESOURCE_ARTIFACT:
  6636. {
  6637. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6638. double r = VLC->objh->resVals[id1], //value of offered resource
  6639. g = VLC->arth->artifacts[id2]->price / effectiveness; //value of bought artifact in gold
  6640. if(id1 != 6) //non-gold prices are doubled
  6641. r /= 2;
  6642. val1 = std::max(1, (int)((g / r) + 0.5)); //don't sell arts for less than 1 resource
  6643. val2 = 1;
  6644. }
  6645. break;
  6646. case EMarketMode::ARTIFACT_RESOURCE:
  6647. {
  6648. double effectiveness = std::min((getMarketEfficiency() + 3.0) / 20.0, 0.6);
  6649. double r = VLC->arth->artifacts[id1]->price * effectiveness,
  6650. g = VLC->objh->resVals[id2];
  6651. // if(id2 != 6) //non-gold prices are doubled
  6652. // r /= 2;
  6653. val1 = 1;
  6654. val2 = std::max(1, (int)((r / g) + 0.5)); //at least one resource is given in return
  6655. }
  6656. break;
  6657. case EMarketMode::CREATURE_EXP:
  6658. {
  6659. val1 = 1;
  6660. val2 = (VLC->creh->creatures[id1]->AIValue / 40) * 5;
  6661. }
  6662. break;
  6663. case EMarketMode::ARTIFACT_EXP:
  6664. {
  6665. val1 = 1;
  6666. int givenClass = VLC->arth->artifacts[id1]->getArtClassSerial();
  6667. if(givenClass < 0 || givenClass > 3)
  6668. {
  6669. val2 = 0;
  6670. return false;
  6671. }
  6672. static const int expPerClass[] = {1000, 1500, 3000, 6000};
  6673. val2 = expPerClass[givenClass];
  6674. }
  6675. break;
  6676. default:
  6677. assert(0);
  6678. return false;
  6679. }
  6680. return true;
  6681. }
  6682. bool IMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6683. {
  6684. return false;
  6685. }
  6686. int IMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6687. {
  6688. switch(mode)
  6689. {
  6690. case EMarketMode::RESOURCE_RESOURCE:
  6691. case EMarketMode::ARTIFACT_RESOURCE:
  6692. case EMarketMode::CREATURE_RESOURCE:
  6693. return -1;
  6694. default:
  6695. return 1;
  6696. }
  6697. }
  6698. std::vector<int> IMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6699. {
  6700. std::vector<int> ret;
  6701. switch(mode)
  6702. {
  6703. case EMarketMode::RESOURCE_RESOURCE:
  6704. case EMarketMode::ARTIFACT_RESOURCE:
  6705. case EMarketMode::CREATURE_RESOURCE:
  6706. for (int i = 0; i < 7; i++)
  6707. ret.push_back(i);
  6708. }
  6709. return ret;
  6710. }
  6711. const IMarket * IMarket::castFrom(const CGObjectInstance *obj, bool verbose /*= true*/)
  6712. {
  6713. switch(obj->ID)
  6714. {
  6715. case Obj::TOWN:
  6716. return static_cast<const CGTownInstance*>(obj);
  6717. case Obj::ALTAR_OF_SACRIFICE:
  6718. case Obj::BLACK_MARKET:
  6719. case Obj::TRADING_POST:
  6720. case Obj::TRADING_POST_SNOW:
  6721. case Obj::FREELANCERS_GUILD:
  6722. return static_cast<const CGMarket*>(obj);
  6723. case Obj::UNIVERSITY:
  6724. return static_cast<const CGUniversity*>(obj);
  6725. default:
  6726. if(verbose)
  6727. logGlobal->errorStream() << "Cannot cast to IMarket object with ID " << obj->ID;
  6728. return nullptr;
  6729. }
  6730. }
  6731. IMarket::IMarket(const CGObjectInstance *O)
  6732. :o(O)
  6733. {
  6734. }
  6735. std::vector<EMarketMode::EMarketMode> IMarket::availableModes() const
  6736. {
  6737. std::vector<EMarketMode::EMarketMode> ret;
  6738. for (int i = 0; i < EMarketMode::MARTKET_AFTER_LAST_PLACEHOLDER; i++)
  6739. if(allowsTrade((EMarketMode::EMarketMode)i))
  6740. ret.push_back((EMarketMode::EMarketMode)i);
  6741. return ret;
  6742. }
  6743. void CGMarket::onHeroVisit(const CGHeroInstance * h) const
  6744. {
  6745. openWindow(OpenWindow::MARKET_WINDOW,id.getNum(),h->id.getNum());
  6746. }
  6747. int CGMarket::getMarketEfficiency() const
  6748. {
  6749. return 5;
  6750. }
  6751. bool CGMarket::allowsTrade(EMarketMode::EMarketMode mode) const
  6752. {
  6753. switch(mode)
  6754. {
  6755. case EMarketMode::RESOURCE_RESOURCE:
  6756. case EMarketMode::RESOURCE_PLAYER:
  6757. switch(ID)
  6758. {
  6759. case Obj::TRADING_POST:
  6760. case Obj::TRADING_POST_SNOW:
  6761. return true;
  6762. default:
  6763. return false;
  6764. }
  6765. case EMarketMode::CREATURE_RESOURCE:
  6766. return ID == Obj::FREELANCERS_GUILD;
  6767. //case ARTIFACT_RESOURCE:
  6768. case EMarketMode::RESOURCE_ARTIFACT:
  6769. return ID == Obj::BLACK_MARKET;
  6770. case EMarketMode::ARTIFACT_EXP:
  6771. case EMarketMode::CREATURE_EXP:
  6772. return ID == Obj::ALTAR_OF_SACRIFICE; //TODO? check here for alignment of visiting hero? - would not be coherent with other checks here
  6773. case EMarketMode::RESOURCE_SKILL:
  6774. return ID == Obj::UNIVERSITY;
  6775. default:
  6776. return false;
  6777. }
  6778. }
  6779. int CGMarket::availableUnits(EMarketMode::EMarketMode mode, int marketItemSerial) const
  6780. {
  6781. return -1;
  6782. }
  6783. std::vector<int> CGMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6784. {
  6785. switch(mode)
  6786. {
  6787. case EMarketMode::RESOURCE_RESOURCE:
  6788. case EMarketMode::RESOURCE_PLAYER:
  6789. return IMarket::availableItemsIds(mode);
  6790. default:
  6791. return std::vector<int>();
  6792. }
  6793. }
  6794. CGMarket::CGMarket()
  6795. :IMarket(this)
  6796. {
  6797. }
  6798. std::vector<int> CGBlackMarket::availableItemsIds(EMarketMode::EMarketMode mode) const
  6799. {
  6800. switch(mode)
  6801. {
  6802. case EMarketMode::ARTIFACT_RESOURCE:
  6803. return IMarket::availableItemsIds(mode);
  6804. case EMarketMode::RESOURCE_ARTIFACT:
  6805. {
  6806. std::vector<int> ret;
  6807. for(const CArtifact *a : artifacts)
  6808. if(a)
  6809. ret.push_back(a->id);
  6810. else
  6811. ret.push_back(-1);
  6812. return ret;
  6813. }
  6814. default:
  6815. return std::vector<int>();
  6816. }
  6817. }
  6818. void CGBlackMarket::newTurn() const
  6819. {
  6820. if(cb->getDate(Date::DAY_OF_MONTH) != 1) //new month
  6821. return;
  6822. SetAvailableArtifacts saa;
  6823. saa.id = id.getNum();
  6824. cb->pickAllowedArtsSet(saa.arts);
  6825. cb->sendAndApply(&saa);
  6826. }
  6827. void CGUniversity::initObj()
  6828. {
  6829. std::vector <int> toChoose;
  6830. for (int i=0; i<GameConstants::SKILL_QUANTITY; i++)
  6831. if (cb->isAllowed(2,i))
  6832. toChoose.push_back(i);
  6833. if (toChoose.size() < 4)
  6834. {
  6835. logGlobal->warnStream()<<"Warning: less then 4 available skills was found by University initializer!";
  6836. return;
  6837. }
  6838. for (int i=0; i<4; i++)//get 4 skills
  6839. {
  6840. int skillPos = ran()%toChoose.size();
  6841. skills.push_back(toChoose[skillPos]);//move it to selected
  6842. toChoose.erase(toChoose.begin()+skillPos);//remove from list
  6843. }
  6844. }
  6845. std::vector<int> CGUniversity::availableItemsIds(EMarketMode::EMarketMode mode) const
  6846. {
  6847. switch (mode)
  6848. {
  6849. case EMarketMode::RESOURCE_SKILL:
  6850. return skills;
  6851. default:
  6852. return std::vector <int> ();
  6853. }
  6854. }
  6855. void CGUniversity::onHeroVisit(const CGHeroInstance * h) const
  6856. {
  6857. openWindow(OpenWindow::UNIVERSITY_WINDOW,id.getNum(),h->id.getNum());
  6858. }
  6859. GrowthInfo::Entry::Entry(const std::string &format, int _count)
  6860. : count(_count)
  6861. {
  6862. description = boost::str(boost::format(format) % count);
  6863. }
  6864. GrowthInfo::Entry::Entry(int subID, BuildingID building, int _count)
  6865. : count(_count)
  6866. {
  6867. description = boost::str(boost::format("%s %+d") % VLC->townh->factions[subID]->town->buildings.at(building)->Name() % count);
  6868. }
  6869. CTownAndVisitingHero::CTownAndVisitingHero()
  6870. {
  6871. setNodeType(TOWN_AND_VISITOR);
  6872. }
  6873. int GrowthInfo::totalGrowth() const
  6874. {
  6875. int ret = 0;
  6876. for(const Entry &entry : entries)
  6877. ret += entry.count;
  6878. return ret;
  6879. }