Scene.cs 213 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293
  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.Services.Interfaces;
  43. using OpenSim.Framework.Communications;
  44. using OpenSim.Framework.Console;
  45. using OpenSim.Region.Framework.Interfaces;
  46. using OpenSim.Region.Framework.Scenes.Scripting;
  47. using OpenSim.Region.Framework.Scenes.Serialization;
  48. using OpenSim.Region.Physics.Manager;
  49. using Timer=System.Timers.Timer;
  50. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  51. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  52. namespace OpenSim.Region.Framework.Scenes
  53. {
  54. public delegate bool FilterAvatarList(ScenePresence avatar);
  55. public partial class Scene : SceneBase
  56. {
  57. public delegate void SynchronizeSceneHandler(Scene scene);
  58. public SynchronizeSceneHandler SynchronizeScene = null;
  59. /* Used by the loadbalancer plugin on GForge */
  60. protected int m_splitRegionID = 0;
  61. public int SplitRegionID
  62. {
  63. get { return m_splitRegionID; }
  64. set { m_splitRegionID = value; }
  65. }
  66. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  67. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  68. #region Fields
  69. protected Timer m_restartWaitTimer = new Timer();
  70. public SimStatsReporter StatsReporter;
  71. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  72. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  73. private volatile int m_bordersLocked = 0;
  74. public bool BordersLocked
  75. {
  76. get { return m_bordersLocked == 1; }
  77. set
  78. {
  79. if (value == true)
  80. m_bordersLocked = 1;
  81. else
  82. m_bordersLocked = 0;
  83. }
  84. }
  85. public List<Border> NorthBorders = new List<Border>();
  86. public List<Border> EastBorders = new List<Border>();
  87. public List<Border> SouthBorders = new List<Border>();
  88. public List<Border> WestBorders = new List<Border>();
  89. /// <value>
  90. /// The scene graph for this scene
  91. /// </value>
  92. /// TODO: Possibly stop other classes being able to manipulate this directly.
  93. private SceneGraph m_sceneGraph;
  94. /// <summary>
  95. /// Are we applying physics to any of the prims in this scene?
  96. /// </summary>
  97. public bool m_physicalPrim;
  98. public float m_maxNonphys = 256;
  99. public float m_maxPhys = 10;
  100. public bool m_clampPrimSize;
  101. public bool m_trustBinaries;
  102. public bool m_allowScriptCrossings;
  103. public bool m_useFlySlow;
  104. public bool m_usePreJump;
  105. public bool m_seeIntoRegionFromNeighbor;
  106. // TODO: need to figure out how allow client agents but deny
  107. // root agents when ACL denies access to root agent
  108. public bool m_strictAccessControl = true;
  109. public int MaxUndoCount = 5;
  110. private int m_RestartTimerCounter;
  111. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  112. private int m_incrementsof15seconds;
  113. private volatile bool m_backingup;
  114. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  115. private Dictionary<UUID, SceneObjectGroup> m_groupsWithTargets = new Dictionary<UUID, SceneObjectGroup>();
  116. protected string m_simulatorVersion = "OpenSimulator Server";
  117. protected ModuleLoader m_moduleLoader;
  118. protected StorageManager m_storageManager;
  119. protected AgentCircuitManager m_authenticateHandler;
  120. protected SceneCommunicationService m_sceneGridService;
  121. public bool LoginsDisabled = true;
  122. public new float TimeDilation
  123. {
  124. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  125. }
  126. public SceneCommunicationService SceneGridService
  127. {
  128. get { return m_sceneGridService; }
  129. }
  130. public IXfer XferManager;
  131. protected IAssetService m_AssetService;
  132. protected IAuthorizationService m_AuthorizationService;
  133. private Object m_heartbeatLock = new Object();
  134. public IAssetService AssetService
  135. {
  136. get
  137. {
  138. if (m_AssetService == null)
  139. {
  140. m_AssetService = RequestModuleInterface<IAssetService>();
  141. if (m_AssetService == null)
  142. {
  143. throw new Exception("No IAssetService available.");
  144. }
  145. }
  146. return m_AssetService;
  147. }
  148. }
  149. public IAuthorizationService AuthorizationService
  150. {
  151. get
  152. {
  153. if (m_AuthorizationService == null)
  154. {
  155. m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
  156. //if (m_AuthorizationService == null)
  157. //{
  158. // // don't throw an exception if no authorization service is set for the time being
  159. // m_log.InfoFormat("[SCENE]: No Authorization service is configured");
  160. //}
  161. }
  162. return m_AuthorizationService;
  163. }
  164. }
  165. protected IInventoryService m_InventoryService;
  166. public IInventoryService InventoryService
  167. {
  168. get
  169. {
  170. if (m_InventoryService == null)
  171. {
  172. m_InventoryService = RequestModuleInterface<IInventoryService>();
  173. if (m_InventoryService == null)
  174. {
  175. 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.");
  176. }
  177. }
  178. return m_InventoryService;
  179. }
  180. }
  181. protected IGridService m_GridService;
  182. public IGridService GridService
  183. {
  184. get
  185. {
  186. if (m_GridService == null)
  187. {
  188. m_GridService = RequestModuleInterface<IGridService>();
  189. if (m_GridService == null)
  190. {
  191. 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.");
  192. }
  193. }
  194. return m_GridService;
  195. }
  196. }
  197. protected ILibraryService m_LibraryService;
  198. public ILibraryService LibraryService
  199. {
  200. get
  201. {
  202. if (m_LibraryService == null)
  203. m_LibraryService = RequestModuleInterface<ILibraryService>();
  204. return m_LibraryService;
  205. }
  206. }
  207. protected ISimulationService m_simulationService;
  208. public ISimulationService SimulationService
  209. {
  210. get
  211. {
  212. if (m_simulationService == null)
  213. m_simulationService = RequestModuleInterface<ISimulationService>();
  214. return m_simulationService;
  215. }
  216. }
  217. protected IAuthenticationService m_AuthenticationService;
  218. public IAuthenticationService AuthenticationService
  219. {
  220. get
  221. {
  222. if (m_AuthenticationService == null)
  223. m_AuthenticationService = RequestModuleInterface<IAuthenticationService>();
  224. return m_AuthenticationService;
  225. }
  226. }
  227. protected IPresenceService m_PresenceService;
  228. public IPresenceService PresenceService
  229. {
  230. get
  231. {
  232. if (m_PresenceService == null)
  233. m_PresenceService = RequestModuleInterface<IPresenceService>();
  234. return m_PresenceService;
  235. }
  236. }
  237. protected IUserAccountService m_UserAccountService;
  238. public IUserAccountService UserAccountService
  239. {
  240. get
  241. {
  242. if (m_UserAccountService == null)
  243. m_UserAccountService = RequestModuleInterface<IUserAccountService>();
  244. return m_UserAccountService;
  245. }
  246. }
  247. protected OpenSim.Services.Interfaces.IAvatarService m_AvatarService;
  248. public OpenSim.Services.Interfaces.IAvatarService AvatarService
  249. {
  250. get
  251. {
  252. if (m_AvatarService == null)
  253. m_AvatarService = RequestModuleInterface<IAvatarService>();
  254. return m_AvatarService;
  255. }
  256. }
  257. protected IGridUserService m_GridUserService;
  258. public IGridUserService GridUserService
  259. {
  260. get
  261. {
  262. if (m_GridUserService == null)
  263. m_GridUserService = RequestModuleInterface<IGridUserService>();
  264. return m_GridUserService;
  265. }
  266. }
  267. protected IXMLRPC m_xmlrpcModule;
  268. protected IWorldComm m_worldCommModule;
  269. public IAttachmentsModule AttachmentsModule { get; set; }
  270. protected IAvatarFactory m_AvatarFactory;
  271. public IAvatarFactory AvatarFactory
  272. {
  273. get { return m_AvatarFactory; }
  274. }
  275. protected IConfigSource m_config;
  276. protected IRegionSerialiserModule m_serialiser;
  277. protected IDialogModule m_dialogModule;
  278. protected IEntityTransferModule m_teleportModule;
  279. protected ICapabilitiesModule m_capsModule;
  280. public ICapabilitiesModule CapsModule
  281. {
  282. get { return m_capsModule; }
  283. }
  284. protected override IConfigSource GetConfig()
  285. {
  286. return m_config;
  287. }
  288. // Central Update Loop
  289. protected int m_fps = 10;
  290. protected uint m_frame;
  291. protected float m_timespan = 0.089f;
  292. protected DateTime m_lastupdate = DateTime.UtcNow;
  293. private int m_update_physics = 1;
  294. private int m_update_entitymovement = 1;
  295. private int m_update_objects = 1; // Update objects which have scheduled themselves for updates
  296. private int m_update_presences = 1; // Update scene presence movements
  297. private int m_update_events = 1;
  298. private int m_update_backup = 200;
  299. private int m_update_terrain = 50;
  300. private int m_update_land = 1;
  301. private int m_update_coarse_locations = 50;
  302. private int frameMS;
  303. private int physicsMS2;
  304. private int physicsMS;
  305. private int otherMS;
  306. private int tempOnRezMS;
  307. private int eventMS;
  308. private int backupMS;
  309. private int terrainMS;
  310. private int landMS;
  311. private int lastCompletedFrame;
  312. public int MonitorFrameTime { get { return frameMS; } }
  313. public int MonitorPhysicsUpdateTime { get { return physicsMS; } }
  314. public int MonitorPhysicsSyncTime { get { return physicsMS2; } }
  315. public int MonitorOtherTime { get { return otherMS; } }
  316. public int MonitorTempOnRezTime { get { return tempOnRezMS; } }
  317. public int MonitorEventTime { get { return eventMS; } } // This may need to be divided into each event?
  318. public int MonitorBackupTime { get { return backupMS; } }
  319. public int MonitorTerrainTime { get { return terrainMS; } }
  320. public int MonitorLandTime { get { return landMS; } }
  321. public int MonitorLastFrameTick { get { return lastCompletedFrame; } }
  322. private bool m_physics_enabled = true;
  323. private bool m_scripts_enabled = true;
  324. private string m_defaultScriptEngine;
  325. private int m_LastLogin;
  326. private Thread HeartbeatThread;
  327. private volatile bool shuttingdown;
  328. private int m_lastUpdate;
  329. private bool m_firstHeartbeat = true;
  330. private object m_deleting_scene_object = new object();
  331. // the minimum time that must elapse before a changed object will be considered for persisted
  332. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  333. // the maximum time that must elapse before a changed object will be considered for persisted
  334. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  335. private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
  336. private bool m_reprioritizationEnabled = true;
  337. private double m_reprioritizationInterval = 5000.0;
  338. private double m_rootReprioritizationDistance = 10.0;
  339. private double m_childReprioritizationDistance = 20.0;
  340. #endregion
  341. #region Properties
  342. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get { return m_priorityScheme; } }
  343. public bool IsReprioritizationEnabled { get { return m_reprioritizationEnabled; } }
  344. public double ReprioritizationInterval { get { return m_reprioritizationInterval; } }
  345. public double RootReprioritizationDistance { get { return m_rootReprioritizationDistance; } }
  346. public double ChildReprioritizationDistance { get { return m_childReprioritizationDistance; } }
  347. public AgentCircuitManager AuthenticateHandler
  348. {
  349. get { return m_authenticateHandler; }
  350. }
  351. public SceneGraph SceneContents
  352. {
  353. get { return m_sceneGraph; }
  354. }
  355. // an instance to the physics plugin's Scene object.
  356. public PhysicsScene PhysicsScene
  357. {
  358. get { return m_sceneGraph.PhysicsScene; }
  359. set
  360. {
  361. // If we're not doing the initial set
  362. // Then we've got to remove the previous
  363. // event handler
  364. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  365. {
  366. PhysicsScene.OnJointMoved -= jointMoved;
  367. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  368. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  369. }
  370. m_sceneGraph.PhysicsScene = value;
  371. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  372. {
  373. // register event handlers to respond to joint movement/deactivation
  374. PhysicsScene.OnJointMoved += jointMoved;
  375. PhysicsScene.OnJointDeactivated += jointDeactivated;
  376. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  377. }
  378. }
  379. }
  380. // This gets locked so things stay thread safe.
  381. public object SyncRoot
  382. {
  383. get { return m_sceneGraph.m_syncRoot; }
  384. }
  385. /// <summary>
  386. /// This is for llGetRegionFPS
  387. /// </summary>
  388. public float SimulatorFPS
  389. {
  390. get { return StatsReporter.getLastReportedSimFPS(); }
  391. }
  392. public float[] SimulatorStats
  393. {
  394. get { return StatsReporter.getLastReportedSimStats(); }
  395. }
  396. public string DefaultScriptEngine
  397. {
  398. get { return m_defaultScriptEngine; }
  399. }
  400. public EntityManager Entities
  401. {
  402. get { return m_sceneGraph.Entities; }
  403. }
  404. public Dictionary<UUID, ScenePresence> m_restorePresences
  405. {
  406. get { return m_sceneGraph.RestorePresences; }
  407. set { m_sceneGraph.RestorePresences = value; }
  408. }
  409. #endregion
  410. #region BinaryStats
  411. public class StatLogger
  412. {
  413. public DateTime StartTime;
  414. public string Path;
  415. public System.IO.BinaryWriter Log;
  416. }
  417. static StatLogger m_statLog = null;
  418. static TimeSpan m_statLogPeriod = TimeSpan.FromSeconds(300);
  419. static string m_statsDir = String.Empty;
  420. static Object m_statLockObject = new Object();
  421. private void LogSimStats(SimStats stats)
  422. {
  423. SimStatsPacket pack = new SimStatsPacket();
  424. pack.Region = new SimStatsPacket.RegionBlock();
  425. pack.Region.RegionX = stats.RegionX;
  426. pack.Region.RegionY = stats.RegionY;
  427. pack.Region.RegionFlags = stats.RegionFlags;
  428. pack.Region.ObjectCapacity = stats.ObjectCapacity;
  429. //pack.Region = //stats.RegionBlock;
  430. pack.Stat = stats.StatsBlock;
  431. pack.Header.Reliable = false;
  432. // note that we are inside the reporter lock when called
  433. DateTime now = DateTime.Now;
  434. // hide some time information into the packet
  435. pack.Header.Sequence = (uint)now.Ticks;
  436. lock (m_statLockObject) // m_statLog is shared so make sure there is only executer here
  437. {
  438. try
  439. {
  440. if (m_statLog == null || now > m_statLog.StartTime + m_statLogPeriod)
  441. {
  442. // First log file or time has expired, start writing to a new log file
  443. if (m_statLog != null && m_statLog.Log != null)
  444. {
  445. m_statLog.Log.Close();
  446. }
  447. m_statLog = new StatLogger();
  448. m_statLog.StartTime = now;
  449. m_statLog.Path = (m_statsDir.Length > 0 ? m_statsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  450. + String.Format("stats-{0}.log", now.ToString("yyyyMMddHHmmss"));
  451. m_statLog.Log = new BinaryWriter(File.Open(m_statLog.Path, FileMode.Append, FileAccess.Write));
  452. }
  453. // Write the serialized data to disk
  454. if (m_statLog != null && m_statLog.Log != null)
  455. m_statLog.Log.Write(pack.ToBytes());
  456. }
  457. catch (Exception ex)
  458. {
  459. m_log.Error("statistics gathering failed: " + ex.Message, ex);
  460. if (m_statLog != null && m_statLog.Log != null)
  461. {
  462. m_statLog.Log.Close();
  463. }
  464. m_statLog = null;
  465. }
  466. }
  467. return;
  468. }
  469. #endregion
  470. #region Constructors
  471. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  472. SceneCommunicationService sceneGridService,
  473. StorageManager storeManager,
  474. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  475. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  476. {
  477. m_config = config;
  478. Random random = new Random();
  479. BordersLocked = true;
  480. Border northBorder = new Border();
  481. northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  482. northBorder.CrossDirection = Cardinals.N;
  483. NorthBorders.Add(northBorder);
  484. Border southBorder = new Border();
  485. southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0); //--->
  486. southBorder.CrossDirection = Cardinals.S;
  487. SouthBorders.Add(southBorder);
  488. Border eastBorder = new Border();
  489. eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  490. eastBorder.CrossDirection = Cardinals.E;
  491. EastBorders.Add(eastBorder);
  492. Border westBorder = new Border();
  493. westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, 0); //--->
  494. westBorder.CrossDirection = Cardinals.W;
  495. WestBorders.Add(westBorder);
  496. BordersLocked = false;
  497. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  498. m_moduleLoader = moduleLoader;
  499. m_authenticateHandler = authen;
  500. m_sceneGridService = sceneGridService;
  501. m_storageManager = storeManager;
  502. m_regInfo = regInfo;
  503. m_regionHandle = m_regInfo.RegionHandle;
  504. m_regionName = m_regInfo.RegionName;
  505. m_datastore = m_regInfo.DataStore;
  506. m_lastUpdate = Util.EnvironmentTickCount();
  507. m_physicalPrim = physicalPrim;
  508. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  509. m_eventManager = new EventManager();
  510. m_permissions = new ScenePermissions(this);
  511. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  512. m_asyncSceneObjectDeleter.Enabled = true;
  513. #region Region Settings
  514. // Load region settings
  515. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  516. if (m_storageManager.EstateDataStore != null)
  517. {
  518. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, false);
  519. if (m_regInfo.EstateSettings.EstateID == 0) // No record at all
  520. {
  521. MainConsole.Instance.Output("Your region is not part of an estate.");
  522. while (true)
  523. {
  524. string response = MainConsole.Instance.CmdPrompt("Do you wish to join an existing estate?", "no", new List<string>() {"yes", "no"});
  525. if (response == "no")
  526. {
  527. // Create a new estate
  528. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, true);
  529. m_regInfo.EstateSettings.EstateName = MainConsole.Instance.CmdPrompt("New estate name", m_regInfo.EstateSettings.EstateName);
  530. m_regInfo.EstateSettings.Save();
  531. break;
  532. }
  533. else
  534. {
  535. response = MainConsole.Instance.CmdPrompt("Estate name to join", "None");
  536. if (response == "None")
  537. continue;
  538. List<int> estateIDs = m_storageManager.EstateDataStore.GetEstates(response);
  539. if (estateIDs.Count < 1)
  540. {
  541. MainConsole.Instance.Output("The name you have entered matches no known estate. Please try again");
  542. continue;
  543. }
  544. int estateID = estateIDs[0];
  545. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(estateID);
  546. if (m_storageManager.EstateDataStore.LinkRegion(m_regInfo.RegionID, estateID))
  547. break;
  548. MainConsole.Instance.Output("Joining the estate failed. Please try again.");
  549. }
  550. }
  551. }
  552. }
  553. #endregion Region Settings
  554. MainConsole.Instance.Commands.AddCommand("region", false, "reload estate",
  555. "reload estate",
  556. "Reload the estate data", HandleReloadEstate);
  557. //Bind Storage Manager functions to some land manager functions for this scene
  558. EventManager.OnLandObjectAdded +=
  559. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  560. EventManager.OnLandObjectRemoved +=
  561. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  562. m_sceneGraph = new SceneGraph(this, m_regInfo);
  563. // If the scene graph has an Unrecoverable error, restart this sim.
  564. // Currently the only thing that causes it to happen is two kinds of specific
  565. // Physics based crashes.
  566. //
  567. // Out of memory
  568. // Operating system has killed the plugin
  569. m_sceneGraph.UnRecoverableError += RestartNow;
  570. RegisterDefaultSceneEvents();
  571. DumpAssetsToFile = dumpAssetsToFile;
  572. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  573. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  574. StatsReporter = new SimStatsReporter(this);
  575. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  576. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  577. StatsReporter.SetObjectCapacity(RegionInfo.ObjectCapacity);
  578. // Old
  579. /*
  580. m_simulatorVersion = simulatorVersion
  581. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  582. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  583. + " PhysPrim:" + m_physicalPrim.ToString();
  584. */
  585. m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";
  586. #region Region Config
  587. try
  588. {
  589. // Region config overrides global config
  590. //
  591. IConfig startupConfig = m_config.Configs["Startup"];
  592. //Animation states
  593. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  594. // TODO: Change default to true once the feature is supported
  595. m_usePreJump = startupConfig.GetBoolean("enableprejump", false);
  596. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  597. if (RegionInfo.NonphysPrimMax > 0)
  598. {
  599. m_maxNonphys = RegionInfo.NonphysPrimMax;
  600. }
  601. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  602. if (RegionInfo.PhysPrimMax > 0)
  603. {
  604. m_maxPhys = RegionInfo.PhysPrimMax;
  605. }
  606. // Here, if clamping is requested in either global or
  607. // local config, it will be used
  608. //
  609. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  610. if (RegionInfo.ClampPrimSize)
  611. {
  612. m_clampPrimSize = true;
  613. }
  614. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  615. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  616. m_dontPersistBefore =
  617. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  618. m_dontPersistBefore *= 10000000;
  619. m_persistAfter =
  620. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  621. m_persistAfter *= 10000000;
  622. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
  623. IConfig packetConfig = m_config.Configs["PacketPool"];
  624. if (packetConfig != null)
  625. {
  626. PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
  627. PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
  628. }
  629. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  630. #region BinaryStats
  631. try
  632. {
  633. IConfig statConfig = m_config.Configs["Statistics.Binary"];
  634. if (statConfig.Contains("enabled") && statConfig.GetBoolean("enabled"))
  635. {
  636. if (statConfig.Contains("collect_region_stats"))
  637. {
  638. if (statConfig.GetBoolean("collect_region_stats"))
  639. {
  640. // if enabled, add us to the event. If not enabled, I won't get called
  641. StatsReporter.OnSendStatsResult += LogSimStats;
  642. }
  643. }
  644. if (statConfig.Contains("region_stats_period_seconds"))
  645. {
  646. m_statLogPeriod = TimeSpan.FromSeconds(statConfig.GetInt("region_stats_period_seconds"));
  647. }
  648. if (statConfig.Contains("stats_dir"))
  649. {
  650. m_statsDir = statConfig.GetString("stats_dir");
  651. }
  652. }
  653. }
  654. catch
  655. {
  656. // if it doesn't work, we don't collect anything
  657. }
  658. #endregion BinaryStats
  659. }
  660. catch
  661. {
  662. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  663. }
  664. #endregion Region Config
  665. #region Interest Management
  666. if (m_config != null)
  667. {
  668. IConfig interestConfig = m_config.Configs["InterestManagement"];
  669. if (interestConfig != null)
  670. {
  671. string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  672. try
  673. {
  674. m_priorityScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
  675. }
  676. catch (Exception)
  677. {
  678. m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default prioritizer Time");
  679. m_priorityScheme = UpdatePrioritizationSchemes.Time;
  680. }
  681. m_reprioritizationEnabled = interestConfig.GetBoolean("ReprioritizationEnabled", true);
  682. m_reprioritizationInterval = interestConfig.GetDouble("ReprioritizationInterval", 5000.0);
  683. m_rootReprioritizationDistance = interestConfig.GetDouble("RootReprioritizationDistance", 10.0);
  684. m_childReprioritizationDistance = interestConfig.GetDouble("ChildReprioritizationDistance", 20.0);
  685. }
  686. }
  687. m_log.Info("[SCENE]: Using the " + m_priorityScheme + " prioritization scheme");
  688. #endregion Interest Management
  689. }
  690. /// <summary>
  691. /// Mock constructor for scene group persistency unit tests.
  692. /// SceneObjectGroup RegionId property is delegated to Scene.
  693. /// </summary>
  694. /// <param name="regInfo"></param>
  695. public Scene(RegionInfo regInfo)
  696. {
  697. BordersLocked = true;
  698. Border northBorder = new Border();
  699. northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  700. northBorder.CrossDirection = Cardinals.N;
  701. NorthBorders.Add(northBorder);
  702. Border southBorder = new Border();
  703. southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue,0); //--->
  704. southBorder.CrossDirection = Cardinals.S;
  705. SouthBorders.Add(southBorder);
  706. Border eastBorder = new Border();
  707. eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  708. eastBorder.CrossDirection = Cardinals.E;
  709. EastBorders.Add(eastBorder);
  710. Border westBorder = new Border();
  711. westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue,0); //--->
  712. westBorder.CrossDirection = Cardinals.W;
  713. WestBorders.Add(westBorder);
  714. BordersLocked = false;
  715. m_regInfo = regInfo;
  716. m_eventManager = new EventManager();
  717. m_lastUpdate = Util.EnvironmentTickCount();
  718. }
  719. #endregion
  720. #region Startup / Close Methods
  721. public bool ShuttingDown
  722. {
  723. get { return shuttingdown; }
  724. }
  725. /// <value>
  726. /// The scene graph for this scene
  727. /// </value>
  728. /// TODO: Possibly stop other classes being able to manipulate this directly.
  729. public SceneGraph SceneGraph
  730. {
  731. get { return m_sceneGraph; }
  732. }
  733. protected virtual void RegisterDefaultSceneEvents()
  734. {
  735. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  736. if (dm != null)
  737. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  738. }
  739. public override string GetSimulatorVersion()
  740. {
  741. return m_simulatorVersion;
  742. }
  743. public string[] GetUserNames(UUID uuid)
  744. {
  745. string[] returnstring = new string[0];
  746. UserAccount account = UserAccountService.GetUserAccount(RegionInfo.ScopeID, uuid);
  747. if (account != null)
  748. {
  749. returnstring = new string[2];
  750. returnstring[0] = account.FirstName;
  751. returnstring[1] = account.LastName;
  752. }
  753. return returnstring;
  754. }
  755. public string GetUserName(UUID uuid)
  756. {
  757. string[] names = GetUserNames(uuid);
  758. if (names.Length == 2)
  759. {
  760. string firstname = names[0];
  761. string lastname = names[1];
  762. return firstname + " " + lastname;
  763. }
  764. return "(hippos)";
  765. }
  766. /// <summary>
  767. /// Another region is up.
  768. ///
  769. /// We only add it to the neighbor list if it's within 1 region from here.
  770. /// Agents may have draw distance values that cross two regions though, so
  771. /// we add it to the notify list regardless of distance. We'll check
  772. /// the agent's draw distance before notifying them though.
  773. /// </summary>
  774. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  775. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  776. public override void OtherRegionUp(GridRegion otherRegion)
  777. {
  778. uint xcell = (uint)((int)otherRegion.RegionLocX / (int)Constants.RegionSize);
  779. uint ycell = (uint)((int)otherRegion.RegionLocY / (int)Constants.RegionSize);
  780. m_log.InfoFormat("[SCENE]: (on region {0}): Region {1} up in coords {2}-{3}",
  781. RegionInfo.RegionName, otherRegion.RegionName, xcell, ycell);
  782. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  783. {
  784. // If these are cast to INT because long + negative values + abs returns invalid data
  785. int resultX = Math.Abs((int)xcell - (int)RegionInfo.RegionLocX);
  786. int resultY = Math.Abs((int)ycell - (int)RegionInfo.RegionLocY);
  787. if (resultX <= 1 && resultY <= 1)
  788. {
  789. // Let the grid service module know, so this can be cached
  790. m_eventManager.TriggerOnRegionUp(otherRegion);
  791. try
  792. {
  793. ForEachScenePresence(delegate(ScenePresence agent)
  794. {
  795. // If agent is a root agent.
  796. if (!agent.IsChildAgent)
  797. {
  798. //agent.ControllingClient.new
  799. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  800. List<ulong> old = new List<ulong>();
  801. old.Add(otherRegion.RegionHandle);
  802. agent.DropOldNeighbours(old);
  803. if (m_teleportModule != null)
  804. m_teleportModule.EnableChildAgent(agent, otherRegion);
  805. }
  806. }
  807. );
  808. }
  809. catch (NullReferenceException)
  810. {
  811. // This means that we're not booted up completely yet.
  812. // This shouldn't happen too often anymore.
  813. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  814. }
  815. }
  816. else
  817. {
  818. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  819. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  820. otherRegion.RegionLocY.ToString() + ")");
  821. }
  822. }
  823. }
  824. public void AddNeighborRegion(RegionInfo region)
  825. {
  826. lock (m_neighbours)
  827. {
  828. if (!CheckNeighborRegion(region))
  829. {
  830. m_neighbours.Add(region);
  831. }
  832. }
  833. }
  834. public bool CheckNeighborRegion(RegionInfo region)
  835. {
  836. bool found = false;
  837. lock (m_neighbours)
  838. {
  839. foreach (RegionInfo reg in m_neighbours)
  840. {
  841. if (reg.RegionHandle == region.RegionHandle)
  842. {
  843. found = true;
  844. break;
  845. }
  846. }
  847. }
  848. return found;
  849. }
  850. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  851. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  852. {
  853. OtherRegionUp(new GridRegion(neighbour));
  854. return new GridRegion(RegionInfo);
  855. }
  856. /// <summary>
  857. /// Given float seconds, this will restart the region.
  858. /// </summary>
  859. /// <param name="seconds">float indicating duration before restart.</param>
  860. public virtual void Restart(float seconds)
  861. {
  862. // notifications are done in 15 second increments
  863. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  864. // It's a 'Cancel restart' request.
  865. // RestartNow() does immediate restarting.
  866. if (seconds < 15)
  867. {
  868. m_restartTimer.Stop();
  869. m_dialogModule.SendGeneralAlert("Restart Aborted");
  870. }
  871. else
  872. {
  873. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  874. m_restartTimer.Interval = 15000;
  875. m_incrementsof15seconds = (int)seconds / 15;
  876. m_RestartTimerCounter = 0;
  877. m_restartTimer.AutoReset = true;
  878. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  879. m_log.Info("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  880. m_restartTimer.Start();
  881. m_dialogModule.SendNotificationToUsersInRegion(
  882. UUID.Random(), String.Empty, RegionInfo.RegionName + String.Format(": Restarting in {0} Minutes", (int)(seconds / 60.0)));
  883. }
  884. }
  885. // The Restart timer has occured.
  886. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  887. // have elapsed.
  888. // If they have elapsed, call RestartNow()
  889. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  890. {
  891. m_RestartTimerCounter++;
  892. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  893. {
  894. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  895. m_dialogModule.SendNotificationToUsersInRegion(
  896. UUID.Random(),
  897. String.Empty,
  898. RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter) * 15) + " seconds");
  899. }
  900. else
  901. {
  902. m_restartTimer.Stop();
  903. m_restartTimer.AutoReset = false;
  904. RestartNow();
  905. }
  906. }
  907. // This causes the region to restart immediatley.
  908. public void RestartNow()
  909. {
  910. IConfig startupConfig = m_config.Configs["Startup"];
  911. if (startupConfig != null)
  912. {
  913. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  914. {
  915. MainConsole.Instance.RunCommand("shutdown");
  916. return;
  917. }
  918. }
  919. if (PhysicsScene != null)
  920. {
  921. PhysicsScene.Dispose();
  922. }
  923. m_log.Error("[REGION]: Closing");
  924. Close();
  925. m_log.Error("[REGION]: Firing Region Restart Message");
  926. base.Restart(0);
  927. }
  928. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  929. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  930. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  931. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  932. // subsequently the agent will never see the region come back online.
  933. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  934. {
  935. m_restartWaitTimer.Stop();
  936. lock (m_regionRestartNotifyList)
  937. {
  938. foreach (RegionInfo region in m_regionRestartNotifyList)
  939. {
  940. GridRegion r = new GridRegion(region);
  941. try
  942. {
  943. ForEachScenePresence(delegate(ScenePresence agent)
  944. {
  945. // If agent is a root agent.
  946. if (!agent.IsChildAgent)
  947. {
  948. if (m_teleportModule != null)
  949. m_teleportModule.EnableChildAgent(agent, r);
  950. }
  951. }
  952. );
  953. }
  954. catch (NullReferenceException)
  955. {
  956. // This means that we're not booted up completely yet.
  957. // This shouldn't happen too often anymore.
  958. }
  959. }
  960. // Reset list to nothing.
  961. m_regionRestartNotifyList.Clear();
  962. }
  963. }
  964. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  965. {
  966. if (m_scripts_enabled != !ScriptEngine)
  967. {
  968. if (ScriptEngine)
  969. {
  970. m_log.Info("Stopping all Scripts in Scene");
  971. foreach (EntityBase ent in Entities)
  972. {
  973. if (ent is SceneObjectGroup)
  974. {
  975. ((SceneObjectGroup) ent).RemoveScriptInstances(false);
  976. }
  977. }
  978. }
  979. else
  980. {
  981. m_log.Info("Starting all Scripts in Scene");
  982. lock (Entities)
  983. {
  984. foreach (EntityBase ent in Entities)
  985. {
  986. if (ent is SceneObjectGroup)
  987. {
  988. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  989. ((SceneObjectGroup)ent).ResumeScripts();
  990. }
  991. }
  992. }
  993. }
  994. m_scripts_enabled = !ScriptEngine;
  995. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  996. }
  997. if (m_physics_enabled != !PhysicsEngine)
  998. {
  999. m_physics_enabled = !PhysicsEngine;
  1000. }
  1001. }
  1002. public int GetInaccurateNeighborCount()
  1003. {
  1004. return m_neighbours.Count;
  1005. }
  1006. // This is the method that shuts down the scene.
  1007. public override void Close()
  1008. {
  1009. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  1010. m_restartTimer.Stop();
  1011. m_restartTimer.Close();
  1012. // Kick all ROOT agents with the message, 'The simulator is going down'
  1013. ForEachScenePresence(delegate(ScenePresence avatar)
  1014. {
  1015. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  1016. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  1017. if (!avatar.IsChildAgent)
  1018. avatar.ControllingClient.Kick("The simulator is going down.");
  1019. avatar.ControllingClient.SendShutdownConnectionNotice();
  1020. });
  1021. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  1022. Thread.Sleep(500);
  1023. // Stop all client threads.
  1024. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(); });
  1025. // Stop updating the scene objects and agents.
  1026. //m_heartbeatTimer.Close();
  1027. shuttingdown = true;
  1028. m_log.Debug("[SCENE]: Persisting changed objects");
  1029. List<EntityBase> entities = GetEntities();
  1030. foreach (EntityBase entity in entities)
  1031. {
  1032. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  1033. {
  1034. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore, false);
  1035. }
  1036. }
  1037. m_sceneGraph.Close();
  1038. // De-register with region communications (events cleanup)
  1039. UnRegisterRegionWithComms();
  1040. // call the base class Close method.
  1041. base.Close();
  1042. }
  1043. /// <summary>
  1044. /// Start the timer which triggers regular scene updates
  1045. /// </summary>
  1046. public void StartTimer()
  1047. {
  1048. //m_log.Debug("[SCENE]: Starting timer");
  1049. //m_heartbeatTimer.Enabled = true;
  1050. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  1051. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  1052. if (HeartbeatThread != null)
  1053. {
  1054. HeartbeatThread.Abort();
  1055. HeartbeatThread = null;
  1056. }
  1057. m_lastUpdate = Util.EnvironmentTickCount();
  1058. HeartbeatThread = Watchdog.StartThread(Heartbeat, "Heartbeat for region " + RegionInfo.RegionName, ThreadPriority.Normal, false);
  1059. }
  1060. /// <summary>
  1061. /// Sets up references to modules required by the scene
  1062. /// </summary>
  1063. public void SetModuleInterfaces()
  1064. {
  1065. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  1066. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  1067. XferManager = RequestModuleInterface<IXfer>();
  1068. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  1069. AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
  1070. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  1071. m_dialogModule = RequestModuleInterface<IDialogModule>();
  1072. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  1073. m_teleportModule = RequestModuleInterface<IEntityTransferModule>();
  1074. // Shoving this in here for now, because we have the needed
  1075. // interfaces at this point
  1076. //
  1077. // TODO: Find a better place for this
  1078. //
  1079. while (m_regInfo.EstateSettings.EstateOwner == UUID.Zero && MainConsole.Instance != null)
  1080. {
  1081. MainConsole.Instance.Output("The current estate has no owner set.");
  1082. string first = MainConsole.Instance.CmdPrompt("Estate owner first name", "Test");
  1083. string last = MainConsole.Instance.CmdPrompt("Estate owner last name", "User");
  1084. UserAccount account = UserAccountService.GetUserAccount(m_regInfo.ScopeID, first, last);
  1085. if (account == null)
  1086. {
  1087. // Create a new account
  1088. account = new UserAccount(m_regInfo.ScopeID, first, last, String.Empty);
  1089. if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0))
  1090. {
  1091. account.ServiceURLs = new Dictionary<string, object>();
  1092. account.ServiceURLs["HomeURI"] = string.Empty;
  1093. account.ServiceURLs["GatekeeperURI"] = string.Empty;
  1094. account.ServiceURLs["InventoryServerURI"] = string.Empty;
  1095. account.ServiceURLs["AssetServerURI"] = string.Empty;
  1096. }
  1097. if (UserAccountService.StoreUserAccount(account))
  1098. {
  1099. string password = MainConsole.Instance.PasswdPrompt("Password");
  1100. string email = MainConsole.Instance.CmdPrompt("Email", "");
  1101. account.Email = email;
  1102. UserAccountService.StoreUserAccount(account);
  1103. bool success = false;
  1104. success = AuthenticationService.SetPassword(account.PrincipalID, password);
  1105. if (!success)
  1106. m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.",
  1107. first, last);
  1108. GridRegion home = null;
  1109. if (GridService != null)
  1110. {
  1111. List<GridRegion> defaultRegions = GridService.GetDefaultRegions(UUID.Zero);
  1112. if (defaultRegions != null && defaultRegions.Count >= 1)
  1113. home = defaultRegions[0];
  1114. if (GridUserService != null && home != null)
  1115. GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0));
  1116. else
  1117. m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.",
  1118. first, last);
  1119. }
  1120. else
  1121. m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.",
  1122. first, last);
  1123. if (InventoryService != null)
  1124. success = InventoryService.CreateUserInventory(account.PrincipalID);
  1125. if (!success)
  1126. m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.",
  1127. first, last);
  1128. m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", first, last);
  1129. m_regInfo.EstateSettings.EstateOwner = account.PrincipalID;
  1130. m_regInfo.EstateSettings.Save();
  1131. }
  1132. else
  1133. m_log.ErrorFormat("[SCENE]: Unable to store account. If this simulator is connected to a grid,\n you must create the estate owner account first.");
  1134. }
  1135. else
  1136. {
  1137. m_regInfo.EstateSettings.EstateOwner = account.PrincipalID;
  1138. m_regInfo.EstateSettings.Save();
  1139. }
  1140. }
  1141. }
  1142. #endregion
  1143. #region Update Methods
  1144. /// <summary>
  1145. /// Performs per-frame updates regularly
  1146. /// </summary>
  1147. private void Heartbeat()
  1148. {
  1149. if (!Monitor.TryEnter(m_heartbeatLock))
  1150. {
  1151. Watchdog.RemoveThread();
  1152. return;
  1153. }
  1154. try
  1155. {
  1156. Update();
  1157. m_lastUpdate = Util.EnvironmentTickCount();
  1158. m_firstHeartbeat = false;
  1159. }
  1160. catch (ThreadAbortException)
  1161. {
  1162. }
  1163. finally
  1164. {
  1165. Monitor.Pulse(m_heartbeatLock);
  1166. Monitor.Exit(m_heartbeatLock);
  1167. }
  1168. Watchdog.RemoveThread();
  1169. }
  1170. /// <summary>
  1171. /// Performs per-frame updates on the scene, this should be the central scene loop
  1172. /// </summary>
  1173. public override void Update()
  1174. {
  1175. float physicsFPS;
  1176. int maintc;
  1177. while (!shuttingdown)
  1178. {
  1179. TimeSpan SinceLastFrame = DateTime.UtcNow - m_lastupdate;
  1180. physicsFPS = 0f;
  1181. maintc = Util.EnvironmentTickCount();
  1182. int tmpFrameMS = maintc;
  1183. tempOnRezMS = eventMS = backupMS = terrainMS = landMS = 0;
  1184. // Increment the frame counter
  1185. ++m_frame;
  1186. try
  1187. {
  1188. // Check if any objects have reached their targets
  1189. CheckAtTargets();
  1190. // Update SceneObjectGroups that have scheduled themselves for updates
  1191. // Objects queue their updates onto all scene presences
  1192. if (m_frame % m_update_objects == 0)
  1193. m_sceneGraph.UpdateObjectGroups();
  1194. // Run through all ScenePresences looking for updates
  1195. // Presence updates and queued object updates for each presence are sent to clients
  1196. if (m_frame % m_update_presences == 0)
  1197. m_sceneGraph.UpdatePresences();
  1198. if (m_frame % m_update_coarse_locations == 0)
  1199. {
  1200. List<Vector3> coarseLocations;
  1201. List<UUID> avatarUUIDs;
  1202. SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
  1203. // Send coarse locations to clients
  1204. ForEachScenePresence(delegate(ScenePresence presence)
  1205. {
  1206. presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
  1207. });
  1208. }
  1209. int tmpPhysicsMS2 = Util.EnvironmentTickCount();
  1210. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  1211. m_sceneGraph.UpdatePreparePhysics();
  1212. physicsMS2 = Util.EnvironmentTickCountSubtract(tmpPhysicsMS2);
  1213. if (m_frame % m_update_entitymovement == 0)
  1214. m_sceneGraph.UpdateScenePresenceMovement();
  1215. int tmpPhysicsMS = Util.EnvironmentTickCount();
  1216. if (m_frame % m_update_physics == 0)
  1217. {
  1218. if (m_physics_enabled)
  1219. physicsFPS = m_sceneGraph.UpdatePhysics(Math.Max(SinceLastFrame.TotalSeconds, m_timespan));
  1220. if (SynchronizeScene != null)
  1221. SynchronizeScene(this);
  1222. }
  1223. physicsMS = Util.EnvironmentTickCountSubtract(tmpPhysicsMS);
  1224. // Delete temp-on-rez stuff
  1225. if (m_frame % m_update_backup == 0)
  1226. {
  1227. int tmpTempOnRezMS = Util.EnvironmentTickCount();
  1228. CleanTempObjects();
  1229. tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpTempOnRezMS);
  1230. }
  1231. if (RegionStatus != RegionStatus.SlaveScene)
  1232. {
  1233. if (m_frame % m_update_events == 0)
  1234. {
  1235. int evMS = Util.EnvironmentTickCount();
  1236. UpdateEvents();
  1237. eventMS = Util.EnvironmentTickCountSubtract(evMS); ;
  1238. }
  1239. if (m_frame % m_update_backup == 0)
  1240. {
  1241. int backMS = Util.EnvironmentTickCount();
  1242. UpdateStorageBackup();
  1243. backupMS = Util.EnvironmentTickCountSubtract(backMS);
  1244. }
  1245. if (m_frame % m_update_terrain == 0)
  1246. {
  1247. int terMS = Util.EnvironmentTickCount();
  1248. UpdateTerrain();
  1249. terrainMS = Util.EnvironmentTickCountSubtract(terMS);
  1250. }
  1251. if (m_frame % m_update_land == 0)
  1252. {
  1253. int ldMS = Util.EnvironmentTickCount();
  1254. UpdateLand();
  1255. landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1256. }
  1257. frameMS = Util.EnvironmentTickCountSubtract(tmpFrameMS);
  1258. otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1259. lastCompletedFrame = Util.EnvironmentTickCount();
  1260. // if (m_frame%m_update_avatars == 0)
  1261. // UpdateInWorldTime();
  1262. StatsReporter.AddPhysicsFPS(physicsFPS);
  1263. StatsReporter.AddTimeDilation(TimeDilation);
  1264. StatsReporter.AddFPS(1);
  1265. StatsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  1266. StatsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  1267. StatsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  1268. StatsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  1269. StatsReporter.addFrameMS(frameMS);
  1270. StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
  1271. StatsReporter.addOtherMS(otherMS);
  1272. StatsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  1273. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  1274. }
  1275. if (LoginsDisabled && m_frame == 20)
  1276. {
  1277. // In 99.9% of cases it is a bad idea to manually force garbage collection. However,
  1278. // this is a rare case where we know we have just went through a long cycle of heap
  1279. // allocations, and there is no more work to be done until someone logs in
  1280. GC.Collect();
  1281. IConfig startupConfig = m_config.Configs["Startup"];
  1282. if (startupConfig == null || !startupConfig.GetBoolean("StartDisabled", false))
  1283. {
  1284. m_log.DebugFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
  1285. LoginsDisabled = false;
  1286. m_sceneGridService.InformNeighborsThatRegionisUp(RequestModuleInterface<INeighbourService>(), RegionInfo);
  1287. }
  1288. }
  1289. }
  1290. catch (NotImplementedException)
  1291. {
  1292. throw;
  1293. }
  1294. catch (AccessViolationException e)
  1295. {
  1296. m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1297. }
  1298. //catch (NullReferenceException e)
  1299. //{
  1300. // m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1301. //}
  1302. catch (InvalidOperationException e)
  1303. {
  1304. m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1305. }
  1306. catch (Exception e)
  1307. {
  1308. m_log.Error("[REGION]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  1309. }
  1310. finally
  1311. {
  1312. m_lastupdate = DateTime.UtcNow;
  1313. }
  1314. maintc = Util.EnvironmentTickCountSubtract(maintc);
  1315. maintc = (int)(m_timespan * 1000) - maintc;
  1316. if (maintc > 0)
  1317. Thread.Sleep(maintc);
  1318. // Tell the watchdog that this thread is still alive
  1319. Watchdog.UpdateThread();
  1320. }
  1321. }
  1322. public void AddGroupTarget(SceneObjectGroup grp)
  1323. {
  1324. lock (m_groupsWithTargets)
  1325. m_groupsWithTargets[grp.UUID] = grp;
  1326. }
  1327. public void RemoveGroupTarget(SceneObjectGroup grp)
  1328. {
  1329. lock (m_groupsWithTargets)
  1330. m_groupsWithTargets.Remove(grp.UUID);
  1331. }
  1332. private void CheckAtTargets()
  1333. {
  1334. lock (m_groupsWithTargets)
  1335. {
  1336. foreach (SceneObjectGroup entry in m_groupsWithTargets.Values)
  1337. {
  1338. entry.checkAtTargets();
  1339. }
  1340. }
  1341. }
  1342. /// <summary>
  1343. /// Send out simstats data to all clients
  1344. /// </summary>
  1345. /// <param name="stats">Stats on the Simulator's performance</param>
  1346. private void SendSimStatsPackets(SimStats stats)
  1347. {
  1348. ForEachScenePresence(
  1349. delegate(ScenePresence agent)
  1350. {
  1351. if (!agent.IsChildAgent)
  1352. agent.ControllingClient.SendSimStats(stats);
  1353. }
  1354. );
  1355. }
  1356. /// <summary>
  1357. /// Recount SceneObjectPart in parcel aabb
  1358. /// </summary>
  1359. private void UpdateLand()
  1360. {
  1361. if (LandChannel != null)
  1362. {
  1363. if (LandChannel.IsLandPrimCountTainted())
  1364. {
  1365. EventManager.TriggerParcelPrimCountUpdate();
  1366. }
  1367. }
  1368. }
  1369. /// <summary>
  1370. /// Update the terrain if it needs to be updated.
  1371. /// </summary>
  1372. private void UpdateTerrain()
  1373. {
  1374. EventManager.TriggerTerrainTick();
  1375. }
  1376. /// <summary>
  1377. /// Back up queued up changes
  1378. /// </summary>
  1379. private void UpdateStorageBackup()
  1380. {
  1381. if (!m_backingup)
  1382. {
  1383. m_backingup = true;
  1384. Util.FireAndForget(BackupWaitCallback);
  1385. }
  1386. }
  1387. /// <summary>
  1388. /// Sends out the OnFrame event to the modules
  1389. /// </summary>
  1390. private void UpdateEvents()
  1391. {
  1392. m_eventManager.TriggerOnFrame();
  1393. }
  1394. /// <summary>
  1395. /// Wrapper for Backup() that can be called with Util.FireAndForget()
  1396. /// </summary>
  1397. private void BackupWaitCallback(object o)
  1398. {
  1399. Backup();
  1400. }
  1401. /// <summary>
  1402. /// Backup the scene. This acts as the main method of the backup thread.
  1403. /// </summary>
  1404. /// <returns></returns>
  1405. public void Backup()
  1406. {
  1407. lock (m_returns)
  1408. {
  1409. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  1410. m_backingup = false;
  1411. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1412. {
  1413. UUID transaction = UUID.Random();
  1414. GridInstantMessage msg = new GridInstantMessage();
  1415. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  1416. msg.toAgentID = new Guid(ret.Key.ToString());
  1417. msg.imSessionID = new Guid(transaction.ToString());
  1418. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  1419. msg.fromAgentName = "Server";
  1420. msg.dialog = (byte)19; // Object msg
  1421. msg.fromGroup = false;
  1422. msg.offline = (byte)1;
  1423. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  1424. msg.Position = Vector3.Zero;
  1425. msg.RegionID = RegionInfo.RegionID.Guid;
  1426. msg.binaryBucket = new byte[0];
  1427. if (ret.Value.count > 1)
  1428. 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);
  1429. else
  1430. 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);
  1431. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1432. if (tr != null)
  1433. tr.SendInstantMessage(msg, delegate(bool success) {});
  1434. }
  1435. m_returns.Clear();
  1436. }
  1437. }
  1438. /// <summary>
  1439. /// Synchronous force backup. For deletes and links/unlinks
  1440. /// </summary>
  1441. /// <param name="group">Object to be backed up</param>
  1442. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1443. {
  1444. if (group != null)
  1445. {
  1446. group.ProcessBackup(m_storageManager.DataStore, true);
  1447. }
  1448. }
  1449. /// <summary>
  1450. /// Return object to avatar Message
  1451. /// </summary>
  1452. /// <param name="agentID">Avatar Unique Id</param>
  1453. /// <param name="objectName">Name of object returned</param>
  1454. /// <param name="location">Location of object returned</param>
  1455. /// <param name="reason">Reasion for object return</param>
  1456. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1457. {
  1458. lock (m_returns)
  1459. {
  1460. if (m_returns.ContainsKey(agentID))
  1461. {
  1462. ReturnInfo info = m_returns[agentID];
  1463. info.count++;
  1464. m_returns[agentID] = info;
  1465. }
  1466. else
  1467. {
  1468. ReturnInfo info = new ReturnInfo();
  1469. info.count = 1;
  1470. info.objectName = objectName;
  1471. info.location = location;
  1472. info.reason = reason;
  1473. m_returns[agentID] = info;
  1474. }
  1475. }
  1476. }
  1477. #endregion
  1478. #region Load Terrain
  1479. /// <summary>
  1480. /// Store the terrain in the persistant data store
  1481. /// </summary>
  1482. public void SaveTerrain()
  1483. {
  1484. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1485. }
  1486. public void StoreWindlightProfile(RegionLightShareData wl)
  1487. {
  1488. m_regInfo.WindlightSettings = wl;
  1489. m_storageManager.DataStore.StoreRegionWindlightSettings(wl);
  1490. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1491. }
  1492. public void LoadWindlightProfile()
  1493. {
  1494. m_regInfo.WindlightSettings = m_storageManager.DataStore.LoadRegionWindlightSettings(RegionInfo.RegionID);
  1495. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1496. }
  1497. /// <summary>
  1498. /// Loads the World heightmap
  1499. /// </summary>
  1500. public override void LoadWorldMap()
  1501. {
  1502. try
  1503. {
  1504. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  1505. if (map == null)
  1506. {
  1507. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  1508. Heightmap = new TerrainChannel();
  1509. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1510. }
  1511. else
  1512. {
  1513. Heightmap = new TerrainChannel(map);
  1514. }
  1515. }
  1516. catch (IOException e)
  1517. {
  1518. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString() + " Regenerating");
  1519. // Non standard region size. If there's an old terrain in the database, it might read past the buffer
  1520. #pragma warning disable 0162
  1521. if ((int)Constants.RegionSize != 256)
  1522. {
  1523. Heightmap = new TerrainChannel();
  1524. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1525. }
  1526. }
  1527. catch (Exception e)
  1528. {
  1529. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  1530. }
  1531. }
  1532. /// <summary>
  1533. /// Register this region with a grid service
  1534. /// </summary>
  1535. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1536. public void RegisterRegionWithGrid()
  1537. {
  1538. RegisterCommsEvents();
  1539. m_sceneGridService.SetScene(this);
  1540. // These two 'commands' *must be* next to each other or sim rebooting fails.
  1541. //m_sceneGridService.RegisterRegion(m_interregionCommsOut, RegionInfo);
  1542. GridRegion region = new GridRegion(RegionInfo);
  1543. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1544. if (error != String.Empty)
  1545. {
  1546. throw new Exception(error);
  1547. }
  1548. }
  1549. /// <summary>
  1550. /// Create a terrain texture for this scene
  1551. /// </summary>
  1552. public void CreateTerrainTexture()
  1553. {
  1554. //create a texture asset of the terrain
  1555. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  1556. // Cannot create a map for a nonexistant heightmap yet.
  1557. if (Heightmap == null)
  1558. return;
  1559. if (terrain == null)
  1560. return;
  1561. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1562. if (data != null)
  1563. {
  1564. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  1565. if (mapModule != null)
  1566. mapModule.RegenerateMaptile(data);
  1567. else
  1568. m_log.DebugFormat("[SCENE]: MapModule is null, can't save maptile");
  1569. }
  1570. }
  1571. #endregion
  1572. #region Load Land
  1573. /// <summary>
  1574. /// Loads all Parcel data from the datastore for region identified by regionID
  1575. /// </summary>
  1576. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1577. public void loadAllLandObjectsFromStorage(UUID regionID)
  1578. {
  1579. m_log.Info("[SCENE]: Loading land objects from storage");
  1580. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1581. if (LandChannel != null)
  1582. {
  1583. if (landData.Count == 0)
  1584. {
  1585. EventManager.TriggerNoticeNoLandDataFromStorage();
  1586. }
  1587. else
  1588. {
  1589. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1590. }
  1591. }
  1592. else
  1593. {
  1594. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1595. }
  1596. }
  1597. #endregion
  1598. #region Primitives Methods
  1599. /// <summary>
  1600. /// Loads the World's objects
  1601. /// </summary>
  1602. public virtual void LoadPrimsFromStorage(UUID regionID)
  1603. {
  1604. m_log.Info("[SCENE]: Loading objects from datastore");
  1605. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1606. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count + " objects from the datastore");
  1607. foreach (SceneObjectGroup group in PrimsFromDB)
  1608. {
  1609. if (group.RootPart == null)
  1610. {
  1611. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1612. group.Children == null ? 0 : group.Children.Count);
  1613. }
  1614. AddRestoredSceneObject(group, true, true);
  1615. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1616. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1617. rootPart.TrimPermissions();
  1618. group.CheckSculptAndLoad();
  1619. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1620. }
  1621. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1622. }
  1623. /// <summary>
  1624. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1625. /// </summary>
  1626. /// <param name="RayStart"></param>
  1627. /// <param name="RayEnd"></param>
  1628. /// <param name="RayTargetID"></param>
  1629. /// <param name="rot"></param>
  1630. /// <param name="bypassRayCast"></param>
  1631. /// <param name="RayEndIsIntersection"></param>
  1632. /// <param name="frontFacesOnly"></param>
  1633. /// <param name="scale"></param>
  1634. /// <param name="FaceCenter"></param>
  1635. /// <returns></returns>
  1636. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1637. {
  1638. Vector3 pos = Vector3.Zero;
  1639. if (RayEndIsIntersection == (byte)1)
  1640. {
  1641. pos = RayEnd;
  1642. return pos;
  1643. }
  1644. if (RayTargetID != UUID.Zero)
  1645. {
  1646. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1647. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1648. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1649. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1650. if (target != null)
  1651. {
  1652. pos = target.AbsolutePosition;
  1653. //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());
  1654. // TODO: Raytrace better here
  1655. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1656. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1657. // Ray Trace against target here
  1658. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1659. // Un-comment out the following line to Get Raytrace results printed to the console.
  1660. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1661. float ScaleOffset = 0.5f;
  1662. // If we hit something
  1663. if (ei.HitTF)
  1664. {
  1665. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1666. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1667. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1668. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1669. ScaleOffset = Math.Abs(ScaleOffset);
  1670. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1671. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1672. // Set the position to the intersection point
  1673. Vector3 offset = (normal * (ScaleOffset / 2f));
  1674. pos = (intersectionpoint + offset);
  1675. //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
  1676. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  1677. // Un-offset the prim (it gets offset later by the consumer method)
  1678. //pos.Z -= 0.25F;
  1679. }
  1680. return pos;
  1681. }
  1682. else
  1683. {
  1684. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1685. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1686. // Un-comment the following line to print the raytrace results to the console.
  1687. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1688. if (ei.HitTF)
  1689. {
  1690. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1691. } else
  1692. {
  1693. // fall back to our stupid functionality
  1694. pos = RayEnd;
  1695. }
  1696. return pos;
  1697. }
  1698. }
  1699. else
  1700. {
  1701. // fall back to our stupid functionality
  1702. pos = RayEnd;
  1703. //increase height so its above the ground.
  1704. //should be getting the normal of the ground at the rez point and using that?
  1705. pos.Z += scale.Z / 2f;
  1706. return pos;
  1707. }
  1708. }
  1709. /// <summary>
  1710. /// Create a New SceneObjectGroup/Part by raycasting
  1711. /// </summary>
  1712. /// <param name="ownerID"></param>
  1713. /// <param name="groupID"></param>
  1714. /// <param name="RayEnd"></param>
  1715. /// <param name="rot"></param>
  1716. /// <param name="shape"></param>
  1717. /// <param name="bypassRaycast"></param>
  1718. /// <param name="RayStart"></param>
  1719. /// <param name="RayTargetID"></param>
  1720. /// <param name="RayEndIsIntersection"></param>
  1721. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1722. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1723. byte RayEndIsIntersection)
  1724. {
  1725. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1726. if (Permissions.CanRezObject(1, ownerID, pos))
  1727. {
  1728. // rez ON the ground, not IN the ground
  1729. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  1730. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1731. }
  1732. }
  1733. public virtual SceneObjectGroup AddNewPrim(
  1734. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1735. {
  1736. //m_log.DebugFormat(
  1737. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1738. SceneObjectGroup sceneObject = null;
  1739. // If an entity creator has been registered for this prim type then use that
  1740. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1741. {
  1742. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1743. }
  1744. else
  1745. {
  1746. // Otherwise, use this default creation code;
  1747. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1748. AddNewSceneObject(sceneObject, true);
  1749. sceneObject.SetGroup(groupID, null);
  1750. }
  1751. sceneObject.ScheduleGroupForFullUpdate();
  1752. return sceneObject;
  1753. }
  1754. /// <summary>
  1755. /// Add an object into the scene that has come from storage
  1756. /// </summary>
  1757. ///
  1758. /// <param name="sceneObject"></param>
  1759. /// <param name="attachToBackup">
  1760. /// If true, changes to the object will be reflected in its persisted data
  1761. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1762. /// </param>
  1763. /// <param name="alreadyPersisted">
  1764. /// If true, we won't persist this object until it changes
  1765. /// If false, we'll persist this object immediately
  1766. /// </param>
  1767. /// <param name="sendClientUpdates">
  1768. /// If true, we send updates to the client to tell it about this object
  1769. /// If false, we leave it up to the caller to do this
  1770. /// </param>
  1771. /// <returns>
  1772. /// true if the object was added, false if an object with the same uuid was already in the scene
  1773. /// </returns>
  1774. public bool AddRestoredSceneObject(
  1775. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
  1776. {
  1777. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates);
  1778. }
  1779. /// <summary>
  1780. /// Add an object into the scene that has come from storage
  1781. /// </summary>
  1782. ///
  1783. /// <param name="sceneObject"></param>
  1784. /// <param name="attachToBackup">
  1785. /// If true, changes to the object will be reflected in its persisted data
  1786. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1787. /// </param>
  1788. /// <param name="alreadyPersisted">
  1789. /// If true, we won't persist this object until it changes
  1790. /// If false, we'll persist this object immediately
  1791. /// </param>
  1792. /// <returns>
  1793. /// true if the object was added, false if an object with the same uuid was already in the scene
  1794. /// </returns>
  1795. public bool AddRestoredSceneObject(
  1796. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1797. {
  1798. return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
  1799. }
  1800. /// <summary>
  1801. /// Add a newly created object to the scene. Updates are also sent to viewers.
  1802. /// </summary>
  1803. /// <param name="sceneObject"></param>
  1804. /// <param name="attachToBackup">
  1805. /// If true, the object is made persistent into the scene.
  1806. /// If false, the object will not persist over server restarts
  1807. /// </param>
  1808. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1809. {
  1810. return AddNewSceneObject(sceneObject, attachToBackup, true);
  1811. }
  1812. /// <summary>
  1813. /// Add a newly created object to the scene
  1814. /// </summary>
  1815. /// <param name="sceneObject"></param>
  1816. /// <param name="attachToBackup">
  1817. /// If true, the object is made persistent into the scene.
  1818. /// If false, the object will not persist over server restarts
  1819. /// </param>
  1820. /// <param name="sendClientUpdates">
  1821. /// If true, updates for the new scene object are sent to all viewers in range.
  1822. /// If false, it is left to the caller to schedule the update
  1823. /// </param>
  1824. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  1825. {
  1826. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates);
  1827. }
  1828. /// <summary>
  1829. /// Delete every object from the scene. This does not include attachments worn by avatars.
  1830. /// </summary>
  1831. public void DeleteAllSceneObjects()
  1832. {
  1833. lock (Entities)
  1834. {
  1835. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1836. foreach (EntityBase e in entities)
  1837. {
  1838. if (e is SceneObjectGroup)
  1839. {
  1840. SceneObjectGroup sog = (SceneObjectGroup)e;
  1841. if (!sog.IsAttachment)
  1842. DeleteSceneObject((SceneObjectGroup)e, false);
  1843. }
  1844. }
  1845. }
  1846. }
  1847. /// <summary>
  1848. /// Synchronously delete the given object from the scene.
  1849. /// </summary>
  1850. /// <param name="group">Object Id</param>
  1851. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  1852. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1853. {
  1854. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  1855. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1856. // Serialise calls to RemoveScriptInstances to avoid
  1857. // deadlocking on m_parts inside SceneObjectGroup
  1858. lock (m_deleting_scene_object)
  1859. {
  1860. group.RemoveScriptInstances(true);
  1861. }
  1862. foreach (SceneObjectPart part in group.Children.Values)
  1863. {
  1864. if (part.IsJoint() && ((part.ObjectFlags&(uint)PrimFlags.Physics) != 0))
  1865. {
  1866. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  1867. }
  1868. else if (part.PhysActor != null)
  1869. {
  1870. PhysicsScene.RemovePrim(part.PhysActor);
  1871. part.PhysActor = null;
  1872. }
  1873. }
  1874. // if (rootPart.PhysActor != null)
  1875. // {
  1876. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1877. // rootPart.PhysActor = null;
  1878. // }
  1879. if (UnlinkSceneObject(group.UUID, false))
  1880. {
  1881. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1882. EventManager.TriggerParcelPrimCountTainted();
  1883. }
  1884. group.DeleteGroup(silent);
  1885. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  1886. }
  1887. /// <summary>
  1888. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1889. /// object itself is not destroyed.
  1890. /// </summary>
  1891. /// <param name="uuid">Id of object.</param>
  1892. /// <returns>true if the object was in the scene, false if it was not</returns>
  1893. /// <param name="softDelete">If true, only deletes from scene, but keeps object in database.</param>
  1894. public bool UnlinkSceneObject(UUID uuid, bool softDelete)
  1895. {
  1896. if (m_sceneGraph.DeleteSceneObject(uuid, softDelete))
  1897. {
  1898. if (!softDelete)
  1899. {
  1900. m_storageManager.DataStore.RemoveObject(uuid,
  1901. m_regInfo.RegionID);
  1902. }
  1903. return true;
  1904. }
  1905. return false;
  1906. }
  1907. /// <summary>
  1908. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1909. /// into.
  1910. ///
  1911. /// </summary>
  1912. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1913. /// <param name="grp">the scene object that we're crossing</param>
  1914. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1915. {
  1916. if (grp == null)
  1917. return;
  1918. if (grp.IsDeleted)
  1919. return;
  1920. if (grp.RootPart.DIE_AT_EDGE)
  1921. {
  1922. // We remove the object here
  1923. try
  1924. {
  1925. DeleteSceneObject(grp, false);
  1926. }
  1927. catch (Exception)
  1928. {
  1929. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1930. }
  1931. return;
  1932. }
  1933. if (grp.RootPart.RETURN_AT_EDGE)
  1934. {
  1935. // We remove the object here
  1936. try
  1937. {
  1938. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  1939. objects.Add(grp);
  1940. SceneObjectGroup[] objectsArray = objects.ToArray();
  1941. returnObjects(objectsArray, UUID.Zero);
  1942. }
  1943. catch (Exception)
  1944. {
  1945. m_log.Warn("[DATABASE]: exception when trying to return the prim that crossed the border.");
  1946. }
  1947. return;
  1948. }
  1949. if (m_teleportModule != null)
  1950. m_teleportModule.Cross(grp, attemptedPosition, silent);
  1951. }
  1952. public Border GetCrossedBorder(Vector3 position, Cardinals gridline)
  1953. {
  1954. if (BordersLocked)
  1955. {
  1956. switch (gridline)
  1957. {
  1958. case Cardinals.N:
  1959. lock (NorthBorders)
  1960. {
  1961. foreach (Border b in NorthBorders)
  1962. {
  1963. if (b.TestCross(position))
  1964. return b;
  1965. }
  1966. }
  1967. break;
  1968. case Cardinals.S:
  1969. lock (SouthBorders)
  1970. {
  1971. foreach (Border b in SouthBorders)
  1972. {
  1973. if (b.TestCross(position))
  1974. return b;
  1975. }
  1976. }
  1977. break;
  1978. case Cardinals.E:
  1979. lock (EastBorders)
  1980. {
  1981. foreach (Border b in EastBorders)
  1982. {
  1983. if (b.TestCross(position))
  1984. return b;
  1985. }
  1986. }
  1987. break;
  1988. case Cardinals.W:
  1989. lock (WestBorders)
  1990. {
  1991. foreach (Border b in WestBorders)
  1992. {
  1993. if (b.TestCross(position))
  1994. return b;
  1995. }
  1996. }
  1997. break;
  1998. }
  1999. }
  2000. else
  2001. {
  2002. switch (gridline)
  2003. {
  2004. case Cardinals.N:
  2005. foreach (Border b in NorthBorders)
  2006. {
  2007. if (b.TestCross(position))
  2008. return b;
  2009. }
  2010. break;
  2011. case Cardinals.S:
  2012. foreach (Border b in SouthBorders)
  2013. {
  2014. if (b.TestCross(position))
  2015. return b;
  2016. }
  2017. break;
  2018. case Cardinals.E:
  2019. foreach (Border b in EastBorders)
  2020. {
  2021. if (b.TestCross(position))
  2022. return b;
  2023. }
  2024. break;
  2025. case Cardinals.W:
  2026. foreach (Border b in WestBorders)
  2027. {
  2028. if (b.TestCross(position))
  2029. return b;
  2030. }
  2031. break;
  2032. }
  2033. }
  2034. return null;
  2035. }
  2036. public bool TestBorderCross(Vector3 position, Cardinals border)
  2037. {
  2038. if (BordersLocked)
  2039. {
  2040. switch (border)
  2041. {
  2042. case Cardinals.N:
  2043. lock (NorthBorders)
  2044. {
  2045. foreach (Border b in NorthBorders)
  2046. {
  2047. if (b.TestCross(position))
  2048. return true;
  2049. }
  2050. }
  2051. break;
  2052. case Cardinals.E:
  2053. lock (EastBorders)
  2054. {
  2055. foreach (Border b in EastBorders)
  2056. {
  2057. if (b.TestCross(position))
  2058. return true;
  2059. }
  2060. }
  2061. break;
  2062. case Cardinals.S:
  2063. lock (SouthBorders)
  2064. {
  2065. foreach (Border b in SouthBorders)
  2066. {
  2067. if (b.TestCross(position))
  2068. return true;
  2069. }
  2070. }
  2071. break;
  2072. case Cardinals.W:
  2073. lock (WestBorders)
  2074. {
  2075. foreach (Border b in WestBorders)
  2076. {
  2077. if (b.TestCross(position))
  2078. return true;
  2079. }
  2080. }
  2081. break;
  2082. }
  2083. }
  2084. else
  2085. {
  2086. switch (border)
  2087. {
  2088. case Cardinals.N:
  2089. foreach (Border b in NorthBorders)
  2090. {
  2091. if (b.TestCross(position))
  2092. return true;
  2093. }
  2094. break;
  2095. case Cardinals.E:
  2096. foreach (Border b in EastBorders)
  2097. {
  2098. if (b.TestCross(position))
  2099. return true;
  2100. }
  2101. break;
  2102. case Cardinals.S:
  2103. foreach (Border b in SouthBorders)
  2104. {
  2105. if (b.TestCross(position))
  2106. return true;
  2107. }
  2108. break;
  2109. case Cardinals.W:
  2110. foreach (Border b in WestBorders)
  2111. {
  2112. if (b.TestCross(position))
  2113. return true;
  2114. }
  2115. break;
  2116. }
  2117. }
  2118. return false;
  2119. }
  2120. /// <summary>
  2121. /// Called when objects or attachments cross the border, or teleport, between regions.
  2122. /// </summary>
  2123. /// <param name="sog"></param>
  2124. /// <returns></returns>
  2125. public bool IncomingCreateObject(ISceneObject sog)
  2126. {
  2127. //m_log.Debug(" >>> IncomingCreateObject(sog) <<< " + ((SceneObjectGroup)sog).AbsolutePosition + " deleted? " + ((SceneObjectGroup)sog).IsDeleted);
  2128. SceneObjectGroup newObject;
  2129. try
  2130. {
  2131. newObject = (SceneObjectGroup)sog;
  2132. }
  2133. catch (Exception e)
  2134. {
  2135. m_log.WarnFormat("[SCENE]: Problem casting object: {0}", e.Message);
  2136. return false;
  2137. }
  2138. if (!AddSceneObject(newObject))
  2139. {
  2140. m_log.DebugFormat("[SCENE]: Problem adding scene object {0} in {1} ", sog.UUID, RegionInfo.RegionName);
  2141. return false;
  2142. }
  2143. newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  2144. newObject.ResumeScripts();
  2145. // Do this as late as possible so that listeners have full access to the incoming object
  2146. EventManager.TriggerOnIncomingSceneObject(newObject);
  2147. TriggerChangedTeleport(newObject);
  2148. return true;
  2149. }
  2150. /// <summary>
  2151. /// Attachment rezzing
  2152. /// </summary>
  2153. /// <param name="userID">Agent Unique ID</param>
  2154. /// <param name="itemID">Object ID</param>
  2155. /// <returns>False</returns>
  2156. public virtual bool IncomingCreateObject(UUID userID, UUID itemID)
  2157. {
  2158. //m_log.DebugFormat(" >>> IncomingCreateObject(userID, itemID) <<< {0} {1}", userID, itemID);
  2159. ScenePresence sp = GetScenePresence(userID);
  2160. if (sp != null && AttachmentsModule != null)
  2161. {
  2162. uint attPt = (uint)sp.Appearance.GetAttachpoint(itemID);
  2163. AttachmentsModule.RezSingleAttachmentFromInventory(sp.ControllingClient, itemID, attPt);
  2164. }
  2165. return false;
  2166. }
  2167. /// <summary>
  2168. /// Adds a Scene Object group to the Scene.
  2169. /// Verifies that the creator of the object is not banned from the simulator.
  2170. /// Checks if the item is an Attachment
  2171. /// </summary>
  2172. /// <param name="sceneObject"></param>
  2173. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2174. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2175. {
  2176. // If the user is banned, we won't let any of their objects
  2177. // enter. Period.
  2178. //
  2179. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  2180. {
  2181. m_log.Info("[INTERREGION]: Denied prim crossing for " +
  2182. "banned avatar");
  2183. return false;
  2184. }
  2185. sceneObject.SetScene(this);
  2186. // Force allocation of new LocalId
  2187. //
  2188. foreach (SceneObjectPart p in sceneObject.Children.Values)
  2189. p.LocalId = 0;
  2190. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2191. {
  2192. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2193. sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
  2194. // Don't sent a full update here because this will cause full updates to be sent twice for
  2195. // attachments on region crossings, resulting in viewer glitches.
  2196. AddRestoredSceneObject(sceneObject, false, false, false);
  2197. // Handle attachment special case
  2198. SceneObjectPart RootPrim = sceneObject.RootPart;
  2199. // Fix up attachment Parent Local ID
  2200. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2201. if (sp != null)
  2202. {
  2203. SceneObjectGroup grp = sceneObject;
  2204. m_log.DebugFormat(
  2205. "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.GetFromItemID(), grp.UUID);
  2206. m_log.DebugFormat(
  2207. "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2208. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2209. if (AttachmentsModule != null)
  2210. AttachmentsModule.AttachObject(
  2211. sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition, false);
  2212. }
  2213. else
  2214. {
  2215. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2216. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2217. }
  2218. }
  2219. else
  2220. {
  2221. AddRestoredSceneObject(sceneObject, true, false);
  2222. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  2223. true, sceneObject.AbsolutePosition))
  2224. {
  2225. // Deny non attachments based on parcel settings
  2226. //
  2227. m_log.Info("[INTERREGION]: Denied prim crossing " +
  2228. "because of parcel settings");
  2229. DeleteSceneObject(sceneObject, false);
  2230. return false;
  2231. }
  2232. }
  2233. return true;
  2234. }
  2235. private void TriggerChangedTeleport(SceneObjectGroup sog)
  2236. {
  2237. ScenePresence sp = GetScenePresence(sog.OwnerID);
  2238. if (sp != null)
  2239. {
  2240. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(sp.UUID);
  2241. if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
  2242. {
  2243. // This will get your attention
  2244. //m_log.Error("[XXX] Triggering ");
  2245. // Trigger CHANGED_TELEPORT
  2246. sp.Scene.EventManager.TriggerOnScriptChangedEvent(sog.LocalId, (uint)Changed.TELEPORT);
  2247. }
  2248. }
  2249. }
  2250. #endregion
  2251. #region Add/Remove Avatar Methods
  2252. /// <summary>
  2253. /// Adding a New Client and Create a Presence for it.
  2254. /// </summary>
  2255. /// <param name="client"></param>
  2256. public override void AddNewClient(IClientAPI client)
  2257. {
  2258. bool vialogin = false;
  2259. m_clientManager.Add(client);
  2260. CheckHeartbeat();
  2261. SubscribeToClientEvents(client);
  2262. ScenePresence presence;
  2263. if (m_restorePresences.ContainsKey(client.AgentId))
  2264. {
  2265. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  2266. presence = m_restorePresences[client.AgentId];
  2267. m_restorePresences.Remove(client.AgentId);
  2268. // This is one of two paths to create avatars that are
  2269. // used. This tends to get called more in standalone
  2270. // than grid, not really sure why, but as such needs
  2271. // an explicity appearance lookup here.
  2272. AvatarAppearance appearance = null;
  2273. GetAvatarAppearance(client, out appearance);
  2274. presence.Appearance = appearance;
  2275. presence.initializeScenePresence(client, RegionInfo, this);
  2276. m_sceneGraph.AddScenePresence(presence);
  2277. lock (m_restorePresences)
  2278. {
  2279. Monitor.PulseAll(m_restorePresences);
  2280. }
  2281. }
  2282. else
  2283. {
  2284. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2285. // Do the verification here
  2286. System.Net.IPEndPoint ep = (System.Net.IPEndPoint)client.GetClientEP();
  2287. if (aCircuit != null)
  2288. {
  2289. if (!VerifyClient(aCircuit, ep, out vialogin))
  2290. {
  2291. // uh-oh, this is fishy
  2292. m_log.WarnFormat("[Scene]: Agent {0} with session {1} connecting with unidentified end point {2}. Refusing service.",
  2293. client.AgentId, client.SessionId, ep.ToString());
  2294. try
  2295. {
  2296. client.Close();
  2297. }
  2298. catch (Exception e)
  2299. {
  2300. m_log.DebugFormat("[Scene]: Exception while closing aborted client: {0}", e.StackTrace);
  2301. }
  2302. return;
  2303. }
  2304. }
  2305. m_log.Debug("[Scene] Adding new agent " + client.Name + " to scene " + RegionInfo.RegionName);
  2306. ScenePresence sp = CreateAndAddScenePresence(client);
  2307. if (aCircuit != null)
  2308. sp.Appearance = aCircuit.Appearance;
  2309. // HERE!!! Do the initial attachments right here
  2310. // first agent upon login is a root agent by design.
  2311. // All other AddNewClient calls find aCircuit.child to be true
  2312. if (aCircuit == null || (aCircuit != null && aCircuit.child == false))
  2313. {
  2314. sp.IsChildAgent = false;
  2315. Util.FireAndForget(delegate(object o) { sp.RezAttachments(); });
  2316. }
  2317. }
  2318. m_LastLogin = Util.EnvironmentTickCount();
  2319. EventManager.TriggerOnNewClient(client);
  2320. if (vialogin)
  2321. EventManager.TriggerOnClientLogin(client);
  2322. }
  2323. private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin)
  2324. {
  2325. vialogin = false;
  2326. // Do the verification here
  2327. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
  2328. {
  2329. m_log.DebugFormat("[Scene]: Incoming client {0} {1} in region {2} via Login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2330. vialogin = true;
  2331. IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
  2332. if (userVerification != null && ep != null)
  2333. {
  2334. if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString()))
  2335. {
  2336. // uh-oh, this is fishy
  2337. m_log.DebugFormat("[Scene]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2338. return false;
  2339. }
  2340. else
  2341. m_log.DebugFormat("[Scene]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2342. }
  2343. }
  2344. return true;
  2345. }
  2346. // Called by Caps, on the first HTTP contact from the client
  2347. public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep)
  2348. {
  2349. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  2350. if (aCircuit != null)
  2351. {
  2352. bool vialogin = false;
  2353. if (!VerifyClient(aCircuit, ep, out vialogin))
  2354. {
  2355. // if it doesn't pass, we remove the agentcircuitdata altogether
  2356. // and the scene presence and the client, if they exist
  2357. try
  2358. {
  2359. ScenePresence sp = GetScenePresence(agentID);
  2360. if (sp != null)
  2361. sp.ControllingClient.Close();
  2362. // BANG! SLASH!
  2363. m_authenticateHandler.RemoveCircuit(agentID);
  2364. return false;
  2365. }
  2366. catch (Exception e)
  2367. {
  2368. m_log.DebugFormat("[Scene]: Exception while closing aborted client: {0}", e.StackTrace);
  2369. }
  2370. }
  2371. else
  2372. return true;
  2373. }
  2374. return false;
  2375. }
  2376. /// <summary>
  2377. /// Register for events from the client
  2378. /// </summary>
  2379. /// <param name="client">The IClientAPI of the connected client</param>
  2380. public virtual void SubscribeToClientEvents(IClientAPI client)
  2381. {
  2382. SubscribeToClientTerrainEvents(client);
  2383. SubscribeToClientPrimEvents(client);
  2384. SubscribeToClientPrimRezEvents(client);
  2385. SubscribeToClientInventoryEvents(client);
  2386. SubscribeToClientAttachmentEvents(client);
  2387. SubscribeToClientTeleportEvents(client);
  2388. SubscribeToClientScriptEvents(client);
  2389. SubscribeToClientParcelEvents(client);
  2390. SubscribeToClientGridEvents(client);
  2391. SubscribeToClientGodEvents(client);
  2392. SubscribeToClientNetworkEvents(client);
  2393. // EventManager.TriggerOnNewClient(client);
  2394. }
  2395. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2396. {
  2397. client.OnRegionHandShakeReply += SendLayerData;
  2398. client.OnUnackedTerrain += TerrainUnAcked;
  2399. }
  2400. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2401. {
  2402. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  2403. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2404. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  2405. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  2406. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2407. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2408. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2409. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2410. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2411. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2412. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2413. client.OnObjectRequest += RequestPrim;
  2414. client.OnObjectSelect += SelectPrim;
  2415. client.OnObjectDeselect += DeselectPrim;
  2416. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  2417. client.OnSpinStart += m_sceneGraph.SpinStart;
  2418. client.OnSpinUpdate += m_sceneGraph.SpinObject;
  2419. client.OnDeRezObject += DeRezObject;
  2420. client.OnObjectName += m_sceneGraph.PrimName;
  2421. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2422. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2423. client.OnLinkObjects += LinkObjects;
  2424. client.OnDelinkObjects += DelinkObjects;
  2425. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  2426. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2427. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2428. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2429. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2430. client.OnGrabObject += ProcessObjectGrab;
  2431. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2432. client.OnDeGrabObject += ProcessObjectDeGrab;
  2433. client.OnUndo += m_sceneGraph.HandleUndo;
  2434. client.OnRedo += m_sceneGraph.HandleRedo;
  2435. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2436. client.OnObjectDrop += m_sceneGraph.DropObject;
  2437. client.OnObjectSaleInfo += ObjectSaleInfo;
  2438. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2439. client.OnObjectOwner += ObjectOwner;
  2440. }
  2441. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2442. {
  2443. client.OnAddPrim += AddNewPrim;
  2444. client.OnRezObject += RezObject;
  2445. }
  2446. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2447. {
  2448. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  2449. client.OnLinkInventoryItem += HandleLinkInventoryItem;
  2450. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2451. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2452. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2453. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2454. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2455. client.OnFetchInventory += HandleFetchInventory;
  2456. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2457. client.OnCopyInventoryItem += CopyInventoryItem;
  2458. client.OnMoveInventoryItem += MoveInventoryItem;
  2459. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2460. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2461. client.OnRezScript += RezScript;
  2462. client.OnRequestTaskInventory += RequestTaskInventory;
  2463. client.OnRemoveTaskItem += RemoveTaskInventory;
  2464. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2465. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2466. }
  2467. public virtual void SubscribeToClientAttachmentEvents(IClientAPI client)
  2468. {
  2469. if (AttachmentsModule != null)
  2470. {
  2471. client.OnRezSingleAttachmentFromInv += AttachmentsModule.RezSingleAttachmentFromInventory;
  2472. client.OnRezMultipleAttachmentsFromInv += AttachmentsModule.RezMultipleAttachmentsFromInventory;
  2473. client.OnObjectAttach += AttachmentsModule.AttachObject;
  2474. client.OnObjectDetach += AttachmentsModule.DetachObject;
  2475. client.OnDetachAttachmentIntoInv += AttachmentsModule.ShowDetachInUserInventory;
  2476. }
  2477. }
  2478. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2479. {
  2480. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2481. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  2482. }
  2483. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2484. {
  2485. client.OnScriptReset += ProcessScriptReset;
  2486. client.OnGetScriptRunning += GetScriptRunning;
  2487. client.OnSetScriptRunning += SetScriptRunning;
  2488. }
  2489. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2490. {
  2491. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  2492. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2493. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2494. client.OnParcelBuy += ProcessParcelBuy;
  2495. }
  2496. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2497. {
  2498. client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
  2499. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2500. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  2501. client.OnSetStartLocationRequest += SetHomeRezPoint;
  2502. client.OnRegionHandleRequest += RegionHandleRequest;
  2503. }
  2504. public virtual void SubscribeToClientGodEvents(IClientAPI client)
  2505. {
  2506. IGodsModule godsModule = RequestModuleInterface<IGodsModule>();
  2507. client.OnGodKickUser += godsModule.KickUser;
  2508. client.OnRequestGodlikePowers += godsModule.RequestGodlikePowers;
  2509. }
  2510. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2511. {
  2512. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2513. client.OnViewerEffect += ProcessViewerEffect;
  2514. }
  2515. protected virtual void UnsubscribeToClientEvents(IClientAPI client)
  2516. {
  2517. }
  2518. /// <summary>
  2519. /// Register for events from the client
  2520. /// </summary>
  2521. /// <param name="client">The IClientAPI of the connected client</param>
  2522. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2523. {
  2524. UnSubscribeToClientTerrainEvents(client);
  2525. UnSubscribeToClientPrimEvents(client);
  2526. UnSubscribeToClientPrimRezEvents(client);
  2527. UnSubscribeToClientInventoryEvents(client);
  2528. UnSubscribeToClientAttachmentEvents(client);
  2529. UnSubscribeToClientTeleportEvents(client);
  2530. UnSubscribeToClientScriptEvents(client);
  2531. UnSubscribeToClientParcelEvents(client);
  2532. UnSubscribeToClientGridEvents(client);
  2533. UnSubscribeToClientGodEvents(client);
  2534. UnSubscribeToClientNetworkEvents(client);
  2535. // EventManager.TriggerOnNewClient(client);
  2536. }
  2537. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2538. {
  2539. client.OnRegionHandShakeReply -= SendLayerData;
  2540. client.OnUnackedTerrain -= TerrainUnAcked;
  2541. }
  2542. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2543. {
  2544. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimPosition;
  2545. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2546. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimRotation;
  2547. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimRotation;
  2548. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2549. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2550. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2551. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2552. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2553. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2554. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2555. client.OnObjectRequest -= RequestPrim;
  2556. client.OnObjectSelect -= SelectPrim;
  2557. client.OnObjectDeselect -= DeselectPrim;
  2558. client.OnGrabUpdate -= m_sceneGraph.MoveObject;
  2559. client.OnSpinStart -= m_sceneGraph.SpinStart;
  2560. client.OnSpinUpdate -= m_sceneGraph.SpinObject;
  2561. client.OnDeRezObject -= DeRezObject;
  2562. client.OnObjectName -= m_sceneGraph.PrimName;
  2563. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2564. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2565. client.OnLinkObjects -= LinkObjects;
  2566. client.OnDelinkObjects -= DelinkObjects;
  2567. client.OnObjectDuplicate -= m_sceneGraph.DuplicateObject;
  2568. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2569. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2570. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2571. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2572. client.OnGrabObject -= ProcessObjectGrab;
  2573. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2574. client.OnUndo -= m_sceneGraph.HandleUndo;
  2575. client.OnRedo -= m_sceneGraph.HandleRedo;
  2576. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2577. client.OnObjectDrop -= m_sceneGraph.DropObject;
  2578. client.OnObjectSaleInfo -= ObjectSaleInfo;
  2579. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2580. client.OnObjectOwner -= ObjectOwner;
  2581. }
  2582. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2583. {
  2584. client.OnAddPrim -= AddNewPrim;
  2585. client.OnRezObject -= RezObject;
  2586. }
  2587. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2588. {
  2589. client.OnCreateNewInventoryItem -= CreateNewInventoryItem;
  2590. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2591. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  2592. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  2593. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  2594. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  2595. client.OnFetchInventory -= HandleFetchInventory;
  2596. client.OnUpdateInventoryItem -= UpdateInventoryItemAsset;
  2597. client.OnCopyInventoryItem -= CopyInventoryItem;
  2598. client.OnMoveInventoryItem -= MoveInventoryItem;
  2599. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  2600. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  2601. client.OnRezScript -= RezScript;
  2602. client.OnRequestTaskInventory -= RequestTaskInventory;
  2603. client.OnRemoveTaskItem -= RemoveTaskInventory;
  2604. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  2605. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  2606. }
  2607. public virtual void UnSubscribeToClientAttachmentEvents(IClientAPI client)
  2608. {
  2609. if (AttachmentsModule != null)
  2610. {
  2611. client.OnRezSingleAttachmentFromInv -= AttachmentsModule.RezSingleAttachmentFromInventory;
  2612. client.OnRezMultipleAttachmentsFromInv -= AttachmentsModule.RezMultipleAttachmentsFromInventory;
  2613. client.OnObjectAttach -= AttachmentsModule.AttachObject;
  2614. client.OnObjectDetach -= AttachmentsModule.DetachObject;
  2615. client.OnDetachAttachmentIntoInv -= AttachmentsModule.ShowDetachInUserInventory;
  2616. }
  2617. }
  2618. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  2619. {
  2620. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  2621. client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  2622. //client.OnTeleportHomeRequest -= TeleportClientHome;
  2623. }
  2624. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  2625. {
  2626. client.OnScriptReset -= ProcessScriptReset;
  2627. client.OnGetScriptRunning -= GetScriptRunning;
  2628. client.OnSetScriptRunning -= SetScriptRunning;
  2629. }
  2630. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  2631. {
  2632. client.OnObjectGroupRequest -= m_sceneGraph.HandleObjectGroupUpdate;
  2633. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  2634. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  2635. client.OnParcelBuy -= ProcessParcelBuy;
  2636. }
  2637. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  2638. {
  2639. client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
  2640. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  2641. client.OnAvatarPickerRequest -= ProcessAvatarPickerRequest;
  2642. client.OnSetStartLocationRequest -= SetHomeRezPoint;
  2643. client.OnRegionHandleRequest -= RegionHandleRequest;
  2644. }
  2645. public virtual void UnSubscribeToClientGodEvents(IClientAPI client)
  2646. {
  2647. IGodsModule godsModule = RequestModuleInterface<IGodsModule>();
  2648. client.OnGodKickUser -= godsModule.KickUser;
  2649. client.OnRequestGodlikePowers -= godsModule.RequestGodlikePowers;
  2650. }
  2651. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  2652. {
  2653. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  2654. client.OnViewerEffect -= ProcessViewerEffect;
  2655. }
  2656. /// <summary>
  2657. /// Teleport an avatar to their home region
  2658. /// </summary>
  2659. /// <param name="agentId">The avatar's Unique ID</param>
  2660. /// <param name="client">The IClientAPI for the client</param>
  2661. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  2662. {
  2663. if (m_teleportModule != null)
  2664. m_teleportModule.TeleportHome(agentId, client);
  2665. else
  2666. {
  2667. m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
  2668. client.SendTeleportFailed("Unable to perform teleports on this simulator.");
  2669. }
  2670. }
  2671. /// <summary>
  2672. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  2673. /// RayEnd and RayStart to determine what the angle of the ray is
  2674. /// </summary>
  2675. /// <param name="localID">ID of object to duplicate</param>
  2676. /// <param name="dupeFlags"></param>
  2677. /// <param name="AgentID">Agent doing the duplication</param>
  2678. /// <param name="GroupID">Group of new object</param>
  2679. /// <param name="RayTargetObj">The target of the Ray</param>
  2680. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  2681. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  2682. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  2683. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  2684. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  2685. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  2686. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  2687. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  2688. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  2689. {
  2690. Vector3 pos;
  2691. const bool frontFacesOnly = true;
  2692. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  2693. SceneObjectPart target = GetSceneObjectPart(localID);
  2694. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  2695. if (target != null && target2 != null)
  2696. {
  2697. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  2698. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  2699. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  2700. if (target2.ParentGroup != null)
  2701. {
  2702. pos = target2.AbsolutePosition;
  2703. //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());
  2704. // TODO: Raytrace better here
  2705. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  2706. Ray NewRay = new Ray(AXOrigin, AXdirection);
  2707. // Ray Trace against target here
  2708. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  2709. // Un-comment out the following line to Get Raytrace results printed to the console.
  2710. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2711. float ScaleOffset = 0.5f;
  2712. // If we hit something
  2713. if (ei.HitTF)
  2714. {
  2715. Vector3 scale = target.Scale;
  2716. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  2717. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2718. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2719. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2720. ScaleOffset = Math.Abs(ScaleOffset);
  2721. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2722. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  2723. Vector3 offset = normal * (ScaleOffset / 2f);
  2724. pos = intersectionpoint + offset;
  2725. // stick in offset format from the original prim
  2726. pos = pos - target.ParentGroup.AbsolutePosition;
  2727. if (CopyRotates)
  2728. {
  2729. Quaternion worldRot = target2.GetWorldRotation();
  2730. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2731. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2732. //obj.Rotation = worldRot;
  2733. //obj.UpdateGroupRotationR(worldRot);
  2734. }
  2735. else
  2736. {
  2737. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  2738. }
  2739. }
  2740. return;
  2741. }
  2742. return;
  2743. }
  2744. }
  2745. /// <summary>
  2746. /// Sets the Home Point. The LoginService uses this to know where to put a user when they log-in
  2747. /// </summary>
  2748. /// <param name="remoteClient"></param>
  2749. /// <param name="regionHandle"></param>
  2750. /// <param name="position"></param>
  2751. /// <param name="lookAt"></param>
  2752. /// <param name="flags"></param>
  2753. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  2754. {
  2755. if (GridUserService != null && GridUserService.SetHome(remoteClient.AgentId.ToString(), RegionInfo.RegionID, position, lookAt))
  2756. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  2757. m_dialogModule.SendAlertToUser(remoteClient, "Home position set.");
  2758. else
  2759. m_dialogModule.SendAlertToUser(remoteClient, "Set Home request Failed.");
  2760. }
  2761. /// <summary>
  2762. /// Create a child agent scene presence and add it to this scene.
  2763. /// </summary>
  2764. /// <param name="client"></param>
  2765. /// <returns></returns>
  2766. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  2767. {
  2768. CheckHeartbeat();
  2769. AvatarAppearance appearance = null;
  2770. GetAvatarAppearance(client, out appearance);
  2771. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  2772. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  2773. m_eventManager.TriggerOnNewPresence(avatar);
  2774. return avatar;
  2775. }
  2776. /// <summary>
  2777. /// Get the avatar apperance for the given client.
  2778. /// </summary>
  2779. /// <param name="client"></param>
  2780. /// <param name="appearance"></param>
  2781. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2782. {
  2783. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2784. if (aCircuit == null)
  2785. {
  2786. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  2787. appearance = new AvatarAppearance(client.AgentId);
  2788. return;
  2789. }
  2790. appearance = aCircuit.Appearance;
  2791. if (appearance == null)
  2792. {
  2793. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  2794. appearance = new AvatarAppearance(client.AgentId);
  2795. }
  2796. }
  2797. /// <summary>
  2798. /// Remove the given client from the scene.
  2799. /// </summary>
  2800. /// <param name="agentID"></param>
  2801. public override void RemoveClient(UUID agentID)
  2802. {
  2803. CheckHeartbeat();
  2804. bool childagentYN = false;
  2805. ScenePresence avatar = GetScenePresence(agentID);
  2806. if (avatar != null)
  2807. {
  2808. childagentYN = avatar.IsChildAgent;
  2809. if (avatar.ParentID != 0)
  2810. {
  2811. avatar.StandUp();
  2812. }
  2813. try
  2814. {
  2815. m_log.DebugFormat(
  2816. "[SCENE]: Removing {0} agent {1} from region {2}",
  2817. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  2818. m_sceneGraph.removeUserCount(!childagentYN);
  2819. CapsModule.RemoveCapsHandler(agentID);
  2820. // REFACTORING PROBLEM -- well not really a problem, but just to point out that whatever
  2821. // this method is doing is HORRIBLE!!!
  2822. avatar.Scene.NeedSceneCacheClear(avatar.UUID);
  2823. if (!avatar.IsChildAgent)
  2824. {
  2825. //List<ulong> childknownRegions = new List<ulong>();
  2826. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  2827. //for (int i = 0; i < ckn.Count; i++)
  2828. //{
  2829. // childknownRegions.Add(ckn[i]);
  2830. //}
  2831. List<ulong> regions = new List<ulong>(avatar.KnownChildRegionHandles);
  2832. regions.Remove(RegionInfo.RegionHandle);
  2833. m_sceneGridService.SendCloseChildAgentConnections(agentID, regions);
  2834. }
  2835. m_eventManager.TriggerClientClosed(agentID, this);
  2836. }
  2837. catch (NullReferenceException)
  2838. {
  2839. // We don't know which count to remove it from
  2840. // Avatar is already disposed :/
  2841. }
  2842. m_eventManager.TriggerOnRemovePresence(agentID);
  2843. ForEachClient(
  2844. delegate(IClientAPI client)
  2845. {
  2846. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  2847. try { client.SendKillObject(avatar.RegionHandle, avatar.LocalId); }
  2848. catch (NullReferenceException) { }
  2849. });
  2850. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  2851. if (agentTransactions != null)
  2852. {
  2853. agentTransactions.RemoveAgentAssetTransactions(agentID);
  2854. }
  2855. // Remove the avatar from the scene
  2856. m_sceneGraph.RemoveScenePresence(agentID);
  2857. m_clientManager.Remove(agentID);
  2858. try
  2859. {
  2860. avatar.Close();
  2861. }
  2862. catch (NullReferenceException)
  2863. {
  2864. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2865. }
  2866. catch (Exception e)
  2867. {
  2868. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  2869. }
  2870. m_authenticateHandler.RemoveCircuit(avatar.ControllingClient.CircuitCode);
  2871. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2872. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2873. }
  2874. }
  2875. /// <summary>
  2876. /// 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.
  2877. ///
  2878. /// </summary>
  2879. /// <param name="avatarID"></param>
  2880. /// <param name="regionslst"></param>
  2881. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2882. {
  2883. ScenePresence av = GetScenePresence(avatarID);
  2884. if (av != null)
  2885. {
  2886. lock (av)
  2887. {
  2888. for (int i = 0; i < regionslst.Count; i++)
  2889. {
  2890. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2891. }
  2892. }
  2893. }
  2894. }
  2895. #endregion
  2896. #region Entities
  2897. public void SendKillObject(uint localID)
  2898. {
  2899. SceneObjectPart part = GetSceneObjectPart(localID);
  2900. if (part != null) // It is a prim
  2901. {
  2902. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2903. {
  2904. if (part.ParentGroup.RootPart != part) // Child part
  2905. return;
  2906. }
  2907. }
  2908. ForEachClient(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2909. }
  2910. #endregion
  2911. #region RegionComms
  2912. /// <summary>
  2913. /// Register the methods that should be invoked when this scene receives various incoming events
  2914. /// </summary>
  2915. public void RegisterCommsEvents()
  2916. {
  2917. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2918. m_sceneGridService.OnCloseAgentConnection += IncomingCloseAgent;
  2919. //m_eventManager.OnRegionUp += OtherRegionUp;
  2920. //m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2921. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2922. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2923. m_sceneGridService.KiPrimitive += SendKillObject;
  2924. m_sceneGridService.OnGetLandData += GetLandData;
  2925. }
  2926. /// <summary>
  2927. /// Deregister this scene from receiving incoming region events
  2928. /// </summary>
  2929. public void UnRegisterRegionWithComms()
  2930. {
  2931. m_sceneGridService.KiPrimitive -= SendKillObject;
  2932. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2933. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2934. //m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2935. //m_eventManager.OnRegionUp -= OtherRegionUp;
  2936. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2937. m_sceneGridService.OnCloseAgentConnection -= IncomingCloseAgent;
  2938. m_sceneGridService.OnGetLandData -= GetLandData;
  2939. // this does nothing; should be removed
  2940. m_sceneGridService.Close();
  2941. if (!GridService.DeregisterRegion(m_regInfo.RegionID))
  2942. m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", m_regInfo.RegionName);
  2943. }
  2944. /// <summary>
  2945. /// Do the work necessary to initiate a new user connection for a particular scene.
  2946. /// At the moment, this consists of setting up the caps infrastructure
  2947. /// The return bool should allow for connections to be refused, but as not all calling paths
  2948. /// take proper notice of it let, we allowed banned users in still.
  2949. /// </summary>
  2950. /// <param name="agent">CircuitData of the agent who is connecting</param>
  2951. /// <param name="reason">Outputs the reason for the false response on this string</param>
  2952. /// <returns>True if the region accepts this agent. False if it does not. False will
  2953. /// also return a reason.</returns>
  2954. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason)
  2955. {
  2956. TeleportFlags tp = (TeleportFlags)teleportFlags;
  2957. reason = String.Empty;
  2958. //Teleport flags:
  2959. //
  2960. // TeleportFlags.ViaGodlikeLure - Border Crossing
  2961. // TeleportFlags.ViaLogin - Login
  2962. // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
  2963. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  2964. // Don't disable this log message - it's too helpful
  2965. m_log.InfoFormat(
  2966. "[CONNECTION BEGIN]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, teleportflags {6})",
  2967. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  2968. agent.AgentID, agent.circuitcode, teleportFlags);
  2969. if (LoginsDisabled)
  2970. {
  2971. reason = "Logins Disabled";
  2972. return false;
  2973. }
  2974. ScenePresence sp = GetScenePresence(agent.AgentID);
  2975. if (sp != null && !sp.IsChildAgent)
  2976. {
  2977. // We have a zombie from a crashed session.
  2978. // Or the same user is trying to be root twice here, won't work.
  2979. // Kill it.
  2980. m_log.DebugFormat("[SCENE]: Zombie scene presence detected for {0} in {1}", agent.AgentID, RegionInfo.RegionName);
  2981. sp.ControllingClient.Close();
  2982. sp = null;
  2983. }
  2984. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  2985. //On login test land permisions
  2986. if (tp == TeleportFlags.ViaLogin)
  2987. {
  2988. if (land != null && !TestLandRestrictions(agent, land, out reason))
  2989. {
  2990. return false;
  2991. }
  2992. }
  2993. if (sp == null) // We don't have an [child] agent here already
  2994. {
  2995. try
  2996. {
  2997. if (!VerifyUserPresence(agent, out reason))
  2998. return false;
  2999. }
  3000. catch (Exception e)
  3001. {
  3002. m_log.DebugFormat("[CONNECTION BEGIN]: Exception verifying presence {0}", e.Message);
  3003. return false;
  3004. }
  3005. try
  3006. {
  3007. if (!AuthorizeUser(agent, out reason))
  3008. return false;
  3009. }
  3010. catch (Exception e)
  3011. {
  3012. m_log.DebugFormat("[CONNECTION BEGIN]: Exception authorizing user {0}", e.Message);
  3013. return false;
  3014. }
  3015. m_log.InfoFormat(
  3016. "[CONNECTION BEGIN]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  3017. RegionInfo.RegionName, (agent.child ? "child" : "root"), agent.firstname, agent.lastname,
  3018. agent.AgentID, agent.circuitcode);
  3019. CapsModule.NewUserConnection(agent);
  3020. CapsModule.AddCapsHandler(agent.AgentID);
  3021. }
  3022. else
  3023. {
  3024. if (sp.IsChildAgent)
  3025. {
  3026. m_log.DebugFormat(
  3027. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  3028. agent.AgentID, RegionInfo.RegionName);
  3029. sp.AdjustKnownSeeds();
  3030. CapsModule.NewUserConnection(agent);
  3031. }
  3032. }
  3033. // In all cases, add or update the circuit data with the new agent circuit data and teleport flags
  3034. agent.teleportFlags = teleportFlags;
  3035. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  3036. if (tp == TeleportFlags.ViaLogin)
  3037. {
  3038. if (TestBorderCross(agent.startpos, Cardinals.E))
  3039. {
  3040. Border crossedBorder = GetCrossedBorder(agent.startpos, Cardinals.E);
  3041. agent.startpos.X = crossedBorder.BorderLine.Z - 1;
  3042. }
  3043. if (TestBorderCross(agent.startpos, Cardinals.N))
  3044. {
  3045. Border crossedBorder = GetCrossedBorder(agent.startpos, Cardinals.N);
  3046. agent.startpos.Y = crossedBorder.BorderLine.Z - 1;
  3047. }
  3048. //Mitigate http://opensimulator.org/mantis/view.php?id=3522
  3049. // Check if start position is outside of region
  3050. // If it is, check the Z start position also.. if not, leave it alone.
  3051. if (BordersLocked)
  3052. {
  3053. lock (EastBorders)
  3054. {
  3055. if (agent.startpos.X > EastBorders[0].BorderLine.Z)
  3056. {
  3057. m_log.Warn("FIX AGENT POSITION");
  3058. agent.startpos.X = EastBorders[0].BorderLine.Z * 0.5f;
  3059. if (agent.startpos.Z > 720)
  3060. agent.startpos.Z = 720;
  3061. }
  3062. }
  3063. lock (NorthBorders)
  3064. {
  3065. if (agent.startpos.Y > NorthBorders[0].BorderLine.Z)
  3066. {
  3067. m_log.Warn("FIX Agent POSITION");
  3068. agent.startpos.Y = NorthBorders[0].BorderLine.Z * 0.5f;
  3069. if (agent.startpos.Z > 720)
  3070. agent.startpos.Z = 720;
  3071. }
  3072. }
  3073. }
  3074. else
  3075. {
  3076. if (agent.startpos.X > EastBorders[0].BorderLine.Z)
  3077. {
  3078. m_log.Warn("FIX AGENT POSITION");
  3079. agent.startpos.X = EastBorders[0].BorderLine.Z * 0.5f;
  3080. if (agent.startpos.Z > 720)
  3081. agent.startpos.Z = 720;
  3082. }
  3083. if (agent.startpos.Y > NorthBorders[0].BorderLine.Z)
  3084. {
  3085. m_log.Warn("FIX Agent POSITION");
  3086. agent.startpos.Y = NorthBorders[0].BorderLine.Z * 0.5f;
  3087. if (agent.startpos.Z > 720)
  3088. agent.startpos.Z = 720;
  3089. }
  3090. }
  3091. // Honor parcel landing type and position.
  3092. if (land != null)
  3093. {
  3094. if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
  3095. {
  3096. agent.startpos = land.LandData.UserLocation;
  3097. }
  3098. }
  3099. }
  3100. return true;
  3101. }
  3102. private bool TestLandRestrictions(AgentCircuitData agent, ILandObject land, out string reason)
  3103. {
  3104. bool banned = land.IsBannedFromLand(agent.AgentID);
  3105. bool restricted = land.IsRestrictedFromLand(agent.AgentID);
  3106. if (banned || restricted)
  3107. {
  3108. ILandObject nearestParcel = GetNearestAllowedParcel(agent.AgentID, agent.startpos.X, agent.startpos.Y);
  3109. if (nearestParcel != null)
  3110. {
  3111. //Move agent to nearest allowed
  3112. Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
  3113. agent.startpos.X = newPosition.X;
  3114. agent.startpos.Y = newPosition.Y;
  3115. }
  3116. else
  3117. {
  3118. if (banned)
  3119. {
  3120. reason = "Cannot regioncross into banned parcel.";
  3121. }
  3122. else
  3123. {
  3124. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3125. RegionInfo.RegionName);
  3126. }
  3127. return false;
  3128. }
  3129. }
  3130. reason = "";
  3131. return true;
  3132. }
  3133. /// <summary>
  3134. /// Verifies that the user has a presence on the Grid
  3135. /// </summary>
  3136. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3137. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3138. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3139. /// also return a reason.</returns>
  3140. public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
  3141. {
  3142. reason = String.Empty;
  3143. IPresenceService presence = RequestModuleInterface<IPresenceService>();
  3144. if (presence == null)
  3145. {
  3146. reason = String.Format("Failed to verify user {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3147. return false;
  3148. }
  3149. OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID);
  3150. if (pinfo == null)
  3151. {
  3152. reason = String.Format("Failed to verify user {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3153. return false;
  3154. }
  3155. return true;
  3156. }
  3157. /// <summary>
  3158. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3159. /// </summary>
  3160. /// <param name="agent">The circuit data for the agent</param>
  3161. /// <param name="reason">outputs the reason to this string</param>
  3162. /// <returns>True if the region accepts this agent. False if it does not. False will
  3163. /// also return a reason.</returns>
  3164. protected virtual bool AuthorizeUser(AgentCircuitData agent, out string reason)
  3165. {
  3166. reason = String.Empty;
  3167. if (!m_strictAccessControl) return true;
  3168. if (Permissions.IsGod(agent.AgentID)) return true;
  3169. if (AuthorizationService != null)
  3170. {
  3171. if (!AuthorizationService.IsAuthorizedForRegion(agent.AgentID.ToString(), RegionInfo.RegionID.ToString(),out reason))
  3172. {
  3173. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  3174. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3175. //reason = String.Format("You are not currently on the access list for {0}",RegionInfo.RegionName);
  3176. return false;
  3177. }
  3178. }
  3179. if (m_regInfo.EstateSettings != null)
  3180. {
  3181. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  3182. {
  3183. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3184. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3185. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  3186. RegionInfo.RegionName);
  3187. return false;
  3188. }
  3189. }
  3190. else
  3191. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
  3192. IGroupsModule groupsModule =
  3193. RequestModuleInterface<IGroupsModule>();
  3194. List<UUID> agentGroups = new List<UUID>();
  3195. if (groupsModule != null)
  3196. {
  3197. GroupMembershipData[] GroupMembership =
  3198. groupsModule.GetMembershipData(agent.AgentID);
  3199. if (GroupMembership != null)
  3200. {
  3201. for (int i = 0; i < GroupMembership.Length; i++)
  3202. agentGroups.Add(GroupMembership[i].GroupID);
  3203. }
  3204. else
  3205. m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
  3206. }
  3207. bool groupAccess = false;
  3208. UUID[] estateGroups = m_regInfo.EstateSettings.EstateGroups;
  3209. if (estateGroups != null)
  3210. {
  3211. foreach (UUID group in estateGroups)
  3212. {
  3213. if (agentGroups.Contains(group))
  3214. {
  3215. groupAccess = true;
  3216. break;
  3217. }
  3218. }
  3219. }
  3220. else
  3221. m_log.ErrorFormat("[CONNECTION BEGIN]: EstateGroups is null!");
  3222. if (!m_regInfo.EstateSettings.PublicAccess &&
  3223. !m_regInfo.EstateSettings.HasAccess(agent.AgentID) &&
  3224. !groupAccess)
  3225. {
  3226. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3227. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3228. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3229. RegionInfo.RegionName);
  3230. return false;
  3231. }
  3232. // TODO: estate/region settings are not properly hooked up
  3233. // to ILandObject.isRestrictedFromLand()
  3234. // if (null != LandChannel)
  3235. // {
  3236. // // region seems to have local Id of 1
  3237. // ILandObject land = LandChannel.GetLandObject(1);
  3238. // if (null != land)
  3239. // {
  3240. // if (land.isBannedFromLand(agent.AgentID))
  3241. // {
  3242. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user has been banned from land",
  3243. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3244. // reason = String.Format("Denied access to private region {0}: You are banned from that region.",
  3245. // RegionInfo.RegionName);
  3246. // return false;
  3247. // }
  3248. // if (land.isRestrictedFromLand(agent.AgentID))
  3249. // {
  3250. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  3251. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3252. // reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3253. // RegionInfo.RegionName);
  3254. // return false;
  3255. // }
  3256. // }
  3257. // }
  3258. return true;
  3259. }
  3260. private ILandObject GetParcelAtPoint(float x, float y)
  3261. {
  3262. foreach (var parcel in AllParcels())
  3263. {
  3264. if (parcel.ContainsPoint((int)x,(int)y))
  3265. {
  3266. return parcel;
  3267. }
  3268. }
  3269. return null;
  3270. }
  3271. /// <summary>
  3272. /// Update an AgentCircuitData object with new information
  3273. /// </summary>
  3274. /// <param name="data">Information to update the AgentCircuitData with</param>
  3275. public void UpdateCircuitData(AgentCircuitData data)
  3276. {
  3277. m_authenticateHandler.UpdateAgentData(data);
  3278. }
  3279. /// <summary>
  3280. /// Change the Circuit Code for the user's Circuit Data
  3281. /// </summary>
  3282. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3283. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3284. /// <returns>True if we successfully changed it. False if we did not</returns>
  3285. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3286. {
  3287. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  3288. }
  3289. /// <summary>
  3290. /// The Grid has requested that we log-off a user. Log them off.
  3291. /// </summary>
  3292. /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3293. /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3294. /// <param name="message">message to display to the user. Reason for being logged off</param>
  3295. public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3296. {
  3297. ScenePresence loggingOffUser = GetScenePresence(AvatarID);
  3298. if (loggingOffUser != null)
  3299. {
  3300. UUID localRegionSecret = UUID.Zero;
  3301. bool parsedsecret = UUID.TryParse(m_regInfo.regionSecret, out localRegionSecret);
  3302. // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3303. // Will update the user server in a few revisions to use it.
  3304. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3305. {
  3306. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  3307. loggingOffUser.ControllingClient.Kick(message);
  3308. // Give them a second to receive the message!
  3309. Thread.Sleep(1000);
  3310. loggingOffUser.ControllingClient.Close();
  3311. }
  3312. else
  3313. {
  3314. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3315. }
  3316. }
  3317. else
  3318. {
  3319. 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());
  3320. }
  3321. }
  3322. /// <summary>
  3323. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3324. /// </summary>
  3325. /// <param name="agentID"></param>
  3326. /// <param name="position"></param>
  3327. /// <param name="isFlying"></param>
  3328. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3329. {
  3330. ScenePresence presence = GetScenePresence(agentID);
  3331. if(presence != null)
  3332. {
  3333. try
  3334. {
  3335. presence.MakeRootAgent(position, isFlying);
  3336. }
  3337. catch (Exception e)
  3338. {
  3339. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  3340. }
  3341. }
  3342. else
  3343. {
  3344. m_log.ErrorFormat(
  3345. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3346. agentID, RegionInfo.RegionName);
  3347. }
  3348. }
  3349. /// <summary>
  3350. /// We've got an update about an agent that sees into this region,
  3351. /// send it to ScenePresence for processing It's the full data.
  3352. /// </summary>
  3353. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3354. /// Appearance, animations, position, etc.</param>
  3355. /// <returns>true if we handled it.</returns>
  3356. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  3357. {
  3358. m_log.DebugFormat(
  3359. "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3360. // XPTO: if this agent is not allowed here as root, always return false
  3361. // We have to wait until the viewer contacts this region after receiving EAC.
  3362. // That calls AddNewClient, which finally creates the ScenePresence
  3363. ScenePresence childAgentUpdate = WaitGetScenePresence(cAgentData.AgentID);
  3364. if (childAgentUpdate != null)
  3365. {
  3366. childAgentUpdate.ChildAgentDataUpdate(cAgentData);
  3367. return true;
  3368. }
  3369. return false;
  3370. }
  3371. /// <summary>
  3372. /// We've got an update about an agent that sees into this region,
  3373. /// send it to ScenePresence for processing It's only positional data
  3374. /// </summary>
  3375. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3376. /// <returns>true if we handled it.</returns>
  3377. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  3378. {
  3379. //m_log.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  3380. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  3381. if (childAgentUpdate != null)
  3382. {
  3383. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  3384. // however to avoid a race condition crossing borders..
  3385. if (childAgentUpdate.IsChildAgent)
  3386. {
  3387. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  3388. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  3389. uint tRegionX = RegionInfo.RegionLocX;
  3390. uint tRegionY = RegionInfo.RegionLocY;
  3391. //Send Data to ScenePresence
  3392. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  3393. // Not Implemented:
  3394. //TODO: Do we need to pass the message on to one of our neighbors?
  3395. }
  3396. return true;
  3397. }
  3398. return false;
  3399. }
  3400. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  3401. {
  3402. int ntimes = 10;
  3403. ScenePresence childAgentUpdate = null;
  3404. while ((childAgentUpdate = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  3405. Thread.Sleep(1000);
  3406. return childAgentUpdate;
  3407. }
  3408. public virtual bool IncomingRetrieveRootAgent(UUID id, out IAgentData agent)
  3409. {
  3410. agent = null;
  3411. ScenePresence sp = GetScenePresence(id);
  3412. if ((sp != null) && (!sp.IsChildAgent))
  3413. {
  3414. sp.IsChildAgent = true;
  3415. return sp.CopyAgent(out agent);
  3416. }
  3417. return false;
  3418. }
  3419. /// <summary>
  3420. /// Tell a single agent to disconnect from the region.
  3421. /// </summary>
  3422. /// <param name="regionHandle"></param>
  3423. /// <param name="agentID"></param>
  3424. public bool IncomingCloseAgent(UUID agentID)
  3425. {
  3426. //m_log.DebugFormat("[SCENE]: Processing incoming close agent for {0}", agentID);
  3427. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  3428. if (presence != null)
  3429. {
  3430. // Nothing is removed here, so down count it as such
  3431. if (presence.IsChildAgent)
  3432. {
  3433. m_sceneGraph.removeUserCount(false);
  3434. }
  3435. else
  3436. {
  3437. m_sceneGraph.removeUserCount(true);
  3438. }
  3439. // Don't do this to root agents on logout, it's not nice for the viewer
  3440. if (presence.IsChildAgent)
  3441. {
  3442. // Tell a single agent to disconnect from the region.
  3443. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  3444. if (eq != null)
  3445. {
  3446. eq.DisableSimulator(RegionInfo.RegionHandle, agentID);
  3447. }
  3448. else
  3449. presence.ControllingClient.SendShutdownConnectionNotice();
  3450. }
  3451. presence.ControllingClient.Close();
  3452. return true;
  3453. }
  3454. // Agent not here
  3455. return false;
  3456. }
  3457. /// <summary>
  3458. /// Tries to teleport agent to other region.
  3459. /// </summary>
  3460. /// <param name="remoteClient"></param>
  3461. /// <param name="regionName"></param>
  3462. /// <param name="position"></param>
  3463. /// <param name="lookAt"></param>
  3464. /// <param name="teleportFlags"></param>
  3465. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  3466. Vector3 lookat, uint teleportFlags)
  3467. {
  3468. GridRegion regionInfo = GridService.GetRegionByName(UUID.Zero, regionName);
  3469. if (regionInfo == null)
  3470. {
  3471. // can't find the region: Tell viewer and abort
  3472. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  3473. return;
  3474. }
  3475. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  3476. }
  3477. /// <summary>
  3478. /// Tries to teleport agent to other region.
  3479. /// </summary>
  3480. /// <param name="remoteClient"></param>
  3481. /// <param name="regionHandle"></param>
  3482. /// <param name="position"></param>
  3483. /// <param name="lookAt"></param>
  3484. /// <param name="teleportFlags"></param>
  3485. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  3486. Vector3 lookAt, uint teleportFlags)
  3487. {
  3488. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  3489. if (sp != null)
  3490. {
  3491. uint regionX = m_regInfo.RegionLocX;
  3492. uint regionY = m_regInfo.RegionLocY;
  3493. Utils.LongToUInts(regionHandle, out regionX, out regionY);
  3494. int shiftx = (int) regionX - (int) m_regInfo.RegionLocX * (int)Constants.RegionSize;
  3495. int shifty = (int) regionY - (int) m_regInfo.RegionLocY * (int)Constants.RegionSize;
  3496. position.X += shiftx;
  3497. position.Y += shifty;
  3498. bool result = false;
  3499. if (TestBorderCross(position,Cardinals.N))
  3500. result = true;
  3501. if (TestBorderCross(position, Cardinals.S))
  3502. result = true;
  3503. if (TestBorderCross(position, Cardinals.E))
  3504. result = true;
  3505. if (TestBorderCross(position, Cardinals.W))
  3506. result = true;
  3507. // bordercross if position is outside of region
  3508. if (!result)
  3509. {
  3510. regionHandle = m_regInfo.RegionHandle;
  3511. }
  3512. else
  3513. {
  3514. // not in this region, undo the shift!
  3515. position.X -= shiftx;
  3516. position.Y -= shifty;
  3517. }
  3518. if (m_teleportModule != null)
  3519. m_teleportModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
  3520. else
  3521. {
  3522. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  3523. sp.ControllingClient.SendTeleportFailed("Unable to perform teleports on this simulator.");
  3524. }
  3525. }
  3526. }
  3527. /// <summary>
  3528. /// Tries to teleport agent to landmark.
  3529. /// </summary>
  3530. /// <param name="remoteClient"></param>
  3531. /// <param name="regionHandle"></param>
  3532. /// <param name="position"></param>
  3533. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  3534. {
  3535. GridRegion info = GridService.GetRegionByUUID(UUID.Zero, regionID);
  3536. if (info == null)
  3537. {
  3538. // can't find the region: Tell viewer and abort
  3539. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  3540. return;
  3541. }
  3542. RequestTeleportLocation(remoteClient, info.RegionHandle, position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  3543. }
  3544. public void CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  3545. {
  3546. if (m_teleportModule != null)
  3547. m_teleportModule.Cross(agent, isFlying);
  3548. else
  3549. {
  3550. m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
  3551. }
  3552. }
  3553. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  3554. {
  3555. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  3556. }
  3557. #endregion
  3558. #region Other Methods
  3559. #endregion
  3560. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  3561. {
  3562. // Check for spoofing.. since this is permissions we're talking about here!
  3563. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  3564. {
  3565. // Tell the object to do permission update
  3566. if (localId != 0)
  3567. {
  3568. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  3569. if (chObjectGroup != null)
  3570. {
  3571. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  3572. }
  3573. }
  3574. }
  3575. }
  3576. /// <summary>
  3577. /// Causes all clients to get a full object update on all of the objects in the scene.
  3578. /// </summary>
  3579. public void ForceClientUpdate()
  3580. {
  3581. List<EntityBase> EntityList = GetEntities();
  3582. foreach (EntityBase ent in EntityList)
  3583. {
  3584. if (ent is SceneObjectGroup)
  3585. {
  3586. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  3587. }
  3588. }
  3589. }
  3590. /// <summary>
  3591. /// This is currently only used for scale (to scale to MegaPrim size)
  3592. /// There is a console command that calls this in OpenSimMain
  3593. /// </summary>
  3594. /// <param name="cmdparams"></param>
  3595. public void HandleEditCommand(string[] cmdparams)
  3596. {
  3597. m_log.Debug("Searching for Primitive: '" + cmdparams[2] + "'");
  3598. List<EntityBase> EntityList = GetEntities();
  3599. foreach (EntityBase ent in EntityList)
  3600. {
  3601. if (ent is SceneObjectGroup)
  3602. {
  3603. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  3604. if (part != null)
  3605. {
  3606. if (part.Name == cmdparams[2])
  3607. {
  3608. part.Resize(
  3609. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  3610. Convert.ToSingle(cmdparams[5])));
  3611. m_log.Debug("Edited scale of Primitive: " + part.Name);
  3612. }
  3613. }
  3614. }
  3615. }
  3616. }
  3617. public override void Show(string[] showParams)
  3618. {
  3619. base.Show(showParams);
  3620. switch (showParams[0])
  3621. {
  3622. case "users":
  3623. m_log.Error("Current Region: " + RegionInfo.RegionName);
  3624. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  3625. "Agent ID", "Session ID", "Circuit", "IP", "World");
  3626. ForEachScenePresence(delegate(ScenePresence sp)
  3627. {
  3628. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  3629. sp.Firstname,
  3630. sp.Lastname,
  3631. sp.UUID,
  3632. sp.ControllingClient.AgentId,
  3633. "Unknown",
  3634. "Unknown",
  3635. RegionInfo.RegionName);
  3636. });
  3637. break;
  3638. }
  3639. }
  3640. #region Script Handling Methods
  3641. /// <summary>
  3642. /// Console command handler to send script command to script engine.
  3643. /// </summary>
  3644. /// <param name="args"></param>
  3645. public void SendCommandToPlugins(string[] args)
  3646. {
  3647. m_eventManager.TriggerOnPluginConsole(args);
  3648. }
  3649. public LandData GetLandData(float x, float y)
  3650. {
  3651. return LandChannel.GetLandObject(x, y).LandData;
  3652. }
  3653. public LandData GetLandData(uint x, uint y)
  3654. {
  3655. m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  3656. return LandChannel.GetLandObject((int)x, (int)y).LandData;
  3657. }
  3658. #endregion
  3659. #region Script Engine
  3660. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  3661. public bool DumpAssetsToFile;
  3662. /// <summary>
  3663. ///
  3664. /// </summary>
  3665. /// <param name="scriptEngine"></param>
  3666. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  3667. {
  3668. ScriptEngines.Add(scriptEngine);
  3669. scriptEngine.InitializeEngine(this);
  3670. }
  3671. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  3672. {
  3673. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  3674. if (part != null)
  3675. {
  3676. if (parcel != null)
  3677. {
  3678. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  3679. {
  3680. return true;
  3681. }
  3682. else if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  3683. {
  3684. if (part.OwnerID == parcel.LandData.OwnerID
  3685. || (parcel.LandData.IsGroupOwned && part.GroupID == parcel.LandData.GroupID)
  3686. || Permissions.IsGod(part.OwnerID))
  3687. {
  3688. return true;
  3689. }
  3690. else
  3691. {
  3692. return false;
  3693. }
  3694. }
  3695. else
  3696. {
  3697. if (part.OwnerID == parcel.LandData.OwnerID)
  3698. {
  3699. return true;
  3700. }
  3701. else
  3702. {
  3703. return false;
  3704. }
  3705. }
  3706. }
  3707. else
  3708. {
  3709. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  3710. {
  3711. // The only time parcel != null when an object is inside a region is when
  3712. // there is nothing behind the landchannel. IE, no land plugin loaded.
  3713. return true;
  3714. }
  3715. else
  3716. {
  3717. // The object is outside of this region. Stop piping events to it.
  3718. return false;
  3719. }
  3720. }
  3721. }
  3722. else
  3723. {
  3724. return false;
  3725. }
  3726. }
  3727. public bool ScriptDanger(uint localID, Vector3 pos)
  3728. {
  3729. SceneObjectPart part = GetSceneObjectPart(localID);
  3730. if (part != null)
  3731. {
  3732. return ScriptDanger(part, pos);
  3733. }
  3734. else
  3735. {
  3736. return false;
  3737. }
  3738. }
  3739. public bool PipeEventsForScript(uint localID)
  3740. {
  3741. SceneObjectPart part = GetSceneObjectPart(localID);
  3742. if (part != null)
  3743. {
  3744. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  3745. // their scripts will actually run.
  3746. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  3747. SceneObjectPart parent = part.ParentGroup.RootPart;
  3748. if (parent != null && parent.IsAttachment)
  3749. return ScriptDanger(parent, parent.GetWorldPosition());
  3750. else
  3751. return ScriptDanger(part, part.GetWorldPosition());
  3752. }
  3753. else
  3754. {
  3755. return false;
  3756. }
  3757. }
  3758. #endregion
  3759. #region SceneGraph wrapper methods
  3760. /// <summary>
  3761. ///
  3762. /// </summary>
  3763. /// <param name="localID"></param>
  3764. /// <returns></returns>
  3765. public UUID ConvertLocalIDToFullID(uint localID)
  3766. {
  3767. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  3768. }
  3769. public void SwapRootAgentCount(bool rootChildChildRootTF)
  3770. {
  3771. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  3772. }
  3773. public void AddPhysicalPrim(int num)
  3774. {
  3775. m_sceneGraph.AddPhysicalPrim(num);
  3776. }
  3777. public void RemovePhysicalPrim(int num)
  3778. {
  3779. m_sceneGraph.RemovePhysicalPrim(num);
  3780. }
  3781. public int GetRootAgentCount()
  3782. {
  3783. return m_sceneGraph.GetRootAgentCount();
  3784. }
  3785. public int GetChildAgentCount()
  3786. {
  3787. return m_sceneGraph.GetChildAgentCount();
  3788. }
  3789. /// <summary>
  3790. /// Request a scene presence by UUID. Fast, indexed lookup.
  3791. /// </summary>
  3792. /// <param name="agentID"></param>
  3793. /// <returns>null if the presence was not found</returns>
  3794. public ScenePresence GetScenePresence(UUID agentID)
  3795. {
  3796. return m_sceneGraph.GetScenePresence(agentID);
  3797. }
  3798. /// <summary>
  3799. /// Request the scene presence by name.
  3800. /// </summary>
  3801. /// <param name="firstName"></param>
  3802. /// <param name="lastName"></param>
  3803. /// <returns>null if the presence was not found</returns>
  3804. public ScenePresence GetScenePresence(string firstName, string lastName)
  3805. {
  3806. return m_sceneGraph.GetScenePresence(firstName, lastName);
  3807. }
  3808. /// <summary>
  3809. /// Request the scene presence by localID.
  3810. /// </summary>
  3811. /// <param name="localID"></param>
  3812. /// <returns>null if the presence was not found</returns>
  3813. public ScenePresence GetScenePresence(uint localID)
  3814. {
  3815. return m_sceneGraph.GetScenePresence(localID);
  3816. }
  3817. public override bool PresenceChildStatus(UUID avatarID)
  3818. {
  3819. ScenePresence cp = GetScenePresence(avatarID);
  3820. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  3821. // This needs to be fixed properly by cleaning up the logout code.
  3822. //if (cp != null)
  3823. // return cp.IsChildAgent;
  3824. //return false;
  3825. return cp.IsChildAgent;
  3826. }
  3827. /// <summary>
  3828. /// Performs action on all scene presences.
  3829. /// </summary>
  3830. /// <param name="action"></param>
  3831. public void ForEachScenePresence(Action<ScenePresence> action)
  3832. {
  3833. if (m_sceneGraph != null)
  3834. {
  3835. m_sceneGraph.ForEachScenePresence(action);
  3836. }
  3837. }
  3838. /// <summary>
  3839. ///
  3840. /// </summary>
  3841. /// <param name="action"></param>
  3842. // public void ForEachObject(Action<SceneObjectGroup> action)
  3843. // {
  3844. // List<SceneObjectGroup> presenceList;
  3845. //
  3846. // lock (m_sceneObjects)
  3847. // {
  3848. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  3849. // }
  3850. //
  3851. // foreach (SceneObjectGroup presence in presenceList)
  3852. // {
  3853. // action(presence);
  3854. // }
  3855. // }
  3856. /// <summary>
  3857. /// Get a named prim contained in this scene (will return the first
  3858. /// found, if there are more than one prim with the same name)
  3859. /// </summary>
  3860. /// <param name="name"></param>
  3861. /// <returns></returns>
  3862. public SceneObjectPart GetSceneObjectPart(string name)
  3863. {
  3864. return m_sceneGraph.GetSceneObjectPart(name);
  3865. }
  3866. /// <summary>
  3867. /// Get a prim via its local id
  3868. /// </summary>
  3869. /// <param name="localID"></param>
  3870. /// <returns></returns>
  3871. public SceneObjectPart GetSceneObjectPart(uint localID)
  3872. {
  3873. return m_sceneGraph.GetSceneObjectPart(localID);
  3874. }
  3875. /// <summary>
  3876. /// Get a prim via its UUID
  3877. /// </summary>
  3878. /// <param name="fullID"></param>
  3879. /// <returns></returns>
  3880. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  3881. {
  3882. return m_sceneGraph.GetSceneObjectPart(fullID);
  3883. }
  3884. /// <summary>
  3885. /// Get a scene object group that contains the prim with the given local id
  3886. /// </summary>
  3887. /// <param name="localID"></param>
  3888. /// <returns>null if no scene object group containing that prim is found</returns>
  3889. public SceneObjectGroup GetGroupByPrim(uint localID)
  3890. {
  3891. return m_sceneGraph.GetGroupByPrim(localID);
  3892. }
  3893. public override bool TryGetScenePresence(UUID avatarId, out ScenePresence avatar)
  3894. {
  3895. return m_sceneGraph.TryGetScenePresence(avatarId, out avatar);
  3896. }
  3897. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  3898. {
  3899. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  3900. }
  3901. public void ForEachClient(Action<IClientAPI> action)
  3902. {
  3903. m_clientManager.ForEachSync(action);
  3904. }
  3905. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  3906. {
  3907. return m_clientManager.TryGetValue(avatarID, out client);
  3908. }
  3909. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  3910. {
  3911. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  3912. }
  3913. public void ForEachSOG(Action<SceneObjectGroup> action)
  3914. {
  3915. m_sceneGraph.ForEachSOG(action);
  3916. }
  3917. /// <summary>
  3918. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  3919. /// will not affect the original list of objects in the scene.
  3920. /// </summary>
  3921. /// <returns></returns>
  3922. public List<EntityBase> GetEntities()
  3923. {
  3924. return m_sceneGraph.GetEntities();
  3925. }
  3926. #endregion
  3927. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  3928. {
  3929. ulong handle = 0;
  3930. if (regionID == RegionInfo.RegionID)
  3931. handle = RegionInfo.RegionHandle;
  3932. else
  3933. {
  3934. GridRegion r = GridService.GetRegionByUUID(UUID.Zero, regionID);
  3935. if (r != null)
  3936. handle = r.RegionHandle;
  3937. }
  3938. if (handle != 0)
  3939. client.SendRegionHandle(regionID, handle);
  3940. }
  3941. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  3942. {
  3943. //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  3944. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  3945. }
  3946. public void SetRootAgentScene(UUID agentID)
  3947. {
  3948. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3949. if (inv == null)
  3950. return;
  3951. inv.SetRootAgentScene(agentID, this);
  3952. EventManager.TriggerSetRootAgentScene(agentID, this);
  3953. }
  3954. public bool NeedSceneCacheClear(UUID agentID)
  3955. {
  3956. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3957. if (inv == null)
  3958. return true;
  3959. return inv.NeedSceneCacheClear(agentID, this);
  3960. }
  3961. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  3962. {
  3963. SceneObjectPart part = GetSceneObjectPart(localID);
  3964. if (part == null || part.ParentGroup == null)
  3965. return;
  3966. if (part.ParentGroup.IsDeleted)
  3967. return;
  3968. part = part.ParentGroup.RootPart;
  3969. part.ObjectSaleType = saleType;
  3970. part.SalePrice = salePrice;
  3971. part.ParentGroup.HasGroupChanged = true;
  3972. part.GetProperties(client);
  3973. }
  3974. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  3975. uint localID, byte saleType)
  3976. {
  3977. SceneObjectPart part = GetSceneObjectPart(localID);
  3978. if (part == null)
  3979. return false;
  3980. if (part.ParentGroup == null)
  3981. return false;
  3982. SceneObjectGroup group = part.ParentGroup;
  3983. switch (saleType)
  3984. {
  3985. case 1: // Sell as original (in-place sale)
  3986. uint effectivePerms=group.GetEffectivePermissions();
  3987. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  3988. {
  3989. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  3990. return false;
  3991. }
  3992. group.SetOwnerId(remoteClient.AgentId);
  3993. group.SetRootPartOwner(part, remoteClient.AgentId,
  3994. remoteClient.ActiveGroupId);
  3995. List<SceneObjectPart> partList =
  3996. new List<SceneObjectPart>(group.Children.Values);
  3997. if (Permissions.PropagatePermissions())
  3998. {
  3999. foreach (SceneObjectPart child in partList)
  4000. {
  4001. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  4002. child.TriggerScriptChangedEvent(Changed.OWNER);
  4003. child.ApplyNextOwnerPermissions();
  4004. }
  4005. }
  4006. part.ObjectSaleType = 0;
  4007. part.SalePrice = 10;
  4008. group.HasGroupChanged = true;
  4009. part.GetProperties(remoteClient);
  4010. part.TriggerScriptChangedEvent(Changed.OWNER);
  4011. group.ResumeScripts();
  4012. part.ScheduleFullUpdate();
  4013. break;
  4014. case 2: // Sell a copy
  4015. Vector3 inventoryStoredPosition = new Vector3
  4016. (((group.AbsolutePosition.X > (int)Constants.RegionSize)
  4017. ? 250
  4018. : group.AbsolutePosition.X)
  4019. ,
  4020. (group.AbsolutePosition.X > (int)Constants.RegionSize)
  4021. ? 250
  4022. : group.AbsolutePosition.X,
  4023. group.AbsolutePosition.Z);
  4024. Vector3 originalPosition = group.AbsolutePosition;
  4025. group.AbsolutePosition = inventoryStoredPosition;
  4026. string sceneObjectXml = SceneObjectSerializer.ToOriginalXmlFormat(group);
  4027. group.AbsolutePosition = originalPosition;
  4028. uint perms=group.GetEffectivePermissions();
  4029. if ((perms & (uint)PermissionMask.Transfer) == 0)
  4030. {
  4031. m_dialogModule.SendAlertToUser(remoteClient, "This item doesn't appear to be for sale");
  4032. return false;
  4033. }
  4034. AssetBase asset = CreateAsset(
  4035. group.GetPartName(localID),
  4036. group.GetPartDescription(localID),
  4037. (sbyte)AssetType.Object,
  4038. Utils.StringToBytes(sceneObjectXml),
  4039. group.OwnerID);
  4040. AssetService.Store(asset);
  4041. InventoryItemBase item = new InventoryItemBase();
  4042. item.CreatorId = part.CreatorID.ToString();
  4043. item.ID = UUID.Random();
  4044. item.Owner = remoteClient.AgentId;
  4045. item.AssetID = asset.FullID;
  4046. item.Description = asset.Description;
  4047. item.Name = asset.Name;
  4048. item.AssetType = asset.Type;
  4049. item.InvType = (int)InventoryType.Object;
  4050. item.Folder = categoryID;
  4051. uint nextPerms=(perms & 7) << 13;
  4052. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  4053. perms &= ~(uint)PermissionMask.Copy;
  4054. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  4055. perms &= ~(uint)PermissionMask.Transfer;
  4056. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  4057. perms &= ~(uint)PermissionMask.Modify;
  4058. item.BasePermissions = perms & part.NextOwnerMask;
  4059. item.CurrentPermissions = perms & part.NextOwnerMask;
  4060. item.NextPermissions = part.NextOwnerMask;
  4061. item.EveryOnePermissions = part.EveryoneMask &
  4062. part.NextOwnerMask;
  4063. item.GroupPermissions = part.GroupMask &
  4064. part.NextOwnerMask;
  4065. item.CurrentPermissions |= 16; // Slam!
  4066. item.CreationDate = Util.UnixTimeSinceEpoch();
  4067. if (InventoryService.AddItem(item))
  4068. remoteClient.SendInventoryItemCreateUpdate(item, 0);
  4069. else
  4070. {
  4071. m_dialogModule.SendAlertToUser(remoteClient, "Cannot buy now. Your inventory is unavailable");
  4072. return false;
  4073. }
  4074. break;
  4075. case 3: // Sell contents
  4076. List<UUID> invList = part.Inventory.GetInventoryList();
  4077. bool okToSell = true;
  4078. foreach (UUID invID in invList)
  4079. {
  4080. TaskInventoryItem item1 = part.Inventory.GetInventoryItem(invID);
  4081. if ((item1.CurrentPermissions &
  4082. (uint)PermissionMask.Transfer) == 0)
  4083. {
  4084. okToSell = false;
  4085. break;
  4086. }
  4087. }
  4088. if (!okToSell)
  4089. {
  4090. m_dialogModule.SendAlertToUser(
  4091. remoteClient, "This item's inventory doesn't appear to be for sale");
  4092. return false;
  4093. }
  4094. if (invList.Count > 0)
  4095. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  4096. part, invList);
  4097. break;
  4098. }
  4099. return true;
  4100. }
  4101. public void CleanTempObjects()
  4102. {
  4103. List<EntityBase> objs = GetEntities();
  4104. foreach (EntityBase obj in objs)
  4105. {
  4106. if (obj is SceneObjectGroup)
  4107. {
  4108. SceneObjectGroup grp = (SceneObjectGroup)obj;
  4109. if (!grp.IsDeleted)
  4110. {
  4111. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4112. {
  4113. if (grp.RootPart.Expires <= DateTime.Now)
  4114. DeleteSceneObject(grp, false);
  4115. }
  4116. }
  4117. }
  4118. }
  4119. }
  4120. public void DeleteFromStorage(UUID uuid)
  4121. {
  4122. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  4123. }
  4124. public int GetHealth()
  4125. {
  4126. // Returns:
  4127. // 1 = sim is up and accepting http requests. The heartbeat has
  4128. // stopped and the sim is probably locked up, but a remote
  4129. // admin restart may succeed
  4130. //
  4131. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4132. // usable for people within and logins _may_ work
  4133. //
  4134. // 3 = We have seen a new user enter within the past 4 minutes
  4135. // which can be seen as positive confirmation of sim health
  4136. //
  4137. int health=1; // Start at 1, means we're up
  4138. if ((Util.EnvironmentTickCountSubtract(m_lastUpdate)) < 1000)
  4139. health+=1;
  4140. else
  4141. return health;
  4142. // A login in the last 4 mins? We can't be doing too badly
  4143. //
  4144. if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000)
  4145. health++;
  4146. else
  4147. return health;
  4148. CheckHeartbeat();
  4149. return health;
  4150. }
  4151. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4152. // update non-physical objects like the joint proxy objects that represent the position
  4153. // of the joints in the scene.
  4154. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4155. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4156. // from within the OdePhysicsScene.
  4157. protected internal void jointMoved(PhysicsJoint joint)
  4158. {
  4159. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  4160. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4161. if (jointProxyObject == null)
  4162. {
  4163. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  4164. return;
  4165. }
  4166. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  4167. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  4168. 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.
  4169. jointProxyObject.Velocity = trackedBody.Velocity;
  4170. jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
  4171. switch (joint.Type)
  4172. {
  4173. case PhysicsJointType.Ball:
  4174. {
  4175. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4176. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  4177. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4178. }
  4179. break;
  4180. case PhysicsJointType.Hinge:
  4181. {
  4182. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4183. // Normally, we would just ask the physics scene to return the axis for the joint.
  4184. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  4185. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  4186. // Therefore the following call does not always work:
  4187. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  4188. // instead we compute the joint orientation by saving the original joint orientation
  4189. // relative to one of the jointed bodies, and applying this transformation
  4190. // to the current position of the jointed bodies (the tracked body) to compute the
  4191. // current joint orientation.
  4192. if (joint.TrackedBodyName == null)
  4193. {
  4194. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  4195. }
  4196. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  4197. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  4198. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4199. jointProxyObject.ParentGroup.UpdateGroupRotationR(q); // schedules the entire group for a terse update
  4200. }
  4201. break;
  4202. }
  4203. }
  4204. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4205. // update non-physical objects like the joint proxy objects that represent the position
  4206. // of the joints in the scene.
  4207. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4208. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4209. // from within the OdePhysicsScene.
  4210. protected internal void jointDeactivated(PhysicsJoint joint)
  4211. {
  4212. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  4213. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4214. if (jointProxyObject == null)
  4215. {
  4216. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  4217. return;
  4218. }
  4219. // turn the proxy non-physical, which also stops its client-side interpolation
  4220. bool wasUsingPhysics = ((jointProxyObject.ObjectFlags & (uint)PrimFlags.Physics) != 0);
  4221. if (wasUsingPhysics)
  4222. {
  4223. 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
  4224. }
  4225. }
  4226. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4227. // alert the user of errors by using the debug channel in the same way that scripts alert
  4228. // the user of compile errors.
  4229. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4230. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4231. // from within the OdePhysicsScene.
  4232. public void jointErrorMessage(PhysicsJoint joint, string message)
  4233. {
  4234. if (joint != null)
  4235. {
  4236. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4237. return;
  4238. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4239. if (jointProxyObject != null)
  4240. {
  4241. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  4242. ChatTypeEnum.DebugChannel,
  4243. 2147483647,
  4244. jointProxyObject.AbsolutePosition,
  4245. jointProxyObject.Name,
  4246. jointProxyObject.UUID,
  4247. false);
  4248. joint.ErrorMessageCount++;
  4249. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4250. {
  4251. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  4252. ChatTypeEnum.DebugChannel,
  4253. 2147483647,
  4254. jointProxyObject.AbsolutePosition,
  4255. jointProxyObject.Name,
  4256. jointProxyObject.UUID,
  4257. false);
  4258. }
  4259. }
  4260. else
  4261. {
  4262. // couldn't find the joint proxy object; the error message is silently suppressed
  4263. }
  4264. }
  4265. }
  4266. public Scene ConsoleScene()
  4267. {
  4268. if (MainConsole.Instance == null)
  4269. return null;
  4270. if (MainConsole.Instance.ConsoleScene is Scene)
  4271. return (Scene)MainConsole.Instance.ConsoleScene;
  4272. return null;
  4273. }
  4274. public float GetGroundHeight(float x, float y)
  4275. {
  4276. if (x < 0)
  4277. x = 0;
  4278. if (x >= Heightmap.Width)
  4279. x = Heightmap.Width - 1;
  4280. if (y < 0)
  4281. y = 0;
  4282. if (y >= Heightmap.Height)
  4283. y = Heightmap.Height - 1;
  4284. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  4285. Vector3 p1 = new Vector3(p0);
  4286. Vector3 p2 = new Vector3(p0);
  4287. p1.X += 1.0f;
  4288. if (p1.X < Heightmap.Width)
  4289. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  4290. p2.Y += 1.0f;
  4291. if (p2.Y < Heightmap.Height)
  4292. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  4293. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  4294. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  4295. v0.Normalize();
  4296. v1.Normalize();
  4297. Vector3 vsn = new Vector3();
  4298. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  4299. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  4300. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  4301. vsn.Normalize();
  4302. float xdiff = x - (float)((int)x);
  4303. float ydiff = y - (float)((int)y);
  4304. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  4305. }
  4306. private void CheckHeartbeat()
  4307. {
  4308. if (m_firstHeartbeat)
  4309. return;
  4310. if (Util.EnvironmentTickCountSubtract(m_lastUpdate) > 2000)
  4311. StartTimer();
  4312. }
  4313. public override ISceneObject DeserializeObject(string representation)
  4314. {
  4315. return SceneObjectSerializer.FromXml2Format(representation);
  4316. }
  4317. public override bool AllowScriptCrossings
  4318. {
  4319. get { return m_allowScriptCrossings; }
  4320. }
  4321. public Vector3? GetNearestAllowedPosition(ScenePresence avatar)
  4322. {
  4323. //simulate to make sure we have pretty up to date positions
  4324. PhysicsScene.Simulate(0);
  4325. ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y);
  4326. if (nearestParcel != null)
  4327. {
  4328. Vector3 dir = Vector3.Normalize(Vector3.Multiply(avatar.Velocity, -1));
  4329. //Try to get a location that feels like where they came from
  4330. Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
  4331. if (nearestPoint != null)
  4332. {
  4333. Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
  4334. return nearestPoint.Value;
  4335. }
  4336. //Sometimes velocity might be zero (local teleport), so try finding point along path from avatar to center of nearest parcel
  4337. Vector3 directionToParcelCenter = Vector3.Subtract(GetParcelCenterAtGround(nearestParcel), avatar.AbsolutePosition);
  4338. dir = Vector3.Normalize(directionToParcelCenter);
  4339. nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
  4340. if (nearestPoint != null)
  4341. {
  4342. Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
  4343. return nearestPoint.Value;
  4344. }
  4345. //Ultimate backup if we have no idea where they are
  4346. Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
  4347. return avatar.lastKnownAllowedPosition;
  4348. }
  4349. //Go to the edge, this happens in teleporting to a region with no available parcels
  4350. Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
  4351. //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
  4352. return nearestRegionEdgePoint;
  4353. return null;
  4354. }
  4355. private Vector3 GetParcelCenterAtGround(ILandObject parcel)
  4356. {
  4357. Vector2 center = GetParcelCenter(parcel);
  4358. return GetPositionAtGround(center.X, center.Y);
  4359. }
  4360. private Vector3? GetNearestPointInParcelAlongDirectionFromPoint(Vector3 pos, Vector3 direction, ILandObject parcel)
  4361. {
  4362. Vector3 unitDirection = Vector3.Normalize(direction);
  4363. //Making distance to search go through some sane limit of distance
  4364. for (float distance = 0; distance < Constants.RegionSize * 2; distance += .5f)
  4365. {
  4366. Vector3 testPos = Vector3.Add(pos, Vector3.Multiply(unitDirection, distance));
  4367. if (parcel.ContainsPoint((int)testPos.X, (int)testPos.Y))
  4368. {
  4369. return testPos;
  4370. }
  4371. }
  4372. return null;
  4373. }
  4374. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
  4375. {
  4376. List<ILandObject> all = AllParcels();
  4377. float minParcelDistance = float.MaxValue;
  4378. ILandObject nearestParcel = null;
  4379. foreach (var parcel in all)
  4380. {
  4381. if (!parcel.IsEitherBannedOrRestricted(avatarId))
  4382. {
  4383. float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
  4384. if (parcelDistance < minParcelDistance)
  4385. {
  4386. minParcelDistance = parcelDistance;
  4387. nearestParcel = parcel;
  4388. }
  4389. }
  4390. }
  4391. return nearestParcel;
  4392. }
  4393. private List<ILandObject> AllParcels()
  4394. {
  4395. return LandChannel.AllParcels();
  4396. }
  4397. private float GetParcelDistancefromPoint(ILandObject parcel, float x, float y)
  4398. {
  4399. return Vector2.Distance(new Vector2(x, y), GetParcelCenter(parcel));
  4400. }
  4401. //calculate the average center point of a parcel
  4402. private Vector2 GetParcelCenter(ILandObject parcel)
  4403. {
  4404. int count = 0;
  4405. int avgx = 0;
  4406. int avgy = 0;
  4407. for (int x = 0; x < Constants.RegionSize; x++)
  4408. {
  4409. for (int y = 0; y < Constants.RegionSize; y++)
  4410. {
  4411. //Just keep a running average as we check if all the points are inside or not
  4412. if (parcel.ContainsPoint(x, y))
  4413. {
  4414. if (count == 0)
  4415. {
  4416. avgx = x;
  4417. avgy = y;
  4418. }
  4419. else
  4420. {
  4421. avgx = (avgx * count + x) / (count + 1);
  4422. avgy = (avgy * count + y) / (count + 1);
  4423. }
  4424. count += 1;
  4425. }
  4426. }
  4427. }
  4428. return new Vector2(avgx, avgy);
  4429. }
  4430. private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
  4431. {
  4432. float xdistance = avatar.AbsolutePosition.X < Constants.RegionSize / 2 ? avatar.AbsolutePosition.X : Constants.RegionSize - avatar.AbsolutePosition.X;
  4433. float ydistance = avatar.AbsolutePosition.Y < Constants.RegionSize / 2 ? avatar.AbsolutePosition.Y : Constants.RegionSize - avatar.AbsolutePosition.Y;
  4434. //find out what vertical edge to go to
  4435. if (xdistance < ydistance)
  4436. {
  4437. if (avatar.AbsolutePosition.X < Constants.RegionSize / 2)
  4438. {
  4439. return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.0f, avatar.AbsolutePosition.Y);
  4440. }
  4441. else
  4442. {
  4443. return GetPositionAtAvatarHeightOrGroundHeight(avatar, Constants.RegionSize, avatar.AbsolutePosition.Y);
  4444. }
  4445. }
  4446. //find out what horizontal edge to go to
  4447. else
  4448. {
  4449. if (avatar.AbsolutePosition.Y < Constants.RegionSize / 2)
  4450. {
  4451. return GetPositionAtAvatarHeightOrGroundHeight(avatar, avatar.AbsolutePosition.X, 0.0f);
  4452. }
  4453. else
  4454. {
  4455. return GetPositionAtAvatarHeightOrGroundHeight(avatar, avatar.AbsolutePosition.X, Constants.RegionSize);
  4456. }
  4457. }
  4458. }
  4459. private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
  4460. {
  4461. Vector3 ground = GetPositionAtGround(x, y);
  4462. if (avatar.AbsolutePosition.Z > ground.Z)
  4463. {
  4464. ground.Z = avatar.AbsolutePosition.Z;
  4465. }
  4466. return ground;
  4467. }
  4468. private Vector3 GetPositionAtGround(float x, float y)
  4469. {
  4470. return new Vector3(x, y, GetGroundHeight(x, y));
  4471. }
  4472. public List<UUID> GetEstateRegions(int estateID)
  4473. {
  4474. if (m_storageManager.EstateDataStore == null)
  4475. return new List<UUID>();
  4476. return m_storageManager.EstateDataStore.GetRegions(estateID);
  4477. }
  4478. public void ReloadEstateData()
  4479. {
  4480. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID, false);
  4481. TriggerEstateSunUpdate();
  4482. }
  4483. public void TriggerEstateSunUpdate()
  4484. {
  4485. float sun;
  4486. if (RegionInfo.RegionSettings.UseEstateSun)
  4487. {
  4488. sun = (float)RegionInfo.EstateSettings.SunPosition;
  4489. if (RegionInfo.EstateSettings.UseGlobalTime)
  4490. {
  4491. sun = EventManager.GetCurrentTimeAsSunLindenHour() - 6.0f;
  4492. }
  4493. //
  4494. EventManager.TriggerEstateToolsSunUpdate(
  4495. RegionInfo.RegionHandle,
  4496. RegionInfo.EstateSettings.FixedSun,
  4497. RegionInfo.RegionSettings.UseEstateSun,
  4498. sun);
  4499. }
  4500. else
  4501. {
  4502. // Use the Sun Position from the Region Settings
  4503. sun = (float)RegionInfo.RegionSettings.SunPosition - 6.0f;
  4504. EventManager.TriggerEstateToolsSunUpdate(
  4505. RegionInfo.RegionHandle,
  4506. RegionInfo.RegionSettings.FixedSun,
  4507. RegionInfo.RegionSettings.UseEstateSun,
  4508. sun);
  4509. }
  4510. }
  4511. private void HandleReloadEstate(string module, string[] cmd)
  4512. {
  4513. if (MainConsole.Instance.ConsoleScene == null ||
  4514. (MainConsole.Instance.ConsoleScene is Scene &&
  4515. (Scene)MainConsole.Instance.ConsoleScene == this))
  4516. {
  4517. ReloadEstateData();
  4518. }
  4519. }
  4520. public Vector3[] GetCombinedBoundingBox(List<SceneObjectGroup> objects, out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  4521. {
  4522. minX = 256;
  4523. maxX = -256;
  4524. minY = 256;
  4525. maxY = -256;
  4526. minZ = 8192;
  4527. maxZ = -256;
  4528. List<Vector3> offsets = new List<Vector3>();
  4529. foreach (SceneObjectGroup g in objects)
  4530. {
  4531. float ominX, ominY, ominZ, omaxX, omaxY, omaxZ;
  4532. g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ);
  4533. if (minX > ominX)
  4534. minX = ominX;
  4535. if (minY > ominY)
  4536. minY = ominY;
  4537. if (minZ > ominZ)
  4538. minZ = ominZ;
  4539. if (maxX < omaxX)
  4540. maxX = omaxX;
  4541. if (maxY < omaxY)
  4542. maxY = omaxY;
  4543. if (maxZ < omaxZ)
  4544. maxZ = omaxZ;
  4545. }
  4546. foreach (SceneObjectGroup g in objects)
  4547. {
  4548. Vector3 vec = g.AbsolutePosition;
  4549. vec.X -= minX;
  4550. vec.Y -= minY;
  4551. vec.Z -= minZ;
  4552. offsets.Add(vec);
  4553. }
  4554. return offsets.ToArray();
  4555. }
  4556. }
  4557. }