Scene.cs 252 KB

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