1
0

Scene.cs 263 KB

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