CObjectHandler.cpp 194 KB

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