Scene.cs 262 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Timers;
  36. using System.Xml;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.Packets;
  40. using OpenMetaverse.Imaging;
  41. using OpenMetaverse.StructuredData;
  42. using OpenSim.Framework;
  43. using OpenSim.Framework.Monitoring;
  44. using OpenSim.Services.Interfaces;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.Framework.Scenes.Scripting;
  48. using OpenSim.Region.Framework.Scenes.Serialization;
  49. using OpenSim.Region.PhysicsModules.SharedBase;
  50. using Timer = System.Timers.Timer;
  51. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  52. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  53. using PermissionMask = OpenSim.Framework.PermissionMask;
  54. namespace OpenSim.Region.Framework.Scenes
  55. {
  56. public delegate bool FilterAvatarList(ScenePresence avatar);
  57. public partial class Scene : SceneBase
  58. {
  59. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  60. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  61. public delegate void SynchronizeSceneHandler(Scene scene);
  62. #region Fields
  63. /// <summary>
  64. /// Show debug information about animations.
  65. /// </summary>
  66. public bool DebugAnimations { get; set; }
  67. /// <summary>
  68. /// Show debug information about teleports.
  69. /// </summary>
  70. public bool DebugTeleporting { get; set; }
  71. /// <summary>
  72. /// Show debug information about the scene loop.
  73. /// </summary>
  74. public bool DebugUpdates { get; set; }
  75. /// <summary>
  76. /// If true then the scene is saved to persistent storage periodically, every m_update_backup frames and
  77. /// if objects meet required conditions (m_dontPersistBefore and m_dontPersistAfter).
  78. /// </summary>
  79. /// <remarks>
  80. /// Even if false, the scene will still be saved on clean shutdown.
  81. /// FIXME: Currently, setting this to false will mean that objects are not periodically returned from parcels.
  82. /// This needs to be fixed.
  83. /// </remarks>
  84. public bool PeriodicBackup { get; set; }
  85. /// <summary>
  86. /// If false then the scene is never saved to persistence storage even if PeriodicBackup == true and even
  87. /// if the scene is being shut down for the final time.
  88. /// </summary>
  89. public bool UseBackup { get; set; }
  90. /// <summary>
  91. /// If false then physical objects are disabled, though collisions will continue as normal.
  92. /// </summary>
  93. public bool PhysicsEnabled
  94. {
  95. get
  96. {
  97. return m_physicsEnabled;
  98. }
  99. set
  100. {
  101. m_physicsEnabled = value;
  102. if (PhysicsScene != null)
  103. {
  104. IPhysicsParameters physScene = PhysicsScene as IPhysicsParameters;
  105. if (physScene != null)
  106. physScene.SetPhysicsParameter(
  107. "Active", m_physicsEnabled.ToString(), PhysParameterEntry.APPLY_TO_NONE);
  108. }
  109. }
  110. }
  111. private bool m_physicsEnabled;
  112. /// <summary>
  113. /// If false then scripts are not enabled on the smiulator
  114. /// </summary>
  115. public bool ScriptsEnabled
  116. {
  117. get { return m_scripts_enabled; }
  118. set
  119. {
  120. if (m_scripts_enabled != value)
  121. {
  122. if (!value)
  123. {
  124. m_log.Info("Stopping all Scripts in Scene");
  125. EntityBase[] entities = Entities.GetEntities();
  126. foreach (EntityBase ent in entities)
  127. {
  128. if (ent is SceneObjectGroup)
  129. ((SceneObjectGroup)ent).RemoveScriptInstances(false);
  130. }
  131. }
  132. else
  133. {
  134. m_log.Info("Starting all Scripts in Scene");
  135. EntityBase[] entities = Entities.GetEntities();
  136. foreach (EntityBase ent in entities)
  137. {
  138. if (ent is SceneObjectGroup)
  139. {
  140. SceneObjectGroup sog = (SceneObjectGroup)ent;
  141. sog.CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  142. sog.ResumeScripts();
  143. }
  144. }
  145. }
  146. m_scripts_enabled = value;
  147. }
  148. }
  149. }
  150. private bool m_scripts_enabled;
  151. public SynchronizeSceneHandler SynchronizeScene;
  152. public bool ClampNegativeZ
  153. {
  154. get { return m_clampNegativeZ; }
  155. }
  156. private bool m_clampNegativeZ = false;
  157. /// <summary>
  158. /// Used to prevent simultaneous calls to code that adds and removes agents.
  159. /// </summary>
  160. private object m_removeClientLock = new object();
  161. /// <summary>
  162. /// Statistical information for this scene.
  163. /// </summary>
  164. public SimStatsReporter StatsReporter { get; private set; }
  165. /// <summary>
  166. /// Controls whether physics can be applied to prims. Even if false, prims still have entries in a
  167. /// PhysicsScene in order to perform collision detection
  168. /// </summary>
  169. public bool PhysicalPrims { get; private set; }
  170. /// <summary>
  171. /// Controls whether prims can be collided with.
  172. /// </summary>
  173. /// <remarks>
  174. /// If this is set to false then prims cannot be subject to physics either.
  175. /// </summary>
  176. public bool CollidablePrims { get; private set; }
  177. /// <summary>
  178. /// Minimum value of the size of a non-physical prim in each axis
  179. /// </summary>
  180. public float m_minNonphys = 0.001f;
  181. /// <summary>
  182. /// Maximum value of the size of a non-physical prim in each axis
  183. /// </summary>
  184. public float m_maxNonphys = 256;
  185. /// <summary>
  186. /// Minimum value of the size of a physical prim in each axis
  187. /// </summary>
  188. public float m_minPhys = 0.01f;
  189. /// <summary>
  190. /// Maximum value of the size of a physical prim in each axis
  191. /// </summary>
  192. public float m_maxPhys = 10;
  193. /// <summary>
  194. /// Max prims an object will hold
  195. /// </summary>
  196. public int m_linksetCapacity = 0;
  197. public bool m_clampPrimSize;
  198. public bool m_trustBinaries;
  199. public bool m_allowScriptCrossings = true;
  200. /// <summary>
  201. /// use legacy sittarget offsets to avoid contents breaks
  202. /// to compensate for SL bug
  203. /// </summary>
  204. public bool LegacySitOffsets = true;
  205. /// <summary>
  206. /// Can avatars cross from and to this region?
  207. /// </summary>
  208. public bool AllowAvatarCrossing { get; set; }
  209. /// Max prims an Physical object will hold
  210. /// </summary>
  211. ///
  212. public int m_linksetPhysCapacity = 0;
  213. /// <summary>
  214. /// When placed outside the region's border, do we transfer the objects or
  215. /// do we keep simulating them here?
  216. /// </summary>
  217. public bool DisableObjectTransfer { get; set; }
  218. public bool m_useFlySlow;
  219. public bool m_useTrashOnDelete = true;
  220. /// <summary>
  221. /// Temporarily setting to trigger appearance resends at 60 second intervals.
  222. /// </summary>
  223. public bool SendPeriodicAppearanceUpdates { get; set; }
  224. /// <summary>
  225. /// How much a root agent has to change position before updates are sent to viewers.
  226. /// </summary>
  227. public float RootPositionUpdateTolerance { get; set; }
  228. /// <summary>
  229. /// How much a root agent has to rotate before updates are sent to viewers.
  230. /// </summary>
  231. public float RootRotationUpdateTolerance { get; set; }
  232. /// <summary>
  233. /// How much a root agent has to change velocity before updates are sent to viewers.
  234. /// </summary>
  235. public float RootVelocityUpdateTolerance { get; set; }
  236. /// <summary>
  237. /// If greater than 1, we only send terse updates to other root agents on every n updates.
  238. /// </summary>
  239. public int RootTerseUpdatePeriod { get; set; }
  240. /// <summary>
  241. /// If greater than 1, we only send terse updates to child agents on every n updates.
  242. /// </summary>
  243. public int ChildTerseUpdatePeriod { get; set; }
  244. protected float m_defaultDrawDistance = 255f;
  245. protected float m_defaultCullingDrawDistance = 16f;
  246. public float DefaultDrawDistance
  247. {
  248. get { return ObjectsCullingByDistance?m_defaultCullingDrawDistance:m_defaultDrawDistance; }
  249. }
  250. protected float m_maxDrawDistance = 512.0f;
  251. // protected float m_maxDrawDistance = 256.0f;
  252. public float MaxDrawDistance
  253. {
  254. get { return m_maxDrawDistance; }
  255. }
  256. protected float m_maxRegionViewDistance = 255f;
  257. public float MaxRegionViewDistance
  258. {
  259. get { return m_maxRegionViewDistance; }
  260. }
  261. private List<string> m_AllowedViewers = new List<string>();
  262. private List<string> m_BannedViewers = new List<string>();
  263. // TODO: need to figure out how allow client agents but deny
  264. // root agents when ACL denies access to root agent
  265. public bool m_strictAccessControl = true;
  266. public bool m_seeIntoBannedRegion = false;
  267. public int MaxUndoCount = 5;
  268. public bool SeeIntoRegion { get; set; }
  269. // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
  270. public bool LoginLock = false;
  271. public bool StartDisabled = false;
  272. public bool LoadingPrims;
  273. public IXfer XferManager;
  274. // the minimum time that must elapse before a changed object will be considered for persisted
  275. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  276. // the maximum time that must elapse before a changed object will be considered for persisted
  277. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  278. protected int m_splitRegionID;
  279. protected Timer m_restartWaitTimer = new Timer();
  280. protected Timer m_timerWatchdog = new Timer();
  281. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  282. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  283. protected string m_simulatorVersion = "OpenSimulator Server";
  284. protected AgentCircuitManager m_authenticateHandler;
  285. protected SceneCommunicationService m_sceneGridService;
  286. protected ISnmpModule m_snmpService = null;
  287. protected ISimulationDataService m_SimulationDataService;
  288. protected IEstateDataService m_EstateDataService;
  289. protected IAssetService m_AssetService;
  290. protected IAuthorizationService m_AuthorizationService;
  291. protected IInventoryService m_InventoryService;
  292. protected IGridService m_GridService;
  293. protected ILibraryService m_LibraryService;
  294. protected ISimulationService m_simulationService;
  295. protected IAuthenticationService m_AuthenticationService;
  296. protected IPresenceService m_PresenceService;
  297. protected IUserAccountService m_UserAccountService;
  298. protected IAvatarService m_AvatarService;
  299. protected IGridUserService m_GridUserService;
  300. protected IAgentPreferencesService m_AgentPreferencesService;
  301. protected IXMLRPC m_xmlrpcModule;
  302. protected IWorldComm m_worldCommModule;
  303. protected IAvatarFactoryModule m_AvatarFactory;
  304. protected IConfigSource m_config;
  305. protected IRegionSerialiserModule m_serialiser;
  306. protected IDialogModule m_dialogModule;
  307. protected ICapabilitiesModule m_capsModule;
  308. protected IGroupsModule m_groupsModule;
  309. private Dictionary<string, string> m_extraSettings;
  310. /// <summary>
  311. /// Current scene frame number
  312. /// </summary>
  313. public uint Frame
  314. {
  315. get;
  316. protected set;
  317. }
  318. /// <summary>
  319. /// Current maintenance run number
  320. /// </summary>
  321. public uint MaintenanceRun { get; private set; }
  322. /// <summary>
  323. /// Frame time
  324. /// </remarks>
  325. public float FrameTime { get; private set; }
  326. public int FrameTimeWarnPercent { get; private set; }
  327. public int FrameTimeCritPercent { get; private set; }
  328. // Normalize the frame related stats to nominal 55fps for viewer and scripts option
  329. // see SimStatsReporter.cs
  330. public bool Normalized55FPS { get; private set; }
  331. /// <summary>
  332. /// The minimum length of time in seconds that will be taken for a scene frame.
  333. /// </summary>
  334. /// <remarks>
  335. /// Always derived from MinFrameTicks.
  336. /// </remarks>
  337. public float MinMaintenanceTime { get; private set; }
  338. private int m_update_physics = 1;
  339. private int m_update_entitymovement = 1;
  340. private int m_update_objects = 1;
  341. private int m_update_presences = 1; // Update scene presence movements
  342. private int m_update_events = 1;
  343. private int m_update_backup = 200;
  344. private int m_update_terrain = 1000;
  345. private int m_update_land = 10;
  346. private int m_update_coarse_locations = 50;
  347. private int m_update_temp_cleaning = 180;
  348. private float agentMS;
  349. private float frameMS;
  350. private float physicsMS2;
  351. private float physicsMS;
  352. private float otherMS;
  353. private float tempOnRezMS;
  354. private float eventMS;
  355. private float backupMS;
  356. private float terrainMS;
  357. private float landMS;
  358. /// <summary>
  359. /// Tick at which the last frame was processed.
  360. /// </summary>
  361. private int m_lastFrameTick;
  362. /// <summary>
  363. /// Tick at which the last maintenance run occurred.
  364. /// </summary>
  365. private int m_lastMaintenanceTick;
  366. /// <summary>
  367. /// Total script execution time (in Stopwatch Ticks) since the last frame
  368. /// </summary>
  369. private long m_scriptExecutionTime = 0;
  370. /// <summary>
  371. /// Signals whether temporary objects are currently being cleaned up. Needed because this is launched
  372. /// asynchronously from the update loop.
  373. /// </summary>
  374. private bool m_cleaningTemps = false;
  375. /// <summary>
  376. /// Used to control main scene thread looping time when not updating via timer.
  377. /// </summary>
  378. private ManualResetEvent m_updateWaitEvent = new ManualResetEvent(false);
  379. /// <summary>
  380. /// Used to control maintenance thread runs.
  381. /// </summary>
  382. private ManualResetEvent m_maintenanceWaitEvent = new ManualResetEvent(false);
  383. // TODO: Possibly stop other classes being able to manipulate this directly.
  384. private SceneGraph m_sceneGraph;
  385. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  386. private volatile bool m_backingup;
  387. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  388. private Dictionary<UUID, int> m_groupsWithTargets = new Dictionary<UUID, int>();
  389. private string m_defaultScriptEngine;
  390. private int m_unixStartTime;
  391. public int UnixStartTime
  392. {
  393. get { return m_unixStartTime; }
  394. }
  395. /// <summary>
  396. /// Tick at which the last login occurred.
  397. /// </summary>
  398. private int m_LastLogin;
  399. private int m_lastIncoming;
  400. private int m_lastOutgoing;
  401. private int m_hbRestarts = 0;
  402. /// <summary>
  403. /// Thread that runs the scene loop.
  404. /// </summary>
  405. private Thread m_heartbeatThread;
  406. /// <summary>
  407. /// True if these scene is in the process of shutting down or is shutdown.
  408. /// </summary>
  409. public bool ShuttingDown
  410. {
  411. get { return m_shuttingDown; }
  412. }
  413. private volatile bool m_shuttingDown;
  414. /// <summary>
  415. /// Is the scene active?
  416. /// </summary>
  417. /// <remarks>
  418. /// If false, maintenance and update loops are not being run, though after setting to false update may still
  419. /// be active for a period (and IsRunning will still be true). Updates can still be triggered manually if
  420. /// the scene is not active.
  421. /// </remarks>
  422. public bool Active
  423. {
  424. get { return m_active; }
  425. set
  426. {
  427. if (value)
  428. {
  429. if (!m_active)
  430. Start(false);
  431. }
  432. else
  433. {
  434. // This appears assymetric with Start() above but is not - setting m_active = false stops the loops
  435. // XXX: Possibly this should be in an explicit Stop() method for symmetry.
  436. m_active = false;
  437. }
  438. }
  439. }
  440. private volatile bool m_active;
  441. /// <summary>
  442. /// If true then updates are running. This may be true for a short period after a scene is de-activated.
  443. /// </summary>
  444. public bool IsRunning { get { return m_isRunning; } }
  445. private volatile bool m_isRunning;
  446. // private int m_lastUpdate;
  447. private bool m_firstHeartbeat = true;
  448. // private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
  449. // private bool m_reprioritizationEnabled = true;
  450. // private double m_reprioritizationInterval = 5000.0;
  451. // private double m_rootReprioritizationDistance = 10.0;
  452. // private double m_childReprioritizationDistance = 20.0;
  453. private Timer m_mapGenerationTimer = new Timer();
  454. private bool m_generateMaptiles;
  455. protected int m_lastHealth = -1;
  456. protected int m_lastUsers = -1;
  457. #endregion Fields
  458. #region Properties
  459. /* Used by the loadbalancer plugin on GForge */
  460. public int SplitRegionID
  461. {
  462. get { return m_splitRegionID; }
  463. set { m_splitRegionID = value; }
  464. }
  465. public new float TimeDilation
  466. {
  467. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  468. }
  469. public void setThreadCount(int inUseThreads)
  470. {
  471. // Just pass the thread count information on its way as the Scene
  472. // does not require the value for anything at this time
  473. StatsReporter.SetThreadCount(inUseThreads);
  474. }
  475. public SceneCommunicationService SceneGridService
  476. {
  477. get { return m_sceneGridService; }
  478. }
  479. public ISnmpModule SnmpService
  480. {
  481. get
  482. {
  483. if (m_snmpService == null)
  484. {
  485. m_snmpService = RequestModuleInterface<ISnmpModule>();
  486. }
  487. return m_snmpService;
  488. }
  489. }
  490. public ISimulationDataService SimulationDataService
  491. {
  492. get
  493. {
  494. if (m_SimulationDataService == null)
  495. {
  496. m_SimulationDataService = RequestModuleInterface<ISimulationDataService>();
  497. if (m_SimulationDataService == null)
  498. {
  499. throw new Exception("No ISimulationDataService available.");
  500. }
  501. }
  502. return m_SimulationDataService;
  503. }
  504. }
  505. public IEstateDataService EstateDataService
  506. {
  507. get
  508. {
  509. if (m_EstateDataService == null)
  510. {
  511. m_EstateDataService = RequestModuleInterface<IEstateDataService>();
  512. if (m_EstateDataService == null)
  513. {
  514. throw new Exception("No IEstateDataService available.");
  515. }
  516. }
  517. return m_EstateDataService;
  518. }
  519. }
  520. public IAssetService AssetService
  521. {
  522. get
  523. {
  524. if (m_AssetService == null)
  525. {
  526. m_AssetService = RequestModuleInterface<IAssetService>();
  527. if (m_AssetService == null)
  528. {
  529. throw new Exception("No IAssetService available.");
  530. }
  531. }
  532. return m_AssetService;
  533. }
  534. }
  535. public IAuthorizationService AuthorizationService
  536. {
  537. get
  538. {
  539. if (m_AuthorizationService == null)
  540. {
  541. m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
  542. //if (m_AuthorizationService == null)
  543. //{
  544. // // don't throw an exception if no authorization service is set for the time being
  545. // m_log.InfoFormat("[SCENE]: No Authorization service is configured");
  546. //}
  547. }
  548. return m_AuthorizationService;
  549. }
  550. }
  551. public IInventoryService InventoryService
  552. {
  553. get
  554. {
  555. if (m_InventoryService == null)
  556. {
  557. m_InventoryService = RequestModuleInterface<IInventoryService>();
  558. if (m_InventoryService == null)
  559. {
  560. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  561. }
  562. }
  563. return m_InventoryService;
  564. }
  565. }
  566. public IGridService GridService
  567. {
  568. get
  569. {
  570. if (m_GridService == null)
  571. {
  572. m_GridService = RequestModuleInterface<IGridService>();
  573. if (m_GridService == null)
  574. {
  575. throw new Exception("No IGridService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  576. }
  577. }
  578. return m_GridService;
  579. }
  580. }
  581. public ILibraryService LibraryService
  582. {
  583. get
  584. {
  585. if (m_LibraryService == null)
  586. m_LibraryService = RequestModuleInterface<ILibraryService>();
  587. return m_LibraryService;
  588. }
  589. }
  590. public ISimulationService SimulationService
  591. {
  592. get
  593. {
  594. if (m_simulationService == null)
  595. m_simulationService = RequestModuleInterface<ISimulationService>();
  596. return m_simulationService;
  597. }
  598. }
  599. public IAuthenticationService AuthenticationService
  600. {
  601. get
  602. {
  603. if (m_AuthenticationService == null)
  604. m_AuthenticationService = RequestModuleInterface<IAuthenticationService>();
  605. return m_AuthenticationService;
  606. }
  607. }
  608. public IPresenceService PresenceService
  609. {
  610. get
  611. {
  612. if (m_PresenceService == null)
  613. m_PresenceService = RequestModuleInterface<IPresenceService>();
  614. return m_PresenceService;
  615. }
  616. }
  617. public IUserAccountService UserAccountService
  618. {
  619. get
  620. {
  621. if (m_UserAccountService == null)
  622. m_UserAccountService = RequestModuleInterface<IUserAccountService>();
  623. return m_UserAccountService;
  624. }
  625. }
  626. public IAvatarService AvatarService
  627. {
  628. get
  629. {
  630. if (m_AvatarService == null)
  631. m_AvatarService = RequestModuleInterface<IAvatarService>();
  632. return m_AvatarService;
  633. }
  634. }
  635. public IGridUserService GridUserService
  636. {
  637. get
  638. {
  639. if (m_GridUserService == null)
  640. m_GridUserService = RequestModuleInterface<IGridUserService>();
  641. return m_GridUserService;
  642. }
  643. }
  644. public IAgentPreferencesService AgentPreferencesService
  645. {
  646. get
  647. {
  648. if (m_AgentPreferencesService == null)
  649. m_AgentPreferencesService = RequestModuleInterface<IAgentPreferencesService>();
  650. return m_AgentPreferencesService;
  651. }
  652. }
  653. public IAttachmentsModule AttachmentsModule { get; set; }
  654. public IEntityTransferModule EntityTransferModule { get; private set; }
  655. public IAgentAssetTransactions AgentTransactionsModule { get; private set; }
  656. public IUserManagement UserManagementModule { get; private set; }
  657. public IAvatarFactoryModule AvatarFactory
  658. {
  659. get { return m_AvatarFactory; }
  660. }
  661. public ICapabilitiesModule CapsModule
  662. {
  663. get { return m_capsModule; }
  664. }
  665. public int MonitorFrameTime { get { return (int)frameMS; } }
  666. public int MonitorPhysicsUpdateTime { get { return (int)physicsMS; } }
  667. public int MonitorPhysicsSyncTime { get { return (int)physicsMS2; } }
  668. public int MonitorOtherTime { get { return (int)otherMS; } }
  669. public int MonitorTempOnRezTime { get { return (int)tempOnRezMS; } }
  670. public int MonitorEventTime { get { return (int)eventMS; } } // This may need to be divided into each event?
  671. public int MonitorBackupTime { get { return (int)backupMS; } }
  672. public int MonitorTerrainTime { get { return (int)terrainMS; } }
  673. public int MonitorLandTime { get { return (int)landMS; } }
  674. public int MonitorLastFrameTick { get { return m_lastFrameTick; } }
  675. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get; set; }
  676. public bool IsReprioritizationEnabled { get; set; }
  677. public float ReprioritizationInterval { get; set; }
  678. public float ReprioritizationDistance { get; set; }
  679. private float m_minReprioritizationDistance = 32f;
  680. public bool ObjectsCullingByDistance = false;
  681. public AgentCircuitManager AuthenticateHandler
  682. {
  683. get { return m_authenticateHandler; }
  684. }
  685. // an instance to the physics plugin's Scene object.
  686. public PhysicsScene PhysicsScene
  687. {
  688. get { return m_sceneGraph.PhysicsScene; }
  689. set
  690. {
  691. // If we're not doing the initial set
  692. // Then we've got to remove the previous
  693. // event handler
  694. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  695. {
  696. PhysicsScene.OnJointMoved -= jointMoved;
  697. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  698. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  699. }
  700. m_sceneGraph.PhysicsScene = value;
  701. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  702. {
  703. // register event handlers to respond to joint movement/deactivation
  704. PhysicsScene.OnJointMoved += jointMoved;
  705. PhysicsScene.OnJointDeactivated += jointDeactivated;
  706. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  707. }
  708. }
  709. }
  710. public string DefaultScriptEngine
  711. {
  712. get { return m_defaultScriptEngine; }
  713. }
  714. public EntityManager Entities
  715. {
  716. get { return m_sceneGraph.Entities; }
  717. }
  718. // used in sequence see: SpawnPoint()
  719. private int m_SpawnPoint;
  720. // can be closest/random/sequence
  721. public string SpawnPointRouting
  722. {
  723. get;
  724. private set;
  725. }
  726. // allow landmarks to pass
  727. public bool TelehubAllowLandmarks
  728. {
  729. get;
  730. private set;
  731. }
  732. #endregion Properties
  733. #region Constructors
  734. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  735. ISimulationDataService simDataService, IEstateDataService estateDataService,
  736. IConfigSource config, string simulatorVersion)
  737. : this(regInfo)
  738. {
  739. m_config = config;
  740. FrameTime = 0.0908f;
  741. FrameTimeWarnPercent = 60;
  742. FrameTimeCritPercent = 40;
  743. Normalized55FPS = true;
  744. MinMaintenanceTime = 1;
  745. SeeIntoRegion = true;
  746. Random random = new Random();
  747. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue / 2)) + (uint)(uint.MaxValue / 4);
  748. m_authenticateHandler = authen;
  749. m_sceneGridService = new SceneCommunicationService();
  750. m_SimulationDataService = simDataService;
  751. m_EstateDataService = estateDataService;
  752. m_lastIncoming = 0;
  753. m_lastOutgoing = 0;
  754. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  755. m_asyncSceneObjectDeleter.Enabled = true;
  756. m_asyncInventorySender = new AsyncInventorySender(this);
  757. #region Region Settings
  758. // Load region settings
  759. // LoadRegionSettings creates new region settings in persistence if they don't already exist for this region.
  760. // However, in this case, the default textures are not set in memory properly, so we need to do it here and
  761. // resave.
  762. // FIXME: It shouldn't be up to the database plugins to create this data - we should do it when a new
  763. // region is set up and avoid these gyrations.
  764. RegionSettings rs = simDataService.LoadRegionSettings(RegionInfo.RegionID);
  765. m_extraSettings = simDataService.GetExtra(RegionInfo.RegionID);
  766. bool updatedTerrainTextures = false;
  767. if (rs.TerrainTexture1 == UUID.Zero)
  768. {
  769. rs.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
  770. updatedTerrainTextures = true;
  771. }
  772. if (rs.TerrainTexture2 == UUID.Zero)
  773. {
  774. rs.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
  775. updatedTerrainTextures = true;
  776. }
  777. if (rs.TerrainTexture3 == UUID.Zero)
  778. {
  779. rs.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
  780. updatedTerrainTextures = true;
  781. }
  782. if (rs.TerrainTexture4 == UUID.Zero)
  783. {
  784. rs.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
  785. updatedTerrainTextures = true;
  786. }
  787. if (updatedTerrainTextures)
  788. rs.Save();
  789. RegionInfo.RegionSettings = rs;
  790. if (estateDataService != null)
  791. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  792. #endregion Region Settings
  793. //Bind Storage Manager functions to some land manager functions for this scene
  794. EventManager.OnLandObjectAdded +=
  795. new EventManager.LandObjectAdded(simDataService.StoreLandObject);
  796. EventManager.OnLandObjectRemoved +=
  797. new EventManager.LandObjectRemoved(simDataService.RemoveLandObject);
  798. RegisterDefaultSceneEvents();
  799. // XXX: Don't set the public property since we don't want to activate here. This needs to be handled
  800. // better in the future.
  801. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  802. PhysicsEnabled = !RegionInfo.RegionSettings.DisablePhysics;
  803. m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";
  804. #region Region Config
  805. // Region config overrides global config
  806. //
  807. if (m_config.Configs["Startup"] != null)
  808. {
  809. IConfig startupConfig = m_config.Configs["Startup"];
  810. StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
  811. m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
  812. m_maxDrawDistance = startupConfig.GetFloat("MaxDrawDistance", m_maxDrawDistance);
  813. m_maxRegionViewDistance = startupConfig.GetFloat("MaxRegionsViewDistance", m_maxRegionViewDistance);
  814. LegacySitOffsets = startupConfig.GetBoolean("LegacySitOffsets", LegacySitOffsets);
  815. if (m_defaultDrawDistance > m_maxDrawDistance)
  816. m_defaultDrawDistance = m_maxDrawDistance;
  817. if (m_maxRegionViewDistance > m_maxDrawDistance)
  818. m_maxRegionViewDistance = m_maxDrawDistance;
  819. UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
  820. if (!UseBackup)
  821. m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
  822. //Animation states
  823. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  824. SeeIntoRegion = startupConfig.GetBoolean("see_into_region", SeeIntoRegion);
  825. MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20);
  826. PhysicalPrims = startupConfig.GetBoolean("physical_prim", true);
  827. CollidablePrims = startupConfig.GetBoolean("collidable_prim", true);
  828. m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
  829. if (RegionInfo.NonphysPrimMin > 0)
  830. {
  831. m_minNonphys = RegionInfo.NonphysPrimMin;
  832. }
  833. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  834. if (RegionInfo.NonphysPrimMax > 0)
  835. {
  836. m_maxNonphys = RegionInfo.NonphysPrimMax;
  837. }
  838. m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
  839. if (RegionInfo.PhysPrimMin > 0)
  840. {
  841. m_minPhys = RegionInfo.PhysPrimMin;
  842. }
  843. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  844. if (RegionInfo.PhysPrimMax > 0)
  845. {
  846. m_maxPhys = RegionInfo.PhysPrimMax;
  847. }
  848. m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
  849. if (RegionInfo.LinksetCapacity > 0)
  850. {
  851. m_linksetCapacity = RegionInfo.LinksetCapacity;
  852. }
  853. m_linksetPhysCapacity = startupConfig.GetInt("LinksetPhysPrims", m_linksetPhysCapacity);
  854. SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
  855. TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
  856. // Here, if clamping is requested in either global or
  857. // local config, it will be used
  858. //
  859. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  860. if (RegionInfo.ClampPrimSize)
  861. {
  862. m_clampPrimSize = true;
  863. }
  864. m_clampNegativeZ = startupConfig.GetBoolean("ClampNegativeZ", m_clampNegativeZ);
  865. m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete",m_useTrashOnDelete);
  866. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  867. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  868. m_dontPersistBefore =
  869. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  870. m_dontPersistBefore *= 10000000;
  871. m_persistAfter =
  872. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  873. m_persistAfter *= 10000000;
  874. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
  875. m_log.InfoFormat("[SCENE]: Default script engine {0}", m_defaultScriptEngine);
  876. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  877. m_seeIntoBannedRegion = startupConfig.GetBoolean("SeeIntoBannedRegion", m_seeIntoBannedRegion);
  878. string[] possibleMapConfigSections = new string[] { "Map", "Startup" };
  879. m_generateMaptiles
  880. = Util.GetConfigVarFromSections<bool>(config, "GenerateMaptiles", possibleMapConfigSections, true);
  881. if (m_generateMaptiles)
  882. {
  883. int maptileRefresh = Util.GetConfigVarFromSections<int>(config, "MaptileRefresh", possibleMapConfigSections, 0);
  884. m_log.InfoFormat("[SCENE]: Region {0}, WORLD MAP refresh time set to {1} seconds", RegionInfo.RegionName, maptileRefresh);
  885. if (maptileRefresh != 0)
  886. {
  887. m_mapGenerationTimer.Interval = maptileRefresh * 1000;
  888. m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
  889. m_mapGenerationTimer.AutoReset = true;
  890. m_mapGenerationTimer.Start();
  891. }
  892. }
  893. else
  894. {
  895. string tile
  896. = Util.GetConfigVarFromSections<string>(
  897. config, "MaptileStaticUUID", possibleMapConfigSections, UUID.Zero.ToString());
  898. UUID tileID;
  899. if (tile != UUID.Zero.ToString() && UUID.TryParse(tile, out tileID))
  900. {
  901. RegionInfo.RegionSettings.TerrainImageID = tileID;
  902. }
  903. else
  904. {
  905. RegionInfo.RegionSettings.TerrainImageID = RegionInfo.MaptileStaticUUID;
  906. m_log.InfoFormat("[SCENE]: Region {0}, maptile set to {1}", RegionInfo.RegionName, RegionInfo.MaptileStaticUUID.ToString());
  907. }
  908. }
  909. string[] possibleAccessControlConfigSections = new string[] { "Startup", "AccessControl"};
  910. string grant
  911. = Util.GetConfigVarFromSections<string>(
  912. config, "AllowedClients", possibleAccessControlConfigSections, string.Empty);
  913. if (grant.Length > 0)
  914. {
  915. foreach (string viewer in grant.Split(','))
  916. {
  917. m_AllowedViewers.Add(viewer.Trim().ToLower());
  918. }
  919. }
  920. grant
  921. = Util.GetConfigVarFromSections<string>(
  922. config, "DeniedClients", possibleAccessControlConfigSections, String.Empty);
  923. // Deal with the mess of someone having used a different word at some point
  924. if (grant == String.Empty)
  925. grant = Util.GetConfigVarFromSections<string>(
  926. config, "BannedClients", possibleAccessControlConfigSections, String.Empty);
  927. if (grant.Length > 0)
  928. {
  929. foreach (string viewer in grant.Split(','))
  930. {
  931. m_BannedViewers.Add(viewer.Trim().ToLower());
  932. }
  933. }
  934. FrameTime = startupConfig.GetFloat( "FrameTime", FrameTime);
  935. FrameTimeWarnPercent = startupConfig.GetInt( "FrameTimeWarnPercent", FrameTimeWarnPercent);
  936. FrameTimeCritPercent = startupConfig.GetInt( "FrameTimeCritPercent", FrameTimeCritPercent);
  937. Normalized55FPS = startupConfig.GetBoolean( "Normalized55FPS", Normalized55FPS);
  938. m_update_backup = startupConfig.GetInt("UpdateStorageEveryNFrames", m_update_backup);
  939. m_update_coarse_locations = startupConfig.GetInt("UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
  940. m_update_entitymovement = startupConfig.GetInt("UpdateEntityMovementEveryNFrames", m_update_entitymovement);
  941. m_update_events = startupConfig.GetInt("UpdateEventsEveryNFrames", m_update_events);
  942. m_update_objects = startupConfig.GetInt("UpdateObjectsEveryNFrames", m_update_objects);
  943. m_update_physics = startupConfig.GetInt("UpdatePhysicsEveryNFrames", m_update_physics);
  944. m_update_presences = startupConfig.GetInt("UpdateAgentsEveryNFrames", m_update_presences);
  945. m_update_terrain = startupConfig.GetInt("UpdateTerrainEveryNFrames", m_update_terrain);
  946. m_update_temp_cleaning = startupConfig.GetInt("UpdateTempCleaningEveryNSeconds", m_update_temp_cleaning);
  947. }
  948. // FIXME: Ultimately this should be in a module.
  949. SendPeriodicAppearanceUpdates = false;
  950. IConfig appearanceConfig = m_config.Configs["Appearance"];
  951. if (appearanceConfig != null)
  952. {
  953. SendPeriodicAppearanceUpdates
  954. = appearanceConfig.GetBoolean("ResendAppearanceUpdates", SendPeriodicAppearanceUpdates);
  955. }
  956. #endregion Region Config
  957. IConfig entityTransferConfig = m_config.Configs["EntityTransfer"];
  958. if (entityTransferConfig != null)
  959. {
  960. AllowAvatarCrossing = entityTransferConfig.GetBoolean("AllowAvatarCrossing", AllowAvatarCrossing);
  961. DisableObjectTransfer = entityTransferConfig.GetBoolean("DisableObjectTransfer", false);
  962. }
  963. #region Interest Management
  964. IConfig interestConfig = m_config.Configs["InterestManagement"];
  965. if (interestConfig != null)
  966. {
  967. string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  968. try
  969. {
  970. UpdatePrioritizationScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
  971. }
  972. catch (Exception)
  973. {
  974. m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default prioritizer Time");
  975. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.Time;
  976. }
  977. IsReprioritizationEnabled
  978. = interestConfig.GetBoolean("ReprioritizationEnabled", IsReprioritizationEnabled);
  979. ReprioritizationInterval
  980. = interestConfig.GetFloat("ReprioritizationInterval", ReprioritizationInterval);
  981. ReprioritizationDistance
  982. = interestConfig.GetFloat("RootReprioritizationDistance", ReprioritizationDistance);
  983. if(ReprioritizationDistance < m_minReprioritizationDistance)
  984. ReprioritizationDistance = m_minReprioritizationDistance;
  985. ObjectsCullingByDistance
  986. = interestConfig.GetBoolean("ObjectsCullingByDistance", ObjectsCullingByDistance);
  987. RootTerseUpdatePeriod = interestConfig.GetInt("RootTerseUpdatePeriod", RootTerseUpdatePeriod);
  988. ChildTerseUpdatePeriod = interestConfig.GetInt("ChildTerseUpdatePeriod", ChildTerseUpdatePeriod);
  989. RootPositionUpdateTolerance
  990. = interestConfig.GetFloat("RootPositionUpdateTolerance", RootPositionUpdateTolerance);
  991. RootRotationUpdateTolerance
  992. = interestConfig.GetFloat("RootRotationUpdateTolerance", RootRotationUpdateTolerance);
  993. RootVelocityUpdateTolerance
  994. = interestConfig.GetFloat("RootVelocityUpdateTolerance", RootVelocityUpdateTolerance);
  995. }
  996. m_log.DebugFormat("[SCENE]: Using the {0} prioritization scheme", UpdatePrioritizationScheme);
  997. #endregion Interest Management
  998. StatsReporter = new SimStatsReporter(this);
  999. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  1000. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  1001. IConfig restartConfig = config.Configs["RestartModule"];
  1002. if (restartConfig != null)
  1003. {
  1004. string markerPath = restartConfig.GetString("MarkerPath", String.Empty);
  1005. if (markerPath != String.Empty)
  1006. {
  1007. string path = Path.Combine(markerPath, RegionInfo.RegionID.ToString() + ".started");
  1008. try
  1009. {
  1010. string pidstring = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
  1011. FileStream fs = File.Create(path);
  1012. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1013. Byte[] buf = enc.GetBytes(pidstring);
  1014. fs.Write(buf, 0, buf.Length);
  1015. fs.Close();
  1016. }
  1017. catch (Exception)
  1018. {
  1019. }
  1020. }
  1021. }
  1022. StartTimerWatchdog();
  1023. }
  1024. public Scene(RegionInfo regInfo)
  1025. : base(regInfo)
  1026. {
  1027. m_sceneGraph = new SceneGraph(this);
  1028. // If the scene graph has an Unrecoverable error, restart this sim.
  1029. // Currently the only thing that causes it to happen is two kinds of specific
  1030. // Physics based crashes.
  1031. //
  1032. // Out of memory
  1033. // Operating system has killed the plugin
  1034. m_sceneGraph.UnRecoverableError
  1035. += () =>
  1036. {
  1037. m_log.ErrorFormat("[SCENE]: Restarting region {0} due to unrecoverable physics crash", Name);
  1038. RestartNow();
  1039. };
  1040. PhysicalPrims = true;
  1041. CollidablePrims = true;
  1042. PhysicsEnabled = true;
  1043. AllowAvatarCrossing = true;
  1044. PeriodicBackup = true;
  1045. UseBackup = true;
  1046. IsReprioritizationEnabled = true;
  1047. UpdatePrioritizationScheme = UpdatePrioritizationSchemes.Time;
  1048. ReprioritizationInterval = 5000;
  1049. RootRotationUpdateTolerance = 0.1f;
  1050. RootVelocityUpdateTolerance = 0.001f;
  1051. RootPositionUpdateTolerance = 0.05f;
  1052. ReprioritizationDistance = m_minReprioritizationDistance;
  1053. m_eventManager = new EventManager();
  1054. m_permissions = new ScenePermissions(this);
  1055. }
  1056. #endregion
  1057. #region Startup / Close Methods
  1058. /// <value>
  1059. /// The scene graph for this scene
  1060. /// </value>
  1061. /// TODO: Possibly stop other classes being able to manipulate this directly.
  1062. public SceneGraph SceneGraph
  1063. {
  1064. get { return m_sceneGraph; }
  1065. }
  1066. /// <summary>
  1067. /// Called by the module loader when all modules are loaded, after each module's
  1068. /// RegionLoaded hook is called. This is the earliest time where RequestModuleInterface
  1069. /// may be used.
  1070. /// </summary>
  1071. public void AllModulesLoaded()
  1072. {
  1073. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  1074. if (dm != null)
  1075. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  1076. ISimulatorFeaturesModule fm = RequestModuleInterface<ISimulatorFeaturesModule>();
  1077. if (fm != null)
  1078. {
  1079. OSD openSimExtras;
  1080. OSDMap openSimExtrasMap;
  1081. if (!fm.TryGetFeature("OpenSimExtras", out openSimExtras))
  1082. openSimExtras = new OSDMap();
  1083. float statisticsFPSfactor = 1.0f;
  1084. if(Normalized55FPS)
  1085. statisticsFPSfactor = 55.0f * FrameTime;
  1086. openSimExtrasMap = (OSDMap)openSimExtras;
  1087. openSimExtrasMap["SimulatorFPS"] = OSD.FromReal(1.0f / FrameTime);
  1088. openSimExtrasMap["SimulatorFPSFactor"] = OSD.FromReal(statisticsFPSfactor);
  1089. openSimExtrasMap["SimulatorFPSWarnPercent"] = OSD.FromInteger(FrameTimeWarnPercent);
  1090. openSimExtrasMap["SimulatorFPSCritPercent"] = OSD.FromInteger(FrameTimeCritPercent);
  1091. fm.AddFeature("OpenSimExtras", openSimExtrasMap);
  1092. }
  1093. }
  1094. protected virtual void RegisterDefaultSceneEvents()
  1095. {
  1096. // m_eventManager.OnSignificantClientMovement += HandleOnSignificantClientMovement;
  1097. }
  1098. public override string GetSimulatorVersion()
  1099. {
  1100. return m_simulatorVersion;
  1101. }
  1102. /// <summary>
  1103. /// Process the fact that a neighbouring region has come up.
  1104. /// </summary>
  1105. /// <remarks>
  1106. /// We only add it to the neighbor list if it's within 1 region from here.
  1107. /// Agents may have draw distance values that cross two regions though, so
  1108. /// we add it to the notify list regardless of distance. We'll check
  1109. /// the agent's draw distance before notifying them though.
  1110. /// </remarks>
  1111. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  1112. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  1113. public override void OtherRegionUp(GridRegion otherRegion)
  1114. {
  1115. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  1116. {
  1117. if (isNeighborRegion(otherRegion))
  1118. {
  1119. // Let the grid service module know, so this can be cached
  1120. m_eventManager.TriggerOnRegionUp(otherRegion);
  1121. try
  1122. {
  1123. ForEachRootScenePresence(delegate(ScenePresence agent)
  1124. {
  1125. //agent.ControllingClient.new
  1126. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  1127. List<ulong> old = new List<ulong>();
  1128. old.Add(otherRegion.RegionHandle);
  1129. agent.DropOldNeighbours(old);
  1130. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1131. EntityTransferModule.EnableChildAgent(agent, otherRegion);
  1132. });
  1133. }
  1134. catch (NullReferenceException)
  1135. {
  1136. // This means that we're not booted up completely yet.
  1137. // This shouldn't happen too often anymore.
  1138. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  1139. }
  1140. }
  1141. else
  1142. {
  1143. m_log.InfoFormat(
  1144. "[SCENE]: Got notice about far away Region: {0} at ({1}, {2})",
  1145. otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);
  1146. }
  1147. }
  1148. }
  1149. public bool isNeighborRegion(GridRegion otherRegion)
  1150. {
  1151. int tmp = otherRegion.RegionLocX - (int)RegionInfo.WorldLocX; ;
  1152. if (tmp < -otherRegion.RegionSizeX && tmp > RegionInfo.RegionSizeX)
  1153. return false;
  1154. tmp = otherRegion.RegionLocY - (int)RegionInfo.WorldLocY;
  1155. if (tmp < -otherRegion.RegionSizeY && tmp > RegionInfo.RegionSizeY)
  1156. return false;
  1157. return true;
  1158. }
  1159. public void AddNeighborRegion(RegionInfo region)
  1160. {
  1161. lock (m_neighbours)
  1162. {
  1163. if (!CheckNeighborRegion(region))
  1164. {
  1165. m_neighbours.Add(region);
  1166. }
  1167. }
  1168. }
  1169. public bool CheckNeighborRegion(RegionInfo region)
  1170. {
  1171. bool found = false;
  1172. lock (m_neighbours)
  1173. {
  1174. foreach (RegionInfo reg in m_neighbours)
  1175. {
  1176. if (reg.RegionHandle == region.RegionHandle)
  1177. {
  1178. found = true;
  1179. break;
  1180. }
  1181. }
  1182. }
  1183. return found;
  1184. }
  1185. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  1186. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  1187. {
  1188. OtherRegionUp(new GridRegion(neighbour));
  1189. return new GridRegion(RegionInfo);
  1190. }
  1191. // This causes the region to restart immediatley.
  1192. public void RestartNow()
  1193. {
  1194. IConfig startupConfig = m_config.Configs["Startup"];
  1195. if (startupConfig != null)
  1196. {
  1197. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  1198. {
  1199. MainConsole.Instance.RunCommand("shutdown");
  1200. return;
  1201. }
  1202. }
  1203. m_log.InfoFormat("[REGION]: Restarting region {0}", Name);
  1204. Close();
  1205. base.Restart();
  1206. }
  1207. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  1208. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  1209. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  1210. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  1211. // subsequently the agent will never see the region come back online.
  1212. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  1213. {
  1214. m_restartWaitTimer.Stop();
  1215. lock (m_regionRestartNotifyList)
  1216. {
  1217. foreach (RegionInfo region in m_regionRestartNotifyList)
  1218. {
  1219. GridRegion r = new GridRegion(region);
  1220. try
  1221. {
  1222. ForEachRootScenePresence(delegate(ScenePresence agent)
  1223. {
  1224. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1225. EntityTransferModule.EnableChildAgent(agent, r);
  1226. });
  1227. }
  1228. catch (NullReferenceException)
  1229. {
  1230. // This means that we're not booted up completely yet.
  1231. // This shouldn't happen too often anymore.
  1232. }
  1233. }
  1234. // Reset list to nothing.
  1235. m_regionRestartNotifyList.Clear();
  1236. }
  1237. }
  1238. public int GetInaccurateNeighborCount()
  1239. {
  1240. return m_neighbours.Count;
  1241. }
  1242. // This is the method that shuts down the scene.
  1243. public override void Close()
  1244. {
  1245. if (m_shuttingDown)
  1246. {
  1247. m_log.WarnFormat("[SCENE]: Ignoring close request because already closing {0}", Name);
  1248. return;
  1249. }
  1250. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  1251. if (etcd != null)
  1252. {
  1253. etcd.Delete("Health");
  1254. etcd.Delete("HealthFlags");
  1255. etcd.Delete("RootAgents");
  1256. }
  1257. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  1258. StatsReporter.Close();
  1259. m_restartTimer.Stop();
  1260. m_restartTimer.Close();
  1261. if (!GridService.DeregisterRegion(RegionInfo.RegionID))
  1262. m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", Name);
  1263. // Kick all ROOT agents with the message, 'The simulator is going down'
  1264. ForEachScenePresence(delegate(ScenePresence avatar)
  1265. {
  1266. avatar.RemoveNeighbourRegion(RegionInfo.RegionHandle);
  1267. if (!avatar.IsChildAgent)
  1268. avatar.ControllingClient.Kick("The simulator is going down.");
  1269. avatar.ControllingClient.SendShutdownConnectionNotice();
  1270. });
  1271. // Stop updating the scene objects and agents.
  1272. m_shuttingDown = true;
  1273. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  1274. // We also need to wait to avoid a race condition with the scene update loop which might not yet
  1275. // have checked ShuttingDown.
  1276. Thread.Sleep(500);
  1277. // Stop all client threads.
  1278. ForEachScenePresence(delegate(ScenePresence avatar) { CloseAgent(avatar.UUID, false); });
  1279. m_log.Debug("[SCENE]: TriggerSceneShuttingDown");
  1280. EventManager.TriggerSceneShuttingDown(this);
  1281. m_log.Debug("[SCENE]: Persisting changed objects");
  1282. Backup(true);
  1283. m_log.Debug("[SCENE]: Closing scene");
  1284. m_sceneGraph.Close();
  1285. base.Close();
  1286. // XEngine currently listens to the EventManager.OnShutdown event to trigger script stop and persistence.
  1287. // Therefore. we must dispose of the PhysicsScene after this to prevent a window where script code can
  1288. // attempt to reference a null or disposed physics scene.
  1289. if (PhysicsScene != null)
  1290. {
  1291. m_log.Debug("[SCENE]: Dispose Physics");
  1292. PhysicsScene phys = PhysicsScene;
  1293. // remove the physics engine from both Scene and SceneGraph
  1294. PhysicsScene = null;
  1295. phys.Dispose();
  1296. phys = null;
  1297. }
  1298. }
  1299. public override void Start()
  1300. {
  1301. Start(true);
  1302. }
  1303. /// <summary>
  1304. /// Start the scene
  1305. /// </summary>
  1306. /// <param name='startScripts'>
  1307. /// Start the scripts within the scene.
  1308. /// </param>
  1309. public void Start(bool startScripts)
  1310. {
  1311. if (IsRunning)
  1312. return;
  1313. m_isRunning = true;
  1314. m_active = true;
  1315. m_unixStartTime = Util.UnixTimeSinceEpoch();
  1316. // m_log.DebugFormat("[SCENE]: Starting Heartbeat timer for {0}", RegionInfo.RegionName);
  1317. if (m_heartbeatThread != null)
  1318. {
  1319. m_hbRestarts++;
  1320. if(m_hbRestarts > 10)
  1321. Environment.Exit(1);
  1322. m_log.ErrorFormat("[SCENE]: Restarting heartbeat thread because it hasn't reported in in region {0}", RegionInfo.RegionName);
  1323. //int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  1324. //System.Diagnostics.Process proc = new System.Diagnostics.Process();
  1325. //proc.EnableRaisingEvents=false;
  1326. //proc.StartInfo.FileName = "/bin/kill";
  1327. //proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  1328. //proc.Start();
  1329. //proc.WaitForExit();
  1330. //Thread.Sleep(1000);
  1331. //Environment.Exit(1);
  1332. m_heartbeatThread.Abort();
  1333. Watchdog.AbortThread(m_heartbeatThread.ManagedThreadId);
  1334. m_heartbeatThread = null;
  1335. }
  1336. GC.Collect();
  1337. GC.WaitForPendingFinalizers();
  1338. GC.Collect();
  1339. // tell physics to finish building actor
  1340. m_sceneGraph.ProcessPhysicsPreSimulation();
  1341. m_heartbeatThread
  1342. = WorkManager.StartThread(
  1343. Heartbeat, string.Format("Heartbeat-({0})", RegionInfo.RegionName.Replace(" ", "_")), ThreadPriority.Normal, false, false);
  1344. StartScripts();
  1345. }
  1346. /// <summary>
  1347. /// Sets up references to modules required by the scene
  1348. /// </summary>
  1349. public void SetModuleInterfaces()
  1350. {
  1351. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  1352. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  1353. XferManager = RequestModuleInterface<IXfer>();
  1354. m_AvatarFactory = RequestModuleInterface<IAvatarFactoryModule>();
  1355. AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
  1356. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  1357. m_dialogModule = RequestModuleInterface<IDialogModule>();
  1358. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  1359. EntityTransferModule = RequestModuleInterface<IEntityTransferModule>();
  1360. m_groupsModule = RequestModuleInterface<IGroupsModule>();
  1361. AgentTransactionsModule = RequestModuleInterface<IAgentAssetTransactions>();
  1362. UserManagementModule = RequestModuleInterface<IUserManagement>();
  1363. }
  1364. #endregion
  1365. #region Update Methods
  1366. /// <summary>
  1367. /// Activate the various loops necessary to continually update the scene.
  1368. /// </summary>
  1369. private void Heartbeat()
  1370. {
  1371. m_eventManager.TriggerOnRegionStarted(this);
  1372. // The first frame can take a very long time due to physics actors being added on startup. Therefore,
  1373. // don't turn on the watchdog alarm for this thread until the second frame, in order to prevent false
  1374. // alarms for scenes with many objects.
  1375. Update(1);
  1376. WorkManager.StartThread(
  1377. Maintenance, string.Format("Maintenance ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, true);
  1378. Watchdog.GetCurrentThreadInfo().AlarmIfTimeout = true;
  1379. m_lastFrameTick = Util.EnvironmentTickCount();
  1380. Update(-1);
  1381. Watchdog.RemoveThread();
  1382. }
  1383. private void Maintenance()
  1384. {
  1385. DoMaintenance(-1);
  1386. Watchdog.RemoveThread();
  1387. }
  1388. public void DoMaintenance(int runs)
  1389. {
  1390. long? endRun = null;
  1391. int runtc, tmpMS;
  1392. int previousMaintenanceTick;
  1393. if (runs >= 0)
  1394. endRun = MaintenanceRun + runs;
  1395. List<Vector3> coarseLocations;
  1396. List<UUID> avatarUUIDs;
  1397. while (!m_shuttingDown && ((endRun == null && Active) || MaintenanceRun < endRun))
  1398. {
  1399. runtc = Util.EnvironmentTickCount();
  1400. ++MaintenanceRun;
  1401. // m_log.DebugFormat("[SCENE]: Maintenance run {0} in {1}", MaintenanceRun, Name);
  1402. // Coarse locations relate to positions of green dots on the mini-map (on a SecondLife client)
  1403. if (MaintenanceRun % (m_update_coarse_locations / 10) == 0)
  1404. {
  1405. SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
  1406. // Send coarse locations to clients
  1407. ForEachScenePresence(delegate(ScenePresence presence)
  1408. {
  1409. presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
  1410. });
  1411. }
  1412. if (SendPeriodicAppearanceUpdates && MaintenanceRun % 60 == 0)
  1413. {
  1414. // m_log.DebugFormat("[SCENE]: Sending periodic appearance updates");
  1415. if (AvatarFactory != null)
  1416. {
  1417. ForEachRootScenePresence(sp => AvatarFactory.SendAppearance(sp.UUID));
  1418. }
  1419. }
  1420. // Delete temp-on-rez stuff
  1421. if (MaintenanceRun % m_update_temp_cleaning == 0 && !m_cleaningTemps)
  1422. {
  1423. // m_log.DebugFormat("[SCENE]: Running temp-on-rez cleaning in {0}", Name);
  1424. tmpMS = Util.EnvironmentTickCount();
  1425. m_cleaningTemps = true;
  1426. WorkManager.RunInThread(
  1427. delegate { CleanTempObjects(); m_cleaningTemps = false; },
  1428. null,
  1429. string.Format("CleanTempObjects ({0})", Name));
  1430. tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1431. }
  1432. Watchdog.UpdateThread();
  1433. previousMaintenanceTick = m_lastMaintenanceTick;
  1434. m_lastMaintenanceTick = Util.EnvironmentTickCount();
  1435. runtc = Util.EnvironmentTickCountSubtract(m_lastMaintenanceTick, runtc);
  1436. runtc = (int)(MinMaintenanceTime * 1000) - runtc;
  1437. if (runtc > 0)
  1438. m_maintenanceWaitEvent.WaitOne(runtc);
  1439. // Optionally warn if a frame takes double the amount of time that it should.
  1440. if (DebugUpdates
  1441. && Util.EnvironmentTickCountSubtract(
  1442. m_lastMaintenanceTick, previousMaintenanceTick) > (int)(MinMaintenanceTime * 1000 * 2))
  1443. m_log.WarnFormat(
  1444. "[SCENE]: Maintenance took {0} ms (desired max {1} ms) in {2}",
  1445. Util.EnvironmentTickCountSubtract(m_lastMaintenanceTick, previousMaintenanceTick),
  1446. MinMaintenanceTime * 1000,
  1447. RegionInfo.RegionName);
  1448. }
  1449. }
  1450. public override void Update(int frames)
  1451. {
  1452. long? endFrame = null;
  1453. if (frames >= 0)
  1454. endFrame = Frame + frames;
  1455. float physicsFPS = 0f;
  1456. float frameTimeMS = FrameTime * 1000.0f;
  1457. int previousFrameTick;
  1458. double tmpMS;
  1459. double tmpMS2;
  1460. double framestart;
  1461. float sleepMS;
  1462. float sleepError = 0;
  1463. while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame))
  1464. {
  1465. framestart = Util.GetTimeStampMS();
  1466. ++Frame;
  1467. // m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
  1468. agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0f;
  1469. try
  1470. {
  1471. EventManager.TriggerRegionHeartbeatStart(this);
  1472. // Apply taints in terrain module to terrain in physics scene
  1473. tmpMS = Util.GetTimeStampMS();
  1474. if (Frame % 4 == 0)
  1475. {
  1476. CheckTerrainUpdates();
  1477. }
  1478. if (Frame % m_update_terrain == 0)
  1479. {
  1480. UpdateTerrain();
  1481. }
  1482. tmpMS2 = Util.GetTimeStampMS();
  1483. terrainMS = (float)(tmpMS2 - tmpMS);
  1484. tmpMS = tmpMS2;
  1485. if (PhysicsEnabled && Frame % m_update_physics == 0)
  1486. m_sceneGraph.UpdatePreparePhysics();
  1487. tmpMS2 = Util.GetTimeStampMS();
  1488. physicsMS2 = (float)(tmpMS2 - tmpMS);
  1489. tmpMS = tmpMS2;
  1490. // Apply any pending avatar force input to the avatar's velocity
  1491. if (Frame % m_update_entitymovement == 0)
  1492. m_sceneGraph.UpdateScenePresenceMovement();
  1493. // Get the simulation frame time that the avatar force input
  1494. // took
  1495. tmpMS2 = Util.GetTimeStampMS();
  1496. agentMS = (float)(tmpMS2 - tmpMS);
  1497. tmpMS = tmpMS2;
  1498. // Perform the main physics update. This will do the actual work of moving objects and avatars according to their
  1499. // velocity
  1500. if (Frame % m_update_physics == 0)
  1501. {
  1502. if (PhysicsEnabled)
  1503. physicsFPS = m_sceneGraph.UpdatePhysics(FrameTime);
  1504. if (SynchronizeScene != null)
  1505. SynchronizeScene(this);
  1506. }
  1507. tmpMS2 = Util.GetTimeStampMS();
  1508. physicsMS = (float)(tmpMS2 - tmpMS);
  1509. tmpMS = tmpMS2;
  1510. // Check if any objects have reached their targets
  1511. CheckAtTargets();
  1512. // Update SceneObjectGroups that have scheduled themselves for updates
  1513. // Objects queue their updates onto all scene presences
  1514. if (Frame % m_update_objects == 0)
  1515. m_sceneGraph.UpdateObjectGroups();
  1516. // Run through all ScenePresences looking for updates
  1517. // Presence updates and queued object updates for each presence are sent to clients
  1518. if (Frame % m_update_presences == 0)
  1519. m_sceneGraph.UpdatePresences();
  1520. tmpMS2 = Util.GetTimeStampMS();
  1521. agentMS += (float)(tmpMS2 - tmpMS);
  1522. tmpMS = tmpMS2;
  1523. // Delete temp-on-rez stuff
  1524. if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
  1525. {
  1526. m_cleaningTemps = true;
  1527. Util.FireAndForget(delegate { CleanTempObjects(); m_cleaningTemps = false; });
  1528. tmpMS2 = Util.GetTimeStampMS();
  1529. tempOnRezMS = (float)(tmpMS2 - tmpMS); // bad.. counts the FireAndForget, not CleanTempObjects
  1530. tmpMS = tmpMS2;
  1531. }
  1532. if (Frame % m_update_events == 0)
  1533. {
  1534. UpdateEvents();
  1535. tmpMS2 = Util.GetTimeStampMS();
  1536. eventMS = (float)(tmpMS2 - tmpMS);
  1537. tmpMS = tmpMS2;
  1538. }
  1539. if (PeriodicBackup && Frame % m_update_backup == 0)
  1540. {
  1541. UpdateStorageBackup();
  1542. tmpMS2 = Util.GetTimeStampMS();
  1543. backupMS = (float)(tmpMS2 - tmpMS);
  1544. tmpMS = tmpMS2;
  1545. }
  1546. //if (Frame % m_update_land == 0)
  1547. //{
  1548. // int ldMS = Util.EnvironmentTickCount();
  1549. // UpdateLand();
  1550. // landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1551. //}
  1552. if (!LoginsEnabled && Frame == 20)
  1553. {
  1554. GC.Collect();
  1555. GC.WaitForPendingFinalizers();
  1556. GC.Collect();
  1557. if (!LoginLock)
  1558. {
  1559. if (!StartDisabled)
  1560. {
  1561. m_log.InfoFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
  1562. LoginsEnabled = true;
  1563. }
  1564. m_sceneGridService.InformNeighborsThatRegionisUp(
  1565. RequestModuleInterface<INeighbourService>(), RegionInfo);
  1566. // Region ready should always be set
  1567. Ready = true;
  1568. }
  1569. else
  1570. {
  1571. // This handles a case of a region having no scripts for the RegionReady module
  1572. if (m_sceneGraph.GetActiveScriptsCount() == 0)
  1573. {
  1574. // In this case, we leave it to the IRegionReadyModule to enable logins
  1575. // LoginLock can currently only be set by a region module implementation.
  1576. // If somehow this hasn't been done then the quickest way to bugfix is to see the
  1577. // NullReferenceException
  1578. IRegionReadyModule rrm = RequestModuleInterface<IRegionReadyModule>();
  1579. rrm.TriggerRegionReady(this);
  1580. }
  1581. }
  1582. }
  1583. }
  1584. catch (Exception e)
  1585. {
  1586. m_log.ErrorFormat(
  1587. "[SCENE]: Failed on region {0} with exception {1}{2}",
  1588. RegionInfo.RegionName, e.Message, e.StackTrace);
  1589. }
  1590. EventManager.TriggerRegionHeartbeatEnd(this);
  1591. m_firstHeartbeat = false;
  1592. Watchdog.UpdateThread();
  1593. otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1594. tmpMS = Util.GetTimeStampMS();
  1595. previousFrameTick = m_lastFrameTick;
  1596. m_lastFrameTick = (int)(tmpMS + 0.5);
  1597. // estimate sleep time
  1598. tmpMS2 = tmpMS - framestart;
  1599. tmpMS2 = (double)frameTimeMS - tmpMS2 - sleepError;
  1600. // reuse frameMS as temporary
  1601. frameMS = (float)tmpMS2;
  1602. // sleep if we can
  1603. if (tmpMS2 > 0)
  1604. {
  1605. Thread.Sleep((int)(tmpMS2 + 0.5));
  1606. tmpMS2 = Util.GetTimeStampMS();
  1607. sleepMS = (float)(tmpMS2 - tmpMS);
  1608. sleepError = sleepMS - frameMS;
  1609. Util.Clamp(sleepError, 0.0f, 20f);
  1610. frameMS = (float)(tmpMS2 - framestart);
  1611. }
  1612. else
  1613. {
  1614. tmpMS2 = Util.GetTimeStampMS();
  1615. frameMS = (float)(tmpMS2 - framestart);
  1616. sleepMS = 0.0f;
  1617. sleepError = 0.0f;
  1618. }
  1619. // script time is not scene frame time, but is displayed per frame
  1620. float scriptTimeMS = GetAndResetScriptExecutionTime();
  1621. StatsReporter.AddFrameStats(TimeDilation, physicsFPS, agentMS,
  1622. physicsMS + physicsMS2, otherMS , sleepMS, frameMS, scriptTimeMS);
  1623. // if (Frame%m_update_avatars == 0)
  1624. // UpdateInWorldTime();
  1625. // Optionally warn if a frame takes double the amount of time that it should.
  1626. if (DebugUpdates
  1627. && Util.EnvironmentTickCountSubtract(
  1628. m_lastFrameTick, previousFrameTick) > (int)(FrameTime * 1000 * 2))
  1629. m_log.WarnFormat(
  1630. "[SCENE]: Frame took {0} ms (desired max {1} ms) in {2}",
  1631. Util.EnvironmentTickCountSubtract(m_lastFrameTick, previousFrameTick),
  1632. FrameTime * 1000,
  1633. RegionInfo.RegionName);
  1634. }
  1635. }
  1636. /// <summary>
  1637. /// Adds the execution time of one script to the total scripts execution time for this region.
  1638. /// </summary>
  1639. /// <param name="ticks">Elapsed Stopwatch ticks</param>
  1640. public void AddScriptExecutionTime(long ticks)
  1641. {
  1642. StatsReporter.addScriptEvents(1);
  1643. Interlocked.Add(ref m_scriptExecutionTime, ticks);
  1644. }
  1645. /// <summary>
  1646. /// Returns the total execution time of all the scripts in the region since the last call
  1647. /// (in milliseconds), and clears the value in preparation for the next call.
  1648. /// </summary>
  1649. /// <returns>Time in milliseconds</returns>
  1650. // Warning: this is now called from StatsReporter, and can't be shared
  1651. public long GetAndResetScriptExecutionTime()
  1652. {
  1653. long ticks = Interlocked.Exchange(ref m_scriptExecutionTime, 0);
  1654. return (ticks * 1000L) / Stopwatch.Frequency;
  1655. }
  1656. public void AddGroupTarget(SceneObjectGroup grp)
  1657. {
  1658. lock (m_groupsWithTargets)
  1659. m_groupsWithTargets[grp.UUID] = 0;
  1660. }
  1661. public void RemoveGroupTarget(SceneObjectGroup grp)
  1662. {
  1663. lock (m_groupsWithTargets)
  1664. m_groupsWithTargets.Remove(grp.UUID);
  1665. }
  1666. private void CheckAtTargets()
  1667. {
  1668. List<UUID> objs = null;
  1669. lock (m_groupsWithTargets)
  1670. {
  1671. if (m_groupsWithTargets.Count != 0)
  1672. objs = new List<UUID>(m_groupsWithTargets.Keys);
  1673. }
  1674. if (objs != null)
  1675. {
  1676. foreach (UUID entry in objs)
  1677. {
  1678. SceneObjectGroup grp = GetSceneObjectGroup(entry);
  1679. if (grp == null)
  1680. m_groupsWithTargets.Remove(entry);
  1681. else
  1682. grp.checkAtTargets();
  1683. }
  1684. }
  1685. }
  1686. /// <summary>
  1687. /// Send out simstats data to all clients
  1688. /// </summary>
  1689. /// <param name="stats">Stats on the Simulator's performance</param>
  1690. private void SendSimStatsPackets(SimStats stats)
  1691. {
  1692. ForEachRootClient(delegate(IClientAPI client)
  1693. {
  1694. client.SendSimStats(stats);
  1695. });
  1696. }
  1697. /// <summary>
  1698. /// Update the terrain if it needs to be updated.
  1699. /// </summary>
  1700. private void UpdateTerrain()
  1701. {
  1702. EventManager.TriggerTerrainTick();
  1703. }
  1704. private void CheckTerrainUpdates()
  1705. {
  1706. EventManager.TriggerTerrainCheckUpdates();
  1707. }
  1708. /// <summary>
  1709. /// Back up queued up changes
  1710. /// </summary>
  1711. private void UpdateStorageBackup()
  1712. {
  1713. if (!m_backingup)
  1714. {
  1715. m_backingup = true;
  1716. WorkManager.RunInThread(o => Backup(false), null, string.Format("BackupWaitCallback ({0})", Name));
  1717. }
  1718. }
  1719. /// <summary>
  1720. /// Sends out the OnFrame event to the modules
  1721. /// </summary>
  1722. private void UpdateEvents()
  1723. {
  1724. m_eventManager.TriggerOnFrame();
  1725. }
  1726. /// <summary>
  1727. /// Backup the scene.
  1728. /// </summary>
  1729. /// <remarks>
  1730. /// This acts as the main method of the backup thread. In a regression test whether the backup thread is not
  1731. /// running independently this can be invoked directly.
  1732. /// </remarks>
  1733. /// <param name="forced">
  1734. /// If true, then any changes that have not yet been persisted are persisted. If false,
  1735. /// then the persistence decision is left to the backup code (in some situations, such as object persistence,
  1736. /// it's much more efficient to backup multiple changes at once rather than every single one).
  1737. /// <returns></returns>
  1738. public void Backup(bool forced)
  1739. {
  1740. lock (m_returns)
  1741. {
  1742. EventManager.TriggerOnBackup(SimulationDataService, forced);
  1743. m_backingup = false;
  1744. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1745. {
  1746. UUID transaction = UUID.Random();
  1747. GridInstantMessage msg = new GridInstantMessage();
  1748. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  1749. msg.toAgentID = new Guid(ret.Key.ToString());
  1750. msg.imSessionID = new Guid(transaction.ToString());
  1751. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  1752. msg.fromAgentName = "Server";
  1753. msg.dialog = (byte)19; // Object msg
  1754. msg.fromGroup = false;
  1755. msg.offline = (byte)1;
  1756. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  1757. msg.Position = Vector3.Zero;
  1758. msg.RegionID = RegionInfo.RegionID.Guid;
  1759. // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
  1760. msg.binaryBucket = Util.StringToBytes256("\0");
  1761. if (ret.Value.count > 1)
  1762. msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1763. else
  1764. msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1765. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1766. if (tr != null)
  1767. tr.SendInstantMessage(msg, delegate(bool success) { });
  1768. }
  1769. m_returns.Clear();
  1770. }
  1771. }
  1772. /// <summary>
  1773. /// Synchronous force backup. For deletes and links/unlinks
  1774. /// </summary>
  1775. /// <param name="group">Object to be backed up</param>
  1776. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1777. {
  1778. if (group != null)
  1779. {
  1780. group.HasGroupChanged = true;
  1781. group.ProcessBackup(SimulationDataService, true);
  1782. }
  1783. }
  1784. /// <summary>
  1785. /// Tell an agent that their object has been returned.
  1786. /// </summary>
  1787. /// <remarks>
  1788. /// The actual return is handled by the caller.
  1789. /// </remarks>
  1790. /// <param name="agentID">Avatar Unique Id</param>
  1791. /// <param name="objectName">Name of object returned</param>
  1792. /// <param name="location">Location of object returned</param>
  1793. /// <param name="reason">Reasion for object return</param>
  1794. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1795. {
  1796. lock (m_returns)
  1797. {
  1798. if (m_returns.ContainsKey(agentID))
  1799. {
  1800. ReturnInfo info = m_returns[agentID];
  1801. info.count++;
  1802. m_returns[agentID] = info;
  1803. }
  1804. else
  1805. {
  1806. ReturnInfo info = new ReturnInfo();
  1807. info.count = 1;
  1808. info.objectName = objectName;
  1809. info.location = location;
  1810. info.reason = reason;
  1811. m_returns[agentID] = info;
  1812. }
  1813. }
  1814. }
  1815. #endregion
  1816. #region Load Terrain
  1817. /// <summary>
  1818. /// Store the terrain in the persistant data store
  1819. /// </summary>
  1820. public void SaveTerrain()
  1821. {
  1822. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1823. }
  1824. /// <summary>
  1825. /// Store the terrain in the persistant data store
  1826. /// </summary>
  1827. public void SaveBakedTerrain()
  1828. {
  1829. if(Bakedmap != null)
  1830. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1831. }
  1832. public void StoreWindlightProfile(RegionLightShareData wl)
  1833. {
  1834. RegionInfo.WindlightSettings = wl;
  1835. SimulationDataService.StoreRegionWindlightSettings(wl);
  1836. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1837. }
  1838. public void LoadWindlightProfile()
  1839. {
  1840. RegionInfo.WindlightSettings = SimulationDataService.LoadRegionWindlightSettings(RegionInfo.RegionID);
  1841. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1842. }
  1843. /// <summary>
  1844. /// Loads the World heightmap
  1845. /// </summary>
  1846. public override void LoadWorldMap()
  1847. {
  1848. try
  1849. {
  1850. Bakedmap = null;
  1851. TerrainData map = SimulationDataService.LoadBakedTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1852. if (map != null)
  1853. {
  1854. Bakedmap = new TerrainChannel(map);
  1855. }
  1856. }
  1857. catch (Exception e)
  1858. {
  1859. m_log.WarnFormat(
  1860. "[TERRAIN]: Scene.cs: LoadWorldMap() baked terrain - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1861. }
  1862. try
  1863. {
  1864. TerrainData map = SimulationDataService.LoadTerrain(RegionInfo.RegionID, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1865. if (map == null)
  1866. {
  1867. if(Bakedmap != null)
  1868. {
  1869. m_log.Warn("[TERRAIN]: terrain not found. Used stored baked terrain.");
  1870. Heightmap = Bakedmap.MakeCopy();
  1871. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1872. }
  1873. else
  1874. {
  1875. // This should be in the Terrain module, but it isn't because
  1876. // the heightmap is needed _way_ before the modules are initialized...
  1877. IConfig terrainConfig = m_config.Configs["Terrain"];
  1878. String m_InitialTerrain = "pinhead-island";
  1879. if (terrainConfig != null)
  1880. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  1881. m_log.InfoFormat("[TERRAIN]: No default terrain. Generating a new terrain {0}.", m_InitialTerrain);
  1882. Heightmap = new TerrainChannel(m_InitialTerrain, (int)RegionInfo.RegionSizeX, (int)RegionInfo.RegionSizeY, (int)RegionInfo.RegionSizeZ);
  1883. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1884. }
  1885. }
  1886. else
  1887. {
  1888. Heightmap = new TerrainChannel(map);
  1889. }
  1890. }
  1891. catch (IOException e)
  1892. {
  1893. m_log.WarnFormat(
  1894. "[TERRAIN]: Scene.cs: LoadWorldMap() - Regenerating as failed with exception {0}{1}",
  1895. e.Message, e.StackTrace);
  1896. #pragma warning disable 0162
  1897. if ((int)Constants.RegionSize != 256)
  1898. {
  1899. Heightmap = new TerrainChannel();
  1900. SimulationDataService.StoreTerrain(Heightmap.GetTerrainData(), RegionInfo.RegionID);
  1901. }
  1902. }
  1903. catch (Exception e)
  1904. {
  1905. m_log.WarnFormat(
  1906. "[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1907. }
  1908. if(Bakedmap == null && Heightmap != null)
  1909. {
  1910. Bakedmap = Heightmap.MakeCopy();
  1911. SimulationDataService.StoreBakedTerrain(Bakedmap.GetTerrainData(), RegionInfo.RegionID);
  1912. }
  1913. }
  1914. /// <summary>
  1915. /// Register this region with a grid service
  1916. /// </summary>
  1917. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1918. public void RegisterRegionWithGrid()
  1919. {
  1920. m_sceneGridService.SetScene(this);
  1921. //// Unfortunately this needs to be here and it can't be async.
  1922. //// The map tile image is stored in RegionSettings, but it also needs to be
  1923. //// stored in the GridService, because that's what the world map module uses
  1924. //// to send the map image UUIDs (of other regions) to the viewer...
  1925. if (m_generateMaptiles)
  1926. RegenerateMaptile();
  1927. GridRegion region = new GridRegion(RegionInfo);
  1928. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1929. // m_log.DebugFormat("[SCENE]: RegisterRegionWithGrid. name={0},id={1},loc=<{2},{3}>,size=<{4},{5}>",
  1930. // m_regionName,
  1931. // RegionInfo.RegionID,
  1932. // RegionInfo.RegionLocX, RegionInfo.RegionLocY,
  1933. // RegionInfo.RegionSizeX, RegionInfo.RegionSizeY);
  1934. if (error != String.Empty)
  1935. throw new Exception(error);
  1936. }
  1937. #endregion
  1938. #region Load Land
  1939. /// <summary>
  1940. /// Loads all Parcel data from the datastore for region identified by regionID
  1941. /// </summary>
  1942. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1943. public void loadAllLandObjectsFromStorage(UUID regionID)
  1944. {
  1945. m_log.Info("[SCENE]: Loading land objects from storage");
  1946. List<LandData> landData = SimulationDataService.LoadLandObjects(regionID);
  1947. if (LandChannel != null)
  1948. {
  1949. if (landData.Count == 0)
  1950. {
  1951. EventManager.TriggerNoticeNoLandDataFromStorage();
  1952. }
  1953. else
  1954. {
  1955. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1956. }
  1957. }
  1958. else
  1959. {
  1960. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1961. }
  1962. }
  1963. #endregion
  1964. #region Primitives Methods
  1965. /// <summary>
  1966. /// Loads the World's objects
  1967. /// </summary>
  1968. /// <param name="regionID"></param>
  1969. public virtual void LoadPrimsFromStorage(UUID regionID)
  1970. {
  1971. LoadingPrims = true;
  1972. m_log.Info("[SCENE]: Loading objects from datastore");
  1973. List<SceneObjectGroup> PrimsFromDB = SimulationDataService.LoadObjects(regionID);
  1974. m_log.InfoFormat("[SCENE]: Loaded {0} objects from the datastore", PrimsFromDB.Count);
  1975. foreach (SceneObjectGroup group in PrimsFromDB)
  1976. {
  1977. AddRestoredSceneObject(group, true, true);
  1978. EventManager.TriggerOnSceneObjectLoaded(group);
  1979. SceneObjectPart rootPart = group.GetPart(group.UUID);
  1980. rootPart.Flags &= ~PrimFlags.Scripted;
  1981. rootPart.TrimPermissions();
  1982. // Don't do this here - it will get done later on when sculpt data is loaded.
  1983. // group.CheckSculptAndLoad();
  1984. }
  1985. LoadingPrims = false;
  1986. EventManager.TriggerPrimsLoaded(this);
  1987. }
  1988. public bool SupportsRayCastFiltered()
  1989. {
  1990. if (PhysicsScene == null)
  1991. return false;
  1992. return PhysicsScene.SupportsRaycastWorldFiltered();
  1993. }
  1994. public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  1995. {
  1996. if (PhysicsScene == null)
  1997. return null;
  1998. return PhysicsScene.RaycastWorld(position, direction, length, Count, filter);
  1999. }
  2000. /// <summary>
  2001. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  2002. /// </summary>
  2003. /// <param name="RayStart"></param>
  2004. /// <param name="RayEnd"></param>
  2005. /// <param name="RayTargetID"></param>
  2006. /// <param name="rot"></param>
  2007. /// <param name="bypassRayCast"></param>
  2008. /// <param name="RayEndIsIntersection"></param>
  2009. /// <param name="frontFacesOnly"></param>
  2010. /// <param name="scale"></param>
  2011. /// <param name="FaceCenter"></param>
  2012. /// <returns></returns>
  2013. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  2014. {
  2015. Vector3 dir = RayEnd - RayStart;
  2016. float wheight = (float)RegionInfo.RegionSettings.WaterHeight;
  2017. Vector3 wpos = Vector3.Zero;
  2018. // Check for water surface intersection from above
  2019. if ((RayStart.Z > wheight) && (RayEnd.Z < wheight))
  2020. {
  2021. float ratio = (wheight - RayStart.Z) / dir.Z;
  2022. wpos.X = RayStart.X + (ratio * dir.X);
  2023. wpos.Y = RayStart.Y + (ratio * dir.Y);
  2024. wpos.Z = wheight;
  2025. }
  2026. Vector3 pos = Vector3.Zero;
  2027. if (RayEndIsIntersection != (byte)1)
  2028. {
  2029. float dist = dir.Length();
  2030. if (dist != 0)
  2031. {
  2032. Vector3 direction = dir * (1 / dist);
  2033. dist += 1.0f;
  2034. if (SupportsRayCastFiltered())
  2035. {
  2036. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  2037. rayfilter |= RayFilterFlags.land;
  2038. rayfilter |= RayFilterFlags.physical;
  2039. rayfilter |= RayFilterFlags.nonphysical;
  2040. rayfilter |= RayFilterFlags.LSLPhantom; // ubODE will only see volume detectors
  2041. // get some more contacts ???
  2042. int physcount = 4;
  2043. List<ContactResult> physresults =
  2044. (List<ContactResult>)RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  2045. if (physresults != null && physresults.Count > 0)
  2046. {
  2047. // look for terrain ?
  2048. if(RayTargetID == UUID.Zero)
  2049. {
  2050. foreach (ContactResult r in physresults)
  2051. {
  2052. if (r.ConsumerID == 0)
  2053. {
  2054. pos = r.Normal * scale;
  2055. pos *= 0.5f;
  2056. pos = r.Pos + pos;
  2057. if (wpos.Z > pos.Z) pos = wpos;
  2058. return pos;
  2059. }
  2060. }
  2061. }
  2062. else
  2063. {
  2064. foreach (ContactResult r in physresults)
  2065. {
  2066. SceneObjectPart part = GetSceneObjectPart(r.ConsumerID);
  2067. if (part == null)
  2068. continue;
  2069. if (part.UUID == RayTargetID)
  2070. {
  2071. pos = r.Normal * scale;
  2072. pos *= 0.5f;
  2073. pos = r.Pos + pos;
  2074. if (wpos.Z > pos.Z) pos = wpos;
  2075. return pos;
  2076. }
  2077. }
  2078. }
  2079. // else the first we got
  2080. pos = physresults[0].Normal * scale;
  2081. pos *= 0.5f;
  2082. pos = physresults[0].Pos + pos;
  2083. if (wpos.Z > pos.Z)
  2084. pos = wpos;
  2085. return pos;
  2086. }
  2087. }
  2088. if (RayTargetID != UUID.Zero)
  2089. {
  2090. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  2091. Ray NewRay = new Ray(RayStart, direction);
  2092. if (target != null)
  2093. {
  2094. pos = target.AbsolutePosition;
  2095. // Ray Trace against target here
  2096. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  2097. // Un-comment out the following line to Get Raytrace results printed to the console.
  2098. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2099. float ScaleOffset = 0.5f;
  2100. // If we hit something
  2101. if (ei.HitTF)
  2102. {
  2103. Vector3 scaleComponent = ei.AAfaceNormal;
  2104. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2105. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2106. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2107. ScaleOffset = Math.Abs(ScaleOffset);
  2108. Vector3 intersectionpoint = ei.ipoint;
  2109. Vector3 normal = ei.normal;
  2110. // Set the position to the intersection point
  2111. Vector3 offset = (normal * (ScaleOffset / 2f));
  2112. pos = (intersectionpoint + offset);
  2113. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  2114. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  2115. // Un-offset the prim (it gets offset later by the consumer method)
  2116. //pos.Z -= 0.25F;
  2117. if (wpos.Z > pos.Z) pos = wpos;
  2118. return pos;
  2119. }
  2120. }
  2121. else
  2122. {
  2123. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  2124. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(NewRay, true, false);
  2125. // Un-comment the following line to print the raytrace results to the console.
  2126. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2127. if (ei.HitTF)
  2128. {
  2129. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2130. }
  2131. else
  2132. {
  2133. // fall back to our stupid functionality
  2134. pos = RayEnd;
  2135. }
  2136. if (wpos.Z > pos.Z) pos = wpos;
  2137. return pos;
  2138. }
  2139. }
  2140. }
  2141. }
  2142. // fall back to our stupid functionality
  2143. pos = RayEnd;
  2144. //increase height so its above the ground.
  2145. //should be getting the normal of the ground at the rez point and using that?
  2146. pos.Z += scale.Z / 2f;
  2147. // return pos;
  2148. // check against posible water intercept
  2149. if (wpos.Z > pos.Z) pos = wpos;
  2150. return pos;
  2151. }
  2152. /// <summary>
  2153. /// Create a New SceneObjectGroup/Part by raycasting
  2154. /// </summary>
  2155. /// <param name="ownerID"></param>
  2156. /// <param name="groupID"></param>
  2157. /// <param name="RayEnd"></param>
  2158. /// <param name="rot"></param>
  2159. /// <param name="shape"></param>
  2160. /// <param name="bypassRaycast"></param>
  2161. /// <param name="RayStart"></param>
  2162. /// <param name="RayTargetID"></param>
  2163. /// <param name="RayEndIsIntersection"></param>
  2164. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  2165. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  2166. byte RayEndIsIntersection)
  2167. {
  2168. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  2169. if (Permissions.CanRezObject(1, ownerID, pos))
  2170. {
  2171. // rez ON the ground, not IN the ground
  2172. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  2173. AddNewPrim(ownerID, groupID, pos, rot, shape);
  2174. }
  2175. else
  2176. {
  2177. IClientAPI client = null;
  2178. if (TryGetClient(ownerID, out client))
  2179. client.SendAlertMessage("You cannot create objects here.");
  2180. }
  2181. }
  2182. public virtual SceneObjectGroup AddNewPrim(
  2183. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  2184. {
  2185. //m_log.DebugFormat(
  2186. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  2187. SceneObjectGroup sceneObject = null;
  2188. // If an entity creator has been registered for this prim type then use that
  2189. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  2190. {
  2191. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  2192. }
  2193. else
  2194. {
  2195. // Otherwise, use this default creation code;
  2196. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  2197. AddNewSceneObject(sceneObject, true);
  2198. sceneObject.SetGroup(groupID, null);
  2199. if (AgentPreferencesService != null) // This will override the brave new full perm world!
  2200. {
  2201. AgentPrefs prefs = AgentPreferencesService.GetAgentPreferences(ownerID);
  2202. // Only apply user selected prefs if the user set them
  2203. if (prefs != null && prefs.PermNextOwner != 0)
  2204. {
  2205. sceneObject.RootPart.GroupMask = (uint)prefs.PermGroup;
  2206. sceneObject.RootPart.EveryoneMask = (uint)prefs.PermEveryone;
  2207. sceneObject.RootPart.NextOwnerMask = (uint)prefs.PermNextOwner;
  2208. }
  2209. }
  2210. }
  2211. if (UserManagementModule != null)
  2212. sceneObject.RootPart.CreatorIdentification = UserManagementModule.GetUserUUI(ownerID);
  2213. sceneObject.ScheduleGroupForFullUpdate();
  2214. return sceneObject;
  2215. }
  2216. /// <summary>
  2217. /// Add an object into the scene that has come from storage
  2218. /// </summary>
  2219. ///
  2220. /// <param name="sceneObject"></param>
  2221. /// <param name="attachToBackup">
  2222. /// If true, changes to the object will be reflected in its persisted data
  2223. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2224. /// </param>
  2225. /// <param name="alreadyPersisted">
  2226. /// If true, we won't persist this object until it changes
  2227. /// If false, we'll persist this object immediately
  2228. /// </param>
  2229. /// <param name="sendClientUpdates">
  2230. /// If true, we send updates to the client to tell it about this object
  2231. /// If false, we leave it up to the caller to do this
  2232. /// </param>
  2233. /// <returns>
  2234. /// true if the object was added, false if an object with the same uuid was already in the scene
  2235. /// </returns>
  2236. public bool AddRestoredSceneObject(
  2237. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
  2238. {
  2239. if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
  2240. {
  2241. sceneObject.IsDeleted = false;
  2242. EventManager.TriggerObjectAddedToScene(sceneObject);
  2243. return true;
  2244. }
  2245. return false;
  2246. }
  2247. /// <summary>
  2248. /// Add an object into the scene that has come from storage
  2249. /// </summary>
  2250. ///
  2251. /// <param name="sceneObject"></param>
  2252. /// <param name="attachToBackup">
  2253. /// If true, changes to the object will be reflected in its persisted data
  2254. /// If false, the persisted data will not be changed even if the object in the scene is changed
  2255. /// </param>
  2256. /// <param name="alreadyPersisted">
  2257. /// If true, we won't persist this object until it changes
  2258. /// If false, we'll persist this object immediately
  2259. /// </param>
  2260. /// <returns>
  2261. /// true if the object was added, false if an object with the same uuid was already in the scene
  2262. /// </returns>
  2263. public bool AddRestoredSceneObject(
  2264. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  2265. {
  2266. return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
  2267. }
  2268. /// <summary>
  2269. /// Add a newly created object to the scene. Updates are also sent to viewers.
  2270. /// </summary>
  2271. /// <param name="sceneObject"></param>
  2272. /// <param name="attachToBackup">
  2273. /// If true, the object is made persistent into the scene.
  2274. /// If false, the object will not persist over server restarts
  2275. /// </param>
  2276. /// <returns>true if the object was added. false if not</returns>
  2277. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  2278. {
  2279. return AddNewSceneObject(sceneObject, attachToBackup, true);
  2280. }
  2281. /// <summary>
  2282. /// Add a newly created object to the scene
  2283. /// </summary>
  2284. /// <param name="sceneObject"></param>
  2285. /// <param name="attachToBackup">
  2286. /// If true, the object is made persistent into the scene.
  2287. /// If false, the object will not persist over server restarts
  2288. /// </param>
  2289. /// <param name="sendClientUpdates">
  2290. /// If true, updates for the new scene object are sent to all viewers in range.
  2291. /// If false, it is left to the caller to schedule the update
  2292. /// </param>
  2293. /// <returns>true if the object was added. false if not</returns>
  2294. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  2295. {
  2296. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates))
  2297. {
  2298. EventManager.TriggerObjectAddedToScene(sceneObject);
  2299. return true;
  2300. }
  2301. return false;
  2302. }
  2303. /// <summary>
  2304. /// Add a newly created object to the scene.
  2305. /// </summary>
  2306. /// <remarks>
  2307. /// This method does not send updates to the client - callers need to handle this themselves.
  2308. /// </remarks>
  2309. /// <param name="sceneObject"></param>
  2310. /// <param name="attachToBackup"></param>
  2311. /// <param name="pos">Position of the object. If null then the position stored in the object is used.</param>
  2312. /// <param name="rot">Rotation of the object. If null then the rotation stored in the object is used.</param>
  2313. /// <param name="vel">Velocity of the object. This parameter only has an effect if the object is physical</param>
  2314. /// <returns></returns>
  2315. public bool AddNewSceneObject(
  2316. SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel)
  2317. {
  2318. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, pos, rot, vel))
  2319. {
  2320. EventManager.TriggerObjectAddedToScene(sceneObject);
  2321. return true;
  2322. }
  2323. return false;
  2324. }
  2325. /// <summary>
  2326. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2327. /// </summary>
  2328. public void DeleteAllSceneObjects()
  2329. {
  2330. DeleteAllSceneObjects(false);
  2331. }
  2332. /// <summary>
  2333. /// Delete every object from the scene. This does not include attachments worn by avatars.
  2334. /// </summary>
  2335. public void DeleteAllSceneObjects(bool exceptNoCopy)
  2336. {
  2337. List<SceneObjectGroup> toReturn = new List<SceneObjectGroup>();
  2338. lock (Entities)
  2339. {
  2340. EntityBase[] entities = Entities.GetEntities();
  2341. foreach (EntityBase e in entities)
  2342. {
  2343. if (e is SceneObjectGroup)
  2344. {
  2345. SceneObjectGroup sog = (SceneObjectGroup)e;
  2346. if (sog != null && !sog.IsAttachment)
  2347. {
  2348. if (!exceptNoCopy || ((sog.GetEffectivePermissions() & (uint)PermissionMask.Copy) != 0))
  2349. {
  2350. DeleteSceneObject((SceneObjectGroup)e, false);
  2351. }
  2352. else
  2353. {
  2354. toReturn.Add((SceneObjectGroup)e);
  2355. }
  2356. }
  2357. }
  2358. }
  2359. }
  2360. if (toReturn.Count > 0)
  2361. {
  2362. returnObjects(toReturn.ToArray(), UUID.Zero);
  2363. }
  2364. }
  2365. /// <summary>
  2366. /// Synchronously delete the given object from the scene.
  2367. /// </summary>
  2368. /// <remarks>
  2369. /// Scripts are also removed.
  2370. /// </remarks>
  2371. /// <param name="group">Object Id</param>
  2372. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2373. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  2374. {
  2375. DeleteSceneObject(group, silent, true);
  2376. }
  2377. /// <summary>
  2378. /// Synchronously delete the given object from the scene.
  2379. /// </summary>
  2380. /// <param name="group">Object Id</param>
  2381. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  2382. /// <param name="removeScripts">If true, then scripts are removed. If false, then they are only stopped.</para>
  2383. public void DeleteSceneObject(SceneObjectGroup group, bool silent, bool removeScripts)
  2384. {
  2385. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  2386. if (removeScripts)
  2387. group.RemoveScriptInstances(true);
  2388. else
  2389. group.StopScriptInstances();
  2390. SceneObjectPart[] partList = group.Parts;
  2391. foreach (SceneObjectPart part in partList)
  2392. {
  2393. if (part.KeyframeMotion != null)
  2394. {
  2395. part.KeyframeMotion.Delete();
  2396. part.KeyframeMotion = null;
  2397. }
  2398. if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
  2399. {
  2400. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  2401. }
  2402. else if (part.PhysActor != null)
  2403. {
  2404. part.RemoveFromPhysics();
  2405. }
  2406. }
  2407. if (UnlinkSceneObject(group, false))
  2408. {
  2409. EventManager.TriggerObjectBeingRemovedFromScene(group);
  2410. EventManager.TriggerParcelPrimCountTainted();
  2411. }
  2412. group.DeleteGroupFromScene(silent);
  2413. // use this to mean also full delete
  2414. if (removeScripts)
  2415. group.Clear();
  2416. partList = null;
  2417. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  2418. }
  2419. /// <summary>
  2420. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  2421. /// object itself is not destroyed.
  2422. /// </summary>
  2423. /// <param name="so">The scene object.</param>
  2424. /// <param name="softDelete">If true, only deletes from scene, but keeps the object in the database.</param>
  2425. /// <returns>true if the object was in the scene, false if it was not</returns>
  2426. public bool UnlinkSceneObject(SceneObjectGroup so, bool softDelete)
  2427. {
  2428. if (m_sceneGraph.DeleteSceneObject(so.UUID, softDelete))
  2429. {
  2430. if (!softDelete)
  2431. {
  2432. // If the group contains prims whose SceneGroupID is incorrect then force a
  2433. // database update, because RemoveObject() works by searching on the SceneGroupID.
  2434. // This is an expensive thing to do so only do it if absolutely necessary.
  2435. if (so.GroupContainsForeignPrims)
  2436. ForceSceneObjectBackup(so);
  2437. so.DetachFromBackup();
  2438. SimulationDataService.RemoveObject(so.UUID, RegionInfo.RegionID);
  2439. }
  2440. // We need to keep track of this state in case this group is still queued for further backup.
  2441. so.IsDeleted = true;
  2442. return true;
  2443. }
  2444. return false;
  2445. }
  2446. public void updateScenePartGroup(SceneObjectPart part, SceneObjectGroup grp)
  2447. {
  2448. m_sceneGraph.updateScenePartGroup(part, grp);
  2449. }
  2450. /* not in use, outdate by async method
  2451. /// <summary>
  2452. /// Move the given scene object into a new region depending on which region its absolute position has moved
  2453. /// into.
  2454. ///
  2455. /// </summary>
  2456. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  2457. /// <param name="grp">the scene object that we're crossing</param>
  2458. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  2459. {
  2460. if (grp == null)
  2461. return;
  2462. if (grp.IsDeleted)
  2463. return;
  2464. if (grp.RootPart.DIE_AT_EDGE)
  2465. {
  2466. // We remove the object here
  2467. try
  2468. {
  2469. DeleteSceneObject(grp, false);
  2470. }
  2471. catch (Exception)
  2472. {
  2473. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  2474. }
  2475. return;
  2476. }
  2477. if (grp.RootPart.RETURN_AT_EDGE)
  2478. {
  2479. // We remove the object here
  2480. try
  2481. {
  2482. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  2483. objects.Add(grp);
  2484. SceneObjectGroup[] objectsArray = objects.ToArray();
  2485. returnObjects(objectsArray, UUID.Zero);
  2486. }
  2487. catch (Exception)
  2488. {
  2489. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  2490. }
  2491. return;
  2492. }
  2493. if (EntityTransferModule != null)
  2494. EntityTransferModule.Cross(grp, attemptedPosition, silent);
  2495. }
  2496. */
  2497. // Simple test to see if a position is in the current region.
  2498. // This test is mostly used to see if a region crossing is necessary.
  2499. // Assuming the position is relative to the region so anything outside its bounds.
  2500. // Return 'true' if position inside region.
  2501. public bool PositionIsInCurrentRegion(Vector3 pos)
  2502. {
  2503. bool ret = false;
  2504. int xx = (int)Math.Floor(pos.X);
  2505. int yy = (int)Math.Floor(pos.Y);
  2506. if (xx < 0 || yy < 0)
  2507. return false;
  2508. if (xx < RegionInfo.RegionSizeX && yy < RegionInfo.RegionSizeY )
  2509. ret = true;
  2510. return ret;
  2511. }
  2512. /// <summary>
  2513. /// Called when objects or attachments cross the border, or teleport, between regions.
  2514. /// </summary>
  2515. /// <param name="sog"></param>
  2516. /// <returns></returns>
  2517. public bool IncomingCreateObject(Vector3 newPosition, ISceneObject sog)
  2518. {
  2519. //m_log.DebugFormat(" >>> IncomingCreateObject(sog) <<< {0} deleted? {1} isAttach? {2}", ((SceneObjectGroup)sog).AbsolutePosition,
  2520. // ((SceneObjectGroup)sog).IsDeleted, ((SceneObjectGroup)sog).RootPart.IsAttachment);
  2521. SceneObjectGroup newObject;
  2522. try
  2523. {
  2524. newObject = (SceneObjectGroup)sog;
  2525. }
  2526. catch (Exception e)
  2527. {
  2528. m_log.WarnFormat("[INTERREGION]: Problem casting object, exception {0}{1}", e.Message, e.StackTrace);
  2529. return false;
  2530. }
  2531. if (!EntityTransferModule.HandleIncomingSceneObject(newObject, newPosition))
  2532. return false;
  2533. // Do this as late as possible so that listeners have full access to the incoming object
  2534. EventManager.TriggerOnIncomingSceneObject(newObject);
  2535. return true;
  2536. }
  2537. /// <summary>
  2538. /// Adds a Scene Object group to the Scene.
  2539. /// Verifies that the creator of the object is not banned from the simulator.
  2540. /// Checks if the item is an Attachment
  2541. /// </summary>
  2542. /// <param name="sceneObject"></param>
  2543. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2544. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2545. {
  2546. if (sceneObject.OwnerID == UUID.Zero)
  2547. {
  2548. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero", sceneObject.UUID);
  2549. return false;
  2550. }
  2551. // If the user is banned, we won't let any of their objects
  2552. // enter. Period.
  2553. //
  2554. int flags = GetUserFlags(sceneObject.OwnerID);
  2555. if (RegionInfo.EstateSettings.IsBanned(sceneObject.OwnerID, flags))
  2556. {
  2557. m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", sceneObject.OwnerID);
  2558. return false;
  2559. }
  2560. // Force allocation of new LocalId
  2561. //
  2562. SceneObjectPart[] parts = sceneObject.Parts;
  2563. for (int i = 0; i < parts.Length; i++)
  2564. parts[i].LocalId = 0;
  2565. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2566. {
  2567. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2568. // sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
  2569. // Don't sent a full update here because this will cause full updates to be sent twice for
  2570. // attachments on region crossings, resulting in viewer glitches.
  2571. AddRestoredSceneObject(sceneObject, false, false, false);
  2572. // Handle attachment special case
  2573. SceneObjectPart RootPrim = sceneObject.RootPart;
  2574. // Fix up attachment Parent Local ID
  2575. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2576. if (sp != null)
  2577. {
  2578. SceneObjectGroup grp = sceneObject;
  2579. // m_log.DebugFormat(
  2580. // "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.FromItemID, grp.UUID);
  2581. // m_log.DebugFormat(
  2582. // "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2583. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2584. // We must currently not resume scripts at this stage since AttachmentsModule does not have the
  2585. // information that this is due to a teleport/border cross rather than an ordinary attachment.
  2586. // We currently do this in Scene.MakeRootAgent() instead.
  2587. if (AttachmentsModule != null)
  2588. AttachmentsModule.AttachObject(sp, grp, 0, false, false, true);
  2589. }
  2590. else
  2591. {
  2592. m_log.DebugFormat("[SCENE]: Attachment {0} arrived and scene presence was not found, setting to temp", sceneObject.UUID);
  2593. // RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2594. // RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2595. }
  2596. if (sceneObject.OwnerID == UUID.Zero)
  2597. {
  2598. m_log.ErrorFormat("[SCENE]: Owner ID for {0} was zero after attachment processing. BUG!", sceneObject.UUID);
  2599. return false;
  2600. }
  2601. }
  2602. else
  2603. {
  2604. if (sceneObject.OwnerID == UUID.Zero)
  2605. {
  2606. m_log.ErrorFormat("[SCENE]: Owner ID for non-attachment {0} was zero", sceneObject.UUID);
  2607. return false;
  2608. }
  2609. AddRestoredSceneObject(sceneObject, true, false);
  2610. }
  2611. return true;
  2612. }
  2613. private int GetStateSource(SceneObjectGroup sog)
  2614. {
  2615. if(!sog.IsAttachmentCheckFull())
  2616. return 2; // StateSource.PrimCrossing
  2617. ScenePresence sp = GetScenePresence(sog.OwnerID);
  2618. if (sp != null)
  2619. return sp.GetStateSource();
  2620. return 2; // StateSource.PrimCrossing
  2621. }
  2622. public int GetUserFlags(UUID user)
  2623. {
  2624. //Unfortunately the SP approach means that the value is cached until region is restarted
  2625. /*
  2626. ScenePresence sp;
  2627. if (TryGetScenePresence(user, out sp))
  2628. {
  2629. return sp.UserFlags;
  2630. }
  2631. else
  2632. {
  2633. */
  2634. UserAccount uac = UserAccountService.GetUserAccount(RegionInfo.ScopeID, user);
  2635. if (uac == null)
  2636. return 0;
  2637. return uac.UserFlags;
  2638. //}
  2639. }
  2640. #endregion
  2641. #region Add/Remove Avatar Methods
  2642. public override ISceneAgent AddNewAgent(IClientAPI client, PresenceType type)
  2643. {
  2644. ScenePresence sp;
  2645. bool vialogin;
  2646. bool reallyNew = true;
  2647. // Update the number of users attempting to login
  2648. StatsReporter.UpdateUsersLoggingIn(true);
  2649. // Validation occurs in LLUDPServer
  2650. //
  2651. // XXX: A race condition exists here where two simultaneous calls to AddNewAgent can interfere with
  2652. // each other. In practice, this does not currently occur in the code.
  2653. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2654. // We lock here on AgentCircuitData to prevent a race condition between the thread adding a new connection
  2655. // and a simultaneous one that removes it (as can happen if the client is closed at a particular point
  2656. // whilst connecting).
  2657. //
  2658. // It would be easier to lock across all NewUserConnection(), AddNewAgent() and
  2659. // RemoveClient() calls for all agents, but this would allow a slow call (e.g. because of slow service
  2660. // response in some module listening to AddNewAgent()) from holding up unrelated agent calls.
  2661. //
  2662. // In practice, the lock (this) in LLUDPServer.AddNewClient() currently lock across all
  2663. // AddNewClient() operations (though not other ops).
  2664. // In the future this can be relieved once locking per agent (not necessarily on AgentCircuitData) is improved.
  2665. lock (aCircuit)
  2666. {
  2667. vialogin
  2668. = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
  2669. || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
  2670. CheckHeartbeat();
  2671. sp = GetScenePresence(client.AgentId);
  2672. if (sp == null)
  2673. {
  2674. m_log.DebugFormat(
  2675. "[SCENE]: Adding new child scene presence {0} {1} to scene {2} at pos {3}, tpflags: {4}",
  2676. client.Name, client.AgentId, RegionInfo.RegionName, client.StartPos,
  2677. ((TPFlags)aCircuit.teleportFlags).ToString());
  2678. m_clientManager.Add(client);
  2679. SubscribeToClientEvents(client);
  2680. sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type);
  2681. sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags;
  2682. m_eventManager.TriggerOnNewPresence(sp);
  2683. }
  2684. else
  2685. {
  2686. // We must set this here so that TriggerOnNewClient and TriggerOnClientLogin can determine whether the
  2687. // client is for a root or child agent.
  2688. // XXX: This may be better set for a new client before that client is added to the client manager.
  2689. // But need to know what happens in the case where a ScenePresence is already present (and if this
  2690. // actually occurs).
  2691. m_log.WarnFormat(
  2692. "[SCENE]: Already found {0} scene presence for {1} in {2} when asked to add new scene presence",
  2693. sp.IsChildAgent ? "child" : "root", sp.Name, RegionInfo.RegionName);
  2694. reallyNew = false;
  2695. }
  2696. client.SceneAgent = sp;
  2697. // This is currently also being done earlier in NewUserConnection for real users to see if this
  2698. // resolves problems where HG agents are occasionally seen by others as "Unknown user" in chat and other
  2699. // places. However, we still need to do it here for NPCs.
  2700. CacheUserName(sp, aCircuit);
  2701. if (reallyNew)
  2702. EventManager.TriggerOnNewClient(client);
  2703. if (vialogin)
  2704. EventManager.TriggerOnClientLogin(client);
  2705. }
  2706. // User has logged into the scene so update the list of users logging
  2707. // in
  2708. StatsReporter.UpdateUsersLoggingIn(false);
  2709. m_LastLogin = Util.EnvironmentTickCount();
  2710. return sp;
  2711. }
  2712. /// <summary>
  2713. /// Returns the Home URI of the agent, or null if unknown.
  2714. /// </summary>
  2715. public string GetAgentHomeURI(UUID agentID)
  2716. {
  2717. AgentCircuitData circuit = AuthenticateHandler.GetAgentCircuitData(agentID);
  2718. if (circuit != null && circuit.ServiceURLs != null && circuit.ServiceURLs.ContainsKey("HomeURI"))
  2719. return circuit.ServiceURLs["HomeURI"].ToString();
  2720. else
  2721. return null;
  2722. }
  2723. /// <summary>
  2724. /// Cache the user name for later use.
  2725. /// </summary>
  2726. /// <param name="sp"></param>
  2727. /// <param name="aCircuit"></param>
  2728. private void CacheUserName(ScenePresence sp, AgentCircuitData aCircuit)
  2729. {
  2730. if (UserManagementModule != null)
  2731. {
  2732. string first = aCircuit.firstname, last = aCircuit.lastname;
  2733. if (sp != null && sp.PresenceType == PresenceType.Npc)
  2734. {
  2735. UserManagementModule.AddUser(aCircuit.AgentID, first, last, true);
  2736. }
  2737. else
  2738. {
  2739. string homeURL = string.Empty;
  2740. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  2741. homeURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  2742. if (aCircuit.lastname.StartsWith("@"))
  2743. {
  2744. string[] parts = aCircuit.firstname.Split('.');
  2745. if (parts.Length >= 2)
  2746. {
  2747. first = parts[0];
  2748. last = parts[1];
  2749. }
  2750. }
  2751. UserManagementModule.AddUser(aCircuit.AgentID, first, last, homeURL);
  2752. }
  2753. }
  2754. }
  2755. private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin)
  2756. {
  2757. vialogin = false;
  2758. // Do the verification here
  2759. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0)
  2760. {
  2761. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via HG login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2762. vialogin = true;
  2763. IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
  2764. if (userVerification != null && ep != null)
  2765. {
  2766. if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString()))
  2767. {
  2768. // uh-oh, this is fishy
  2769. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2770. return false;
  2771. }
  2772. else
  2773. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2774. }
  2775. }
  2776. else if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
  2777. {
  2778. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via regular login. Client IP verification not performed.",
  2779. aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2780. vialogin = true;
  2781. }
  2782. return true;
  2783. }
  2784. // Called by Caps, on the first HTTP contact from the client
  2785. public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep)
  2786. {
  2787. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  2788. if (aCircuit != null)
  2789. {
  2790. bool vialogin = false;
  2791. if (!VerifyClient(aCircuit, ep, out vialogin))
  2792. {
  2793. // if it doesn't pass, we remove the agentcircuitdata altogether
  2794. // and the scene presence and the client, if they exist
  2795. try
  2796. {
  2797. ScenePresence sp = WaitGetScenePresence(agentID);
  2798. if (sp != null)
  2799. {
  2800. PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  2801. CloseAgent(sp.UUID, false);
  2802. }
  2803. // BANG! SLASH!
  2804. m_authenticateHandler.RemoveCircuit(agentID);
  2805. return false;
  2806. }
  2807. catch (Exception e)
  2808. {
  2809. m_log.DebugFormat("[SCENE]: Exception while closing aborted client: {0}", e.StackTrace);
  2810. }
  2811. }
  2812. else
  2813. return true;
  2814. }
  2815. return false;
  2816. }
  2817. /// <summary>
  2818. /// Register for events from the client
  2819. /// </summary>
  2820. /// <param name="client">The IClientAPI of the connected client</param>
  2821. public virtual void SubscribeToClientEvents(IClientAPI client)
  2822. {
  2823. SubscribeToClientTerrainEvents(client);
  2824. SubscribeToClientPrimEvents(client);
  2825. SubscribeToClientPrimRezEvents(client);
  2826. SubscribeToClientInventoryEvents(client);
  2827. SubscribeToClientTeleportEvents(client);
  2828. SubscribeToClientScriptEvents(client);
  2829. SubscribeToClientParcelEvents(client);
  2830. SubscribeToClientGridEvents(client);
  2831. SubscribeToClientNetworkEvents(client);
  2832. }
  2833. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2834. {
  2835. // client.OnRegionHandShakeReply += SendLayerData;
  2836. }
  2837. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2838. {
  2839. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
  2840. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2841. client.onClientChangeObject += m_sceneGraph.ClientChangeObject;
  2842. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2843. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2844. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2845. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2846. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2847. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2848. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2849. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2850. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2851. client.OnObjectRequest += RequestPrim;
  2852. client.OnObjectSelect += SelectPrim;
  2853. client.OnObjectDeselect += DeselectPrim;
  2854. client.OnDeRezObject += DeRezObjects;
  2855. client.OnObjectName += m_sceneGraph.PrimName;
  2856. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2857. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2858. client.OnLinkObjects += LinkObjects;
  2859. client.OnDelinkObjects += DelinkObjects;
  2860. client.OnObjectDuplicate += DuplicateObject;
  2861. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2862. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2863. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2864. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2865. client.OnGrabObject += ProcessObjectGrab;
  2866. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2867. client.OnDeGrabObject += ProcessObjectDeGrab;
  2868. client.OnSpinStart += ProcessSpinStart;
  2869. client.OnSpinUpdate += ProcessSpinObject;
  2870. client.OnSpinStop += ProcessSpinObjectStop;
  2871. client.OnUndo += m_sceneGraph.HandleUndo;
  2872. client.OnRedo += m_sceneGraph.HandleRedo;
  2873. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2874. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2875. client.OnObjectOwner += ObjectOwner;
  2876. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  2877. }
  2878. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2879. {
  2880. client.OnAddPrim += AddNewPrim;
  2881. client.OnRezObject += RezObject;
  2882. }
  2883. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2884. {
  2885. client.OnLinkInventoryItem += HandleLinkInventoryItem;
  2886. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2887. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2888. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2889. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2890. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2891. client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
  2892. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2893. client.OnCopyInventoryItem += CopyInventoryItem;
  2894. client.OnMoveItemsAndLeaveCopy += MoveInventoryItemsLeaveCopy;
  2895. client.OnMoveInventoryItem += MoveInventoryItem;
  2896. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2897. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2898. client.OnRezScript += RezScript;
  2899. client.OnRequestTaskInventory += RequestTaskInventory;
  2900. client.OnRemoveTaskItem += RemoveTaskInventory;
  2901. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2902. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2903. }
  2904. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2905. {
  2906. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2907. }
  2908. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2909. {
  2910. client.OnScriptReset += ProcessScriptReset;
  2911. client.OnGetScriptRunning += GetScriptRunning;
  2912. client.OnSetScriptRunning += SetScriptRunning;
  2913. }
  2914. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2915. {
  2916. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2917. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2918. client.OnParcelBuy += ProcessParcelBuy;
  2919. }
  2920. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2921. {
  2922. //client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
  2923. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2924. }
  2925. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2926. {
  2927. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2928. client.OnViewerEffect += ProcessViewerEffect;
  2929. }
  2930. /// <summary>
  2931. /// Unsubscribe the client from events.
  2932. /// </summary>
  2933. /// FIXME: Not called anywhere!
  2934. /// <param name="client">The IClientAPI of the client</param>
  2935. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2936. {
  2937. UnSubscribeToClientTerrainEvents(client);
  2938. UnSubscribeToClientPrimEvents(client);
  2939. UnSubscribeToClientPrimRezEvents(client);
  2940. UnSubscribeToClientInventoryEvents(client);
  2941. UnSubscribeToClientTeleportEvents(client);
  2942. UnSubscribeToClientScriptEvents(client);
  2943. UnSubscribeToClientParcelEvents(client);
  2944. UnSubscribeToClientGridEvents(client);
  2945. UnSubscribeToClientNetworkEvents(client);
  2946. }
  2947. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2948. {
  2949. // client.OnRegionHandShakeReply -= SendLayerData;
  2950. }
  2951. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2952. {
  2953. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
  2954. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2955. client.onClientChangeObject -= m_sceneGraph.ClientChangeObject;
  2956. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2957. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2958. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2959. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2960. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2961. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2962. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2963. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2964. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2965. client.OnObjectRequest -= RequestPrim;
  2966. client.OnObjectSelect -= SelectPrim;
  2967. client.OnObjectDeselect -= DeselectPrim;
  2968. client.OnDeRezObject -= DeRezObjects;
  2969. client.OnObjectName -= m_sceneGraph.PrimName;
  2970. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2971. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2972. client.OnLinkObjects -= LinkObjects;
  2973. client.OnDelinkObjects -= DelinkObjects;
  2974. client.OnObjectDuplicate -= DuplicateObject;
  2975. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2976. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2977. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2978. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2979. client.OnGrabObject -= ProcessObjectGrab;
  2980. client.OnGrabUpdate -= ProcessObjectGrabUpdate;
  2981. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2982. client.OnSpinStart -= ProcessSpinStart;
  2983. client.OnSpinUpdate -= ProcessSpinObject;
  2984. client.OnSpinStop -= ProcessSpinObjectStop;
  2985. client.OnUndo -= m_sceneGraph.HandleUndo;
  2986. client.OnRedo -= m_sceneGraph.HandleRedo;
  2987. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2988. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2989. client.OnObjectOwner -= ObjectOwner;
  2990. }
  2991. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2992. {
  2993. client.OnAddPrim -= AddNewPrim;
  2994. client.OnRezObject -= RezObject;
  2995. }
  2996. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2997. {
  2998. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2999. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  3000. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  3001. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  3002. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  3003. client.OnFetchInventory -= m_asyncInventorySender.HandleFetchInventory;
  3004. client.OnUpdateInventoryItem -= UpdateInventoryItemAsset;
  3005. client.OnCopyInventoryItem -= CopyInventoryItem;
  3006. client.OnMoveInventoryItem -= MoveInventoryItem;
  3007. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  3008. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  3009. client.OnRezScript -= RezScript;
  3010. client.OnRequestTaskInventory -= RequestTaskInventory;
  3011. client.OnRemoveTaskItem -= RemoveTaskInventory;
  3012. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  3013. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  3014. }
  3015. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  3016. {
  3017. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  3018. //client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  3019. //client.OnTeleportHomeRequest -= TeleportClientHome;
  3020. }
  3021. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  3022. {
  3023. client.OnScriptReset -= ProcessScriptReset;
  3024. client.OnGetScriptRunning -= GetScriptRunning;
  3025. client.OnSetScriptRunning -= SetScriptRunning;
  3026. }
  3027. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  3028. {
  3029. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  3030. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  3031. client.OnParcelBuy -= ProcessParcelBuy;
  3032. }
  3033. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  3034. {
  3035. //client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
  3036. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  3037. }
  3038. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  3039. {
  3040. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  3041. client.OnViewerEffect -= ProcessViewerEffect;
  3042. }
  3043. /// <summary>
  3044. /// Teleport an avatar to their home region
  3045. /// </summary>
  3046. /// <param name="agentId">The avatar's Unique ID</param>
  3047. /// <param name="client">The IClientAPI for the client</param>
  3048. public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
  3049. {
  3050. if (EntityTransferModule != null)
  3051. {
  3052. return EntityTransferModule.TeleportHome(agentId, client);
  3053. }
  3054. else
  3055. {
  3056. m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
  3057. client.SendTeleportFailed("Unable to perform teleports on this simulator.");
  3058. }
  3059. return false;
  3060. }
  3061. /// <summary>
  3062. /// Duplicates object specified by localID. This is the event handler for IClientAPI.
  3063. /// </summary>
  3064. /// <param name="originalPrim">ID of object to duplicate</param>
  3065. /// <param name="offset"></param>
  3066. /// <param name="flags"></param>
  3067. /// <param name="AgentID">Agent doing the duplication</param>
  3068. /// <param name="GroupID">Group of new object</param>
  3069. public void DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID)
  3070. {
  3071. SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, flags, AgentID, GroupID, Quaternion.Identity);
  3072. if (copy != null)
  3073. EventManager.TriggerObjectAddedToScene(copy);
  3074. }
  3075. /// <summary>
  3076. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  3077. /// RayEnd and RayStart to determine what the angle of the ray is
  3078. /// </summary>
  3079. /// <param name="localID">ID of object to duplicate</param>
  3080. /// <param name="dupeFlags"></param>
  3081. /// <param name="AgentID">Agent doing the duplication</param>
  3082. /// <param name="GroupID">Group of new object</param>
  3083. /// <param name="RayTargetObj">The target of the Ray</param>
  3084. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  3085. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  3086. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  3087. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  3088. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  3089. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  3090. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  3091. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  3092. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  3093. {
  3094. Vector3 pos;
  3095. const bool frontFacesOnly = true;
  3096. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  3097. SceneObjectPart target = GetSceneObjectPart(localID);
  3098. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  3099. if (target != null && target2 != null)
  3100. {
  3101. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  3102. pos = target2.AbsolutePosition;
  3103. //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString());
  3104. // TODO: Raytrace better here
  3105. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  3106. Ray NewRay = new Ray(RayStart,direction);
  3107. // Ray Trace against target here
  3108. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  3109. // Un-comment out the following line to Get Raytrace results printed to the console.
  3110. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  3111. float ScaleOffset = 0.5f;
  3112. // If we hit something
  3113. if (ei.HitTF)
  3114. {
  3115. Vector3 scale = target.Scale;
  3116. Vector3 scaleComponent = ei.AAfaceNormal;
  3117. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  3118. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  3119. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  3120. ScaleOffset = Math.Abs(ScaleOffset);
  3121. Vector3 intersectionpoint = ei.ipoint;
  3122. Vector3 normal = ei.normal;
  3123. Vector3 offset = normal * (ScaleOffset / 2f);
  3124. pos = intersectionpoint + offset;
  3125. // stick in offset format from the original prim
  3126. pos = pos - target.ParentGroup.AbsolutePosition;
  3127. SceneObjectGroup copy;
  3128. if (CopyRotates)
  3129. {
  3130. Quaternion worldRot = target2.GetWorldRotation();
  3131. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  3132. copy = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  3133. //obj.Rotation = worldRot;
  3134. //obj.UpdateGroupRotationR(worldRot);
  3135. }
  3136. else
  3137. {
  3138. copy = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, Quaternion.Identity);
  3139. }
  3140. if (copy != null)
  3141. EventManager.TriggerObjectAddedToScene(copy);
  3142. }
  3143. }
  3144. }
  3145. /// <summary>
  3146. /// Get the avatar appearance for the given client.
  3147. /// </summary>
  3148. /// <param name="client"></param>
  3149. /// <param name="appearance"></param>
  3150. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  3151. {
  3152. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  3153. if (aCircuit == null)
  3154. {
  3155. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  3156. appearance = new AvatarAppearance();
  3157. return;
  3158. }
  3159. appearance = aCircuit.Appearance;
  3160. if (appearance == null)
  3161. {
  3162. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  3163. appearance = new AvatarAppearance();
  3164. }
  3165. }
  3166. /// <summary>
  3167. /// Remove the given client from the scene.
  3168. /// </summary>
  3169. /// <remarks>
  3170. /// Only clientstack code should call this directly. All other code should call IncomingCloseAgent() instead
  3171. /// to properly operate the state machine and avoid race conditions with other close requests (such as directly
  3172. /// from viewers).
  3173. /// </remarks>
  3174. /// <param name='agentID'>ID of agent to close</param>
  3175. /// <param name='closeChildAgents'>
  3176. /// Close the neighbour child agents associated with this client.
  3177. /// </param>
  3178. ///
  3179. private object m_removeClientPrivLock = new Object();
  3180. public void RemoveClient(UUID agentID, bool closeChildAgents)
  3181. {
  3182. AgentCircuitData acd = m_authenticateHandler.GetAgentCircuitData(agentID);
  3183. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3184. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3185. // However, will keep for now just in case.
  3186. if (acd == null)
  3187. {
  3188. m_log.ErrorFormat(
  3189. "[SCENE]: No agent circuit found for {0} in {1}, aborting Scene.RemoveClient", agentID, Name);
  3190. return;
  3191. }
  3192. // TODO: Can we now remove this lock?
  3193. lock (m_removeClientPrivLock)
  3194. {
  3195. bool isChildAgent = false;
  3196. ScenePresence avatar = GetScenePresence(agentID);
  3197. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  3198. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  3199. // However, will keep for now just in case.
  3200. if (avatar == null)
  3201. {
  3202. m_log.ErrorFormat(
  3203. "[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in the scene.", agentID);
  3204. m_authenticateHandler.RemoveCircuit(agentID);
  3205. return;
  3206. }
  3207. try
  3208. {
  3209. isChildAgent = avatar.IsChildAgent;
  3210. m_log.DebugFormat(
  3211. "[SCENE]: Removing {0} agent {1} {2} from {3}",
  3212. isChildAgent ? "child" : "root", avatar.Name, agentID, Name);
  3213. // Don't do this to root agents, it's not nice for the viewer
  3214. if (closeChildAgents && isChildAgent)
  3215. {
  3216. // Tell a single agent to disconnect from the region.
  3217. // Let's do this via UDP
  3218. avatar.ControllingClient.SendShutdownConnectionNotice();
  3219. }
  3220. // Only applies to root agents.
  3221. if (avatar.ParentID != 0)
  3222. {
  3223. avatar.StandUp();
  3224. }
  3225. m_sceneGraph.removeUserCount(!isChildAgent);
  3226. // TODO: We shouldn't use closeChildAgents here - it's being used by the NPC module to stop
  3227. // unnecessary operations. This should go away once NPCs have no accompanying IClientAPI
  3228. if (closeChildAgents && CapsModule != null)
  3229. CapsModule.RemoveCaps(agentID, avatar.ControllingClient.CircuitCode);
  3230. if (closeChildAgents && !isChildAgent)
  3231. {
  3232. List<ulong> regions = avatar.KnownRegionHandles;
  3233. regions.Remove(RegionInfo.RegionHandle);
  3234. // This ends up being done asynchronously so that a logout isn't held up where there are many present but unresponsive neighbours.
  3235. m_sceneGridService.SendCloseChildAgentConnections(agentID, acd.SessionID.ToString(), regions);
  3236. }
  3237. m_eventManager.TriggerClientClosed(agentID, this);
  3238. // m_log.Debug("[Scene]TriggerClientClosed done");
  3239. m_eventManager.TriggerOnRemovePresence(agentID);
  3240. // m_log.Debug("[Scene]TriggerOnRemovePresence done");
  3241. if (!isChildAgent)
  3242. {
  3243. if (AttachmentsModule != null)
  3244. {
  3245. // m_log.Debug("[Scene]DeRezAttachments");
  3246. AttachmentsModule.DeRezAttachments(avatar);
  3247. // m_log.Debug("[Scene]DeRezAttachments done");
  3248. }
  3249. ForEachClient(
  3250. delegate(IClientAPI client)
  3251. {
  3252. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  3253. try { client.SendKillObject(new List<uint> { avatar.LocalId }); }
  3254. catch (NullReferenceException) { }
  3255. });
  3256. }
  3257. // It's possible for child agents to have transactions if changes are being made cross-border.
  3258. if (AgentTransactionsModule != null)
  3259. {
  3260. // m_log.Debug("[Scene]RemoveAgentAssetTransactions");
  3261. AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
  3262. }
  3263. m_log.Debug("[Scene] The avatar has left the building");
  3264. }
  3265. catch (Exception e)
  3266. {
  3267. m_log.Error(
  3268. string.Format("[SCENE]: Exception removing {0} from {1}. Cleaning up. Exception ", avatar.Name, Name), e);
  3269. }
  3270. finally
  3271. {
  3272. try
  3273. {
  3274. // Always clean these structures up so that any failure above doesn't cause them to remain in the
  3275. // scene with possibly bad effects (e.g. continually timing out on unacked packets and triggering
  3276. // the same cleanup exception continually.
  3277. m_authenticateHandler.RemoveCircuit(agentID);
  3278. m_sceneGraph.RemoveScenePresence(agentID);
  3279. m_clientManager.Remove(agentID);
  3280. avatar.Close();
  3281. }
  3282. catch (Exception e)
  3283. {
  3284. m_log.Error(
  3285. string.Format("[SCENE]: Exception in final clean up of {0} in {1}. Exception ", avatar.Name, Name), e);
  3286. }
  3287. }
  3288. }
  3289. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  3290. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  3291. }
  3292. /// <summary>
  3293. /// Removes region from an avatar's known region list. This coincides with child agents. For each child agent, there will be a known region entry.
  3294. ///
  3295. /// </summary>
  3296. /// <param name="avatarID"></param>
  3297. /// <param name="regionslst"></param>
  3298. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  3299. {
  3300. ScenePresence av = GetScenePresence(avatarID);
  3301. if (av != null)
  3302. {
  3303. lock (av)
  3304. {
  3305. for (int i = 0; i < regionslst.Count; i++)
  3306. {
  3307. av.RemoveNeighbourRegion(regionslst[i]);
  3308. }
  3309. }
  3310. }
  3311. }
  3312. #endregion
  3313. #region Entities
  3314. public void SendKillObject(List<uint> localIDs)
  3315. {
  3316. List<uint> deleteIDs = new List<uint>();
  3317. foreach (uint localID in localIDs)
  3318. {
  3319. SceneObjectPart part = GetSceneObjectPart(localID);
  3320. if (part != null && part.ParentGroup != null &&
  3321. part.ParentGroup.RootPart == part)
  3322. deleteIDs.Add(localID);
  3323. }
  3324. ForEachClient(c => c.SendKillObject(deleteIDs));
  3325. }
  3326. #endregion
  3327. #region RegionComms
  3328. /// <summary>
  3329. /// Do the work necessary to initiate a new user connection for a particular scene.
  3330. /// </summary>
  3331. /// <param name="agent">CircuitData of the agent who is connecting</param>
  3332. /// <param name="teleportFlags"></param>
  3333. /// <param name="source">Source region (may be null)</param>
  3334. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3335. /// <returns>True if the region accepts this agent. False if it does not. False will
  3336. /// also return a reason.</returns>
  3337. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, GridRegion source, out string reason)
  3338. {
  3339. return NewUserConnection(agent, teleportFlags, source, out reason, true);
  3340. }
  3341. /// <summary>
  3342. /// Do the work necessary to initiate a new user connection for a particular scene.
  3343. /// </summary>
  3344. /// <remarks>
  3345. /// The return bool should allow for connections to be refused, but as not all calling paths
  3346. /// take proper notice of it yet, we still allowed banned users in.
  3347. ///
  3348. /// At the moment this method consists of setting up the caps infrastructure
  3349. /// The return bool should allow for connections to be refused, but as not all calling paths
  3350. /// take proper notice of it let, we allowed banned users in still.
  3351. ///
  3352. /// This method is called by the login service (in the case of login) or another simulator (in the case of region
  3353. /// cross or teleport) to initiate the connection. It is not triggered by the viewer itself - the connection
  3354. /// is activated later when the viewer sends the initial UseCircuitCodePacket UDP packet (in the case of
  3355. /// the LLUDP stack).
  3356. /// </remarks>
  3357. /// <param name="acd">CircuitData of the agent who is connecting</param>
  3358. /// <param name="source">Source region (may be null)</param>
  3359. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3360. /// <param name="requirePresenceLookup">True for normal presence. False for NPC
  3361. /// or other applications where a full grid/Hypergrid presence may not be required.</param>
  3362. /// <returns>True if the region accepts this agent. False if it does not. False will
  3363. /// also return a reason.</returns>
  3364. ///
  3365. private object m_newUserConnLock = new object();
  3366. public bool NewUserConnection(AgentCircuitData acd, uint teleportFlags, GridRegion source, out string reason, bool requirePresenceLookup)
  3367. {
  3368. bool vialogin = ((teleportFlags & (uint)TPFlags.ViaLogin) != 0 ||
  3369. (teleportFlags & (uint)TPFlags.ViaHGLogin) != 0);
  3370. bool viahome = ((teleportFlags & (uint)TPFlags.ViaHome) != 0);
  3371. // bool godlike = ((teleportFlags & (uint)TPFlags.Godlike) != 0);
  3372. reason = String.Empty;
  3373. //Teleport flags:
  3374. //
  3375. // TeleportFlags.ViaGodlikeLure - Border Crossing
  3376. // TeleportFlags.ViaLogin - Login
  3377. // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
  3378. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  3379. // Don't disable this log message - it's too helpful
  3380. string curViewer = Util.GetViewerName(acd);
  3381. m_log.DebugFormat(
  3382. "[SCENE]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, IP {6}, viewer {7}, teleportflags ({8}), position {9}. {10}",
  3383. RegionInfo.RegionName,
  3384. (acd.child ? "child" : "root"),
  3385. acd.firstname,
  3386. acd.lastname,
  3387. acd.AgentID,
  3388. acd.circuitcode,
  3389. acd.IPAddress,
  3390. curViewer,
  3391. ((TPFlags)teleportFlags).ToString(),
  3392. acd.startpos,
  3393. (source == null) ? "" : string.Format("From region {0} ({1}){2}", source.RegionName, source.RegionID, (source.RawServerURI == null) ? "" : " @ " + source.ServerURI)
  3394. );
  3395. // m_log.DebugFormat("NewUserConnection stack {0}", Environment.StackTrace);
  3396. if (!LoginsEnabled)
  3397. {
  3398. reason = "Logins to this region are disabled";
  3399. return false;
  3400. }
  3401. //Check if the viewer is banned or in the viewer access list
  3402. //We check if the substring is listed for higher flexebility
  3403. bool ViewerDenied = true;
  3404. //Check if the specific viewer is listed in the allowed viewer list
  3405. if (m_AllowedViewers.Count > 0)
  3406. {
  3407. foreach (string viewer in m_AllowedViewers)
  3408. {
  3409. if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
  3410. {
  3411. ViewerDenied = false;
  3412. break;
  3413. }
  3414. }
  3415. }
  3416. else
  3417. {
  3418. ViewerDenied = false;
  3419. }
  3420. //Check if the viewer is in the banned list
  3421. if (m_BannedViewers.Count > 0)
  3422. {
  3423. foreach (string viewer in m_BannedViewers)
  3424. {
  3425. if (viewer == curViewer.Substring(0, Math.Min(viewer.Length, curViewer.Length)).Trim().ToLower())
  3426. {
  3427. ViewerDenied = true;
  3428. break;
  3429. }
  3430. }
  3431. }
  3432. if (ViewerDenied)
  3433. {
  3434. m_log.DebugFormat(
  3435. "[SCENE]: Access denied for {0} {1} using {2}",
  3436. acd.firstname, acd.lastname, curViewer);
  3437. reason = "Access denied, your viewer is banned by the region owner";
  3438. return false;
  3439. }
  3440. ScenePresence sp;
  3441. lock (m_removeClientLock)
  3442. {
  3443. sp = GetScenePresence(acd.AgentID);
  3444. // We need to ensure that we are not already removing the scene presence before we ask it not to be
  3445. // closed.
  3446. if (sp != null && sp.IsChildAgent
  3447. && (sp.LifecycleState == ScenePresenceState.Running
  3448. || sp.LifecycleState == ScenePresenceState.PreRemove))
  3449. {
  3450. m_log.DebugFormat(
  3451. "[SCENE]: Reusing existing child scene presence for {0}, state {1} in {2}",
  3452. sp.Name, sp.LifecycleState, Name);
  3453. // In the case where, for example, an A B C D region layout, an avatar may
  3454. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. When C
  3455. // renews the lease on the child agent at B, we must make sure that the close from A does not succeed.
  3456. //
  3457. // XXX: In the end, this should not be necessary if child agents are closed without delay on
  3458. // teleport, since realistically, the close request should always be processed before any other
  3459. // region tried to re-establish a child agent. This is much simpler since the logic below is
  3460. // vulnerable to an issue when a viewer quits a region without sending a proper logout but then
  3461. // re-establishes the connection on a relogin. This could wrongly set the DoNotCloseAfterTeleport
  3462. // flag when no teleport had taken place (and hence no close was going to come).
  3463. // if (!acd.ChildrenCapSeeds.ContainsKey(RegionInfo.RegionHandle))
  3464. // {
  3465. // m_log.DebugFormat(
  3466. // "[SCENE]: Setting DoNotCloseAfterTeleport for child scene presence {0} in {1} because source will attempt close.",
  3467. // sp.Name, Name);
  3468. //
  3469. // sp.DoNotCloseAfterTeleport = true;
  3470. // }
  3471. // else if (EntityTransferModule.IsInTransit(sp.UUID))
  3472. sp.LifecycleState = ScenePresenceState.Running;
  3473. if (EntityTransferModule.IsInTransit(sp.UUID))
  3474. {
  3475. sp.DoNotCloseAfterTeleport = true;
  3476. m_log.DebugFormat(
  3477. "[SCENE]: Set DoNotCloseAfterTeleport for child scene presence {0} in {1} because this region will attempt end-of-teleport close from a previous close.",
  3478. sp.Name, Name);
  3479. }
  3480. }
  3481. }
  3482. // Need to poll here in case we are currently deleting an sp. Letting threads run over each other will
  3483. // allow unpredictable things to happen.
  3484. if (sp != null)
  3485. {
  3486. const int polls = 10;
  3487. const int pollInterval = 1000;
  3488. int pollsLeft = polls;
  3489. while (sp.LifecycleState == ScenePresenceState.Removing && pollsLeft-- > 0)
  3490. Thread.Sleep(pollInterval);
  3491. if (sp.LifecycleState == ScenePresenceState.Removing)
  3492. {
  3493. m_log.WarnFormat(
  3494. "[SCENE]: Agent {0} in {1} was still being removed after {2}s. Aborting NewUserConnection.",
  3495. sp.Name, Name, polls * pollInterval / 1000);
  3496. return false;
  3497. }
  3498. else if (polls != pollsLeft)
  3499. {
  3500. m_log.DebugFormat(
  3501. "[SCENE]: NewUserConnection for agent {0} in {1} had to wait {2}s for in-progress removal to complete on an old presence.",
  3502. sp.Name, Name, polls * pollInterval / 1000);
  3503. }
  3504. }
  3505. // TODO: can we remove this lock?
  3506. lock (m_newUserConnLock)
  3507. {
  3508. if (sp != null && !sp.IsChildAgent)
  3509. {
  3510. // We have a root agent. Is it in transit?
  3511. if (!EntityTransferModule.IsInTransit(sp.UUID))
  3512. {
  3513. // We have a zombie from a crashed session.
  3514. // Or the same user is trying to be root twice here, won't work.
  3515. // Kill it.
  3516. m_log.WarnFormat(
  3517. "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
  3518. sp.Name, sp.UUID, RegionInfo.RegionName);
  3519. if (sp.ControllingClient != null)
  3520. CloseAgent(sp.UUID, true);
  3521. sp = null;
  3522. }
  3523. //else
  3524. // m_log.WarnFormat("[SCENE]: Existing root scene presence for {0} {1} in {2}, but agent is in trasit", sp.Name, sp.UUID, RegionInfo.RegionName);
  3525. }
  3526. // Optimistic: add or update the circuit data with the new agent circuit data and teleport flags.
  3527. // We need the circuit data here for some of the subsequent checks. (groups, for example)
  3528. // If the checks fail, we remove the circuit.
  3529. acd.teleportFlags = teleportFlags;
  3530. if (vialogin)
  3531. {
  3532. IUserAccountCacheModule cache = RequestModuleInterface<IUserAccountCacheModule>();
  3533. if (cache != null)
  3534. // cache.Remove(acd.firstname + " " + acd.lastname);
  3535. cache.Remove(acd.AgentID);
  3536. // Remove any preexisting circuit - we don't want duplicates
  3537. // This is a stab at preventing avatar "ghosting"
  3538. m_authenticateHandler.RemoveCircuit(acd.AgentID);
  3539. }
  3540. m_authenticateHandler.AddNewCircuit(acd.circuitcode, acd);
  3541. if (sp == null) // We don't have an [child] agent here already
  3542. {
  3543. if (requirePresenceLookup)
  3544. {
  3545. try
  3546. {
  3547. if (!VerifyUserPresence(acd, out reason))
  3548. {
  3549. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3550. return false;
  3551. }
  3552. }
  3553. catch (Exception e)
  3554. {
  3555. m_log.ErrorFormat(
  3556. "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
  3557. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3558. return false;
  3559. }
  3560. }
  3561. try
  3562. {
  3563. if (!AuthorizeUser(acd, (vialogin ? false : SeeIntoRegion), out reason))
  3564. {
  3565. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3566. return false;
  3567. }
  3568. }
  3569. catch (Exception e)
  3570. {
  3571. m_log.ErrorFormat(
  3572. "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
  3573. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3574. return false;
  3575. }
  3576. m_log.InfoFormat(
  3577. "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  3578. Name, (acd.child ? "child" : "root"), acd.firstname, acd.lastname,
  3579. acd.AgentID, acd.circuitcode);
  3580. if (CapsModule != null)
  3581. {
  3582. CapsModule.SetAgentCapsSeeds(acd);
  3583. CapsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3584. }
  3585. }
  3586. else
  3587. {
  3588. // Let the SP know how we got here. This has a lot of interesting
  3589. // uses down the line.
  3590. sp.TeleportFlags = (TPFlags)teleportFlags;
  3591. if (sp.IsChildAgent)
  3592. {
  3593. m_log.DebugFormat(
  3594. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  3595. acd.AgentID, RegionInfo.RegionName);
  3596. if (CapsModule != null)
  3597. {
  3598. CapsModule.SetAgentCapsSeeds(acd);
  3599. CapsModule.CreateCaps(acd.AgentID, acd.circuitcode);
  3600. }
  3601. sp.AdjustKnownSeeds();
  3602. }
  3603. }
  3604. // Try caching an incoming user name much earlier on to see if this helps with an issue
  3605. // where HG users are occasionally seen by others as "Unknown User" because their UUIDName
  3606. // request for the HG avatar appears to trigger before the user name is cached.
  3607. CacheUserName(null, acd);
  3608. }
  3609. if (CapsModule != null)
  3610. {
  3611. CapsModule.ActivateCaps(acd.circuitcode);
  3612. }
  3613. // if (vialogin)
  3614. // {
  3615. // CleanDroppedAttachments();
  3616. // }
  3617. if(teleportFlags != (uint) TPFlags.Default)
  3618. {
  3619. // Make sure root avatar position is in the region
  3620. if (acd.startpos.X < 0)
  3621. acd.startpos.X = 1f;
  3622. else if (acd.startpos.X >= RegionInfo.RegionSizeX)
  3623. acd.startpos.X = RegionInfo.RegionSizeX - 1f;
  3624. if (acd.startpos.Y < 0)
  3625. acd.startpos.Y = 1f;
  3626. else if (acd.startpos.Y >= RegionInfo.RegionSizeY)
  3627. acd.startpos.Y = RegionInfo.RegionSizeY - 1f;
  3628. }
  3629. // only check access, actual relocations will happen later on ScenePresence MakeRoot
  3630. // allow child agents creation
  3631. // if(!godlike && teleportFlags != (uint) TPFlags.Default)
  3632. if(teleportFlags != (uint) TPFlags.Default)
  3633. {
  3634. bool checkTeleHub;
  3635. // don't check hubs if via home or via lure
  3636. if((teleportFlags & (uint) TPFlags.ViaHome) != 0
  3637. || (teleportFlags & (uint) TPFlags.ViaLure) != 0)
  3638. checkTeleHub = false;
  3639. else
  3640. checkTeleHub = vialogin
  3641. || (TelehubAllowLandmarks == true ? false : ((teleportFlags & (uint)TPFlags.ViaLandmark) != 0 ))
  3642. || (teleportFlags & (uint) TPFlags.ViaLocation) != 0;
  3643. if(!CheckLandPositionAccess(acd.AgentID, true, checkTeleHub, acd.startpos, out reason))
  3644. {
  3645. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3646. return false;
  3647. }
  3648. }
  3649. return true;
  3650. }
  3651. private bool IsPositionAllowed(UUID agentID, Vector3 pos, ref string reason)
  3652. {
  3653. ILandObject land = LandChannel.GetLandObject(pos);
  3654. if (land == null)
  3655. return true;
  3656. if (land.IsBannedFromLand(agentID) || land.IsRestrictedFromLand(agentID))
  3657. {
  3658. reason = "You are banned from the region.";
  3659. return false;
  3660. }
  3661. return true;
  3662. }
  3663. public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
  3664. {
  3665. if (posX < 0)
  3666. posX = 0;
  3667. else if (posX >= RegionInfo.RegionSizeX)
  3668. posX = RegionInfo.RegionSizeX - 0.5f;
  3669. if (posY < 0)
  3670. posY = 0;
  3671. else if (posY >= RegionInfo.RegionSizeY)
  3672. posY = RegionInfo.RegionSizeY - 0.5f;
  3673. reason = String.Empty;
  3674. if (Permissions.IsGod(agentID))
  3675. return true;
  3676. ILandObject land = LandChannel.GetLandObject(posX, posY);
  3677. if (land == null)
  3678. return false;
  3679. bool banned = land.IsBannedFromLand(agentID);
  3680. bool restricted = land.IsRestrictedFromLand(agentID);
  3681. if (banned || restricted)
  3682. {
  3683. ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
  3684. Vector2? newPosition = null;
  3685. if (nearestParcel != null)
  3686. {
  3687. //Move agent to nearest allowed
  3688. // Vector2 newPosition = GetParcelSafeCorner(nearestParcel);
  3689. newPosition = nearestParcel.GetNearestPoint(new Vector3(posX, posY,0));
  3690. }
  3691. if(newPosition == null)
  3692. {
  3693. if (banned)
  3694. {
  3695. reason = "Cannot regioncross into banned parcel.";
  3696. }
  3697. else
  3698. {
  3699. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3700. RegionInfo.RegionName);
  3701. }
  3702. return false;
  3703. }
  3704. else
  3705. {
  3706. posX = newPosition.Value.X;
  3707. posY = newPosition.Value.Y;
  3708. }
  3709. }
  3710. reason = "";
  3711. return true;
  3712. }
  3713. /// <summary>
  3714. /// Verifies that the user has a presence on the Grid
  3715. /// </summary>
  3716. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3717. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3718. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3719. /// also return a reason.</returns>
  3720. public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
  3721. {
  3722. reason = String.Empty;
  3723. IPresenceService presence = RequestModuleInterface<IPresenceService>();
  3724. if (presence == null)
  3725. {
  3726. reason = String.Format("Failed to verify user presence in the grid for {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3727. return false;
  3728. }
  3729. OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID);
  3730. if (pinfo == null)
  3731. {
  3732. reason = String.Format("Failed to verify user presence in the grid for {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3733. return false;
  3734. }
  3735. return true;
  3736. }
  3737. /// <summary>
  3738. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3739. /// </summary>
  3740. /// <param name="agent">The circuit data for the agent</param>
  3741. /// <param name="reason">outputs the reason to this string</param>
  3742. /// <returns>True if the region accepts this agent. False if it does not. False will
  3743. /// also return a reason.</returns>
  3744. protected virtual bool AuthorizeUser(AgentCircuitData agent, bool bypassAccessControl, out string reason)
  3745. {
  3746. reason = String.Empty;
  3747. if (!m_strictAccessControl)
  3748. return true;
  3749. if (Permissions.IsGod(agent.AgentID))
  3750. return true;
  3751. if (AuthorizationService != null)
  3752. {
  3753. if (!AuthorizationService.IsAuthorizedForRegion(
  3754. agent.AgentID.ToString(), agent.firstname, agent.lastname, RegionInfo.RegionID.ToString(), out reason))
  3755. {
  3756. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because: {4}",
  3757. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName, reason);
  3758. return false;
  3759. }
  3760. }
  3761. // We only test the things below when we want to cut off
  3762. // child agents from being present in the scene for which their root
  3763. // agent isn't allowed. Otherwise, we allow child agents. The test for
  3764. // the root is done elsewhere (QueryAccess)
  3765. if (!bypassAccessControl)
  3766. {
  3767. if(RegionInfo.EstateSettings == null)
  3768. {
  3769. // something is broken? let it get in
  3770. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
  3771. return true;
  3772. }
  3773. // check estate ban
  3774. int flags = GetUserFlags(agent.AgentID);
  3775. if (RegionInfo.EstateSettings.IsBanned(agent.AgentID, flags))
  3776. {
  3777. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3778. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3779. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  3780. RegionInfo.RegionName);
  3781. return false;
  3782. }
  3783. // public access
  3784. if (RegionInfo.EstateSettings.PublicAccess)
  3785. return true;
  3786. // in access list / owner / manager
  3787. if (RegionInfo.EstateSettings.HasAccess(agent.AgentID))
  3788. return true;
  3789. // finally test groups
  3790. bool groupAccess = false;
  3791. // some say GOTO is ugly
  3792. if(m_groupsModule == null) // if no groups refuse
  3793. goto Label_GroupsDone;
  3794. UUID[] estateGroups = RegionInfo.EstateSettings.EstateGroups;
  3795. if(estateGroups == null)
  3796. {
  3797. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate GroupMembership is null!");
  3798. goto Label_GroupsDone;
  3799. }
  3800. if(estateGroups.Length == 0)
  3801. goto Label_GroupsDone;
  3802. List<UUID> agentGroups = new List<UUID>();
  3803. GroupMembershipData[] GroupMembership = m_groupsModule.GetMembershipData(agent.AgentID);
  3804. if(GroupMembership == null)
  3805. {
  3806. m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
  3807. goto Label_GroupsDone;
  3808. }
  3809. if(GroupMembership.Length == 0)
  3810. goto Label_GroupsDone;
  3811. for(int i = 0;i < GroupMembership.Length;i++)
  3812. agentGroups.Add(GroupMembership[i].GroupID);
  3813. foreach(UUID group in estateGroups)
  3814. {
  3815. if(agentGroups.Contains(group))
  3816. {
  3817. groupAccess = true;
  3818. break;
  3819. }
  3820. }
  3821. Label_GroupsDone:
  3822. if (!groupAccess)
  3823. {
  3824. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3825. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3826. reason = String.Format("Denied access to private region {0}: You do not have access to that region.",
  3827. RegionInfo.RegionName);
  3828. return false;
  3829. }
  3830. }
  3831. return true;
  3832. }
  3833. /// <summary>
  3834. /// Update an AgentCircuitData object with new information
  3835. /// </summary>
  3836. /// <param name="data">Information to update the AgentCircuitData with</param>
  3837. public void UpdateCircuitData(AgentCircuitData data)
  3838. {
  3839. m_authenticateHandler.UpdateAgentData(data);
  3840. }
  3841. /// <summary>
  3842. /// Change the Circuit Code for the user's Circuit Data
  3843. /// </summary>
  3844. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3845. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3846. /// <returns>True if we successfully changed it. False if we did not</returns>
  3847. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3848. {
  3849. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  3850. }
  3851. // /// <summary>
  3852. // /// The Grid has requested that we log-off a user. Log them off.
  3853. // /// </summary>
  3854. // /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3855. // /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3856. // /// <param name="message">message to display to the user. Reason for being logged off</param>
  3857. // public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3858. // {
  3859. // ScenePresence loggingOffUser = GetScenePresence(AvatarID);
  3860. // if (loggingOffUser != null)
  3861. // {
  3862. // UUID localRegionSecret = UUID.Zero;
  3863. // bool parsedsecret = UUID.TryParse(RegionInfo.regionSecret, out localRegionSecret);
  3864. //
  3865. // // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3866. // // Will update the user server in a few revisions to use it.
  3867. //
  3868. // if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3869. // {
  3870. // m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, loggingOffUser.KnownRegionHandles);
  3871. // loggingOffUser.ControllingClient.Kick(message);
  3872. // // Give them a second to receive the message!
  3873. // Thread.Sleep(1000);
  3874. // loggingOffUser.ControllingClient.Close();
  3875. // }
  3876. // else
  3877. // {
  3878. // m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3879. // }
  3880. // }
  3881. // else
  3882. // {
  3883. // m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  3884. // }
  3885. // }
  3886. // /// <summary>
  3887. // /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3888. // /// </summary>
  3889. // /// <param name="agentID"></param>
  3890. // /// <param name="position"></param>
  3891. // /// <param name="isFlying"></param>
  3892. // public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3893. // {
  3894. // ScenePresence presence = GetScenePresence(agentID);
  3895. // if (presence != null)
  3896. // {
  3897. // try
  3898. // {
  3899. // presence.MakeRootAgent(position, isFlying);
  3900. // }
  3901. // catch (Exception e)
  3902. // {
  3903. // m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}{1}", e.Message, e.StackTrace);
  3904. // }
  3905. // }
  3906. // else
  3907. // {
  3908. // m_log.ErrorFormat(
  3909. // "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3910. // agentID, RegionInfo.RegionName);
  3911. // }
  3912. // }
  3913. /// <summary>
  3914. /// We've got an update about an agent that sees into this region,
  3915. /// send it to ScenePresence for processing It's the full data.
  3916. /// </summary>
  3917. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3918. /// Appearance, animations, position, etc.</param>
  3919. /// <returns>true if we handled it.</returns>
  3920. public virtual bool IncomingUpdateChildAgent(AgentData cAgentData)
  3921. {
  3922. m_log.DebugFormat(
  3923. "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3924. if (!LoginsEnabled)
  3925. {
  3926. // reason = "Logins Disabled";
  3927. m_log.DebugFormat(
  3928. "[SCENE]: update for {0} in {1} refused: Logins Disabled", cAgentData.AgentID, RegionInfo.RegionName);
  3929. return false;
  3930. }
  3931. // We have to wait until the viewer contacts this region after receiving EAC.
  3932. // That calls AddNewClient, which finally creates the ScenePresence
  3933. int flags = GetUserFlags(cAgentData.AgentID);
  3934. if (RegionInfo.EstateSettings.IsBanned(cAgentData.AgentID, flags))
  3935. {
  3936. m_log.DebugFormat("[SCENE]: Denying root agent entry to {0}: banned", cAgentData.AgentID);
  3937. return false;
  3938. }
  3939. // TODO: This check should probably be in QueryAccess().
  3940. ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID,
  3941. (float)RegionInfo.RegionSizeX * 0.5f, (float)RegionInfo.RegionSizeY * 0.5f);
  3942. if (nearestParcel == null)
  3943. {
  3944. m_log.InfoFormat(
  3945. "[SCENE]: Denying root agent entry to {0} in {1}: no allowed parcel",
  3946. cAgentData.AgentID, RegionInfo.RegionName);
  3947. return false;
  3948. }
  3949. // We have to wait until the viewer contacts this region
  3950. // after receiving the EnableSimulator HTTP Event Queue message (for the v1 teleport protocol)
  3951. // or TeleportFinish (for the v2 teleport protocol). This triggers the viewer to send
  3952. // a UseCircuitCode packet which in turn calls AddNewAgent which finally creates the ScenePresence.
  3953. ScenePresence sp = WaitGetScenePresence(cAgentData.AgentID);
  3954. if (sp != null)
  3955. {
  3956. if (!sp.IsChildAgent)
  3957. {
  3958. m_log.WarnFormat("[SCENE]: Ignoring a child update on a root agent {0} {1} in {2}",
  3959. sp.Name, sp.UUID, Name);
  3960. return false;
  3961. }
  3962. if (cAgentData.SessionID != sp.ControllingClient.SessionId)
  3963. {
  3964. m_log.WarnFormat(
  3965. "[SCENE]: Attempt to update agent {0} with invalid session id {1} (possibly from simulator in older version; tell them to update).",
  3966. sp.UUID, cAgentData.SessionID);
  3967. Console.WriteLine(String.Format("[SCENE]: Attempt to update agent {0} ({1}) with invalid session id {2}",
  3968. sp.UUID, sp.ControllingClient.SessionId, cAgentData.SessionID));
  3969. }
  3970. sp.UpdateChildAgent(cAgentData);
  3971. int ntimes = 20;
  3972. if (cAgentData.SenderWantsToWaitForRoot)
  3973. {
  3974. while (sp.IsChildAgent && ntimes-- > 0)
  3975. Thread.Sleep(1000);
  3976. if (sp.IsChildAgent)
  3977. m_log.WarnFormat(
  3978. "[SCENE]: Found presence {0} {1} unexpectedly still child in {2}",
  3979. sp.Name, sp.UUID, Name);
  3980. else
  3981. m_log.InfoFormat(
  3982. "[SCENE]: Found presence {0} {1} as root in {2} after {3} waits",
  3983. sp.Name, sp.UUID, Name, 20 - ntimes);
  3984. if (sp.IsChildAgent)
  3985. return false;
  3986. }
  3987. return true;
  3988. }
  3989. return false;
  3990. }
  3991. /// <summary>
  3992. /// We've got an update about an agent that sees into this region,
  3993. /// send it to ScenePresence for processing It's only positional data
  3994. /// </summary>
  3995. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3996. /// <returns>true if we handled it.</returns>
  3997. public virtual bool IncomingUpdateChildAgent(AgentPosition cAgentData)
  3998. {
  3999. // m_log.DebugFormat(
  4000. // "[SCENE PRESENCE]: IncomingChildAgentDataUpdate POSITION for {0} in {1}, position {2}",
  4001. // cAgentData.AgentID, Name, cAgentData.Position);
  4002. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  4003. if (childAgentUpdate != null)
  4004. {
  4005. // if (childAgentUpdate.ControllingClient.SessionId != cAgentData.SessionID)
  4006. // // Only warn for now
  4007. // m_log.WarnFormat("[SCENE]: Attempt at updating position of agent {0} with invalid session id {1}. Neighbor running older version?",
  4008. // childAgentUpdate.UUID, cAgentData.SessionID);
  4009. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  4010. // however to avoid a race condition crossing borders..
  4011. if (childAgentUpdate.IsChildAgent)
  4012. {
  4013. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  4014. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  4015. uint tRegionX = RegionInfo.RegionLocX;
  4016. uint tRegionY = RegionInfo.RegionLocY;
  4017. //Send Data to ScenePresence
  4018. childAgentUpdate.UpdateChildAgent(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  4019. // Not Implemented:
  4020. //TODO: Do we need to pass the message on to one of our neighbors?
  4021. }
  4022. return true;
  4023. }
  4024. return false;
  4025. }
  4026. /// <summary>
  4027. /// Poll until the requested ScenePresence appears or we timeout.
  4028. /// </summary>
  4029. /// <returns>The scene presence is found, else null.</returns>
  4030. /// <param name='agentID'></param>
  4031. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  4032. {
  4033. int ntimes = 30;
  4034. ScenePresence sp = null;
  4035. while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  4036. Thread.Sleep(1000);
  4037. if (sp == null)
  4038. m_log.WarnFormat(
  4039. "[SCENE PRESENCE]: Did not find presence with id {0} in {1} before timeout",
  4040. agentID, RegionInfo.RegionName);
  4041. return sp;
  4042. }
  4043. /// <summary>
  4044. /// Authenticated close (via network)
  4045. /// </summary>
  4046. /// <param name="agentID"></param>
  4047. /// <param name="force"></param>
  4048. /// <param name="auth_token"></param>
  4049. /// <returns></returns>
  4050. public bool CloseAgent(UUID agentID, bool force, string auth_token)
  4051. {
  4052. //m_log.DebugFormat("[SCENE]: Processing incoming close agent {0} in region {1} with auth_token {2}", agentID, RegionInfo.RegionName, auth_token);
  4053. // Check that the auth_token is valid
  4054. AgentCircuitData acd = AuthenticateHandler.GetAgentCircuitData(agentID);
  4055. if (acd == null)
  4056. {
  4057. m_log.DebugFormat(
  4058. "[SCENE]: Request to close agent {0} but no such agent in scene {1}. May have been closed previously.",
  4059. agentID, Name);
  4060. return false;
  4061. }
  4062. if (acd.SessionID.ToString() == auth_token)
  4063. {
  4064. return CloseAgent(agentID, force);
  4065. }
  4066. else
  4067. {
  4068. m_log.WarnFormat(
  4069. "[SCENE]: Request to close agent {0} with invalid authorization token {1} in {2}",
  4070. agentID, auth_token, Name);
  4071. }
  4072. return false;
  4073. }
  4074. // public bool IncomingCloseAgent(UUID agentID)
  4075. // {
  4076. // return IncomingCloseAgent(agentID, false);
  4077. // }
  4078. // public bool IncomingCloseChildAgent(UUID agentID)
  4079. // {
  4080. // return IncomingCloseAgent(agentID, true);
  4081. // }
  4082. /// <summary>
  4083. /// Tell a single client to prepare to close.
  4084. /// </summary>
  4085. /// <remarks>
  4086. /// This should only be called if we may close the client but there will be some delay in so doing. Meant for
  4087. /// internal use - other callers should almost certainly called CloseClient().
  4088. /// </remarks>
  4089. /// <param name="sp"></param>
  4090. /// <returns>true if pre-close state notification was successful. false if the agent
  4091. /// was not in a state where it could transition to pre-close.</returns>
  4092. public bool IncomingPreCloseClient(ScenePresence sp)
  4093. {
  4094. lock (m_removeClientLock)
  4095. {
  4096. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4097. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4098. // want to obey this close since C may have renewed the child agent lease on B.
  4099. if (sp.DoNotCloseAfterTeleport)
  4100. {
  4101. m_log.DebugFormat(
  4102. "[SCENE]: Not pre-closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4103. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4104. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4105. sp.DoNotCloseAfterTeleport = false;
  4106. return false;
  4107. }
  4108. if (sp.LifecycleState != ScenePresenceState.Running)
  4109. {
  4110. m_log.DebugFormat(
  4111. "[SCENE]: Called IncomingPreCloseAgent() for {0} in {1} but presence is already in state {2}",
  4112. sp.Name, Name, sp.LifecycleState);
  4113. return false;
  4114. }
  4115. sp.LifecycleState = ScenePresenceState.PreRemove;
  4116. return true;
  4117. }
  4118. }
  4119. /// <summary>
  4120. /// Tell a single agent to disconnect from the region.
  4121. /// </summary>
  4122. /// <param name="agentID"></param>
  4123. /// <param name="force">
  4124. /// Force the agent to close even if it might be in the middle of some other operation. You do not want to
  4125. /// force unless you are absolutely sure that the agent is dead and a normal close is not working.
  4126. /// </param>
  4127. public override bool CloseAgent(UUID agentID, bool force)
  4128. {
  4129. ScenePresence sp;
  4130. lock (m_removeClientLock)
  4131. {
  4132. sp = GetScenePresence(agentID);
  4133. if (sp == null)
  4134. {
  4135. // If there is no scene presence, we may be handling a dead
  4136. // client. These can keep an avatar from reentering a region
  4137. // and since they don't get cleaned up they will stick
  4138. // around until region restart. So, if there is no SP,
  4139. // remove the client as well.
  4140. IClientAPI client = null;
  4141. if (m_clientManager.TryGetValue(agentID, out client))
  4142. {
  4143. m_clientManager.Remove(agentID);
  4144. if (CapsModule != null)
  4145. CapsModule.RemoveCaps(agentID, 0);
  4146. m_log.DebugFormat( "[SCENE]: Dead client for agent ID {0} was cleaned up in {1}", agentID, Name);
  4147. return true;
  4148. }
  4149. m_log.DebugFormat(
  4150. "[SCENE]: Called CloseClient() with agent ID {0} but no such presence is in {1}",
  4151. agentID, Name);
  4152. return false;
  4153. }
  4154. if (sp.LifecycleState != ScenePresenceState.Running && sp.LifecycleState != ScenePresenceState.PreRemove)
  4155. {
  4156. m_log.DebugFormat(
  4157. "[SCENE]: Called CloseClient() for {0} in {1} but presence is already in state {2}",
  4158. sp.Name, Name, sp.LifecycleState);
  4159. return false;
  4160. }
  4161. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  4162. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  4163. // want to obey this close since C may have renewed the child agent lease on B.
  4164. if (sp.DoNotCloseAfterTeleport)
  4165. {
  4166. m_log.DebugFormat(
  4167. "[SCENE]: Not closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  4168. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  4169. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  4170. sp.DoNotCloseAfterTeleport = false;
  4171. return false;
  4172. }
  4173. sp.LifecycleState = ScenePresenceState.Removing;
  4174. }
  4175. if (sp != null)
  4176. {
  4177. sp.ControllingClient.Close(force, force);
  4178. return true;
  4179. }
  4180. return true;
  4181. }
  4182. /// <summary>
  4183. /// Tries to teleport agent to another region.
  4184. /// </summary>
  4185. /// <remarks>
  4186. /// The region name must exactly match that given.
  4187. /// </remarks>
  4188. /// <param name="remoteClient"></param>
  4189. /// <param name="regionName"></param>
  4190. /// <param name="position"></param>
  4191. /// <param name="lookAt"></param>
  4192. /// <param name="teleportFlags"></param>
  4193. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  4194. Vector3 lookat, uint teleportFlags)
  4195. {
  4196. GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
  4197. if (region == null)
  4198. {
  4199. // can't find the region: Tell viewer and abort
  4200. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  4201. return;
  4202. }
  4203. RequestTeleportLocation(remoteClient, region.RegionHandle, position, lookat, teleportFlags);
  4204. }
  4205. /// <summary>
  4206. /// Tries to teleport agent to other region.
  4207. /// </summary>
  4208. /// <param name="remoteClient"></param>
  4209. /// <param name="regionHandle"></param>
  4210. /// <param name="position"></param>
  4211. /// <param name="lookAt"></param>
  4212. /// <param name="teleportFlags"></param>
  4213. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  4214. Vector3 lookAt, uint teleportFlags)
  4215. {
  4216. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  4217. if (sp != null)
  4218. {
  4219. if (EntityTransferModule != null)
  4220. {
  4221. EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
  4222. }
  4223. else
  4224. {
  4225. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  4226. sp.ControllingClient.SendTeleportFailed("Unable to perform teleports on this simulator.");
  4227. }
  4228. }
  4229. }
  4230. public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  4231. {
  4232. if (EntityTransferModule != null)
  4233. {
  4234. return EntityTransferModule.Cross(agent, isFlying);
  4235. }
  4236. else
  4237. {
  4238. m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
  4239. }
  4240. return false;
  4241. }
  4242. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  4243. {
  4244. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  4245. }
  4246. #endregion
  4247. #region Other Methods
  4248. protected override IConfigSource GetConfig()
  4249. {
  4250. return m_config;
  4251. }
  4252. #endregion
  4253. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  4254. {
  4255. // Check for spoofing.. since this is permissions we're talking about here!
  4256. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  4257. {
  4258. // Tell the object to do permission update
  4259. if (localId != 0)
  4260. {
  4261. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  4262. if (chObjectGroup != null)
  4263. {
  4264. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  4265. }
  4266. }
  4267. }
  4268. }
  4269. /// <summary>
  4270. /// Causes all clients to get a full object update on all of the objects in the scene.
  4271. /// </summary>
  4272. public void ForceClientUpdate()
  4273. {
  4274. EntityBase[] entityList = GetEntities();
  4275. foreach (EntityBase ent in entityList)
  4276. {
  4277. if (ent is SceneObjectGroup)
  4278. {
  4279. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  4280. }
  4281. }
  4282. }
  4283. /// <summary>
  4284. /// This is currently only used for scale (to scale to MegaPrim size)
  4285. /// There is a console command that calls this in OpenSimMain
  4286. /// </summary>
  4287. /// <param name="cmdparams"></param>
  4288. public void HandleEditCommand(string[] cmdparams)
  4289. {
  4290. m_log.DebugFormat("Searching for Primitive: '{0}'", cmdparams[2]);
  4291. EntityBase[] entityList = GetEntities();
  4292. foreach (EntityBase ent in entityList)
  4293. {
  4294. if (ent is SceneObjectGroup)
  4295. {
  4296. SceneObjectPart part = ((SceneObjectGroup)ent).GetPart(((SceneObjectGroup)ent).UUID);
  4297. if (part != null)
  4298. {
  4299. if (part.Name == cmdparams[2])
  4300. {
  4301. part.Resize(
  4302. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  4303. Convert.ToSingle(cmdparams[5])));
  4304. m_log.DebugFormat("Edited scale of Primitive: {0}", part.Name);
  4305. }
  4306. }
  4307. }
  4308. }
  4309. }
  4310. #region Script Handling Methods
  4311. /// <summary>
  4312. /// Console command handler to send script command to script engine.
  4313. /// </summary>
  4314. /// <param name="args"></param>
  4315. public void SendCommandToPlugins(string[] args)
  4316. {
  4317. m_eventManager.TriggerOnPluginConsole(args);
  4318. }
  4319. public LandData GetLandData(float x, float y)
  4320. {
  4321. ILandObject parcel = LandChannel.GetLandObject(x, y);
  4322. if (parcel == null)
  4323. return null;
  4324. return parcel.LandData;
  4325. }
  4326. /// <summary>
  4327. /// Get LandData by position.
  4328. /// </summary>
  4329. /// <param name="pos"></param>
  4330. /// <returns></returns>
  4331. public LandData GetLandData(Vector3 pos)
  4332. {
  4333. return GetLandData(pos.X, pos.Y);
  4334. }
  4335. public LandData GetLandData(uint x, uint y)
  4336. {
  4337. // m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  4338. ILandObject parcel = LandChannel.GetLandObject((int)x, (int)y);
  4339. if (parcel == null)
  4340. return null;
  4341. return parcel.LandData;
  4342. }
  4343. #endregion
  4344. #region Script Engine
  4345. private bool ScriptDanger(SceneObjectPart part, Vector3 pos)
  4346. {
  4347. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4348. if (part != null)
  4349. {
  4350. if (parcel != null)
  4351. {
  4352. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4353. {
  4354. return true;
  4355. }
  4356. else if ((part.OwnerID == parcel.LandData.OwnerID) || Permissions.IsGod(part.OwnerID))
  4357. {
  4358. return true;
  4359. }
  4360. else if (((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4361. && (parcel.LandData.GroupID != UUID.Zero) && (parcel.LandData.GroupID == part.GroupID))
  4362. {
  4363. return true;
  4364. }
  4365. else
  4366. {
  4367. return false;
  4368. }
  4369. }
  4370. else
  4371. {
  4372. if (pos.X > 0f && pos.X < RegionInfo.RegionSizeX && pos.Y > 0f && pos.Y < RegionInfo.RegionSizeY)
  4373. {
  4374. // The only time parcel != null when an object is inside a region is when
  4375. // there is nothing behind the landchannel. IE, no land plugin loaded.
  4376. return true;
  4377. }
  4378. else
  4379. {
  4380. // The object is outside of this region. Stop piping events to it.
  4381. return false;
  4382. }
  4383. }
  4384. }
  4385. else
  4386. {
  4387. return false;
  4388. }
  4389. }
  4390. public bool ScriptDanger(uint localID, Vector3 pos)
  4391. {
  4392. SceneObjectPart part = GetSceneObjectPart(localID);
  4393. if (part != null)
  4394. {
  4395. return ScriptDanger(part, pos);
  4396. }
  4397. else
  4398. {
  4399. return false;
  4400. }
  4401. }
  4402. public bool PipeEventsForScript(uint localID)
  4403. {
  4404. SceneObjectPart part = GetSceneObjectPart(localID);
  4405. if (part != null)
  4406. {
  4407. SceneObjectPart parent = part.ParentGroup.RootPart;
  4408. return ScriptDanger(parent, parent.GetWorldPosition());
  4409. }
  4410. else
  4411. {
  4412. return false;
  4413. }
  4414. }
  4415. #endregion
  4416. #region SceneGraph wrapper methods
  4417. /// <summary>
  4418. ///
  4419. /// </summary>
  4420. /// <param name="localID"></param>
  4421. /// <returns></returns>
  4422. public UUID ConvertLocalIDToFullID(uint localID)
  4423. {
  4424. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  4425. }
  4426. public void SwapRootAgentCount(bool rootChildChildRootTF)
  4427. {
  4428. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  4429. }
  4430. public void AddPhysicalPrim(int num)
  4431. {
  4432. m_sceneGraph.AddPhysicalPrim(num);
  4433. }
  4434. public void RemovePhysicalPrim(int num)
  4435. {
  4436. m_sceneGraph.RemovePhysicalPrim(num);
  4437. }
  4438. public int GetRootAgentCount()
  4439. {
  4440. return m_sceneGraph.GetRootAgentCount();
  4441. }
  4442. public int GetChildAgentCount()
  4443. {
  4444. return m_sceneGraph.GetChildAgentCount();
  4445. }
  4446. /// <summary>
  4447. /// Request a scene presence by UUID. Fast, indexed lookup.
  4448. /// </summary>
  4449. /// <param name="agentID"></param>
  4450. /// <returns>null if the presence was not found</returns>
  4451. public ScenePresence GetScenePresence(UUID agentID)
  4452. {
  4453. return m_sceneGraph.GetScenePresence(agentID);
  4454. }
  4455. /// <summary>
  4456. /// Request the scene presence by name.
  4457. /// </summary>
  4458. /// <param name="firstName"></param>
  4459. /// <param name="lastName"></param>
  4460. /// <returns>null if the presence was not found</returns>
  4461. public ScenePresence GetScenePresence(string firstName, string lastName)
  4462. {
  4463. return m_sceneGraph.GetScenePresence(firstName, lastName);
  4464. }
  4465. /// <summary>
  4466. /// Request the scene presence by localID.
  4467. /// </summary>
  4468. /// <param name="localID"></param>
  4469. /// <returns>null if the presence was not found</returns>
  4470. public ScenePresence GetScenePresence(uint localID)
  4471. {
  4472. return m_sceneGraph.GetScenePresence(localID);
  4473. }
  4474. /// <summary>
  4475. /// Gets all the scene presences in this scene.
  4476. /// </summary>
  4477. /// <remarks>
  4478. /// This method will return both root and child scene presences.
  4479. ///
  4480. /// Consider using ForEachScenePresence() or ForEachRootScenePresence() if possible since these will not
  4481. /// involving creating a new List object.
  4482. /// </remarks>
  4483. /// <returns>
  4484. /// A list of the scene presences. Adding or removing from the list will not affect the presences in the scene.
  4485. /// </returns>
  4486. public List<ScenePresence> GetScenePresences()
  4487. {
  4488. return new List<ScenePresence>(m_sceneGraph.GetScenePresences());
  4489. }
  4490. /// <summary>
  4491. /// Performs action on all avatars in the scene (root scene presences)
  4492. /// Avatars may be an NPC or a 'real' client.
  4493. /// </summary>
  4494. /// <param name="action"></param>
  4495. public void ForEachRootScenePresence(Action<ScenePresence> action)
  4496. {
  4497. m_sceneGraph.ForEachAvatar(action);
  4498. }
  4499. /// <summary>
  4500. /// Performs action on all scene presences (root and child)
  4501. /// </summary>
  4502. /// <param name="action"></param>
  4503. public void ForEachScenePresence(Action<ScenePresence> action)
  4504. {
  4505. m_sceneGraph.ForEachScenePresence(action);
  4506. }
  4507. /// <summary>
  4508. /// Get all the scene object groups.
  4509. /// </summary>
  4510. /// <returns>
  4511. /// The scene object groups. If the scene is empty then an empty list is returned.
  4512. /// </returns>
  4513. public List<SceneObjectGroup> GetSceneObjectGroups()
  4514. {
  4515. return m_sceneGraph.GetSceneObjectGroups();
  4516. }
  4517. /// <summary>
  4518. /// Get a group via its UUID
  4519. /// </summary>
  4520. /// <param name="fullID"></param>
  4521. /// <returns>null if no group with that id exists</returns>
  4522. public SceneObjectGroup GetSceneObjectGroup(UUID fullID)
  4523. {
  4524. return m_sceneGraph.GetSceneObjectGroup(fullID);
  4525. }
  4526. /// <summary>
  4527. /// Get a group via its local ID
  4528. /// </summary>
  4529. /// <remarks>This will only return a group if the local ID matches a root part</remarks>
  4530. /// <param name="localID"></param>
  4531. /// <returns>null if no group with that id exists</returns>
  4532. public SceneObjectGroup GetSceneObjectGroup(uint localID)
  4533. {
  4534. return m_sceneGraph.GetSceneObjectGroup(localID);
  4535. }
  4536. /// <summary>
  4537. /// Get a group by name from the scene (will return the first
  4538. /// found, if there are more than one prim with the same name)
  4539. /// </summary>
  4540. /// <param name="name"></param>
  4541. /// <returns>null if no group with that name exists</returns>
  4542. public SceneObjectGroup GetSceneObjectGroup(string name)
  4543. {
  4544. return m_sceneGraph.GetSceneObjectGroup(name);
  4545. }
  4546. /// <summary>
  4547. /// Attempt to get the SOG via its UUID
  4548. /// </summary>
  4549. /// <param name="fullID"></param>
  4550. /// <param name="sog"></param>
  4551. /// <returns></returns>
  4552. public bool TryGetSceneObjectGroup(UUID fullID, out SceneObjectGroup sog)
  4553. {
  4554. sog = GetSceneObjectGroup(fullID);
  4555. return sog != null;
  4556. }
  4557. /// <summary>
  4558. /// Get a prim by name from the scene (will return the first
  4559. /// found, if there are more than one prim with the same name)
  4560. /// </summary>
  4561. /// <param name="name"></param>
  4562. /// <returns></returns>
  4563. public SceneObjectPart GetSceneObjectPart(string name)
  4564. {
  4565. return m_sceneGraph.GetSceneObjectPart(name);
  4566. }
  4567. /// <summary>
  4568. /// Get a prim via its local id
  4569. /// </summary>
  4570. /// <param name="localID"></param>
  4571. /// <returns></returns>
  4572. public SceneObjectPart GetSceneObjectPart(uint localID)
  4573. {
  4574. return m_sceneGraph.GetSceneObjectPart(localID);
  4575. }
  4576. /// <summary>
  4577. /// Get a prim via its UUID
  4578. /// </summary>
  4579. /// <param name="fullID"></param>
  4580. /// <returns></returns>
  4581. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  4582. {
  4583. return m_sceneGraph.GetSceneObjectPart(fullID);
  4584. }
  4585. /// <summary>
  4586. /// Attempt to get a prim via its UUID
  4587. /// </summary>
  4588. /// <param name="fullID"></param>
  4589. /// <param name="sop"></param>
  4590. /// <returns></returns>
  4591. public bool TryGetSceneObjectPart(UUID fullID, out SceneObjectPart sop)
  4592. {
  4593. sop = GetSceneObjectPart(fullID);
  4594. return sop != null;
  4595. }
  4596. /// <summary>
  4597. /// Get a scene object group that contains the prim with the given local id
  4598. /// </summary>
  4599. /// <param name="localID"></param>
  4600. /// <returns>null if no scene object group containing that prim is found</returns>
  4601. public SceneObjectGroup GetGroupByPrim(uint localID)
  4602. {
  4603. return m_sceneGraph.GetGroupByPrim(localID);
  4604. }
  4605. /// <summary>
  4606. /// Get a scene object group that contains the prim with the given uuid
  4607. /// </summary>
  4608. /// <param name="fullID"></param>
  4609. /// <returns>null if no scene object group containing that prim is found</returns>
  4610. public SceneObjectGroup GetGroupByPrim(UUID fullID)
  4611. {
  4612. return m_sceneGraph.GetGroupByPrim(fullID);
  4613. }
  4614. public override bool TryGetScenePresence(UUID agentID, out ScenePresence sp)
  4615. {
  4616. return m_sceneGraph.TryGetScenePresence(agentID, out sp);
  4617. }
  4618. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  4619. {
  4620. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  4621. }
  4622. /// <summary>
  4623. /// Perform an action on all clients with an avatar in this scene (root only)
  4624. /// </summary>
  4625. /// <param name="action"></param>
  4626. public void ForEachRootClient(Action<IClientAPI> action)
  4627. {
  4628. ForEachRootScenePresence(delegate(ScenePresence presence)
  4629. {
  4630. action(presence.ControllingClient);
  4631. });
  4632. }
  4633. /// <summary>
  4634. /// Perform an action on all clients connected to the region (root and child)
  4635. /// </summary>
  4636. /// <param name="action"></param>
  4637. public void ForEachClient(Action<IClientAPI> action)
  4638. {
  4639. m_clientManager.ForEachSync(action);
  4640. }
  4641. public int GetNumberOfClients()
  4642. {
  4643. return m_clientManager.Count;
  4644. }
  4645. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  4646. {
  4647. return m_clientManager.TryGetValue(avatarID, out client);
  4648. }
  4649. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  4650. {
  4651. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  4652. }
  4653. public void ForEachSOG(Action<SceneObjectGroup> action)
  4654. {
  4655. m_sceneGraph.ForEachSOG(action);
  4656. }
  4657. /// <summary>
  4658. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  4659. /// will not affect the original list of objects in the scene.
  4660. /// </summary>
  4661. /// <returns></returns>
  4662. public EntityBase[] GetEntities()
  4663. {
  4664. return m_sceneGraph.GetEntities();
  4665. }
  4666. #endregion
  4667. // Commented pending deletion since this method no longer appears to do anything at all
  4668. // public bool NeedSceneCacheClear(UUID agentID)
  4669. // {
  4670. // IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  4671. // if (inv == null)
  4672. // return true;
  4673. //
  4674. // return inv.NeedSceneCacheClear(agentID, this);
  4675. // }
  4676. public void CleanTempObjects()
  4677. {
  4678. DateTime now = DateTime.UtcNow;
  4679. EntityBase[] entities = GetEntities();
  4680. foreach (EntityBase obj in entities)
  4681. {
  4682. if (obj is SceneObjectGroup)
  4683. {
  4684. SceneObjectGroup grp = (SceneObjectGroup)obj;
  4685. if (!grp.IsDeleted)
  4686. {
  4687. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4688. {
  4689. if (grp.GetSittingAvatarsCount() == 0 && grp.RootPart.Expires <= now)
  4690. DeleteSceneObject(grp, false);
  4691. }
  4692. }
  4693. }
  4694. }
  4695. }
  4696. public void DeleteFromStorage(UUID uuid)
  4697. {
  4698. SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
  4699. }
  4700. public int GetHealth(out int flags, out string message)
  4701. {
  4702. // Returns:
  4703. // 1 = sim is up and accepting http requests. The heartbeat has
  4704. // stopped and the sim is probably locked up, but a remote
  4705. // admin restart may succeed
  4706. //
  4707. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4708. // usable for people within
  4709. //
  4710. // 3 = Sim is up and one packet thread is running. Sim is
  4711. // unstable and will not accept new logins
  4712. //
  4713. // 4 = Sim is up and both packet threads are running. Sim is
  4714. // likely usable
  4715. //
  4716. // 5 = We have seen a new user enter within the past 4 minutes
  4717. // which can be seen as positive confirmation of sim health
  4718. //
  4719. int health = 1; // Start at 1, means we're up
  4720. flags = 0;
  4721. message = String.Empty;
  4722. CheckHeartbeat();
  4723. if (m_firstHeartbeat || (m_lastIncoming == 0 && m_lastOutgoing == 0))
  4724. {
  4725. // We're still starting
  4726. // 0 means "in startup", it can't happen another way, since
  4727. // to get here, we must be able to accept http connections
  4728. return 0;
  4729. }
  4730. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 2000)
  4731. {
  4732. health+=1;
  4733. flags |= 1;
  4734. }
  4735. if (Util.EnvironmentTickCountSubtract(m_lastIncoming) < 2000)
  4736. {
  4737. health+=1;
  4738. flags |= 2;
  4739. }
  4740. if (Util.EnvironmentTickCountSubtract(m_lastOutgoing) < 2000)
  4741. {
  4742. health+=1;
  4743. flags |= 4;
  4744. }
  4745. /*
  4746. else
  4747. {
  4748. int pid = System.Diagnostics.Process.GetCurrentProcess().Id;
  4749. System.Diagnostics.Process proc = new System.Diagnostics.Process();
  4750. proc.EnableRaisingEvents=false;
  4751. proc.StartInfo.FileName = "/bin/kill";
  4752. proc.StartInfo.Arguments = "-QUIT " + pid.ToString();
  4753. proc.Start();
  4754. proc.WaitForExit();
  4755. Thread.Sleep(1000);
  4756. Environment.Exit(1);
  4757. }
  4758. */
  4759. if (flags != 7)
  4760. return health;
  4761. // A login in the last 4 mins? We can't be doing too badly
  4762. //
  4763. if (Util.EnvironmentTickCountSubtract(m_LastLogin) < 240000)
  4764. health++;
  4765. else
  4766. return health;
  4767. return health;
  4768. }
  4769. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4770. // update non-physical objects like the joint proxy objects that represent the position
  4771. // of the joints in the scene.
  4772. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4773. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4774. // from within the OdePhysicsScene.
  4775. protected internal void jointMoved(PhysicsJoint joint)
  4776. {
  4777. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  4778. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4779. if (jointProxyObject == null)
  4780. {
  4781. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  4782. return;
  4783. }
  4784. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  4785. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  4786. if (trackedBody == null) return; // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
  4787. jointProxyObject.Velocity = trackedBody.Velocity;
  4788. jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
  4789. switch (joint.Type)
  4790. {
  4791. case PhysicsJointType.Ball:
  4792. {
  4793. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4794. Vector3 proxyPos = jointAnchor;
  4795. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4796. }
  4797. break;
  4798. case PhysicsJointType.Hinge:
  4799. {
  4800. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4801. // Normally, we would just ask the physics scene to return the axis for the joint.
  4802. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  4803. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  4804. // Therefore the following call does not always work:
  4805. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  4806. // instead we compute the joint orientation by saving the original joint orientation
  4807. // relative to one of the jointed bodies, and applying this transformation
  4808. // to the current position of the jointed bodies (the tracked body) to compute the
  4809. // current joint orientation.
  4810. if (joint.TrackedBodyName == null)
  4811. {
  4812. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  4813. }
  4814. Vector3 proxyPos = jointAnchor;
  4815. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  4816. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4817. jointProxyObject.ParentGroup.UpdateGroupRotationR(q); // schedules the entire group for a terse update
  4818. }
  4819. break;
  4820. }
  4821. }
  4822. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4823. // update non-physical objects like the joint proxy objects that represent the position
  4824. // of the joints in the scene.
  4825. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4826. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4827. // from within the OdePhysicsScene.
  4828. protected internal void jointDeactivated(PhysicsJoint joint)
  4829. {
  4830. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  4831. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4832. if (jointProxyObject == null)
  4833. {
  4834. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  4835. return;
  4836. }
  4837. // turn the proxy non-physical, which also stops its client-side interpolation
  4838. bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
  4839. if (wasUsingPhysics)
  4840. {
  4841. jointProxyObject.UpdatePrimFlags(false, false, true, false,false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
  4842. }
  4843. }
  4844. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4845. // alert the user of errors by using the debug channel in the same way that scripts alert
  4846. // the user of compile errors.
  4847. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4848. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4849. // from within the OdePhysicsScene.
  4850. public void jointErrorMessage(PhysicsJoint joint, string message)
  4851. {
  4852. if (joint != null)
  4853. {
  4854. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4855. return;
  4856. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4857. if (jointProxyObject != null)
  4858. {
  4859. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  4860. ChatTypeEnum.DebugChannel,
  4861. 2147483647,
  4862. jointProxyObject.AbsolutePosition,
  4863. jointProxyObject.Name,
  4864. jointProxyObject.UUID,
  4865. false);
  4866. joint.ErrorMessageCount++;
  4867. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4868. {
  4869. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  4870. ChatTypeEnum.DebugChannel,
  4871. 2147483647,
  4872. jointProxyObject.AbsolutePosition,
  4873. jointProxyObject.Name,
  4874. jointProxyObject.UUID,
  4875. false);
  4876. }
  4877. }
  4878. else
  4879. {
  4880. // couldn't find the joint proxy object; the error message is silently suppressed
  4881. }
  4882. }
  4883. }
  4884. public Scene ConsoleScene()
  4885. {
  4886. if (MainConsole.Instance == null)
  4887. return null;
  4888. if (MainConsole.Instance.ConsoleScene is Scene)
  4889. return (Scene)MainConsole.Instance.ConsoleScene;
  4890. return null;
  4891. }
  4892. // Get terrain height at the specified <x,y> location.
  4893. // Presumes the underlying implementation is a heightmap which is a 1m grid.
  4894. // Finds heightmap grid points before and after the point and
  4895. // does a linear approximation of the height at this intermediate point.
  4896. public float GetGroundHeight(float x, float y)
  4897. {
  4898. if (x < 0)
  4899. x = 0;
  4900. if (x >= Heightmap.Width)
  4901. x = Heightmap.Width - 1;
  4902. if (y < 0)
  4903. y = 0;
  4904. if (y >= Heightmap.Height)
  4905. y = Heightmap.Height - 1;
  4906. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  4907. Vector3 p1 = p0;
  4908. Vector3 p2 = p0;
  4909. p1.X += 1.0f;
  4910. if (p1.X < Heightmap.Width)
  4911. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  4912. p2.Y += 1.0f;
  4913. if (p2.Y < Heightmap.Height)
  4914. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  4915. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  4916. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  4917. v0.Normalize();
  4918. v1.Normalize();
  4919. Vector3 vsn = new Vector3();
  4920. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  4921. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  4922. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  4923. vsn.Normalize();
  4924. float xdiff = x - (float)((int)x);
  4925. float ydiff = y - (float)((int)y);
  4926. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  4927. }
  4928. private void CheckHeartbeat()
  4929. {
  4930. if (m_firstHeartbeat)
  4931. return;
  4932. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) > 5000)
  4933. Start();
  4934. }
  4935. public override ISceneObject DeserializeObject(string representation)
  4936. {
  4937. return SceneObjectSerializer.FromXml2Format(representation);
  4938. }
  4939. public override bool AllowScriptCrossings
  4940. {
  4941. get { return m_allowScriptCrossings; }
  4942. }
  4943. public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
  4944. {
  4945. return GetNearestAllowedPosition(avatar, null);
  4946. }
  4947. public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
  4948. {
  4949. Vector3 pos = avatar.AbsolutePosition;
  4950. ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, pos.X, pos.Y, excludeParcel);
  4951. if (nearestParcel != null)
  4952. {
  4953. Vector2? nearestPoint = null;
  4954. Vector3 dir = -avatar.Velocity;
  4955. float dirlen = dir.Length();
  4956. if(dirlen > 1.0f)
  4957. //Try to get a location that feels like where they came from
  4958. nearestPoint = nearestParcel.GetNearestPointAlongDirection(pos, dir);
  4959. if (nearestPoint == null)
  4960. nearestPoint = nearestParcel.GetNearestPoint(pos);
  4961. if (nearestPoint != null)
  4962. {
  4963. return GetPositionAtAvatarHeightOrGroundHeight(avatar,
  4964. nearestPoint.Value.X, nearestPoint.Value.Y);
  4965. }
  4966. ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
  4967. if (dest != excludeParcel)
  4968. {
  4969. // Ultimate backup if we have no idea where they are and
  4970. // the last allowed position was in another parcel
  4971. m_log.Debug("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
  4972. return avatar.lastKnownAllowedPosition;
  4973. }
  4974. // else fall through to region edge
  4975. }
  4976. //Go to the edge, this happens in teleporting to a region with no available parcels
  4977. Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
  4978. //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
  4979. return nearestRegionEdgePoint;
  4980. }
  4981. private Vector3 GetParcelCenterAtGround(ILandObject parcel)
  4982. {
  4983. Vector2 center = parcel.CenterPoint;
  4984. return GetPositionAtGround(center.X, center.Y);
  4985. }
  4986. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
  4987. {
  4988. return GetNearestAllowedParcel(avatarId, x, y, null);
  4989. }
  4990. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
  4991. {
  4992. if(LandChannel == null)
  4993. return null;
  4994. List<ILandObject> all = LandChannel.AllParcels();
  4995. if(all == null || all.Count == 0)
  4996. return null;
  4997. float minParcelDistanceSQ = float.MaxValue;
  4998. ILandObject nearestParcel = null;
  4999. Vector2 curCenter;
  5000. float parcelDistanceSQ;
  5001. foreach (var parcel in all)
  5002. {
  5003. if (parcel != excludeParcel && !parcel.IsEitherBannedOrRestricted(avatarId))
  5004. {
  5005. curCenter = parcel.CenterPoint;
  5006. curCenter.X -= x;
  5007. curCenter.Y -= y;
  5008. parcelDistanceSQ = curCenter.LengthSquared();
  5009. if (parcelDistanceSQ < minParcelDistanceSQ)
  5010. {
  5011. minParcelDistanceSQ = parcelDistanceSQ;
  5012. nearestParcel = parcel;
  5013. }
  5014. }
  5015. }
  5016. return nearestParcel;
  5017. }
  5018. private Vector2 GetParcelSafeCorner(ILandObject parcel)
  5019. {
  5020. Vector2 place = parcel.StartPoint;
  5021. place.X += 2f;
  5022. place.Y += 2f;
  5023. return place;
  5024. }
  5025. private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
  5026. {
  5027. float posX = avatar.AbsolutePosition.X;
  5028. float posY = avatar.AbsolutePosition.Y;
  5029. float regionSizeX = RegionInfo.RegionSizeX;
  5030. float halfRegionSizeX = regionSizeX * 0.5f;
  5031. float regionSizeY = RegionInfo.RegionSizeY;
  5032. float halfRegionSizeY = regionSizeY * 0.5f;
  5033. float xdistance = posX < halfRegionSizeX ? posX : regionSizeX - posX;
  5034. float ydistance = posY < halfRegionSizeY ? posY : regionSizeY - posY;
  5035. //find out what vertical edge to go to
  5036. if (xdistance < ydistance)
  5037. {
  5038. if (posX < halfRegionSizeX)
  5039. return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.5f, posY);
  5040. else
  5041. return GetPositionAtAvatarHeightOrGroundHeight(avatar, regionSizeX - 0.5f, posY);
  5042. }
  5043. //find out what horizontal edge to go to
  5044. else
  5045. {
  5046. if (posY < halfRegionSizeY)
  5047. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, 0.5f);
  5048. else
  5049. return GetPositionAtAvatarHeightOrGroundHeight(avatar, posX, regionSizeY - 0.5f);
  5050. }
  5051. }
  5052. private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
  5053. {
  5054. Vector3 ground = GetPositionAtGround(x, y);
  5055. if(avatar.Appearance != null)
  5056. ground.Z += avatar.Appearance.AvatarHeight * 0.5f;
  5057. else
  5058. ground.Z += 0.8f;
  5059. if (avatar.AbsolutePosition.Z > ground.Z)
  5060. {
  5061. ground.Z = avatar.AbsolutePosition.Z;
  5062. }
  5063. return ground;
  5064. }
  5065. private Vector3 GetPositionAtGround(float x, float y)
  5066. {
  5067. return new Vector3(x, y, GetGroundHeight(x, y));
  5068. }
  5069. public List<UUID> GetEstateRegions(int estateID)
  5070. {
  5071. IEstateDataService estateDataService = EstateDataService;
  5072. if (estateDataService == null)
  5073. return new List<UUID>(0);
  5074. return estateDataService.GetRegions(estateID);
  5075. }
  5076. public void ReloadEstateData()
  5077. {
  5078. IEstateDataService estateDataService = EstateDataService;
  5079. if (estateDataService != null)
  5080. {
  5081. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  5082. TriggerEstateSunUpdate();
  5083. }
  5084. }
  5085. public void TriggerEstateSunUpdate()
  5086. {
  5087. EventManager.TriggerEstateToolsSunUpdate(RegionInfo.RegionHandle);
  5088. }
  5089. private void HandleReloadEstate(string module, string[] cmd)
  5090. {
  5091. if (MainConsole.Instance.ConsoleScene == null ||
  5092. (MainConsole.Instance.ConsoleScene is Scene &&
  5093. (Scene)MainConsole.Instance.ConsoleScene == this))
  5094. {
  5095. ReloadEstateData();
  5096. }
  5097. }
  5098. /// <summary>
  5099. /// Get the volume of space that will encompass all the given objects.
  5100. /// </summary>
  5101. /// <param name="objects"></param>
  5102. /// <param name="minX"></param>
  5103. /// <param name="maxX"></param>
  5104. /// <param name="minY"></param>
  5105. /// <param name="maxY"></param>
  5106. /// <param name="minZ"></param>
  5107. /// <param name="maxZ"></param>
  5108. /// <returns></returns>
  5109. public static Vector3[] GetCombinedBoundingBox(
  5110. List<SceneObjectGroup> objects,
  5111. out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  5112. {
  5113. minX = float.MaxValue;
  5114. maxX = float.MinValue;
  5115. minY = float.MaxValue;
  5116. maxY = float.MinValue;
  5117. minZ = float.MaxValue;
  5118. maxZ = float.MinValue;
  5119. List<Vector3> offsets = new List<Vector3>();
  5120. foreach (SceneObjectGroup g in objects)
  5121. {
  5122. float ominX, ominY, ominZ, omaxX, omaxY, omaxZ;
  5123. Vector3 vec = g.AbsolutePosition;
  5124. g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ);
  5125. // m_log.DebugFormat(
  5126. // "[SCENE]: For {0} found AxisAlignedBoundingBoxRaw {1}, {2}",
  5127. // g.Name, new Vector3(ominX, ominY, ominZ), new Vector3(omaxX, omaxY, omaxZ));
  5128. ominX += vec.X;
  5129. omaxX += vec.X;
  5130. ominY += vec.Y;
  5131. omaxY += vec.Y;
  5132. ominZ += vec.Z;
  5133. omaxZ += vec.Z;
  5134. if (minX > ominX)
  5135. minX = ominX;
  5136. if (minY > ominY)
  5137. minY = ominY;
  5138. if (minZ > ominZ)
  5139. minZ = ominZ;
  5140. if (maxX < omaxX)
  5141. maxX = omaxX;
  5142. if (maxY < omaxY)
  5143. maxY = omaxY;
  5144. if (maxZ < omaxZ)
  5145. maxZ = omaxZ;
  5146. }
  5147. foreach (SceneObjectGroup g in objects)
  5148. {
  5149. Vector3 vec = g.AbsolutePosition;
  5150. vec.X -= minX;
  5151. vec.Y -= minY;
  5152. vec.Z -= minZ;
  5153. offsets.Add(vec);
  5154. }
  5155. return offsets.ToArray();
  5156. }
  5157. /// <summary>
  5158. /// Regenerate the maptile for this scene.
  5159. /// </summary>
  5160. /// <param name="sender"></param>
  5161. /// <param name="e"></param>
  5162. private void RegenerateMaptile()
  5163. {
  5164. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  5165. if (mapModule != null)
  5166. mapModule.GenerateMaptile();
  5167. }
  5168. // public void CleanDroppedAttachments()
  5169. // {
  5170. // List<SceneObjectGroup> objectsToDelete =
  5171. // new List<SceneObjectGroup>();
  5172. //
  5173. // lock (m_cleaningAttachments)
  5174. // {
  5175. // ForEachSOG(delegate (SceneObjectGroup grp)
  5176. // {
  5177. // if (grp.RootPart.Shape.PCode == 0 && grp.RootPart.Shape.State != 0 && (!objectsToDelete.Contains(grp)))
  5178. // {
  5179. // UUID agentID = grp.OwnerID;
  5180. // if (agentID == UUID.Zero)
  5181. // {
  5182. // objectsToDelete.Add(grp);
  5183. // return;
  5184. // }
  5185. //
  5186. // ScenePresence sp = GetScenePresence(agentID);
  5187. // if (sp == null)
  5188. // {
  5189. // objectsToDelete.Add(grp);
  5190. // return;
  5191. // }
  5192. // }
  5193. // });
  5194. // }
  5195. //
  5196. // foreach (SceneObjectGroup grp in objectsToDelete)
  5197. // {
  5198. // m_log.InfoFormat("[SCENE]: Deleting dropped attachment {0} of user {1}", grp.UUID, grp.OwnerID);
  5199. // DeleteSceneObject(grp, true);
  5200. // }
  5201. // }
  5202. public void ThreadAlive(int threadCode)
  5203. {
  5204. switch(threadCode)
  5205. {
  5206. case 1: // Incoming
  5207. m_lastIncoming = Util.EnvironmentTickCount();
  5208. break;
  5209. case 2: // Incoming
  5210. m_lastOutgoing = Util.EnvironmentTickCount();
  5211. break;
  5212. }
  5213. }
  5214. public void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
  5215. {
  5216. RegenerateMaptile();
  5217. // We need to propagate the new image UUID to the grid service
  5218. // so that all simulators can retrieve it
  5219. string error = GridService.RegisterRegion(RegionInfo.ScopeID, new GridRegion(RegionInfo));
  5220. if (error != string.Empty)
  5221. throw new Exception(error);
  5222. }
  5223. /// <summary>
  5224. /// This method is called across the simulation connector to
  5225. /// determine if a given agent is allowed in this region
  5226. /// AS A ROOT AGENT
  5227. /// </summary>
  5228. /// <remarks>
  5229. /// Returning false here will prevent them
  5230. /// from logging into the region, teleporting into the region
  5231. /// or corssing the broder walking, but will NOT prevent
  5232. /// child agent creation, thereby emulating the SL behavior.
  5233. /// </remarks>
  5234. /// <param name='agentID'>The visitor's User ID</param>
  5235. /// <param name="agentHomeURI">The visitor's Home URI (may be null)</param>
  5236. /// <param name='position'></param>
  5237. /// <param name='reason'></param>
  5238. /// <returns></returns>
  5239. public bool QueryAccess(UUID agentID, string agentHomeURI, bool viaTeleport, Vector3 position, List<UUID> features, out string reason)
  5240. {
  5241. reason = string.Empty;
  5242. if (Permissions.IsGod(agentID))
  5243. return true;
  5244. if (!AllowAvatarCrossing && !viaTeleport)
  5245. {
  5246. reason = "Region Crossing not allowed";
  5247. return false;
  5248. }
  5249. bool isAdmin = Permissions.IsAdministrator(agentID);
  5250. bool isManager = Permissions.IsEstateManager(agentID);
  5251. // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
  5252. // However, the long term fix is to make sure root agent count is always accurate.
  5253. m_sceneGraph.RecalculateStats();
  5254. int num = m_sceneGraph.GetRootAgentCount();
  5255. if (num >= RegionInfo.RegionSettings.AgentLimit)
  5256. {
  5257. if (!(isAdmin || isManager))
  5258. {
  5259. reason = "The region is full";
  5260. m_log.DebugFormat(
  5261. "[SCENE]: Denying presence with id {0} entry into {1} since region is at agent limit of {2}",
  5262. agentID, RegionInfo.RegionName, RegionInfo.RegionSettings.AgentLimit);
  5263. return false;
  5264. }
  5265. }
  5266. ScenePresence presence = GetScenePresence(agentID);
  5267. IClientAPI client = null;
  5268. AgentCircuitData aCircuit = null;
  5269. if (presence != null)
  5270. {
  5271. client = presence.ControllingClient;
  5272. if (client != null)
  5273. aCircuit = client.RequestClientInfo();
  5274. }
  5275. // We may be called before there is a presence or a client.
  5276. // Fake AgentCircuitData to keep IAuthorizationModule smiling
  5277. if (client == null)
  5278. {
  5279. aCircuit = new AgentCircuitData();
  5280. aCircuit.AgentID = agentID;
  5281. aCircuit.firstname = String.Empty;
  5282. aCircuit.lastname = String.Empty;
  5283. }
  5284. try
  5285. {
  5286. if (!AuthorizeUser(aCircuit, false, out reason))
  5287. {
  5288. //m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
  5289. // reason = "Region authorization fail";
  5290. return false;
  5291. }
  5292. }
  5293. catch (Exception e)
  5294. {
  5295. m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} " + e.StackTrace, e.Message);
  5296. reason = "Error authorizing agent: " + e.Message;
  5297. return false;
  5298. }
  5299. // last check aditional land access restrictions and relocations
  5300. // if crossing (viaTeleport false) check only the specified parcel
  5301. return CheckLandPositionAccess(agentID, viaTeleport, true, position, out reason);
  5302. }
  5303. // check access to land.
  5304. public bool CheckLandPositionAccess(UUID agentID, bool NotCrossing, bool checkTeleHub, Vector3 position, out string reason)
  5305. {
  5306. reason = string.Empty;
  5307. if (Permissions.IsGod(agentID))
  5308. return true;
  5309. // Permissions.IsAdministrator is the same as IsGod for now
  5310. // bool isAdmin = Permissions.IsAdministrator(agentID);
  5311. // if(isAdmin)
  5312. // return true;
  5313. // also honor estate managers access rights
  5314. bool isManager = Permissions.IsEstateManager(agentID);
  5315. if(isManager)
  5316. return true;
  5317. if (NotCrossing)
  5318. {
  5319. if (!RegionInfo.EstateSettings.AllowDirectTeleport)
  5320. {
  5321. SceneObjectGroup telehub;
  5322. if (RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = GetSceneObjectGroup (RegionInfo.RegionSettings.TelehubObject)) != null && checkTeleHub)
  5323. {
  5324. bool banned = true;
  5325. bool validTelehub = false;
  5326. List<SpawnPoint> spawnPoints = RegionInfo.RegionSettings.SpawnPoints();
  5327. Vector3 spawnPoint;
  5328. ILandObject land = null;
  5329. Vector3 telehubPosition = telehub.AbsolutePosition;
  5330. if(spawnPoints.Count == 0)
  5331. {
  5332. // will this ever happen?
  5333. // if so use the telehub object position
  5334. spawnPoint = telehubPosition;
  5335. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5336. if(land != null && !land.IsEitherBannedOrRestricted(agentID))
  5337. {
  5338. banned = false;
  5339. validTelehub = true;
  5340. }
  5341. }
  5342. else
  5343. {
  5344. Quaternion telehubRotation = telehub.GroupRotation;
  5345. foreach (SpawnPoint spawn in spawnPoints)
  5346. {
  5347. spawnPoint = spawn.GetLocation(telehubPosition, telehubRotation);
  5348. land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  5349. if (land == null)
  5350. continue;
  5351. validTelehub = true;
  5352. if (!land.IsEitherBannedOrRestricted(agentID))
  5353. {
  5354. banned = false;
  5355. break;
  5356. }
  5357. }
  5358. }
  5359. if(validTelehub)
  5360. {
  5361. if (banned)
  5362. {
  5363. reason = "No suitable landing point found";
  5364. return false;
  5365. }
  5366. else
  5367. return true;
  5368. }
  5369. // possible broken telehub, fall into normal check
  5370. }
  5371. }
  5372. float posX = position.X;
  5373. float posY = position.Y;
  5374. // allow position relocation
  5375. if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
  5376. {
  5377. // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
  5378. reason = "You dont have access to the region parcels";
  5379. return false;
  5380. }
  5381. }
  5382. else // check for query region crossing only
  5383. {
  5384. // no relocation allowed on crossings
  5385. ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
  5386. if (land == null)
  5387. {
  5388. reason = "No parcel found";
  5389. return false;
  5390. }
  5391. bool banned = land.IsBannedFromLand(agentID);
  5392. bool restricted = land.IsRestrictedFromLand(agentID);
  5393. if (banned || restricted)
  5394. {
  5395. if (banned)
  5396. reason = "You are banned from the parcel";
  5397. else
  5398. reason = "The parcel is restricted";
  5399. return false;
  5400. }
  5401. }
  5402. return true;
  5403. }
  5404. public void StartTimerWatchdog()
  5405. {
  5406. m_timerWatchdog.Interval = 1000;
  5407. m_timerWatchdog.Elapsed += TimerWatchdog;
  5408. m_timerWatchdog.AutoReset = true;
  5409. m_timerWatchdog.Start();
  5410. }
  5411. public void TimerWatchdog(object sender, ElapsedEventArgs e)
  5412. {
  5413. CheckHeartbeat();
  5414. IEtcdModule etcd = RequestModuleInterface<IEtcdModule>();
  5415. int flags;
  5416. string message;
  5417. if (etcd != null)
  5418. {
  5419. int health = GetHealth(out flags, out message);
  5420. if (health != m_lastHealth)
  5421. {
  5422. m_lastHealth = health;
  5423. etcd.Store("Health", health.ToString(), 300000);
  5424. etcd.Store("HealthFlags", flags.ToString(), 300000);
  5425. }
  5426. int roots = 0;
  5427. foreach (ScenePresence sp in GetScenePresences())
  5428. if (!sp.IsChildAgent && !sp.IsNPC)
  5429. roots++;
  5430. if (m_lastUsers != roots)
  5431. {
  5432. m_lastUsers = roots;
  5433. etcd.Store("RootAgents", roots.ToString(), 300000);
  5434. }
  5435. }
  5436. }
  5437. /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
  5438. /// autopilot that moves an avatar to a sit target!.
  5439. /// </summary>
  5440. /// <remarks>
  5441. /// This is not intended as a permament location for this method.
  5442. /// </remarks>
  5443. /// <param name="presence"></param>
  5444. /* move to target is now done on presence update
  5445. private void HandleOnSignificantClientMovement(ScenePresence presence)
  5446. {
  5447. if (presence.MovingToTarget)
  5448. {
  5449. double distanceToTarget = Util.GetDistanceTo(presence.AbsolutePosition, presence.MoveToPositionTarget);
  5450. // m_log.DebugFormat(
  5451. // "[SCENE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  5452. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget, distanceToTarget);
  5453. // Check the error term of the current position in relation to the target position
  5454. if (distanceToTarget <= ScenePresence.SIGNIFICANT_MOVEMENT)
  5455. {
  5456. // We are close enough to the target
  5457. // m_log.DebugFormat("[SCENEE]: Stopping autopilot of {0}", presence.Name);
  5458. presence.Velocity = Vector3.Zero;
  5459. presence.AbsolutePosition = presence.MoveToPositionTarget;
  5460. presence.ResetMoveToTarget();
  5461. if (presence.Flying)
  5462. {
  5463. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  5464. // the target if flying.
  5465. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  5466. // least be able to set collision status once, rather than 5 times to give it enough
  5467. // weighting so that that PhysicsActor thinks it really is colliding.
  5468. for (int i = 0; i < 5; i++)
  5469. presence.IsColliding = true;
  5470. if (presence.LandAtTarget)
  5471. presence.Flying = false;
  5472. // Vector3 targetPos = presence.MoveToPositionTarget;
  5473. // float terrainHeight = (float)presence.Scene.Heightmap[(int)targetPos.X, (int)targetPos.Y];
  5474. // if (targetPos.Z - terrainHeight < 0.2)
  5475. // {
  5476. // presence.Flying = false;
  5477. // }
  5478. }
  5479. // m_log.DebugFormat(
  5480. // "[SCENE]: AgentControlFlags {0}, MovementFlag {1} for {2}",
  5481. // presence.AgentControlFlags, presence.MovementFlag, presence.Name);
  5482. }
  5483. else
  5484. {
  5485. // m_log.DebugFormat(
  5486. // "[SCENE]: Updating npc {0} at {1} for next movement to {2}",
  5487. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget);
  5488. Vector3 agent_control_v3 = new Vector3();
  5489. presence.HandleMoveToTargetUpdate(1, ref agent_control_v3);
  5490. presence.AddNewMovement(agent_control_v3);
  5491. }
  5492. }
  5493. }
  5494. */
  5495. // manage and select spawn points in sequence
  5496. public int SpawnPoint()
  5497. {
  5498. int spawnpoints = RegionInfo.RegionSettings.SpawnPoints().Count;
  5499. if (spawnpoints == 0)
  5500. return 0;
  5501. m_SpawnPoint++;
  5502. if (m_SpawnPoint > spawnpoints)
  5503. m_SpawnPoint = 1;
  5504. return m_SpawnPoint - 1;
  5505. }
  5506. private void HandleGcCollect(string module, string[] args)
  5507. {
  5508. GC.Collect();
  5509. }
  5510. /// <summary>
  5511. /// Wrappers to get physics modules retrieve assets.
  5512. /// </summary>
  5513. /// <remarks>
  5514. /// Has to be done this way
  5515. /// because we can't assign the asset service to physics directly - at the
  5516. /// time physics are instantiated it's not registered but it will be by
  5517. /// the time the first prim exists.
  5518. /// </remarks>
  5519. /// <param name="assetID"></param>
  5520. /// <param name="callback"></param>
  5521. public void PhysicsRequestAsset(UUID assetID, AssetReceivedDelegate callback)
  5522. {
  5523. AssetService.Get(assetID.ToString(), callback, PhysicsAssetReceived);
  5524. }
  5525. private void PhysicsAssetReceived(string id, Object sender, AssetBase asset)
  5526. {
  5527. AssetReceivedDelegate callback = (AssetReceivedDelegate)sender;
  5528. callback(asset);
  5529. }
  5530. public string GetExtraSetting(string name)
  5531. {
  5532. if (m_extraSettings == null)
  5533. return String.Empty;
  5534. string val;
  5535. if (!m_extraSettings.TryGetValue(name, out val))
  5536. return String.Empty;
  5537. return val;
  5538. }
  5539. public void StoreExtraSetting(string name, string val)
  5540. {
  5541. if (m_extraSettings == null)
  5542. return;
  5543. string oldVal;
  5544. if (m_extraSettings.TryGetValue(name, out oldVal))
  5545. {
  5546. if (oldVal == val)
  5547. return;
  5548. }
  5549. m_extraSettings[name] = val;
  5550. m_SimulationDataService.SaveExtra(RegionInfo.RegionID, name, val);
  5551. m_eventManager.TriggerExtraSettingChanged(this, name, val);
  5552. }
  5553. public void RemoveExtraSetting(string name)
  5554. {
  5555. if (m_extraSettings == null)
  5556. return;
  5557. if (!m_extraSettings.ContainsKey(name))
  5558. return;
  5559. m_extraSettings.Remove(name);
  5560. m_SimulationDataService.RemoveExtra(RegionInfo.RegionID, name);
  5561. m_eventManager.TriggerExtraSettingChanged(this, name, String.Empty);
  5562. }
  5563. }
  5564. }