CObjectHandler.cpp 202 KB

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