Scene.cs 242 KB

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