CObjectHandler.cpp 199 KB

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