CObjectHandler.cpp 209 KB

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