CObjectHandler.cpp 203 KB

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