Scene.cs 262 KB

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