CObjectHandler.cpp 193 KB

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