CObjectHandler.cpp 203 KB

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