Scene.cs 178 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418
  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 OpenSim 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.Drawing;
  30. using System.Drawing.Imaging;
  31. using System.IO;
  32. using System.Xml;
  33. using System.Threading;
  34. using System.Timers;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Imaging;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Communications;
  40. using OpenSim.Framework.Communications.Cache;
  41. using OpenSim.Framework.Servers;
  42. using OpenSim.Region.Environment.Interfaces;
  43. using OpenSim.Region.Interfaces;
  44. using OpenSim.Region.Environment.Modules.World.Terrain;
  45. using OpenSim.Region.Environment.Scenes.Scripting;
  46. using OpenSim.Region.Physics.Manager;
  47. using Nini.Config;
  48. using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
  49. using Image = System.Drawing.Image;
  50. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  51. using Timer = System.Timers.Timer;
  52. using OSD = OpenMetaverse.StructuredData.OSD;
  53. namespace OpenSim.Region.Environment.Scenes
  54. {
  55. public delegate bool FilterAvatarList(ScenePresence avatar);
  56. public partial class Scene : SceneBase
  57. {
  58. public delegate void SynchronizeSceneHandler(Scene scene);
  59. public SynchronizeSceneHandler SynchronizeScene = null;
  60. public int splitID = 0;
  61. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  62. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  63. #region Fields
  64. protected Timer m_restartWaitTimer = new Timer();
  65. protected SimStatsReporter m_statsReporter;
  66. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  67. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  68. /// <value>
  69. /// The scene graph for this scene
  70. /// </value>
  71. /// TODO: Possibly stop other classes being able to manipulate this directly.
  72. public SceneGraph m_sceneGraph;
  73. private int m_timePhase = 24;
  74. /// <summary>
  75. /// Are we applying physics to any of the prims in this scene?
  76. /// </summary>
  77. public bool m_physicalPrim;
  78. public float m_maxNonphys = 65536;
  79. public float m_maxPhys = 10;
  80. public bool m_clampPrimSize = false;
  81. public bool m_trustBinaries = false;
  82. public bool m_allowScriptCrossings = false;
  83. public bool m_seeIntoRegionFromNeighbor;
  84. public int MaxUndoCount = 5;
  85. private int m_RestartTimerCounter;
  86. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  87. private int m_incrementsof15seconds = 0;
  88. private volatile bool m_backingup = false;
  89. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  90. protected string m_simulatorVersion = "OpenSimulator Server";
  91. protected ModuleLoader m_moduleLoader;
  92. protected StorageManager m_storageManager;
  93. protected AgentCircuitManager m_authenticateHandler;
  94. public CommunicationsManager CommsManager;
  95. protected SceneCommunicationService m_sceneGridService;
  96. public SceneCommunicationService SceneGridService
  97. {
  98. get { return m_sceneGridService; }
  99. }
  100. /// <summary>
  101. /// Each agent has its own capabilities handler.
  102. /// </summary>
  103. protected Dictionary<UUID, Caps> m_capsHandlers = new Dictionary<UUID, Caps>();
  104. protected BaseHttpServer m_httpListener;
  105. /// <value>
  106. /// All the region modules attached to this scene.
  107. /// </value>
  108. public Dictionary<string, IRegionModule> Modules
  109. {
  110. get { return m_modules; }
  111. }
  112. protected Dictionary<string, IRegionModule> m_modules = new Dictionary<string, IRegionModule>();
  113. /// <value>
  114. /// The module interfaces available from this scene.
  115. /// </value>
  116. protected Dictionary<Type, List<object> > ModuleInterfaces = new Dictionary<Type, List<object> >();
  117. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  118. protected Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
  119. //API module interfaces
  120. public IXfer XferManager;
  121. protected IHttpRequests m_httpRequestModule;
  122. protected IXMLRPC m_xmlrpcModule;
  123. protected IWorldComm m_worldCommModule;
  124. protected IAvatarFactory m_AvatarFactory;
  125. protected IConfigSource m_config;
  126. protected IRegionSerialiserModule m_serialiser;
  127. // Central Update Loop
  128. protected int m_fps = 10;
  129. protected int m_frame = 0;
  130. protected float m_timespan = 0.089f;
  131. protected DateTime m_lastupdate = DateTime.Now;
  132. protected float m_timedilation = 1.0f;
  133. private int m_update_physics = 1;
  134. private int m_update_entitymovement = 1;
  135. private int m_update_entities = 1; // Run through all objects checking for updates
  136. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  137. private int m_update_presences = 1; // Update scene presence movements
  138. private int m_update_events = 1;
  139. private int m_update_backup = 200;
  140. private int m_update_terrain = 50;
  141. private int m_update_land = 1;
  142. private int frameMS = 0;
  143. private int physicsMS2 = 0;
  144. private int physicsMS = 0;
  145. private int otherMS = 0;
  146. private bool m_physics_enabled = true;
  147. private bool m_scripts_enabled = true;
  148. private string m_defaultScriptEngine;
  149. private int m_LastLogin = 0;
  150. private Thread HeartbeatThread;
  151. private volatile bool shuttingdown = false;
  152. private object m_deleting_scene_object = new object();
  153. // the minimum time that must elapse before a changed object will be considered for persisted
  154. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  155. // the maximum time that must elapse before a changed object will be considered for persisted
  156. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  157. #endregion
  158. #region Properties
  159. public AgentCircuitManager AuthenticateHandler
  160. {
  161. get { return m_authenticateHandler; }
  162. }
  163. // an instance to the physics plugin's Scene object.
  164. public PhysicsScene PhysicsScene
  165. {
  166. set { m_sceneGraph.PhysicsScene = value; }
  167. get { return m_sceneGraph.PhysicsScene; }
  168. }
  169. // This gets locked so things stay thread safe.
  170. public object SyncRoot
  171. {
  172. get { return m_sceneGraph.m_syncRoot; }
  173. }
  174. public float TimeDilation
  175. {
  176. get { return m_timedilation; }
  177. }
  178. /// <summary>
  179. /// This is for llGetRegionFPS
  180. /// </summary>
  181. public float SimulatorFPS
  182. {
  183. get { return m_statsReporter.getLastReportedSimFPS(); }
  184. }
  185. public int TimePhase
  186. {
  187. get { return m_timePhase; }
  188. }
  189. public string DefaultScriptEngine
  190. {
  191. get { return m_defaultScriptEngine; }
  192. }
  193. // Local reference to the objects in the scene (which are held in the scenegraph)
  194. // public Dictionary<UUID, SceneObjectGroup> Objects
  195. // {
  196. // get { return m_sceneGraph.SceneObjects; }
  197. // }
  198. // Reference to all of the agents in the scene (root and child)
  199. protected Dictionary<UUID, ScenePresence> m_scenePresences
  200. {
  201. get { return m_sceneGraph.ScenePresences; }
  202. set { m_sceneGraph.ScenePresences = value; }
  203. }
  204. // protected Dictionary<UUID, SceneObjectGroup> m_sceneObjects
  205. // {
  206. // get { return m_sceneGraph.SceneObjects; }
  207. // set { m_sceneGraph.SceneObjects = value; }
  208. // }
  209. public EntityManager Entities
  210. {
  211. get { return m_sceneGraph.Entities; }
  212. }
  213. public Dictionary<UUID, ScenePresence> m_restorePresences
  214. {
  215. get { return m_sceneGraph.RestorePresences; }
  216. set { m_sceneGraph.RestorePresences = value; }
  217. }
  218. public int objectCapacity = 45000;
  219. /// <value>
  220. /// Registered classes that are capable of creating entities.
  221. /// </value>
  222. protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
  223. #endregion
  224. #region Constructors
  225. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  226. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  227. AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
  228. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  229. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  230. {
  231. m_config = config;
  232. Random random = new Random();
  233. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue/2))+(uint)(uint.MaxValue/4);
  234. m_moduleLoader = moduleLoader;
  235. m_authenticateHandler = authen;
  236. CommsManager = commsMan;
  237. m_sceneGridService = sceneGridService;
  238. m_storageManager = storeManager;
  239. AssetCache = assetCach;
  240. m_regInfo = regInfo;
  241. m_regionHandle = m_regInfo.RegionHandle;
  242. m_regionName = m_regInfo.RegionName;
  243. m_datastore = m_regInfo.DataStore;
  244. m_physicalPrim = physicalPrim;
  245. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  246. m_eventManager = new EventManager();
  247. m_permissions = new ScenePermissions(this);
  248. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  249. m_asyncSceneObjectDeleter.Enabled = true;
  250. // Load region settings
  251. m_regInfo.RegionSettings = m_storageManager.DataStore.LoadRegionSettings(m_regInfo.RegionID);
  252. if (m_storageManager.EstateDataStore != null)
  253. m_regInfo.EstateSettings = m_storageManager.EstateDataStore.LoadEstateSettings(m_regInfo.RegionID);
  254. //Bind Storage Manager functions to some land manager functions for this scene
  255. EventManager.OnLandObjectAdded +=
  256. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  257. EventManager.OnLandObjectRemoved +=
  258. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  259. m_sceneGraph = new SceneGraph(this, m_regInfo);
  260. // If the scene graph has an Unrecoverable error, restart this sim.
  261. // Currently the only thing that causes it to happen is two kinds of specific
  262. // Physics based crashes.
  263. //
  264. // Out of memory
  265. // Operating system has killed the plugin
  266. m_sceneGraph.UnRecoverableError += RestartNow;
  267. RegisterDefaultSceneEvents();
  268. m_httpListener = httpServer;
  269. m_dumpAssetsToFile = dumpAssetsToFile;
  270. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  271. m_physics_enabled = !RegionInfo.RegionSettings.DisablePhysics;
  272. m_statsReporter = new SimStatsReporter(this);
  273. m_statsReporter.OnSendStatsResult += SendSimStatsPackets;
  274. m_statsReporter.SetObjectCapacity(objectCapacity);
  275. m_simulatorVersion = simulatorVersion
  276. + " (OS " + Util.GetOperatingSystemInformation() + ")"
  277. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  278. + " PhysPrim:" + m_physicalPrim.ToString();
  279. try
  280. {
  281. IConfig startupConfig = m_config.Configs["Startup"];
  282. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", 65536.0f);
  283. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", 10.0f);
  284. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", false);
  285. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", false);
  286. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", false);
  287. m_dontPersistBefore =
  288. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  289. m_dontPersistBefore *= 10000000;
  290. m_persistAfter =
  291. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  292. m_persistAfter *= 10000000;
  293. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "DotNetEngine");
  294. }
  295. catch
  296. {
  297. m_log.Warn("[SCENE]: Failed to load StartupConfig");
  298. }
  299. }
  300. #endregion
  301. #region Startup / Close Methods
  302. public bool ShuttingDown
  303. {
  304. get { return shuttingdown; }
  305. }
  306. protected virtual void RegisterDefaultSceneEvents()
  307. {
  308. m_eventManager.OnPermissionError += SendPermissionAlert;
  309. }
  310. public override string GetSimulatorVersion()
  311. {
  312. return m_simulatorVersion;
  313. }
  314. /// <summary>
  315. /// Another region is up. Gets called from Grid Comms:
  316. /// (OGS1 -> LocalBackEnd -> RegionListened -> SceneCommunicationService)
  317. /// We have to tell all our ScenePresences about it, and add it to the
  318. /// neighbor list.
  319. ///
  320. /// We only add it to the neighbor list if it's within 1 region from here.
  321. /// Agents may have draw distance values that cross two regions though, so
  322. /// we add it to the notify list regardless of distance. We'll check
  323. /// the agent's draw distance before notifying them though.
  324. /// </summary>
  325. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  326. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  327. public override bool OtherRegionUp(RegionInfo otherRegion)
  328. {
  329. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  330. {
  331. for (int i = 0; i < m_neighbours.Count; i++)
  332. {
  333. // The purpose of this loop is to re-update the known neighbors
  334. // when another region comes up on top of another one.
  335. // The latest region in that location ends up in the
  336. // 'known neighbors list'
  337. // Additionally, the commFailTF property gets reset to false.
  338. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  339. {
  340. lock (m_neighbours)
  341. {
  342. m_neighbours[i] = otherRegion;
  343. }
  344. }
  345. }
  346. // If the value isn't in the neighbours, add it.
  347. // If the RegionInfo isn't exact but is for the same XY World location,
  348. // then the above loop will fix that.
  349. if (!(CheckNeighborRegion(otherRegion)))
  350. {
  351. lock (m_neighbours)
  352. {
  353. m_neighbours.Add(otherRegion);
  354. //m_log.Info("[UP]: " + otherRegion.RegionHandle.ToString());
  355. }
  356. }
  357. // If these are cast to INT because long + negative values + abs returns invalid data
  358. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  359. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  360. if (resultX <= 1 && resultY <= 1)
  361. {
  362. try
  363. {
  364. ForEachScenePresence(delegate(ScenePresence agent)
  365. {
  366. // If agent is a root agent.
  367. if (!agent.IsChildAgent)
  368. {
  369. //agent.ControllingClient.new
  370. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  371. InformClientOfNeighbor(agent, otherRegion);
  372. }
  373. }
  374. );
  375. }
  376. catch (NullReferenceException)
  377. {
  378. // This means that we're not booted up completely yet.
  379. // This shouldn't happen too often anymore.
  380. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  381. }
  382. }
  383. else
  384. {
  385. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  386. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  387. otherRegion.RegionLocY.ToString() + ")");
  388. }
  389. }
  390. return true;
  391. }
  392. public void AddNeighborRegion(RegionInfo region)
  393. {
  394. lock (m_neighbours)
  395. {
  396. if (!CheckNeighborRegion(region))
  397. {
  398. m_neighbours.Add(region);
  399. }
  400. }
  401. }
  402. public bool CheckNeighborRegion(RegionInfo region)
  403. {
  404. bool found = false;
  405. lock (m_neighbours)
  406. {
  407. foreach (RegionInfo reg in m_neighbours)
  408. {
  409. if (reg.RegionHandle == region.RegionHandle)
  410. {
  411. found = true;
  412. break;
  413. }
  414. }
  415. }
  416. return found;
  417. }
  418. /// <summary>
  419. /// Given float seconds, this will restart the region.
  420. /// </summary>
  421. /// <param name="seconds">float indicating duration before restart.</param>
  422. public virtual void Restart(float seconds)
  423. {
  424. // notifications are done in 15 second increments
  425. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  426. // It's a 'Cancel restart' request.
  427. // RestartNow() does immediate restarting.
  428. if (seconds < 15)
  429. {
  430. m_restartTimer.Stop();
  431. SendGeneralAlert("Restart Aborted");
  432. }
  433. else
  434. {
  435. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  436. m_restartTimer.Interval = 15000;
  437. m_incrementsof15seconds = (int)seconds / 15;
  438. m_RestartTimerCounter = 0;
  439. m_restartTimer.AutoReset = true;
  440. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  441. m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  442. m_restartTimer.Start();
  443. SendRegionMessageFromEstateTools(UUID.Random(), UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  444. //SendGeneralAlert(RegionInfo.RegionName + ": Restarting in 2 Minutes");
  445. }
  446. }
  447. // The Restart timer has occured.
  448. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  449. // have elapsed.
  450. // If they have elapsed, call RestartNow()
  451. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  452. {
  453. m_RestartTimerCounter++;
  454. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  455. {
  456. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  457. SendRegionMessageFromEstateTools(UUID.Random(), UUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " +
  458. ((8 - m_RestartTimerCounter) * 15) + " seconds");
  459. // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) +
  460. //" seconds");
  461. }
  462. else
  463. {
  464. m_restartTimer.Stop();
  465. m_restartTimer.AutoReset = false;
  466. RestartNow();
  467. }
  468. }
  469. // This causes the region to restart immediatley.
  470. public void RestartNow()
  471. {
  472. if (PhysicsScene != null)
  473. {
  474. PhysicsScene.Dispose();
  475. }
  476. m_log.Error("[REGION]: Closing");
  477. Close();
  478. m_log.Error("[REGION]: Firing Region Restart Message");
  479. base.Restart(0);
  480. }
  481. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  482. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  483. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  484. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  485. // subsequently the agent will never see the region come back online.
  486. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  487. {
  488. m_restartWaitTimer.Stop();
  489. lock (m_regionRestartNotifyList)
  490. {
  491. foreach (RegionInfo region in m_regionRestartNotifyList)
  492. {
  493. try
  494. {
  495. ForEachScenePresence(delegate(ScenePresence agent)
  496. {
  497. // If agent is a root agent.
  498. if (!agent.IsChildAgent)
  499. {
  500. //agent.ControllingClient.new
  501. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  502. InformClientOfNeighbor(agent, region);
  503. }
  504. }
  505. );
  506. }
  507. catch (NullReferenceException)
  508. {
  509. // This means that we're not booted up completely yet.
  510. // This shouldn't happen too often anymore.
  511. }
  512. }
  513. // Reset list to nothing.
  514. m_regionRestartNotifyList.Clear();
  515. }
  516. }
  517. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  518. {
  519. if (m_scripts_enabled != !ScriptEngine)
  520. {
  521. // Tedd! Here's the method to disable the scripting engine!
  522. if (ScriptEngine)
  523. {
  524. m_log.Info("Stopping all Scripts in Scene");
  525. foreach (EntityBase ent in Entities)
  526. {
  527. if (ent is SceneObjectGroup)
  528. {
  529. ((SceneObjectGroup) ent).RemoveScriptInstances();
  530. }
  531. }
  532. }
  533. else
  534. {
  535. m_log.Info("Starting all Scripts in Scene");
  536. lock (Entities)
  537. {
  538. foreach (EntityBase ent in Entities)
  539. {
  540. if (ent is SceneObjectGroup)
  541. {
  542. ((SceneObjectGroup)ent).CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  543. }
  544. }
  545. }
  546. }
  547. m_scripts_enabled = !ScriptEngine;
  548. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  549. }
  550. if (m_physics_enabled != !PhysicsEngine)
  551. {
  552. m_physics_enabled = !PhysicsEngine;
  553. }
  554. }
  555. public int GetInaccurateNeighborCount()
  556. {
  557. lock (m_neighbours)
  558. {
  559. return m_neighbours.Count;
  560. }
  561. }
  562. // This is the method that shuts down the scene.
  563. public override void Close()
  564. {
  565. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  566. // Kick all ROOT agents with the message, 'The simulator is going down'
  567. ForEachScenePresence(delegate(ScenePresence avatar)
  568. {
  569. if (avatar.KnownChildRegionHandles.Contains(RegionInfo.RegionHandle))
  570. avatar.KnownChildRegionHandles.Remove(RegionInfo.RegionHandle);
  571. if (!avatar.IsChildAgent)
  572. avatar.ControllingClient.Kick("The simulator is going down.");
  573. avatar.ControllingClient.SendShutdownConnectionNotice();
  574. });
  575. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  576. Thread.Sleep(500);
  577. // Stop all client threads.
  578. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  579. // Stop updating the scene objects and agents.
  580. //m_heartbeatTimer.Close();
  581. shuttingdown = true;
  582. m_log.Debug("[SCENE]: Persisting changed objects");
  583. List<EntityBase> entities = GetEntities();
  584. foreach (EntityBase entity in entities)
  585. {
  586. if (!entity.IsDeleted && entity is SceneObjectGroup && ((SceneObjectGroup)entity).HasGroupChanged)
  587. {
  588. ((SceneObjectGroup)entity).ProcessBackup(m_storageManager.DataStore);
  589. }
  590. }
  591. m_sceneGraph.Close();
  592. // De-register with region communications (events cleanup)
  593. UnRegisterRegionWithComms();
  594. // Shut down all non shared modules.
  595. foreach (IRegionModule module in Modules.Values)
  596. {
  597. if (!module.IsSharedModule)
  598. {
  599. module.Close();
  600. }
  601. }
  602. Modules.Clear();
  603. // call the base class Close method.
  604. base.Close();
  605. }
  606. /// <summary>
  607. /// Start the timer which triggers regular scene updates
  608. /// </summary>
  609. public void StartTimer()
  610. {
  611. //m_log.Debug("[SCENE]: Starting timer");
  612. //m_heartbeatTimer.Enabled = true;
  613. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  614. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  615. HeartbeatThread = new Thread(new ParameterizedThreadStart(Heartbeat));
  616. HeartbeatThread.SetApartmentState(ApartmentState.MTA);
  617. HeartbeatThread.Name = "Heartbeat";
  618. HeartbeatThread.Priority = ThreadPriority.AboveNormal;
  619. ThreadTracker.Add(HeartbeatThread);
  620. HeartbeatThread.Start();
  621. }
  622. /// <summary>
  623. /// Sets up references to modules required by the scene
  624. /// </summary>
  625. public void SetModuleInterfaces()
  626. {
  627. m_httpRequestModule = RequestModuleInterface<IHttpRequests>();
  628. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  629. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  630. XferManager = RequestModuleInterface<IXfer>();
  631. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  632. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  633. }
  634. #endregion
  635. #region Update Methods
  636. /// <summary>
  637. /// Performs per-frame updates regularly
  638. /// </summary>
  639. /// <param name="sender"></param>
  640. /// <param name="e"></param>
  641. private void Heartbeat(object sender)
  642. {
  643. Update();
  644. }
  645. /// <summary>
  646. /// Performs per-frame updates on the scene, this should be the central scene loop
  647. /// </summary>
  648. public override void Update()
  649. {
  650. int maintc = 0;
  651. while (!shuttingdown)
  652. {
  653. maintc = System.Environment.TickCount;
  654. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  655. // Aquire a lock so only one update call happens at once
  656. //updateLock.WaitOne();
  657. float physicsFPS = 0;
  658. //m_log.Info("sadfadf" + m_neighbours.Count.ToString());
  659. int agentsInScene = m_sceneGraph.GetRootAgentCount() + m_sceneGraph.GetChildAgentCount();
  660. if (agentsInScene > 21)
  661. {
  662. if (m_update_entities == 1)
  663. {
  664. m_update_entities = 5;
  665. m_statsReporter.SetUpdateMS(6000);
  666. }
  667. }
  668. else
  669. {
  670. if (m_update_entities == 5)
  671. {
  672. m_update_entities = 1;
  673. m_statsReporter.SetUpdateMS(3000);
  674. }
  675. }
  676. frameMS = System.Environment.TickCount;
  677. try
  678. {
  679. // Increment the frame counter
  680. m_frame++;
  681. // Loop it
  682. if (m_frame == Int32.MaxValue)
  683. m_frame = 0;
  684. physicsMS2 = System.Environment.TickCount;
  685. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  686. m_sceneGraph.UpdatePreparePhysics();
  687. physicsMS2 = System.Environment.TickCount - physicsMS2;
  688. if (m_frame % m_update_entitymovement == 0)
  689. m_sceneGraph.UpdateEntityMovement();
  690. physicsMS = System.Environment.TickCount;
  691. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  692. physicsFPS = m_sceneGraph.UpdatePhysics(
  693. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  694. );
  695. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  696. SynchronizeScene(this);
  697. physicsMS = System.Environment.TickCount - physicsMS;
  698. physicsMS += physicsMS2;
  699. otherMS = System.Environment.TickCount;
  700. // run through all entities looking for updates (slow)
  701. if (m_frame % m_update_entities == 0)
  702. m_sceneGraph.UpdateEntities();
  703. // run through entities that have scheduled themselves for
  704. // updates looking for updates(faster)
  705. if (m_frame % m_update_entitiesquick == 0)
  706. m_sceneGraph.ProcessUpdates();
  707. // Run through scenepresences looking for updates
  708. if (m_frame % m_update_presences == 0)
  709. m_sceneGraph.UpdatePresences();
  710. // Delete temp-on-rez stuff
  711. if (m_frame % m_update_backup == 0)
  712. CleanTempObjects();
  713. if (Region_Status != RegionStatus.SlaveScene)
  714. {
  715. if (m_frame % m_update_events == 0)
  716. UpdateEvents();
  717. if (m_frame % m_update_backup == 0)
  718. {
  719. UpdateStorageBackup();
  720. }
  721. if (m_frame % m_update_terrain == 0)
  722. UpdateTerrain();
  723. if (m_frame % m_update_land == 0)
  724. UpdateLand();
  725. otherMS = System.Environment.TickCount - otherMS;
  726. // if (m_frame%m_update_avatars == 0)
  727. // UpdateInWorldTime();
  728. m_statsReporter.AddPhysicsFPS(physicsFPS);
  729. m_statsReporter.AddTimeDilation(m_timedilation);
  730. m_statsReporter.AddFPS(1);
  731. m_statsReporter.AddInPackets(0);
  732. m_statsReporter.SetRootAgents(m_sceneGraph.GetRootAgentCount());
  733. m_statsReporter.SetChildAgents(m_sceneGraph.GetChildAgentCount());
  734. m_statsReporter.SetObjects(m_sceneGraph.GetTotalObjectsCount());
  735. m_statsReporter.SetActiveObjects(m_sceneGraph.GetActiveObjectsCount());
  736. frameMS = System.Environment.TickCount - frameMS;
  737. m_statsReporter.addFrameMS(frameMS);
  738. m_statsReporter.addPhysicsMS(physicsMS);
  739. m_statsReporter.addOtherMS(otherMS);
  740. m_statsReporter.SetActiveScripts(m_sceneGraph.GetActiveScriptsCount());
  741. m_statsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  742. }
  743. }
  744. catch (NotImplementedException)
  745. {
  746. throw;
  747. }
  748. catch (AccessViolationException e)
  749. {
  750. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  751. }
  752. catch (NullReferenceException e)
  753. {
  754. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  755. }
  756. catch (InvalidOperationException e)
  757. {
  758. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  759. }
  760. catch (Exception e)
  761. {
  762. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  763. }
  764. finally
  765. {
  766. //updateLock.ReleaseMutex();
  767. // Get actual time dilation
  768. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  769. // If actual time dilation is greater then one, we're catching up, so subtract
  770. // the amount that's greater then 1 from the time dilation
  771. if (tmpval > 1.0)
  772. {
  773. tmpval = tmpval - (tmpval - 1.0f);
  774. }
  775. m_timedilation = tmpval;
  776. m_lastupdate = DateTime.Now;
  777. }
  778. maintc = System.Environment.TickCount - maintc;
  779. maintc = (int)(m_timespan * 1000) - maintc;
  780. if ((maintc < (m_timespan * 1000)) && maintc > 0)
  781. Thread.Sleep(maintc);
  782. }
  783. }
  784. private void SendSimStatsPackets(SimStats stats)
  785. {
  786. List<ScenePresence> StatSendAgents = GetScenePresences();
  787. foreach (ScenePresence agent in StatSendAgents)
  788. {
  789. if (!agent.IsChildAgent)
  790. {
  791. agent.ControllingClient.SendSimStats(stats);
  792. }
  793. }
  794. }
  795. private void UpdateLand()
  796. {
  797. if (LandChannel != null)
  798. {
  799. if (LandChannel.IsLandPrimCountTainted())
  800. {
  801. EventManager.TriggerParcelPrimCountUpdate();
  802. }
  803. }
  804. }
  805. private void UpdateTerrain()
  806. {
  807. EventManager.TriggerTerrainTick();
  808. }
  809. private void UpdateStorageBackup()
  810. {
  811. if (!m_backingup)
  812. {
  813. m_backingup = true;
  814. Thread backupthread = new Thread(Backup);
  815. backupthread.Name = "BackupWriter";
  816. backupthread.IsBackground = true;
  817. backupthread.Start();
  818. }
  819. }
  820. private void UpdateEvents()
  821. {
  822. m_eventManager.TriggerOnFrame();
  823. }
  824. /// <summary>
  825. /// Perform delegate action on all clients subscribing to updates from this region.
  826. /// </summary>
  827. /// <returns></returns>
  828. internal void Broadcast(Action<IClientAPI> whatToDo)
  829. {
  830. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  831. }
  832. /// <summary>
  833. /// Backup the scene. This acts as the main method of the backup thread.
  834. /// </summary>
  835. /// <returns></returns>
  836. public void Backup()
  837. {
  838. lock (m_returns)
  839. {
  840. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  841. m_backingup = false;
  842. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  843. {
  844. UUID transaction = UUID.Random();
  845. GridInstantMessage msg = new GridInstantMessage();
  846. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  847. msg.toAgentID = new Guid(ret.Key.ToString());
  848. msg.imSessionID = new Guid(transaction.ToString());
  849. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  850. msg.fromAgentName = "Server";
  851. msg.dialog = (byte)19; // Object msg
  852. msg.fromGroup = false;
  853. msg.offline = (byte)1;
  854. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  855. msg.Position = Vector3.Zero;
  856. msg.RegionID = RegionInfo.RegionID.Guid;
  857. msg.binaryBucket = new byte[0];
  858. if (ret.Value.count > 1)
  859. 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);
  860. else
  861. 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);
  862. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  863. if (tr != null)
  864. tr.SendInstantMessage(msg, delegate(bool success) {} );
  865. }
  866. m_returns.Clear();
  867. }
  868. }
  869. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  870. {
  871. lock (m_returns)
  872. {
  873. if (m_returns.ContainsKey(agentID))
  874. {
  875. ReturnInfo info = m_returns[agentID];
  876. info.count++;
  877. m_returns[agentID] = info;
  878. }
  879. else
  880. {
  881. ReturnInfo info = new ReturnInfo();
  882. info.count = 1;
  883. info.objectName = objectName;
  884. info.location = location;
  885. info.reason = reason;
  886. m_returns[agentID] = info;
  887. }
  888. }
  889. }
  890. #endregion
  891. #region Load Terrain
  892. public void ExportWorldMap(string fileName)
  893. {
  894. List<MapBlockData> mapBlocks =
  895. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  896. (int)(RegionInfo.RegionLocY - 9),
  897. (int)(RegionInfo.RegionLocX + 9),
  898. (int)(RegionInfo.RegionLocY + 9));
  899. List<AssetBase> textures = new List<AssetBase>();
  900. List<Image> bitImages = new List<Image>();
  901. foreach (MapBlockData mapBlock in mapBlocks)
  902. {
  903. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  904. if (texAsset != null)
  905. {
  906. textures.Add(texAsset);
  907. }
  908. else
  909. {
  910. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  911. if (texAsset != null)
  912. {
  913. textures.Add(texAsset);
  914. }
  915. }
  916. }
  917. foreach (AssetBase asset in textures)
  918. {
  919. ManagedImage managedImage;
  920. Image image;
  921. if (OpenJPEG.DecodeToImage(asset.Data, out managedImage, out image))
  922. bitImages.Add(image);
  923. }
  924. Bitmap mapTexture = new Bitmap(2560, 2560);
  925. Graphics g = Graphics.FromImage(mapTexture);
  926. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  927. g.FillRectangle(sea, 0, 0, 2560, 2560);
  928. for (int i = 0; i < mapBlocks.Count; i++)
  929. {
  930. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  931. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  932. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  933. }
  934. mapTexture.Save(fileName, ImageFormat.Jpeg);
  935. }
  936. public void SaveTerrain()
  937. {
  938. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  939. }
  940. /// <summary>
  941. /// Loads the World heightmap
  942. /// </summary>
  943. public override void LoadWorldMap()
  944. {
  945. try
  946. {
  947. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  948. if (map == null)
  949. {
  950. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  951. Heightmap = new TerrainChannel();
  952. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  953. }
  954. else
  955. {
  956. Heightmap = new TerrainChannel(map);
  957. }
  958. }
  959. catch (Exception e)
  960. {
  961. m_log.Warn("[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  962. }
  963. }
  964. /// <summary>
  965. /// Register this region with a grid service
  966. /// </summary>
  967. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  968. public void RegisterRegionWithGrid()
  969. {
  970. RegisterCommsEvents();
  971. // These two 'commands' *must be* next to each other or sim rebooting fails.
  972. m_sceneGridService.RegisterRegion(RegionInfo);
  973. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  974. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  975. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  976. {
  977. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  978. {
  979. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  980. EventManager.TriggerSetAllowForcefulBan(false);
  981. }
  982. else
  983. {
  984. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  985. EventManager.TriggerSetAllowForcefulBan(true);
  986. }
  987. }
  988. }
  989. /// <summary>
  990. ///
  991. /// </summary>
  992. public void CreateTerrainTexture(bool temporary)
  993. {
  994. //create a texture asset of the terrain
  995. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  996. // Cannot create a map for a nonexistant heightmap yet.
  997. if (Heightmap == null)
  998. return;
  999. if (terrain == null)
  1000. {
  1001. #region Fallback default maptile generation
  1002. int tc = System.Environment.TickCount;
  1003. m_log.Info("[MAPTILE]: Generating Maptile Step 1: Terrain");
  1004. Bitmap mapbmp = new Bitmap(256, 256);
  1005. double[,] hm = Heightmap.GetDoubles();
  1006. bool ShadowDebugContinue = true;
  1007. //Color prim = Color.FromArgb(120, 120, 120);
  1008. //Vector3 RayEnd = new Vector3(0, 0, 0);
  1009. //Vector3 RayStart = new Vector3(0, 0, 0);
  1010. //Vector3 direction = new Vector3(0, 0, -1);
  1011. //Vector3 AXOrigin = new Vector3();
  1012. //Vector3 AXdirection = new Vector3();
  1013. //Ray testRay = new Ray();
  1014. //EntityIntersection rt = new EntityIntersection();
  1015. bool terraincorruptedwarningsaid = false;
  1016. float low = 255;
  1017. float high = 0;
  1018. for (int x = 0; x < 256; x++)
  1019. {
  1020. for (int y = 0; y < 256; y++)
  1021. {
  1022. float hmval = (float)hm[x, y];
  1023. if (hmval < low)
  1024. low = hmval;
  1025. if (hmval > high)
  1026. high = hmval;
  1027. }
  1028. }
  1029. float mid = (high + low) * 0.5f;
  1030. // temporary initializer
  1031. float hfvalue = (float)m_regInfo.RegionSettings.WaterHeight;
  1032. float hfvaluecompare = hfvalue;
  1033. float hfdiff = hfvalue;
  1034. int hfdiffi = 0;
  1035. for (int x = 0; x < 256; x++)
  1036. {
  1037. //int tc = System.Environment.TickCount;
  1038. for (int y = 0; y < 256; y++)
  1039. {
  1040. //RayEnd = new Vector3(x, y, 0);
  1041. //RayStart = new Vector3(x, y, 255);
  1042. //direction = Vector3.Norm(RayEnd - RayStart);
  1043. //AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1044. //AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1045. //testRay = new Ray(AXOrigin, AXdirection);
  1046. //rt = m_sceneGraph.GetClosestIntersectingPrim(testRay);
  1047. //if (rt.HitTF)
  1048. //{
  1049. //mapbmp.SetPixel(x, y, prim);
  1050. //}
  1051. //else
  1052. //{
  1053. //float tmpval = (float)hm[x, y];
  1054. float heightvalue = (float)hm[x, y];
  1055. if (heightvalue > (float)m_regInfo.RegionSettings.WaterHeight)
  1056. {
  1057. // scale height value
  1058. heightvalue = low + mid * (heightvalue - low) / mid;
  1059. if (heightvalue > 255)
  1060. heightvalue = 255;
  1061. if (heightvalue < 0)
  1062. heightvalue = 0;
  1063. if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
  1064. heightvalue = 0;
  1065. try
  1066. {
  1067. Color green = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
  1068. // Y flip the cordinates
  1069. mapbmp.SetPixel(x, (256 - y) - 1, green);
  1070. //X
  1071. // .
  1072. //
  1073. // Shade the terrain for shadows
  1074. if ((x - 1 > 0) && (y - 1 > 0))
  1075. {
  1076. hfvalue = (float)hm[x, y];
  1077. hfvaluecompare = (float)hm[x - 1, y - 1];
  1078. if (Single.IsInfinity(hfvalue) || Single.IsNaN(hfvalue))
  1079. hfvalue = 0;
  1080. if (Single.IsInfinity(hfvaluecompare) || Single.IsNaN(hfvaluecompare))
  1081. hfvaluecompare = 0;
  1082. hfdiff = hfvaluecompare - hfvalue;
  1083. if (hfdiff > 0.3f)
  1084. {
  1085. }
  1086. else if (hfdiff < -0.3f)
  1087. {
  1088. // We have to desaturate and blacken the land at the same time
  1089. // we use floats, colors use bytes, so shrink are space down to
  1090. // 0-255
  1091. try
  1092. {
  1093. hfdiffi = Math.Abs((int)((hfdiff * 4) + (hfdiff * 0.5))) + 1;
  1094. if (hfdiff % 1 != 0)
  1095. {
  1096. hfdiffi = hfdiffi + Math.Abs((int)(((hfdiff % 1) * 0.5f) * 10f) - 1);
  1097. }
  1098. }
  1099. catch (System.OverflowException)
  1100. {
  1101. m_log.Debug("[MAPTILE]: Shadow failed at value: " + hfdiff.ToString());
  1102. ShadowDebugContinue = false;
  1103. }
  1104. if (ShadowDebugContinue)
  1105. {
  1106. if ((256 - y) - 1 > 0)
  1107. {
  1108. Color Shade = mapbmp.GetPixel(x - 1, (256 - y) - 1);
  1109. int r = Shade.R;
  1110. int g = Shade.G;
  1111. int b = Shade.B;
  1112. Shade = Color.FromArgb((r - hfdiffi > 0) ? r - hfdiffi : 0, (g - hfdiffi > 0) ? g - hfdiffi : 0, (b - hfdiffi > 0) ? b - hfdiffi : 0);
  1113. //Console.WriteLine("d:" + hfdiff.ToString() + ", i:" + hfdiffi + ", pos: " + x + "," + y + " - R:" + Shade.R.ToString() + ", G:" + Shade.G.ToString() + ", B:" + Shade.G.ToString());
  1114. mapbmp.SetPixel(x - 1, (256 - y) - 1, Shade);
  1115. }
  1116. }
  1117. }
  1118. }
  1119. }
  1120. catch (System.ArgumentException)
  1121. {
  1122. if (!terraincorruptedwarningsaid)
  1123. {
  1124. m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", RegionInfo.RegionName);
  1125. terraincorruptedwarningsaid = true;
  1126. }
  1127. Color black = Color.Black;
  1128. mapbmp.SetPixel(x, (256 - y) - 1, black);
  1129. }
  1130. }
  1131. else
  1132. {
  1133. // Y flip the cordinates
  1134. heightvalue = (float)m_regInfo.RegionSettings.WaterHeight - heightvalue;
  1135. if (heightvalue > 19)
  1136. heightvalue = 19;
  1137. if (heightvalue < 0)
  1138. heightvalue = 0;
  1139. heightvalue = 100 - (heightvalue * 100) / 19;
  1140. if (heightvalue > 255)
  1141. heightvalue = 255;
  1142. if (heightvalue < 0)
  1143. heightvalue = 0;
  1144. if (Single.IsInfinity(heightvalue) || Single.IsNaN(heightvalue))
  1145. heightvalue = 0;
  1146. try
  1147. {
  1148. Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
  1149. mapbmp.SetPixel(x, (256 - y) - 1, water);
  1150. }
  1151. catch (System.ArgumentException)
  1152. {
  1153. if (!terraincorruptedwarningsaid)
  1154. {
  1155. m_log.WarnFormat("[MAPIMAGE]: Your terrain is corrupted in region {0}, it might take a few minutes to generate the map image depending on the corruption level", RegionInfo.RegionName);
  1156. terraincorruptedwarningsaid = true;
  1157. }
  1158. Color black = Color.Black;
  1159. mapbmp.SetPixel(x, (256 - y) - 1, black);
  1160. }
  1161. }
  1162. }
  1163. //}
  1164. //tc = System.Environment.TickCount - tc;
  1165. //m_log.Info("[MAPTILE]: Completed One row in " + tc + " ms");
  1166. }
  1167. m_log.Info("[MAPTILE]: Generating Maptile Step 1: Done in " + (System.Environment.TickCount - tc) + " ms");
  1168. bool drawPrimVolume = true;
  1169. try
  1170. {
  1171. IConfig startupConfig = m_config.Configs["Startup"];
  1172. drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", true);
  1173. }
  1174. catch
  1175. {
  1176. m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
  1177. }
  1178. if (drawPrimVolume)
  1179. {
  1180. tc = System.Environment.TickCount;
  1181. m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
  1182. List<EntityBase> objs = GetEntities();
  1183. lock (objs)
  1184. {
  1185. foreach (EntityBase obj in objs)
  1186. {
  1187. // Only draw the contents of SceneObjectGroup
  1188. if (obj is SceneObjectGroup)
  1189. {
  1190. SceneObjectGroup mapdot = (SceneObjectGroup)obj;
  1191. Color mapdotspot = Color.Gray; // Default color when prim color is white
  1192. // Loop over prim in group
  1193. foreach (SceneObjectPart part in mapdot.Children.Values)
  1194. {
  1195. if (part == null)
  1196. continue;
  1197. // Draw if the object is at least 1 meter wide in any direction
  1198. if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
  1199. {
  1200. // Try to get the RGBA of the default texture entry..
  1201. //
  1202. try
  1203. {
  1204. if (part == null)
  1205. continue;
  1206. if (part.Shape == null)
  1207. continue;
  1208. if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree)
  1209. continue; // eliminates trees from this since we don't really have a good tree representation
  1210. // if you want tree blocks on the map comment the above line and uncomment the below line
  1211. //mapdotspot = Color.PaleGreen;
  1212. if (part.Shape.Textures == null)
  1213. continue;
  1214. if (part.Shape.Textures.DefaultTexture == null)
  1215. continue;
  1216. Color4 texcolor = part.Shape.Textures.DefaultTexture.RGBA;
  1217. // Not sure why some of these are null, oh well.
  1218. int colorr = 255 - (int)(texcolor.R * 255f);
  1219. int colorg = 255 - (int)(texcolor.G * 255f);
  1220. int colorb = 255 - (int)(texcolor.B * 255f);
  1221. if (!(colorr == 255 && colorg == 255 && colorb == 255))
  1222. {
  1223. //Try to set the map spot color
  1224. try
  1225. {
  1226. // If the color gets goofy somehow, skip it *shakes fist at Color4
  1227. mapdotspot = Color.FromArgb(colorr, colorg, colorb);
  1228. }
  1229. catch (ArgumentException)
  1230. {
  1231. }
  1232. }
  1233. }
  1234. catch (IndexOutOfRangeException)
  1235. {
  1236. // Windows Array
  1237. }
  1238. catch (ArgumentOutOfRangeException)
  1239. {
  1240. // Mono Array
  1241. }
  1242. Vector3 pos = part.GetWorldPosition();
  1243. // skip prim outside of retion
  1244. if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
  1245. continue;
  1246. // skip prim in non-finite position
  1247. if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) || Single.IsInfinity(pos.X)
  1248. || Single.IsInfinity(pos.Y))
  1249. continue;
  1250. // Figure out if object is under 256m above the height of the terrain
  1251. bool isBelow256AboveTerrain = false;
  1252. try
  1253. {
  1254. isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
  1255. }
  1256. catch (Exception)
  1257. {
  1258. }
  1259. if (isBelow256AboveTerrain)
  1260. {
  1261. // Translate scale by rotation so scale is represented properly when object is rotated
  1262. Vector3 scale = part.Shape.Scale;
  1263. Quaternion rot = part.GetWorldRotation();
  1264. scale *= rot;
  1265. // negative scales don't work in this situation
  1266. scale.X = Math.Abs(scale.X);
  1267. scale.Y = Math.Abs(scale.Y);
  1268. scale.Z = Math.Abs(scale.Z);
  1269. // This scaling isn't very accurate and doesn't take into account the face rotation :P
  1270. int mapdrawstartX = (int)(pos.X - scale.X);
  1271. int mapdrawstartY = (int)(pos.Y - scale.Y);
  1272. int mapdrawendX = (int)(pos.X + scale.X);
  1273. int mapdrawendY = (int)(pos.Y + scale.Y);
  1274. // If object is beyond the edge of the map, don't draw it to avoid errors
  1275. if (mapdrawstartX < 0 || mapdrawstartX > 255 || mapdrawendX < 0 || mapdrawendX > 255
  1276. || mapdrawstartY < 0 || mapdrawstartY > 255 || mapdrawendY < 0
  1277. || mapdrawendY > 255)
  1278. continue;
  1279. int wy = 0;
  1280. bool breakYN = false; // If we run into an error drawing, break out of the
  1281. // loop so we don't lag to death on error handling
  1282. for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
  1283. {
  1284. for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
  1285. {
  1286. //m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
  1287. try
  1288. {
  1289. // Remember, flip the y!
  1290. mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
  1291. }
  1292. catch (ArgumentException)
  1293. {
  1294. breakYN = true;
  1295. }
  1296. if (breakYN)
  1297. break;
  1298. }
  1299. if (breakYN)
  1300. break;
  1301. }
  1302. } // Object is within 256m Z of terrain
  1303. } // object is at least a meter wide
  1304. } // loop over group children
  1305. } // entitybase is sceneobject group
  1306. } // foreach loop over entities
  1307. } // lock entities objs
  1308. m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (System.Environment.TickCount - tc) + " ms");
  1309. } // end if drawPrimOnMaptle
  1310. byte[] data;
  1311. try
  1312. {
  1313. data = OpenJPEG.EncodeFromImage(mapbmp, false);
  1314. }
  1315. catch (Exception)
  1316. {
  1317. return;
  1318. }
  1319. LazySaveGeneratedMaptile(data,temporary);
  1320. #endregion
  1321. }
  1322. else
  1323. {
  1324. // Use the module to generate the maptile.
  1325. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  1326. if (data != null)
  1327. {
  1328. LazySaveGeneratedMaptile(data,temporary);
  1329. }
  1330. }
  1331. }
  1332. public void LazySaveGeneratedMaptile(byte[] data, bool temporary)
  1333. {
  1334. // Overwrites the local Asset cache with new maptile data
  1335. // Assets are single write, this causes the asset server to ignore this update,
  1336. // but the local asset cache does not
  1337. // this is on purpose! The net result of this is the region always has the most up to date
  1338. // map tile while protecting the (grid) asset database from bloat caused by a new asset each
  1339. // time a mapimage is generated!
  1340. UUID lastMapRegionUUID = m_regInfo.lastMapUUID;
  1341. int lastMapRefresh = 0;
  1342. int twoDays = 172800;
  1343. int RefreshSeconds = twoDays;
  1344. try
  1345. {
  1346. lastMapRefresh = Convert.ToInt32(m_regInfo.lastMapRefresh);
  1347. }
  1348. catch (ArgumentException)
  1349. {
  1350. }
  1351. catch (FormatException)
  1352. {
  1353. }
  1354. catch (OverflowException)
  1355. {
  1356. }
  1357. UUID TerrainImageUUID = UUID.Random();
  1358. if (lastMapRegionUUID == UUID.Zero || (lastMapRefresh + RefreshSeconds) < Util.UnixTimeSinceEpoch())
  1359. {
  1360. m_regInfo.SaveLastMapUUID(TerrainImageUUID);
  1361. m_log.Warn("[MAPTILE]: STORING MAPTILE IMAGE");
  1362. }
  1363. else
  1364. {
  1365. TerrainImageUUID = lastMapRegionUUID;
  1366. m_log.Warn("[MAPTILE]: REUSING OLD MAPTILE IMAGE ID");
  1367. }
  1368. m_regInfo.RegionSettings.TerrainImageID = TerrainImageUUID;
  1369. AssetBase asset = new AssetBase();
  1370. asset.FullID = m_regInfo.RegionSettings.TerrainImageID;
  1371. asset.Data = data;
  1372. asset.Name = "terrainImage_" + m_regInfo.RegionID.ToString() + "_" + lastMapRefresh.ToString();
  1373. asset.Description = RegionInfo.RegionName;
  1374. asset.Type = 0;
  1375. asset.Temporary = temporary;
  1376. AssetCache.AddAsset(asset);
  1377. }
  1378. #endregion
  1379. #region Load Land
  1380. public void loadAllLandObjectsFromStorage(UUID regionID)
  1381. {
  1382. m_log.Info("[SCENE]: Loading land objects from storage");
  1383. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  1384. if (LandChannel != null)
  1385. {
  1386. if (landData.Count == 0)
  1387. {
  1388. EventManager.TriggerNoticeNoLandDataFromStorage();
  1389. }
  1390. else
  1391. {
  1392. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1393. }
  1394. }
  1395. else
  1396. {
  1397. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1398. }
  1399. }
  1400. #endregion
  1401. #region Primitives Methods
  1402. /// <summary>
  1403. /// Loads the World's objects
  1404. /// </summary>
  1405. public virtual void LoadPrimsFromStorage(UUID regionID)
  1406. {
  1407. m_log.Info("[SCENE]: Loading objects from datastore");
  1408. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1409. foreach (SceneObjectGroup group in PrimsFromDB)
  1410. {
  1411. if (group.RootPart == null)
  1412. {
  1413. m_log.ErrorFormat("[SCENE] Found a SceneObjectGroup with m_rootPart == null and {0} children",
  1414. group.Children == null ? 0 : group.Children.Count);
  1415. }
  1416. AddRestoredSceneObject(group, true, true);
  1417. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1418. rootPart.ObjectFlags &= ~(uint)PrimFlags.Scripted;
  1419. rootPart.TrimPermissions();
  1420. group.CheckSculptAndLoad();
  1421. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1422. }
  1423. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1424. }
  1425. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1426. {
  1427. Vector3 pos = Vector3.Zero;
  1428. if (RayEndIsIntersection == (byte)1)
  1429. {
  1430. pos = RayEnd;
  1431. return pos;
  1432. }
  1433. if (RayTargetID != UUID.Zero)
  1434. {
  1435. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1436. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1437. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1438. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1439. if (target != null)
  1440. {
  1441. pos = target.AbsolutePosition;
  1442. //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());
  1443. // TODO: Raytrace better here
  1444. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1445. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1446. // Ray Trace against target here
  1447. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1448. // Un-comment out the following line to Get Raytrace results printed to the console.
  1449. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1450. float ScaleOffset = 0.5f;
  1451. // If we hit something
  1452. if (ei.HitTF)
  1453. {
  1454. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1455. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1456. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1457. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1458. ScaleOffset = Math.Abs(ScaleOffset);
  1459. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1460. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1461. // Set the position to the intersection point
  1462. Vector3 offset = (normal * (ScaleOffset / 2f));
  1463. pos = (intersectionpoint + offset);
  1464. // Un-offset the prim (it gets offset later by the consumer method)
  1465. pos.Z -= 0.25F;
  1466. }
  1467. return pos;
  1468. }
  1469. else
  1470. {
  1471. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1472. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1473. // Un-comment the following line to print the raytrace results to the console.
  1474. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1475. if (ei.HitTF)
  1476. {
  1477. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1478. } else
  1479. {
  1480. // fall back to our stupid functionality
  1481. pos = RayEnd;
  1482. }
  1483. return pos;
  1484. }
  1485. }
  1486. else
  1487. {
  1488. // fall back to our stupid functionality
  1489. pos = RayEnd;
  1490. return pos;
  1491. }
  1492. }
  1493. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1494. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1495. byte RayEndIsIntersection)
  1496. {
  1497. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1498. if (Permissions.CanRezObject(1, ownerID, pos))
  1499. {
  1500. // rez ON the ground, not IN the ground
  1501. pos.Z += 0.25F;
  1502. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1503. }
  1504. }
  1505. public virtual SceneObjectGroup AddNewPrim(
  1506. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1507. {
  1508. //m_log.DebugFormat(
  1509. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1510. // If an entity creator has been registered for this prim type then use that
  1511. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1512. return m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1513. // Otherwise, use this default creation code;
  1514. SceneObjectGroup sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1515. AddNewSceneObject(sceneObject, true);
  1516. sceneObject.SetGroup(groupID, null);
  1517. return sceneObject;
  1518. }
  1519. /// <summary>
  1520. /// Add an object into the scene that has come from storage
  1521. /// </summary>
  1522. /// <param name="sceneObject"></param>
  1523. /// <param name="attachToBackup">
  1524. /// If true, changes to the object will be reflected in its persisted data
  1525. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1526. /// </param>
  1527. /// <param name="alreadyPersisted">
  1528. /// If true, we won't persist this object until it changes
  1529. /// If false, we'll persist this object immediately
  1530. /// </param>
  1531. /// <returns>
  1532. /// true if the object was added, false if an object with the same uuid was already in the scene
  1533. /// </returns>
  1534. public bool AddRestoredSceneObject(
  1535. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1536. {
  1537. return m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted);
  1538. }
  1539. /// <summary>
  1540. /// Add a newly created object to the scene
  1541. /// </summary>
  1542. /// <param name="sceneObject"></param>
  1543. /// <param name="attachToBackup">
  1544. /// If true, the object is made persistent into the scene.
  1545. /// If false, the object will not persist over server restarts
  1546. /// </param>
  1547. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1548. {
  1549. return m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup);
  1550. }
  1551. /// <summary>
  1552. /// Delete every object from the scene
  1553. /// </summary>
  1554. public void DeleteAllSceneObjects()
  1555. {
  1556. lock (Entities)
  1557. {
  1558. ICollection<EntityBase> entities = new List<EntityBase>(Entities);
  1559. foreach (EntityBase e in entities)
  1560. {
  1561. if (e is SceneObjectGroup)
  1562. DeleteSceneObject((SceneObjectGroup)e, false);
  1563. }
  1564. }
  1565. }
  1566. /// <summary>
  1567. /// Synchronously delete the given object from the scene.
  1568. /// </summary>
  1569. /// <param name="group"></param>
  1570. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1571. {
  1572. //SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1573. // Serialise calls to RemoveScriptInstances to avoid
  1574. // deadlocking on m_parts inside SceneObjectGroup
  1575. lock (m_deleting_scene_object)
  1576. {
  1577. group.RemoveScriptInstances();
  1578. }
  1579. foreach (SceneObjectPart part in group.Children.Values)
  1580. {
  1581. if (part.PhysActor != null)
  1582. {
  1583. PhysicsScene.RemovePrim(part.PhysActor);
  1584. part.PhysActor = null;
  1585. }
  1586. }
  1587. // if (rootPart.PhysActor != null)
  1588. // {
  1589. // PhysicsScene.RemovePrim(rootPart.PhysActor);
  1590. // rootPart.PhysActor = null;
  1591. // }
  1592. if (UnlinkSceneObject(group.UUID, false))
  1593. {
  1594. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1595. EventManager.TriggerParcelPrimCountTainted();
  1596. }
  1597. group.DeleteGroup(silent);
  1598. }
  1599. /// <summary>
  1600. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1601. /// object itself is not destroyed.
  1602. /// </summary>
  1603. /// <param name="uuid"></param>
  1604. /// <returns>true if the object was in the scene, false if it was not</returns>
  1605. public bool UnlinkSceneObject(UUID uuid, bool resultOfLinkingObjects)
  1606. {
  1607. if (m_sceneGraph.DeleteSceneObject(uuid, resultOfLinkingObjects))
  1608. {
  1609. if (!resultOfLinkingObjects)
  1610. m_storageManager.DataStore.RemoveObject(uuid,
  1611. m_regInfo.RegionID);
  1612. return true;
  1613. }
  1614. return false;
  1615. }
  1616. /// <summary>
  1617. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1618. /// into.
  1619. ///
  1620. /// This method locates the new region handle and offsets the prim position for the new region
  1621. /// </summary>
  1622. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1623. /// <param name="grp">the scene object that we're crossing</param>
  1624. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  1625. {
  1626. if (grp == null)
  1627. return;
  1628. if (grp.IsDeleted)
  1629. return;
  1630. if (grp.RootPart.DIE_AT_EDGE)
  1631. {
  1632. // We remove the object here
  1633. try
  1634. {
  1635. DeleteSceneObject(grp, false);
  1636. }
  1637. catch (Exception)
  1638. {
  1639. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1640. }
  1641. return;
  1642. }
  1643. int thisx = (int)RegionInfo.RegionLocX;
  1644. int thisy = (int)RegionInfo.RegionLocY;
  1645. ulong newRegionHandle = 0;
  1646. Vector3 pos = attemptedPosition;
  1647. if (attemptedPosition.X > Constants.RegionSize + 0.1f)
  1648. {
  1649. pos.X = ((pos.X - Constants.RegionSize));
  1650. newRegionHandle
  1651. = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1652. // x + 1
  1653. }
  1654. else if (attemptedPosition.X < -0.1f)
  1655. {
  1656. pos.X = ((pos.X + Constants.RegionSize));
  1657. newRegionHandle
  1658. = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1659. // x - 1
  1660. }
  1661. if (attemptedPosition.Y > Constants.RegionSize + 0.1f)
  1662. {
  1663. pos.Y = ((pos.Y - Constants.RegionSize));
  1664. newRegionHandle
  1665. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1666. // y + 1
  1667. }
  1668. else if (attemptedPosition.Y < -0.1f)
  1669. {
  1670. pos.Y = ((pos.Y + Constants.RegionSize));
  1671. newRegionHandle
  1672. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1673. // y - 1
  1674. }
  1675. // Offset the positions for the new region across the border
  1676. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1677. grp.OffsetForNewRegion(pos);
  1678. // If we fail to cross the border, then reset the position of the scene object on that border.
  1679. if (!CrossPrimGroupIntoNewRegion(newRegionHandle, grp, silent))
  1680. {
  1681. grp.OffsetForNewRegion(oldGroupPosition);
  1682. grp.ScheduleGroupForFullUpdate();
  1683. }
  1684. }
  1685. /// <summary>
  1686. /// Move the given scene object into a new region
  1687. /// </summary>
  1688. /// <param name="newRegionHandle"></param>
  1689. /// <param name="grp">Scene Object Group that we're crossing</param>
  1690. /// <returns>
  1691. /// true if the crossing itself was successful, false on failure
  1692. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1693. /// </returns>
  1694. public bool CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp, bool silent)
  1695. {
  1696. bool successYN = false;
  1697. grp.RootPart.UpdateFlag = 0;
  1698. int primcrossingXMLmethod = 0;
  1699. if (newRegionHandle != 0)
  1700. {
  1701. string objectState = grp.GetStateSnapshot();
  1702. successYN
  1703. = m_sceneGridService.PrimCrossToNeighboringRegion(
  1704. newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1705. if (successYN && (objectState != "") && m_allowScriptCrossings)
  1706. {
  1707. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1708. newRegionHandle, grp.UUID, objectState, 100);
  1709. }
  1710. if (successYN)
  1711. {
  1712. // We remove the object here
  1713. try
  1714. {
  1715. DeleteSceneObject(grp, silent);
  1716. }
  1717. catch (Exception e)
  1718. {
  1719. m_log.ErrorFormat(
  1720. "[INTERREGION]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1721. grp, e);
  1722. }
  1723. }
  1724. else
  1725. {
  1726. if (!grp.IsDeleted)
  1727. {
  1728. if (grp.RootPart.PhysActor != null)
  1729. {
  1730. grp.RootPart.PhysActor.CrossingFailure();
  1731. }
  1732. }
  1733. m_log.ErrorFormat("[INTERREGION]: Prim crossing failed for {0}", grp);
  1734. }
  1735. }
  1736. else
  1737. {
  1738. m_log.Error("[INTERREGION]: region handle was unexpectedly 0 in Scene.CrossPrimGroupIntoNewRegion()");
  1739. }
  1740. return successYN;
  1741. }
  1742. /// <summary>
  1743. /// Handle a scene object that is crossing into this region from another.
  1744. /// </summary>
  1745. /// <param name="regionHandle"></param>
  1746. /// <param name="primID"></param>
  1747. /// <param name="objXMLData"></param>
  1748. /// <param name="XMLMethod"></param>
  1749. /// <returns></returns>
  1750. public bool IncomingInterRegionPrimGroup(UUID primID, string objXMLData, int XMLMethod)
  1751. {
  1752. if (XMLMethod == 0)
  1753. {
  1754. m_log.DebugFormat("[INTERREGION]: A new prim {0} arrived from a neighbor", primID);
  1755. SceneObjectGroup sceneObject = m_serialiser.DeserializeGroupFromXml2(objXMLData);
  1756. // If the user is banned, we won't let any of their objects
  1757. // enter. Period.
  1758. //
  1759. if (m_regInfo.EstateSettings.IsBanned(sceneObject.OwnerID))
  1760. {
  1761. m_log.Info("[INTERREGION]: Denied prim crossing for "+
  1762. "banned avatar");
  1763. return false;
  1764. }
  1765. // Force allocation of new LocalId
  1766. //
  1767. foreach (SceneObjectPart p in sceneObject.Children.Values)
  1768. p.LocalId = 0;
  1769. if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim)
  1770. {
  1771. if (sceneObject.RootPart.Shape.State != 0)
  1772. {
  1773. // Fix up attachment Parent Local ID
  1774. //
  1775. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  1776. uint parentLocalID = 0;
  1777. if (sp != null)
  1778. parentLocalID = sp.LocalId;
  1779. sceneObject.RootPart.IsAttachment = true;
  1780. sceneObject.RootPart.SetParentLocalId(parentLocalID);
  1781. AddRestoredSceneObject(sceneObject, false, false);
  1782. // Handle attachment special case
  1783. //
  1784. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1785. if (RootPrim != null)
  1786. {
  1787. SceneObjectGroup grp = RootPrim.ParentGroup;
  1788. RootPrim.SetParentLocalId(parentLocalID);
  1789. if (grp != null)
  1790. {
  1791. m_log.DebugFormat("[ATTACHMENT]: Received "+
  1792. "attachment {0}, inworld asset id {1}",
  1793. grp.RootPart.LastOwnerID.ToString(),
  1794. grp.UUID.ToString());
  1795. if (sp != null)
  1796. {
  1797. grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1798. m_log.DebugFormat("[ATTACHMENT]: Attach "+
  1799. "to avatar {0}",
  1800. sp.UUID.ToString());
  1801. AttachObject(sp.ControllingClient,
  1802. grp.LocalId, (uint)0,
  1803. grp.GroupRotation,
  1804. grp.AbsolutePosition, false);
  1805. grp.SendGroupFullUpdate();
  1806. }
  1807. else
  1808. {
  1809. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  1810. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  1811. }
  1812. }
  1813. }
  1814. }
  1815. else
  1816. {
  1817. AddRestoredSceneObject(sceneObject, true, false);
  1818. if (!Permissions.CanObjectEntry(sceneObject.UUID,
  1819. true, sceneObject.AbsolutePosition))
  1820. {
  1821. // Deny non attachments based on parcel settings
  1822. //
  1823. m_log.Info("[INTERREGION]: Denied prim crossing "+
  1824. "because of parcel settings");
  1825. DeleteSceneObject(sceneObject, false);
  1826. return false;
  1827. }
  1828. }
  1829. }
  1830. }
  1831. else if ((XMLMethod == 100) && m_allowScriptCrossings)
  1832. {
  1833. m_log.Warn("[INTERREGION]: Prim state data arrived from a neighbor");
  1834. XmlDocument doc = new XmlDocument();
  1835. doc.LoadXml(objXMLData);
  1836. XmlNodeList rootL = doc.GetElementsByTagName("ScriptData");
  1837. if (rootL.Count == 1)
  1838. {
  1839. XmlNode rootNode = rootL[0];
  1840. if (rootNode != null)
  1841. {
  1842. XmlNodeList partL = rootNode.ChildNodes;
  1843. foreach (XmlNode part in partL)
  1844. {
  1845. XmlNodeList nodeL = part.ChildNodes;
  1846. switch (part.Name)
  1847. {
  1848. case "Assemblies":
  1849. foreach (XmlNode asm in nodeL)
  1850. {
  1851. string fn = asm.Attributes.GetNamedItem("Filename").Value;
  1852. Byte[] filedata = Convert.FromBase64String(asm.InnerText);
  1853. string path = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1854. path = Path.Combine(path, fn);
  1855. if (!File.Exists(path))
  1856. {
  1857. FileStream fs = File.Create(path);
  1858. fs.Write(filedata, 0, filedata.Length);
  1859. fs.Close();
  1860. }
  1861. }
  1862. break;
  1863. case "ScriptStates":
  1864. foreach (XmlNode st in nodeL)
  1865. {
  1866. string id = st.Attributes.GetNamedItem("UUID").Value;
  1867. UUID uuid = new UUID(id);
  1868. XmlNode state = st.ChildNodes[0];
  1869. XmlDocument sdoc = new XmlDocument();
  1870. XmlNode sxmlnode = sdoc.CreateNode(
  1871. XmlNodeType.XmlDeclaration,
  1872. "", "");
  1873. sdoc.AppendChild(sxmlnode);
  1874. XmlNode newnode = sdoc.ImportNode(state, true);
  1875. sdoc.AppendChild(newnode);
  1876. string spath = Path.Combine("ScriptEngines", RegionInfo.RegionID.ToString());
  1877. spath = Path.Combine(spath, uuid.ToString());
  1878. FileStream sfs = File.Create(spath + ".state");
  1879. System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
  1880. Byte[] buf = enc.GetBytes(sdoc.InnerXml);
  1881. sfs.Write(buf, 0, buf.Length);
  1882. sfs.Close();
  1883. }
  1884. break;
  1885. }
  1886. }
  1887. }
  1888. }
  1889. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1890. RootPrim.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, 1);
  1891. return true;
  1892. }
  1893. return true;
  1894. }
  1895. #endregion
  1896. #region Add/Remove Avatar Methods
  1897. public override void AddNewClient(IClientAPI client)
  1898. {
  1899. SubscribeToClientEvents(client);
  1900. ScenePresence presence;
  1901. if (m_restorePresences.ContainsKey(client.AgentId))
  1902. {
  1903. m_log.DebugFormat("[SCENE]: Restoring agent {0} {1} in {2}", client.Name, client.AgentId, RegionInfo.RegionName);
  1904. presence = m_restorePresences[client.AgentId];
  1905. m_restorePresences.Remove(client.AgentId);
  1906. // This is one of two paths to create avatars that are
  1907. // used. This tends to get called more in standalone
  1908. // than grid, not really sure why, but as such needs
  1909. // an explicity appearance lookup here.
  1910. AvatarAppearance appearance = null;
  1911. GetAvatarAppearance(client, out appearance);
  1912. presence.Appearance = appearance;
  1913. presence.initializeScenePresence(client, RegionInfo, this);
  1914. m_sceneGraph.AddScenePresence(presence);
  1915. lock (m_restorePresences)
  1916. {
  1917. Monitor.PulseAll(m_restorePresences);
  1918. }
  1919. }
  1920. else
  1921. {
  1922. m_log.DebugFormat(
  1923. "[SCENE]: Adding new child agent {0} for new user connection in {1}",
  1924. client.Name, RegionInfo.RegionName);
  1925. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1926. CreateAndAddScenePresence(client);
  1927. }
  1928. m_LastLogin = System.Environment.TickCount;
  1929. EventManager.TriggerOnNewClient(client);
  1930. }
  1931. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1932. {
  1933. client.OnRegionHandShakeReply += SendLayerData;
  1934. client.OnAddPrim += AddNewPrim;
  1935. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimPosition;
  1936. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  1937. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimRotation;
  1938. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimRotation;
  1939. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  1940. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  1941. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  1942. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  1943. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  1944. //client.OnRequestMapBlocks += RequestMapBlocks; // handled in a module now.
  1945. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  1946. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1947. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1948. client.OnObjectSelect += SelectPrim;
  1949. client.OnObjectDeselect += DeselectPrim;
  1950. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  1951. client.OnDeRezObject += DeRezObject;
  1952. client.OnRezObject += RezObject;
  1953. client.OnRezSingleAttachmentFromInv += RezSingleAttachment;
  1954. client.OnDetachAttachmentIntoInv += DetachSingleAttachmentToInv;
  1955. client.OnObjectAttach += m_sceneGraph.AttachObject;
  1956. client.OnObjectDetach += m_sceneGraph.DetachObject;
  1957. client.OnObjectDrop += m_sceneGraph.DropObject;
  1958. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1959. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  1960. client.OnObjectName += m_sceneGraph.PrimName;
  1961. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  1962. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  1963. client.OnLinkObjects += m_sceneGraph.LinkObjects;
  1964. client.OnDelinkObjects += m_sceneGraph.DelinkObjects;
  1965. client.OnObjectDuplicate += m_sceneGraph.DuplicateObject;
  1966. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  1967. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  1968. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  1969. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  1970. client.OnGodKickUser += HandleGodlikeKickUser;
  1971. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1972. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1973. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  1974. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  1975. client.OnMoveInventoryFolder += HandleMoveInventoryFolder;
  1976. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  1977. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents;
  1978. client.OnFetchInventory += HandleFetchInventory;
  1979. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1980. client.OnCopyInventoryItem += CopyInventoryItem;
  1981. client.OnMoveInventoryItem += MoveInventoryItem;
  1982. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1983. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1984. client.OnRezScript += RezScript;
  1985. client.OnRequestTaskInventory += RequestTaskInventory;
  1986. client.OnRemoveTaskItem += RemoveTaskInventory;
  1987. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1988. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  1989. client.OnGrabObject += ProcessObjectGrab;
  1990. client.OnDeGrabObject += ProcessObjectDeGrab;
  1991. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1992. client.OnParcelBuy += ProcessParcelBuy;
  1993. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1994. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  1995. client.OnTeleportHomeRequest += TeleportClientHome;
  1996. client.OnSetStartLocationRequest += SetHomeRezPoint;
  1997. client.OnUndo += m_sceneGraph.HandleUndo;
  1998. client.OnObjectGroupRequest += m_sceneGraph.HandleObjectGroupUpdate;
  1999. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2000. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2001. client.OnObjectSaleInfo += ObjectSaleInfo;
  2002. client.OnScriptReset += ProcessScriptReset;
  2003. client.OnGetScriptRunning += GetScriptRunning;
  2004. client.OnSetScriptRunning += SetScriptRunning;
  2005. client.OnRegionHandleRequest += RegionHandleRequest;
  2006. client.OnUnackedTerrain += TerrainUnAcked;
  2007. IGesturesModule gesturesModule = RequestModuleInterface<IGesturesModule>();
  2008. if (gesturesModule != null)
  2009. {
  2010. client.OnActivateGesture += gesturesModule.ActivateGesture;
  2011. client.OnDeactivateGesture += gesturesModule.DeactivateGesture;
  2012. }
  2013. ISoundModule soundModule = RequestModuleInterface<ISoundModule>();
  2014. if (soundModule != null)
  2015. client.OnSoundTrigger += soundModule.TriggerSound;
  2016. client.OnObjectOwner += ObjectOwner;
  2017. // EventManager.TriggerOnNewClient(client);
  2018. }
  2019. /// <summary>
  2020. /// Teleport an avatar to their home region
  2021. /// </summary>
  2022. /// <param name="agentId"></param>
  2023. /// <param name="client"></param>
  2024. public virtual void TeleportClientHome(UUID agentId, IClientAPI client)
  2025. {
  2026. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(agentId);
  2027. if (UserProfile != null)
  2028. {
  2029. RegionInfo regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegionID);
  2030. if (regionInfo == null)
  2031. {
  2032. regionInfo = CommsManager.GridService.RequestNeighbourInfo(UserProfile.HomeRegion);
  2033. if (regionInfo != null) // home region can be away temporarily, too
  2034. {
  2035. UserProfile.HomeRegionID = regionInfo.RegionID;
  2036. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2037. }
  2038. }
  2039. if (regionInfo == null)
  2040. {
  2041. // can't find the Home region: Tell viewer and abort
  2042. client.SendTeleportFailed("Your home-region could not be found.");
  2043. return;
  2044. }
  2045. RequestTeleportLocation(
  2046. client, regionInfo.RegionHandle, UserProfile.HomeLocation, UserProfile.HomeLookAt,
  2047. (uint)(TPFlags.SetLastToTarget | TPFlags.ViaHome));
  2048. }
  2049. }
  2050. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  2051. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  2052. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  2053. {
  2054. Vector3 pos;
  2055. const bool frontFacesOnly = true;
  2056. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  2057. SceneObjectPart target = GetSceneObjectPart(localID);
  2058. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  2059. if (target != null && target2 != null)
  2060. {
  2061. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  2062. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  2063. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  2064. if (target2.ParentGroup != null)
  2065. {
  2066. pos = target2.AbsolutePosition;
  2067. //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());
  2068. // TODO: Raytrace better here
  2069. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  2070. Ray NewRay = new Ray(AXOrigin, AXdirection);
  2071. // Ray Trace against target here
  2072. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  2073. // Un-comment out the following line to Get Raytrace results printed to the console.
  2074. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2075. float ScaleOffset = 0.5f;
  2076. // If we hit something
  2077. if (ei.HitTF)
  2078. {
  2079. Vector3 scale = target.Scale;
  2080. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  2081. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2082. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2083. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2084. ScaleOffset = Math.Abs(ScaleOffset);
  2085. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2086. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  2087. Vector3 offset = normal * (ScaleOffset / 2f);
  2088. pos = intersectionpoint + offset;
  2089. // stick in offset format from the original prim
  2090. pos = pos - target.ParentGroup.AbsolutePosition;
  2091. if (CopyRotates)
  2092. {
  2093. Quaternion worldRot = target2.GetWorldRotation();
  2094. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2095. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2096. //obj.Rotation = worldRot;
  2097. //obj.UpdateGroupRotation(worldRot);
  2098. }
  2099. else
  2100. {
  2101. m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  2102. }
  2103. }
  2104. return;
  2105. }
  2106. return;
  2107. }
  2108. }
  2109. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, Vector3 position, Vector3 lookAt, uint flags)
  2110. {
  2111. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  2112. if (UserProfile != null)
  2113. {
  2114. // I know I'm ignoring the regionHandle provided by the teleport location request.
  2115. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  2116. UserProfile.HomeRegionID = RegionInfo.RegionID;
  2117. // TODO: The next line can be removed, as soon as only homeRegionID based UserServers are around.
  2118. // TODO: The HomeRegion property can be removed then, too
  2119. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  2120. UserProfile.HomeLocation = position;
  2121. UserProfile.HomeLookAt = lookAt;
  2122. CommsManager.UserService.UpdateUserProfile(UserProfile);
  2123. // FUBAR ALERT: this needs to be "Home position set." so the viewer saves a home-screenshot.
  2124. remoteClient.SendAgentAlertMessage("Home position set.",false);
  2125. }
  2126. else
  2127. {
  2128. remoteClient.SendAgentAlertMessage("Set Home request Failed",false);
  2129. }
  2130. }
  2131. /// <summary>
  2132. /// Create a child agent scene presence and add it to this scene.
  2133. /// </summary>
  2134. /// <param name="client"></param>
  2135. /// <returns></returns>
  2136. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client)
  2137. {
  2138. AvatarAppearance appearance = null;
  2139. GetAvatarAppearance(client, out appearance);
  2140. ScenePresence avatar = m_sceneGraph.CreateAndAddChildScenePresence(client, appearance);
  2141. //avatar.KnownRegions = GetChildrenSeeds(avatar.UUID);
  2142. return avatar;
  2143. }
  2144. /// <summary>
  2145. /// Get the avatar apperance for the given client.
  2146. /// </summary>
  2147. /// <param name="client"></param>
  2148. /// <param name="appearance"></param>
  2149. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2150. {
  2151. appearance = new AvatarAppearance();
  2152. try
  2153. {
  2154. if (m_AvatarFactory != null)
  2155. {
  2156. if (m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  2157. return;
  2158. }
  2159. }
  2160. catch (Exception e)
  2161. {
  2162. m_log.ErrorFormat("[APPEARANCE]: Problem fetching appearance for avatar {0}, {1}",
  2163. client.Name, e);
  2164. }
  2165. m_log.Warn("[APPEARANCE]: Appearance not found, returning default");
  2166. }
  2167. /// <summary>
  2168. /// Remove the given client from the scene.
  2169. /// </summary>
  2170. /// <param name="agentID"></param>
  2171. public override void RemoveClient(UUID agentID)
  2172. {
  2173. bool childagentYN = false;
  2174. ScenePresence avatar = GetScenePresence(agentID);
  2175. if (avatar != null)
  2176. {
  2177. childagentYN = avatar.IsChildAgent;
  2178. }
  2179. try
  2180. {
  2181. m_log.DebugFormat(
  2182. "[SCENE]: Removing {0} agent {1} from region {2}",
  2183. (childagentYN ? "child" : "root"), agentID, RegionInfo.RegionName);
  2184. m_sceneGraph.removeUserCount(!childagentYN);
  2185. RemoveCapsHandler(agentID);
  2186. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  2187. {
  2188. m_log.InfoFormat("[SCENE]: User {0} is going to another region, profile cache removed in {1}", avatar.UUID, RegionInfo.RegionName);
  2189. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  2190. }
  2191. if (!avatar.IsChildAgent)
  2192. {
  2193. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle, avatar.AbsolutePosition, avatar.Lookat);
  2194. //List<ulong> childknownRegions = new List<ulong>();
  2195. //List<ulong> ckn = avatar.KnownChildRegionHandles;
  2196. //for (int i = 0; i < ckn.Count; i++)
  2197. //{
  2198. // childknownRegions.Add(ckn[i]);
  2199. //}
  2200. m_sceneGridService.SendCloseChildAgentConnections(agentID, avatar.KnownChildRegionHandles);
  2201. }
  2202. m_eventManager.TriggerClientClosed(agentID);
  2203. }
  2204. catch (NullReferenceException)
  2205. {
  2206. // We don't know which count to remove it from
  2207. // Avatar is already disposed :/
  2208. }
  2209. m_eventManager.TriggerOnRemovePresence(agentID);
  2210. Broadcast(delegate(IClientAPI client)
  2211. {
  2212. try
  2213. {
  2214. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  2215. }
  2216. catch (NullReferenceException)
  2217. {
  2218. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2219. }
  2220. });
  2221. ForEachScenePresence(
  2222. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2223. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  2224. if (agentTransactions != null)
  2225. {
  2226. agentTransactions.RemoveAgentAssetTransactions(agentID);
  2227. }
  2228. m_sceneGraph.RemoveScenePresence(agentID);
  2229. try
  2230. {
  2231. avatar.Close();
  2232. }
  2233. catch (NullReferenceException)
  2234. {
  2235. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  2236. }
  2237. catch (Exception e)
  2238. {
  2239. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  2240. }
  2241. // Remove client agent from profile, so new logins will work
  2242. if (!childagentYN)
  2243. {
  2244. m_sceneGridService.ClearUserAgent(agentID);
  2245. }
  2246. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2247. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2248. }
  2249. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  2250. {
  2251. ScenePresence av = GetScenePresence(avatarID);
  2252. if (av != null)
  2253. {
  2254. lock (av)
  2255. {
  2256. for (int i = 0; i < regionslst.Count; i++)
  2257. {
  2258. av.KnownChildRegionHandles.Remove(regionslst[i]);
  2259. }
  2260. }
  2261. }
  2262. }
  2263. public override void CloseAllAgents(uint circuitcode)
  2264. {
  2265. // Called by ClientView to kill all circuit codes
  2266. ClientManager.CloseAllAgents(circuitcode);
  2267. }
  2268. public void NotifyMyCoarseLocationChange()
  2269. {
  2270. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  2271. }
  2272. #endregion
  2273. #region Entities
  2274. public void SendKillObject(uint localID)
  2275. {
  2276. SceneObjectPart part = GetSceneObjectPart(localID);
  2277. if (part != null) // It is a prim
  2278. {
  2279. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  2280. {
  2281. if (part.ParentGroup.RootPart != part) // Child part
  2282. return;
  2283. }
  2284. }
  2285. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  2286. }
  2287. #endregion
  2288. #region RegionComms
  2289. /// <summary>
  2290. /// Register the methods that should be invoked when this scene receives various incoming events
  2291. /// </summary>
  2292. public void RegisterCommsEvents()
  2293. {
  2294. m_sceneGridService.OnExpectUser += NewUserConnection;
  2295. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  2296. m_sceneGridService.OnCloseAgentConnection += CloseConnection;
  2297. m_sceneGridService.OnRegionUp += OtherRegionUp;
  2298. m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  2299. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  2300. //m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  2301. m_sceneGridService.OnLogOffUser += HandleLogOffUserFromGrid;
  2302. m_sceneGridService.KiPrimitive += SendKillObject;
  2303. m_sceneGridService.OnGetLandData += GetLandData;
  2304. }
  2305. /// <summary>
  2306. /// Deregister this scene from receiving incoming region events
  2307. /// </summary>
  2308. public void UnRegisterRegionWithComms()
  2309. {
  2310. m_sceneGridService.KiPrimitive -= SendKillObject;
  2311. m_sceneGridService.OnLogOffUser -= HandleLogOffUserFromGrid;
  2312. //m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  2313. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  2314. m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  2315. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  2316. m_sceneGridService.OnExpectUser -= NewUserConnection;
  2317. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  2318. m_sceneGridService.OnCloseAgentConnection -= CloseConnection;
  2319. m_sceneGridService.OnGetLandData -= GetLandData;
  2320. m_sceneGridService.Close();
  2321. }
  2322. /// <summary>
  2323. /// Do the work necessary to initiate a new user connection for a particular scene.
  2324. /// At the moment, this consists of setting up the caps infrastructure
  2325. /// </summary>
  2326. /// <param name="regionHandle"></param>
  2327. /// <param name="agent"></param>
  2328. public void NewUserConnection(AgentCircuitData agent)
  2329. {
  2330. if (m_regInfo.EstateSettings.IsBanned(agent.AgentID))
  2331. {
  2332. m_log.WarnFormat(
  2333. "[CONNECTION DEBUGGING]: Denied access to: {0} at {1} because the user is on the region banlist",
  2334. agent.AgentID, RegionInfo.RegionName);
  2335. }
  2336. /// Diva: Horrible stuff!
  2337. capsPaths[agent.AgentID] = agent.CapsPath;
  2338. childrenSeeds[agent.AgentID] = ((agent.ChildrenCapSeeds == null) ? new Dictionary<ulong, string>() : agent.ChildrenCapSeeds);
  2339. ScenePresence sp = m_sceneGraph.GetScenePresence(agent.AgentID);
  2340. if (sp != null)
  2341. {
  2342. m_log.DebugFormat("[CONNECTION DEBUGGING]: Updated agent {0} in {1}", agent.AgentID, RegionInfo.RegionName);
  2343. sp.AdjustKnownSeeds();
  2344. return;
  2345. }
  2346. m_log.DebugFormat("[CONNECTION DEBUGGING]: Adding NewUserConnection for {0} in {1} with CC of {2}", agent.AgentID,
  2347. RegionInfo.RegionName, agent.circuitcode);
  2348. AddCapsHandler(agent.AgentID);
  2349. if (!agent.child)
  2350. {
  2351. // Honor parcel landing type and position.
  2352. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  2353. if (land != null)
  2354. {
  2355. if (land.landData.LandingType == (byte)1 && land.landData.UserLocation != Vector3.Zero)
  2356. {
  2357. agent.startpos = land.landData.UserLocation;
  2358. }
  2359. }
  2360. }
  2361. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  2362. // rewrite session_id
  2363. CachedUserInfo userinfo = CommsManager.UserProfileCacheService.GetUserDetails(agent.AgentID);
  2364. if (userinfo != null)
  2365. {
  2366. userinfo.SessionID = agent.SessionID;
  2367. }
  2368. else
  2369. {
  2370. m_log.WarnFormat("[USERINFO CACHE]: We couldn't find a User Info record for {0}. This is usually an indication that the UUID we're looking up is invalid", agent.AgentID);
  2371. }
  2372. }
  2373. public void UpdateCircuitData(AgentCircuitData data)
  2374. {
  2375. m_authenticateHandler.UpdateAgentData(data);
  2376. }
  2377. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  2378. {
  2379. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  2380. }
  2381. protected void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  2382. {
  2383. ScenePresence loggingOffUser = null;
  2384. loggingOffUser = GetScenePresence(AvatarID);
  2385. if (loggingOffUser != null)
  2386. {
  2387. if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId)
  2388. {
  2389. m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, new List<ulong>(loggingOffUser.KnownRegions.Keys));
  2390. loggingOffUser.ControllingClient.Kick(message);
  2391. // Give them a second to receive the message!
  2392. System.Threading.Thread.Sleep(1000);
  2393. loggingOffUser.ControllingClient.Close(true);
  2394. }
  2395. else
  2396. {
  2397. m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  2398. }
  2399. }
  2400. else
  2401. {
  2402. 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());
  2403. }
  2404. }
  2405. /// <summary>
  2406. /// Add a caps handler for the given agent. If the CAPS handler already exists for this agent,
  2407. /// then it is replaced by a new CAPS handler.
  2408. ///
  2409. /// FIXME: On login this is called twice, once for the login and once when the connection is made.
  2410. /// This is somewhat innefficient and should be fixed. The initial login creation is necessary
  2411. /// since the client asks for capabilities immediately after being informed of the seed.
  2412. /// </summary>
  2413. /// <param name="agentId"></param>
  2414. /// <param name="capsObjectPath"></param>
  2415. public void AddCapsHandler(UUID agentId)
  2416. {
  2417. if (RegionInfo.EstateSettings.IsBanned(agentId))
  2418. return;
  2419. String capsObjectPath = GetCapsPath(agentId);
  2420. m_log.DebugFormat(
  2421. "[CAPS]: Setting up CAPS handler for agent {0} in {1}",
  2422. agentId, RegionInfo.RegionName);
  2423. Caps cap = null;
  2424. if (m_capsHandlers.TryGetValue(agentId, out cap))
  2425. {
  2426. m_log.DebugFormat("[CAPS] Attempt at registering twice for the same agent {0}. {1}. Ignoring.", agentId, capsObjectPath);
  2427. return;
  2428. }
  2429. cap = new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port,
  2430. capsObjectPath, agentId, m_dumpAssetsToFile, RegionInfo.RegionName);
  2431. cap.RegisterHandlers();
  2432. EventManager.TriggerOnRegisterCaps(agentId, cap);
  2433. cap.AddNewInventoryItem = AddUploadedInventoryItem;
  2434. cap.ItemUpdatedCall = CapsUpdateInventoryItemAsset;
  2435. cap.TaskScriptUpdatedCall = CapsUpdateTaskInventoryScriptAsset;
  2436. cap.CAPSFetchInventoryDescendents = HandleFetchInventoryDescendentsCAPS;
  2437. cap.GetClient = m_sceneGraph.GetControllingClient;
  2438. m_capsHandlers[agentId] = cap;
  2439. }
  2440. public Caps GetCapsHandlerForUser(UUID agentId)
  2441. {
  2442. lock (m_capsHandlers)
  2443. {
  2444. if (m_capsHandlers.ContainsKey(agentId))
  2445. {
  2446. return m_capsHandlers[agentId];
  2447. }
  2448. }
  2449. return null;
  2450. }
  2451. /// <summary>
  2452. /// Remove the caps handler for a given agent.
  2453. /// </summary>
  2454. /// <param name="agentId"></param>
  2455. public void RemoveCapsHandler(UUID agentId)
  2456. {
  2457. if (childrenSeeds.ContainsKey(agentId))
  2458. {
  2459. //Console.WriteLine(" !!! Removing seeds for {0} in {1}", agentId, RegionInfo.RegionName);
  2460. childrenSeeds.Remove(agentId);
  2461. }
  2462. lock (m_capsHandlers)
  2463. {
  2464. if (m_capsHandlers.ContainsKey(agentId))
  2465. {
  2466. m_log.DebugFormat(
  2467. "[CAPS]: Removing CAPS handler for root agent {0} in {1}",
  2468. agentId, RegionInfo.RegionName);
  2469. m_capsHandlers[agentId].DeregisterHandlers();
  2470. EventManager.TriggerOnDeregisterCaps(agentId, m_capsHandlers[agentId]);
  2471. m_capsHandlers.Remove(agentId);
  2472. }
  2473. else
  2474. {
  2475. m_log.WarnFormat(
  2476. "[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
  2477. agentId, RegionInfo.RegionName);
  2478. }
  2479. }
  2480. }
  2481. /// <summary>
  2482. /// Triggered when an agent crosses into this sim. Also happens on initial login.
  2483. /// </summary>
  2484. /// <param name="agentID"></param>
  2485. /// <param name="position"></param>
  2486. /// <param name="isFlying"></param>
  2487. public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  2488. {
  2489. ScenePresence presence;
  2490. lock (m_scenePresences)
  2491. {
  2492. m_scenePresences.TryGetValue(agentID, out presence);
  2493. }
  2494. if (presence != null)
  2495. {
  2496. try
  2497. {
  2498. presence.MakeRootAgent(position, isFlying);
  2499. }
  2500. catch (Exception e)
  2501. {
  2502. m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}", e);
  2503. }
  2504. }
  2505. else
  2506. {
  2507. m_log.ErrorFormat(
  2508. "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  2509. agentID, RegionInfo.RegionName);
  2510. }
  2511. }
  2512. public virtual bool IncomingChildAgentDataUpdate(ChildAgentDataUpdate cAgentData)
  2513. {
  2514. ScenePresence childAgentUpdate = GetScenePresence(new UUID(cAgentData.AgentID));
  2515. if (childAgentUpdate != null)
  2516. {
  2517. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  2518. // however to avoid a race condition crossing borders..
  2519. if (childAgentUpdate.IsChildAgent)
  2520. {
  2521. uint rRegionX = (uint)(cAgentData.regionHandle >> 40);
  2522. uint rRegionY = (((uint)(cAgentData.regionHandle)) >> 8);
  2523. uint tRegionX = RegionInfo.RegionLocX;
  2524. uint tRegionY = RegionInfo.RegionLocY;
  2525. //Send Data to ScenePresence
  2526. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  2527. // Not Implemented:
  2528. //TODO: Do we need to pass the message on to one of our neighbors?
  2529. }
  2530. return true;
  2531. }
  2532. return false;
  2533. }
  2534. /// <summary>
  2535. /// Tell a single agent to disconnect from the region.
  2536. /// </summary>
  2537. /// <param name="regionHandle"></param>
  2538. /// <param name="agentID"></param>
  2539. public bool CloseConnection(UUID agentID)
  2540. {
  2541. ScenePresence presence = m_sceneGraph.GetScenePresence(agentID);
  2542. if (presence != null)
  2543. {
  2544. // Nothing is removed here, so down count it as such
  2545. // if (presence.IsChildAgent)
  2546. // {
  2547. // m_sceneGraph.removeUserCount(false);
  2548. // }
  2549. // else
  2550. // {
  2551. // m_sceneGraph.removeUserCount(true);
  2552. // }
  2553. // Don't do this to root agents on logout, it's not nice for the viewer
  2554. if (presence.IsChildAgent)
  2555. {
  2556. // Tell a single agent to disconnect from the region.
  2557. IEventQueue eq = RequestModuleInterface<IEventQueue>();
  2558. if (eq != null)
  2559. {
  2560. OSD Item = EventQueueHelper.DisableSimulator(RegionInfo.RegionHandle);
  2561. eq.Enqueue(Item, agentID);
  2562. }
  2563. else
  2564. presence.ControllingClient.SendShutdownConnectionNotice();
  2565. }
  2566. presence.ControllingClient.Close(true);
  2567. }
  2568. return true;
  2569. }
  2570. /// <summary>
  2571. /// Tell neighboring regions about this agent
  2572. /// When the regions respond with a true value,
  2573. /// tell the agents about the region.
  2574. ///
  2575. /// We have to tell the regions about the agents first otherwise it'll deny them access
  2576. ///
  2577. /// </summary>
  2578. /// <param name="presence"></param>
  2579. public void InformClientOfNeighbours(ScenePresence presence)
  2580. {
  2581. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  2582. }
  2583. /// <summary>
  2584. /// Tell a neighboring region about this agent
  2585. /// </summary>
  2586. /// <param name="presence"></param>
  2587. /// <param name="region"></param>
  2588. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  2589. {
  2590. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  2591. }
  2592. /// <summary>
  2593. /// Requests information about this region from gridcomms
  2594. /// </summary>
  2595. /// <param name="regionHandle"></param>
  2596. /// <returns></returns>
  2597. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  2598. {
  2599. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  2600. }
  2601. /// <summary>
  2602. /// Requests textures for map from minimum region to maximum region in world cordinates
  2603. /// </summary>
  2604. /// <param name="remoteClient"></param>
  2605. /// <param name="minX"></param>
  2606. /// <param name="minY"></param>
  2607. /// <param name="maxX"></param>
  2608. /// <param name="maxY"></param>
  2609. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  2610. {
  2611. m_log.InfoFormat("[MAPBLOCK]: {0}-{1}, {2}-{3}", minX, minY, maxX, maxY);
  2612. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxY);
  2613. }
  2614. /// <summary>
  2615. /// Tries to teleport agent to other region.
  2616. /// </summary>
  2617. /// <param name="remoteClient"></param>
  2618. /// <param name="regionName"></param>
  2619. /// <param name="position"></param>
  2620. /// <param name="lookAt"></param>
  2621. /// <param name="teleportFlags"></param>
  2622. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  2623. Vector3 lookat, uint teleportFlags)
  2624. {
  2625. RegionInfo regionInfo = m_sceneGridService.RequestClosestRegion(regionName);
  2626. if (regionInfo == null)
  2627. {
  2628. // can't find the region: Tell viewer and abort
  2629. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  2630. return;
  2631. }
  2632. RequestTeleportLocation(remoteClient, regionInfo.RegionHandle, position, lookat, teleportFlags);
  2633. }
  2634. /// <summary>
  2635. /// Tries to teleport agent to other region.
  2636. /// </summary>
  2637. /// <param name="remoteClient"></param>
  2638. /// <param name="regionHandle"></param>
  2639. /// <param name="position"></param>
  2640. /// <param name="lookAt"></param>
  2641. /// <param name="teleportFlags"></param>
  2642. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  2643. Vector3 lookAt, uint teleportFlags)
  2644. {
  2645. lock (m_scenePresences)
  2646. {
  2647. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2648. {
  2649. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  2650. position, lookAt, teleportFlags);
  2651. }
  2652. }
  2653. }
  2654. /// <summary>
  2655. /// Tries to teleport agent to landmark.
  2656. /// </summary>
  2657. /// <param name="remoteClient"></param>
  2658. /// <param name="regionHandle"></param>
  2659. /// <param name="position"></param>
  2660. public void RequestTeleportLandmark(IClientAPI remoteClient, UUID regionID, Vector3 position)
  2661. {
  2662. RegionInfo info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  2663. if (info == null)
  2664. {
  2665. // can't find the region: Tell viewer and abort
  2666. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  2667. return;
  2668. }
  2669. lock (m_scenePresences)
  2670. {
  2671. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  2672. {
  2673. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], info.RegionHandle,
  2674. position, Vector3.Zero, (uint)(TPFlags.SetLastToTarget | TPFlags.ViaLandmark));
  2675. }
  2676. }
  2677. }
  2678. /// <summary>
  2679. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  2680. /// </summary>
  2681. /// <param name="regionHandle"></param>
  2682. /// <param name="agentID"></param>
  2683. /// <param name="position"></param>
  2684. /// <param name="isFlying"></param>
  2685. /// <returns></returns>
  2686. public bool InformNeighbourOfCrossing(ulong regionHandle, UUID agentID, Vector3 position, bool isFlying)
  2687. {
  2688. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  2689. }
  2690. public void SendOutChildAgentUpdates(ChildAgentDataUpdate cadu, ScenePresence presence)
  2691. {
  2692. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  2693. }
  2694. #endregion
  2695. #region Module Methods
  2696. /// <summary>
  2697. /// Add a module to this scene.
  2698. /// </summary>
  2699. /// <param name="name"></param>
  2700. /// <param name="module"></param>
  2701. public void AddModule(string name, IRegionModule module)
  2702. {
  2703. if (!Modules.ContainsKey(name))
  2704. {
  2705. Modules.Add(name, module);
  2706. }
  2707. }
  2708. public void RegisterModuleCommander(string name, ICommander commander)
  2709. {
  2710. lock (m_moduleCommanders)
  2711. {
  2712. m_moduleCommanders.Add(name, commander);
  2713. }
  2714. }
  2715. public ICommander GetCommander(string name)
  2716. {
  2717. lock (m_moduleCommanders)
  2718. {
  2719. return m_moduleCommanders[name];
  2720. }
  2721. }
  2722. public Dictionary<string, ICommander> GetCommanders()
  2723. {
  2724. return m_moduleCommanders;
  2725. }
  2726. /// <summary>
  2727. /// Register an interface to a region module. This allows module methods to be called directly as
  2728. /// well as via events. If there is already a module registered for this interface, it is not replaced
  2729. /// (is this the best behaviour?)
  2730. /// </summary>
  2731. /// <param name="mod"></param>
  2732. public void RegisterModuleInterface<M>(M mod)
  2733. {
  2734. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  2735. {
  2736. List<Object> l = new List<Object>();
  2737. l.Add(mod);
  2738. ModuleInterfaces.Add(typeof(M), l);
  2739. if (mod is IEntityCreator)
  2740. {
  2741. IEntityCreator entityCreator = (IEntityCreator)mod;
  2742. foreach (PCode pcode in entityCreator.CreationCapabilities)
  2743. {
  2744. m_entityCreators[pcode] = entityCreator;
  2745. }
  2746. }
  2747. }
  2748. }
  2749. public void StackModuleInterface<M>(M mod)
  2750. {
  2751. List<Object> l;
  2752. if (ModuleInterfaces.ContainsKey(typeof(M)))
  2753. l = ModuleInterfaces[typeof(M)];
  2754. else
  2755. l = new List<Object>();
  2756. if (l.Contains(mod))
  2757. return;
  2758. l.Add(mod);
  2759. if (mod is IEntityCreator)
  2760. {
  2761. IEntityCreator entityCreator = (IEntityCreator)mod;
  2762. foreach (PCode pcode in entityCreator.CreationCapabilities)
  2763. {
  2764. m_entityCreators[pcode] = entityCreator;
  2765. }
  2766. }
  2767. ModuleInterfaces[typeof(M)] = l;
  2768. }
  2769. /// <summary>
  2770. /// For the given interface, retrieve the region module which implements it.
  2771. /// </summary>
  2772. /// <returns>null if there is no registered module implementing that interface</returns>
  2773. public override T RequestModuleInterface<T>()
  2774. {
  2775. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2776. {
  2777. return (T)ModuleInterfaces[typeof(T)][0];
  2778. }
  2779. else
  2780. {
  2781. return default(T);
  2782. }
  2783. }
  2784. /// <summary>
  2785. /// For the given interface, retrieve an array of region modules that implement it.
  2786. /// </summary>
  2787. /// <returns>an empty array if there are no registered modules implementing that interface</returns>
  2788. public override T[] RequestModuleInterfaces<T>()
  2789. {
  2790. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2791. {
  2792. List<T> ret = new List<T>();
  2793. foreach (Object o in ModuleInterfaces[typeof(T)])
  2794. ret.Add((T)o);
  2795. return ret.ToArray();
  2796. }
  2797. else
  2798. {
  2799. return new T[] { default(T) };
  2800. }
  2801. }
  2802. public void SetObjectCapacity(int objects)
  2803. {
  2804. if (m_statsReporter != null)
  2805. {
  2806. m_statsReporter.SetObjectCapacity(objects);
  2807. }
  2808. objectCapacity = objects;
  2809. }
  2810. public List<FriendListItem> GetFriendList(UUID avatarID)
  2811. {
  2812. return CommsManager.GetUserFriendList(avatarID);
  2813. }
  2814. public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids)
  2815. {
  2816. return CommsManager.GetFriendRegionInfos(uuids);
  2817. }
  2818. public List<UUID> InformFriendsInOtherRegion(UUID agentId, ulong destRegionHandle, List<UUID> friends, bool online)
  2819. {
  2820. return CommsManager.InformFriendsInOtherRegion(agentId, destRegionHandle, friends, online);
  2821. }
  2822. public bool TriggerTerminateFriend(ulong regionHandle, UUID agentID, UUID exFriendID)
  2823. {
  2824. return CommsManager.TriggerTerminateFriend(regionHandle, agentID, exFriendID);
  2825. }
  2826. #endregion
  2827. #region Other Methods
  2828. /// <summary>
  2829. ///
  2830. /// </summary>
  2831. /// <param name="phase"></param>
  2832. public void SetTimePhase(int phase)
  2833. {
  2834. m_timePhase = phase;
  2835. }
  2836. /// <summary>
  2837. ///
  2838. /// </summary>
  2839. /// <param name="avatarID"></param>
  2840. /// <param name="objectName"></param>
  2841. /// <param name="objectID"></param>
  2842. /// <param name="ownerID"></param>
  2843. /// <param name="groupOwned"></param>
  2844. /// <param name="message"></param>
  2845. /// <param name="url"></param>
  2846. public void SendUrlToUser(UUID avatarID, string objectName, UUID objectID, UUID ownerID, bool groupOwned,
  2847. string message, string url)
  2848. {
  2849. lock (m_scenePresences)
  2850. {
  2851. if (m_scenePresences.ContainsKey(avatarID))
  2852. {
  2853. m_scenePresences[avatarID].ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned,
  2854. message, url);
  2855. }
  2856. }
  2857. }
  2858. public void SendDialogToUser(UUID avatarID, string objectName, UUID objectID, UUID ownerID, string message, UUID TextureID, int ch, string[] buttonlabels)
  2859. {
  2860. lock (m_scenePresences)
  2861. {
  2862. if (m_scenePresences.ContainsKey(avatarID))
  2863. {
  2864. m_scenePresences[avatarID].ControllingClient.SendDialog(
  2865. objectName, objectID, ownerID, message, TextureID, ch, buttonlabels);
  2866. }
  2867. }
  2868. }
  2869. /// <summary>
  2870. ///
  2871. /// </summary>
  2872. /// <param name="url"></param>
  2873. /// <param name="type"></param>
  2874. /// <param name="body"></param>
  2875. /// <returns></returns>
  2876. public UUID MakeHttpRequest(string url, string type, string body)
  2877. {
  2878. if (m_httpRequestModule != null)
  2879. {
  2880. return m_httpRequestModule.MakeHttpRequest(url, type, body);
  2881. }
  2882. return UUID.Zero;
  2883. }
  2884. public virtual void StoreAddFriendship(UUID ownerID, UUID friendID, uint perms)
  2885. {
  2886. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2887. }
  2888. public virtual void StoreUpdateFriendship(UUID ownerID, UUID friendID, uint perms)
  2889. {
  2890. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2891. }
  2892. public virtual void StoreRemoveFriendship(UUID ownerID, UUID ExfriendID)
  2893. {
  2894. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2895. }
  2896. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  2897. {
  2898. m_statsReporter.AddInPackets(inPackets);
  2899. m_statsReporter.AddOutPackets(outPackets);
  2900. m_statsReporter.AddunAckedBytes(unAckedBytes);
  2901. }
  2902. public void AddAgentTime(int ms)
  2903. {
  2904. m_statsReporter.addFrameMS(ms);
  2905. m_statsReporter.addAgentMS(ms);
  2906. }
  2907. public void AddAgentUpdates(int count)
  2908. {
  2909. m_statsReporter.AddAgentUpdates(count);
  2910. }
  2911. public void AddPendingDownloads(int count)
  2912. {
  2913. m_statsReporter.addPendingDownload(count);
  2914. }
  2915. #endregion
  2916. #region Console Commands
  2917. #region Alert Methods
  2918. private void SendPermissionAlert(UUID user, string reason)
  2919. {
  2920. SendAlertToUser(user, reason, false);
  2921. }
  2922. /// <summary>
  2923. /// Send an alert messages to all avatars in this scene.
  2924. /// </summary>
  2925. /// <param name="message"></param>
  2926. public void SendGeneralAlert(string message)
  2927. {
  2928. List<ScenePresence> presenceList = GetScenePresences();
  2929. foreach (ScenePresence presence in presenceList)
  2930. {
  2931. if (!presence.IsChildAgent)
  2932. presence.ControllingClient.SendAlertMessage(message);
  2933. }
  2934. }
  2935. /// <summary>
  2936. /// Send an alert message to a particular agent.
  2937. /// </summary>
  2938. /// <param name="agentID"></param>
  2939. /// <param name="message"></param>
  2940. /// <param name="modal"></param>
  2941. public void SendAlertToUser(UUID agentID, string message, bool modal)
  2942. {
  2943. lock (m_scenePresences)
  2944. {
  2945. if (m_scenePresences.ContainsKey(agentID))
  2946. {
  2947. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage(message, modal);
  2948. }
  2949. }
  2950. }
  2951. /// <summary>
  2952. /// Handle a request for admin rights
  2953. /// </summary>
  2954. /// <param name="agentID"></param>
  2955. /// <param name="sessionID"></param>
  2956. /// <param name="token"></param>
  2957. /// <param name="controllingClient"></param>
  2958. public void handleRequestGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godLike,
  2959. IClientAPI controllingClient)
  2960. {
  2961. lock (m_scenePresences)
  2962. {
  2963. // User needs to be logged into this sim
  2964. if (m_scenePresences.ContainsKey(agentID))
  2965. {
  2966. if (godLike == false)
  2967. {
  2968. m_scenePresences[agentID].GrantGodlikePowers(agentID, sessionID, token, godLike);
  2969. return;
  2970. }
  2971. // First check that this is the sim owner
  2972. if (Permissions.IsGod(agentID))
  2973. {
  2974. // Next we check for spoofing.....
  2975. UUID testSessionID = m_scenePresences[agentID].ControllingClient.SessionId;
  2976. if (sessionID == testSessionID)
  2977. {
  2978. if (sessionID == controllingClient.SessionId)
  2979. {
  2980. //m_log.Info("godlike: " + godLike.ToString());
  2981. m_scenePresences[agentID].GrantGodlikePowers(agentID, testSessionID, token, godLike);
  2982. }
  2983. }
  2984. }
  2985. else
  2986. {
  2987. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage("Request for god powers denied", false);
  2988. }
  2989. }
  2990. }
  2991. }
  2992. /// <summary>
  2993. /// Sends a Big Blue Box message on the upper right of the screen to the client
  2994. /// for all agents in the region
  2995. /// </summary>
  2996. /// <param name="FromAvatarID">The person sending the message</param>
  2997. /// <param name="fromSessionID">The session of the person sending the message</param>
  2998. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  2999. /// <param name="Message">The Message being sent to the user</param>
  3000. public void SendRegionMessageFromEstateTools(UUID FromAvatarID, UUID fromSessionID, String FromAvatarName, String Message)
  3001. {
  3002. List<ScenePresence> presenceList = GetScenePresences();
  3003. foreach (ScenePresence presence in presenceList)
  3004. {
  3005. if (!presence.IsChildAgent)
  3006. presence.ControllingClient.SendBlueBoxMessage(FromAvatarID, FromAvatarName, Message);
  3007. }
  3008. }
  3009. /// <summary>
  3010. /// Sends a Big Blue Box message on the upper right of the screen to the client
  3011. /// for all agents in the estate
  3012. /// </summary>
  3013. /// <param name="FromAvatarID">The person sending the message</param>
  3014. /// <param name="fromSessionID">The session of the person sending the message</param>
  3015. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  3016. /// <param name="Message">The Message being sent to the user</param>
  3017. public void SendEstateMessageFromEstateTools(UUID FromAvatarID, UUID fromSessionID, String FromAvatarName, String Message)
  3018. {
  3019. ClientManager.ForEachClient(delegate(IClientAPI controller)
  3020. {
  3021. controller.SendBlueBoxMessage(FromAvatarID, FromAvatarName, Message);
  3022. }
  3023. );
  3024. }
  3025. /// <summary>
  3026. /// Kicks User specified from the simulator. This logs them off of the grid
  3027. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  3028. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  3029. /// agent is assigned
  3030. /// </summary>
  3031. /// <param name="godID">The person doing the kicking</param>
  3032. /// <param name="sessionID">The session of the person doing the kicking</param>
  3033. /// <param name="agentID">the person that is being kicked</param>
  3034. /// <param name="kickflags">This isn't used apparently</param>
  3035. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  3036. public void HandleGodlikeKickUser(UUID godID, UUID sessionID, UUID agentID, uint kickflags, byte[] reason)
  3037. {
  3038. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  3039. UUID kickUserID = new UUID("44e87126e7944ded05b37c42da3d5cdb");
  3040. lock (m_scenePresences)
  3041. {
  3042. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  3043. {
  3044. if (Permissions.IsGod(godID))
  3045. {
  3046. if (agentID == kickUserID)
  3047. {
  3048. ClientManager.ForEachClient(delegate(IClientAPI controller)
  3049. {
  3050. if (controller.AgentId != godID)
  3051. controller.Kick(Utils.BytesToString(reason));
  3052. }
  3053. );
  3054. // This is a bit crude. It seems the client will be null before it actually stops the thread
  3055. // The thread will kill itself eventually :/
  3056. // Is there another way to make sure *all* clients get this 'inter region' message?
  3057. ClientManager.ForEachClient(delegate(IClientAPI controller)
  3058. {
  3059. ScenePresence p = GetScenePresence(controller.AgentId);
  3060. bool childagent = p != null && p.IsChildAgent;
  3061. if (controller.AgentId != godID && !childagent)
  3062. // Do we really want to kick the initiator of this madness?
  3063. {
  3064. controller.Close(true);
  3065. }
  3066. }
  3067. );
  3068. }
  3069. else
  3070. {
  3071. m_sceneGraph.removeUserCount(!m_scenePresences[agentID].IsChildAgent);
  3072. m_scenePresences[agentID].ControllingClient.Kick(Utils.BytesToString(reason));
  3073. m_scenePresences[agentID].ControllingClient.Close(true);
  3074. }
  3075. }
  3076. else
  3077. {
  3078. if (m_scenePresences.ContainsKey(godID))
  3079. m_scenePresences[godID].ControllingClient.SendAgentAlertMessage("Kick request denied", false);
  3080. }
  3081. }
  3082. }
  3083. }
  3084. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  3085. {
  3086. // Check for spoofing.. since this is permissions we're talking about here!
  3087. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  3088. {
  3089. // Tell the object to do permission update
  3090. if (localId != 0)
  3091. {
  3092. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  3093. if (chObjectGroup != null)
  3094. {
  3095. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  3096. }
  3097. }
  3098. }
  3099. }
  3100. /// <summary>
  3101. ///
  3102. /// </summary>
  3103. /// <param name="firstName"></param>
  3104. /// <param name="lastName"></param>
  3105. /// <param name="message"></param>
  3106. /// <param name="modal"></param>
  3107. public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
  3108. {
  3109. List<ScenePresence> presenceList = GetScenePresences();
  3110. foreach (ScenePresence presence in presenceList)
  3111. {
  3112. if (presence.Firstname == firstName && presence.Lastname == lastName)
  3113. {
  3114. presence.ControllingClient.SendAgentAlertMessage(message, modal);
  3115. break;
  3116. }
  3117. }
  3118. }
  3119. /// <summary>
  3120. /// Handle an alert command from the console.
  3121. /// FIXME: Command parsing code really shouldn't be in this core Scene class.
  3122. /// </summary>
  3123. /// <param name="commandParams"></param>
  3124. public void HandleAlertCommand(string[] commandParams)
  3125. {
  3126. if (commandParams[0] == "general")
  3127. {
  3128. string message = CombineParams(commandParams, 1);
  3129. SendGeneralAlert(message);
  3130. }
  3131. else
  3132. {
  3133. string message = CombineParams(commandParams, 2);
  3134. SendAlertToUser(commandParams[0], commandParams[1], message, false);
  3135. }
  3136. }
  3137. private string CombineParams(string[] commandParams, int pos)
  3138. {
  3139. string result = String.Empty;
  3140. for (int i = pos; i < commandParams.Length; i++)
  3141. {
  3142. result += commandParams[i] + " ";
  3143. }
  3144. return result;
  3145. }
  3146. #endregion
  3147. /// <summary>
  3148. /// Causes all clients to get a full object update on all of the objects in the scene.
  3149. /// </summary>
  3150. public void ForceClientUpdate()
  3151. {
  3152. List<EntityBase> EntityList = GetEntities();
  3153. foreach (EntityBase ent in EntityList)
  3154. {
  3155. if (ent is SceneObjectGroup)
  3156. {
  3157. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  3158. }
  3159. }
  3160. }
  3161. /// <summary>
  3162. /// This is currently only used for scale (to scale to MegaPrim size)
  3163. /// There is a console command that calls this in OpenSimMain
  3164. /// </summary>
  3165. /// <param name="cmdparams"></param>
  3166. public void HandleEditCommand(string[] cmdparams)
  3167. {
  3168. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  3169. List<EntityBase> EntityList = GetEntities();
  3170. foreach (EntityBase ent in EntityList)
  3171. {
  3172. if (ent is SceneObjectGroup)
  3173. {
  3174. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  3175. if (part != null)
  3176. {
  3177. if (part.Name == cmdparams[0])
  3178. {
  3179. part.Resize(
  3180. new Vector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  3181. Convert.ToSingle(cmdparams[3])));
  3182. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  3183. }
  3184. }
  3185. }
  3186. }
  3187. }
  3188. /// <summary>
  3189. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  3190. /// </summary>
  3191. /// <param name="showParams">What to show</param>
  3192. public void Show(string[] showParams)
  3193. {
  3194. switch (showParams[0])
  3195. {
  3196. case "users":
  3197. m_log.Error("Current Region: " + RegionInfo.RegionName);
  3198. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  3199. "Agent ID", "Session ID", "Circuit", "IP", "World");
  3200. foreach (ScenePresence scenePresence in GetAvatars())
  3201. {
  3202. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  3203. scenePresence.Firstname,
  3204. scenePresence.Lastname,
  3205. scenePresence.UUID,
  3206. scenePresence.ControllingClient.AgentId,
  3207. "Unknown",
  3208. "Unknown",
  3209. RegionInfo.RegionName);
  3210. }
  3211. break;
  3212. case "modules":
  3213. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  3214. foreach (IRegionModule module in Modules.Values)
  3215. {
  3216. if (!module.IsSharedModule)
  3217. {
  3218. m_log.Error("Region Module: " + module.Name);
  3219. }
  3220. }
  3221. break;
  3222. }
  3223. }
  3224. #endregion
  3225. #region Script Handling Methods
  3226. /// <summary>
  3227. /// Console command handler to send script command to script engine.
  3228. /// </summary>
  3229. /// <param name="args"></param>
  3230. public void SendCommandToPlugins(string[] args)
  3231. {
  3232. m_eventManager.TriggerOnPluginConsole(args);
  3233. }
  3234. public double GetLandHeight(int x, int y)
  3235. {
  3236. return Heightmap[x, y];
  3237. }
  3238. public UUID GetLandOwner(float x, float y)
  3239. {
  3240. ILandObject land = LandChannel.GetLandObject(x, y);
  3241. if (land == null)
  3242. {
  3243. return UUID.Zero;
  3244. }
  3245. else
  3246. {
  3247. return land.landData.OwnerID;
  3248. }
  3249. }
  3250. public LandData GetLandData(float x, float y)
  3251. {
  3252. return LandChannel.GetLandObject(x, y).landData;
  3253. }
  3254. public LandData GetLandData(uint x, uint y)
  3255. {
  3256. m_log.DebugFormat("[SCENE] returning land for {0},{1}", x, y);
  3257. return LandChannel.GetLandObject((int)x, (int)y).landData;
  3258. }
  3259. public void SetLandMusicURL(float x, float y, string url)
  3260. {
  3261. ILandObject land = LandChannel.GetLandObject(x, y);
  3262. if (land == null)
  3263. {
  3264. return;
  3265. }
  3266. else
  3267. {
  3268. land.landData.MusicURL = url;
  3269. land.sendLandUpdateToAvatarsOverMe();
  3270. return;
  3271. }
  3272. }
  3273. public void SetLandMediaURL(float x, float y, string url)
  3274. {
  3275. ILandObject land = LandChannel.GetLandObject(x, y);
  3276. if (land == null)
  3277. {
  3278. return;
  3279. }
  3280. else
  3281. {
  3282. land.landData.MediaURL = url;
  3283. land.sendLandUpdateToAvatarsOverMe();
  3284. return;
  3285. }
  3286. }
  3287. public RegionInfo RequestClosestRegion(string name)
  3288. {
  3289. return m_sceneGridService.RequestClosestRegion(name);
  3290. }
  3291. #endregion
  3292. #region Script Engine
  3293. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  3294. private bool m_dumpAssetsToFile;
  3295. /// <summary>
  3296. ///
  3297. /// </summary>
  3298. /// <param name="scriptEngine"></param>
  3299. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  3300. {
  3301. ScriptEngines.Add(scriptEngine);
  3302. scriptEngine.InitializeEngine(this);
  3303. }
  3304. public void TriggerObjectChanged(uint localID, uint change)
  3305. {
  3306. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  3307. }
  3308. public void TriggerAtTargetEvent(uint localID, uint handle, Vector3 targetpos, Vector3 currentpos)
  3309. {
  3310. m_eventManager.TriggerAtTargetEvent(localID, handle, targetpos, currentpos);
  3311. }
  3312. public void TriggerNotAtTargetEvent(uint localID)
  3313. {
  3314. m_eventManager.TriggerNotAtTargetEvent(localID);
  3315. }
  3316. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  3317. {
  3318. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  3319. if (part != null)
  3320. {
  3321. if (parcel != null)
  3322. {
  3323. if ((parcel.landData.Flags & (uint)Parcel.ParcelFlags.AllowOtherScripts) != 0)
  3324. {
  3325. return true;
  3326. }
  3327. else if ((parcel.landData.Flags & (uint)Parcel.ParcelFlags.AllowGroupScripts) != 0)
  3328. {
  3329. if (part.OwnerID == parcel.landData.OwnerID || (parcel.landData.IsGroupOwned && part.GroupID == parcel.landData.GroupID) || Permissions.IsGod(part.OwnerID))
  3330. {
  3331. return true;
  3332. }
  3333. else
  3334. {
  3335. return false;
  3336. }
  3337. }
  3338. else
  3339. {
  3340. if (part.OwnerID == parcel.landData.OwnerID)
  3341. {
  3342. return true;
  3343. }
  3344. else
  3345. {
  3346. return false;
  3347. }
  3348. }
  3349. }
  3350. else
  3351. {
  3352. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  3353. {
  3354. // The only time parcel != null when an object is inside a region is when
  3355. // there is nothing behind the landchannel. IE, no land plugin loaded.
  3356. return true;
  3357. }
  3358. else
  3359. {
  3360. // The object is outside of this region. Stop piping events to it.
  3361. return false;
  3362. }
  3363. }
  3364. }
  3365. else
  3366. {
  3367. return false;
  3368. }
  3369. }
  3370. public bool ScriptDanger(uint localID, Vector3 pos)
  3371. {
  3372. SceneObjectPart part = GetSceneObjectPart(localID);
  3373. if (part != null)
  3374. {
  3375. return ScriptDanger(part, pos);
  3376. }
  3377. else
  3378. {
  3379. return false;
  3380. }
  3381. }
  3382. public bool PipeEventsForScript(uint localID)
  3383. {
  3384. SceneObjectPart part = GetSceneObjectPart(localID);
  3385. if (part != null)
  3386. {
  3387. // Changed so that child prims of attachments return ScriptDanger for their parent, so that
  3388. // their scripts will actually run.
  3389. // -- Leaf, Tue Aug 12 14:17:05 EDT 2008
  3390. SceneObjectPart parent = part.ParentGroup.RootPart;
  3391. if (parent != null && parent.IsAttachment)
  3392. return ScriptDanger(parent, parent.GetWorldPosition());
  3393. else
  3394. return ScriptDanger(part, part.GetWorldPosition());
  3395. }
  3396. else
  3397. {
  3398. return false;
  3399. }
  3400. }
  3401. #endregion
  3402. #region SceneGraph wrapper methods
  3403. /// <summary>
  3404. ///
  3405. /// </summary>
  3406. /// <param name="localID"></param>
  3407. /// <returns></returns>
  3408. public UUID ConvertLocalIDToFullID(uint localID)
  3409. {
  3410. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  3411. }
  3412. public void SwapRootAgentCount(bool rootChildChildRootTF)
  3413. {
  3414. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  3415. }
  3416. public void AddPhysicalPrim(int num)
  3417. {
  3418. m_sceneGraph.AddPhysicalPrim(num);
  3419. }
  3420. public void RemovePhysicalPrim(int num)
  3421. {
  3422. m_sceneGraph.RemovePhysicalPrim(num);
  3423. }
  3424. //The idea is to have a group of method that return a list of avatars meeting some requirement
  3425. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  3426. /// <summary>
  3427. /// Return a list of all avatars in this region.
  3428. /// This list is a new object, so it can be iterated over without locking.
  3429. /// </summary>
  3430. /// <returns></returns>
  3431. public List<ScenePresence> GetAvatars()
  3432. {
  3433. return m_sceneGraph.GetAvatars();
  3434. }
  3435. /// <summary>
  3436. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  3437. /// This list is a new object, so it can be iterated over without locking.
  3438. /// </summary>
  3439. /// <returns></returns>
  3440. public List<ScenePresence> GetScenePresences()
  3441. {
  3442. return m_sceneGraph.GetScenePresences();
  3443. }
  3444. /// <summary>
  3445. /// Request a filtered list of ScenePresences in this region.
  3446. /// This list is a new object, so it can be iterated over without locking.
  3447. /// </summary>
  3448. /// <param name="filter"></param>
  3449. /// <returns></returns>
  3450. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  3451. {
  3452. return m_sceneGraph.GetScenePresences(filter);
  3453. }
  3454. /// <summary>
  3455. /// Request a scene presence by UUID
  3456. /// </summary>
  3457. /// <param name="avatarID"></param>
  3458. /// <returns></returns>
  3459. public ScenePresence GetScenePresence(UUID avatarID)
  3460. {
  3461. return m_sceneGraph.GetScenePresence(avatarID);
  3462. }
  3463. public override bool PresenceChildStatus(UUID avatarID)
  3464. {
  3465. ScenePresence cp = GetScenePresence(avatarID);
  3466. // FIXME: This is really crap - some logout code is relying on a NullReferenceException to halt its processing
  3467. // This needs to be fixed properly by cleaning up the logout code.
  3468. //if (cp != null)
  3469. // return cp.IsChildAgent;
  3470. //return false;
  3471. return cp.IsChildAgent;
  3472. }
  3473. /// <summary>
  3474. ///
  3475. /// </summary>
  3476. /// <param name="action"></param>
  3477. public void ForEachScenePresence(Action<ScenePresence> action)
  3478. {
  3479. // We don't want to try to send messages if there are no avatars.
  3480. if (m_scenePresences != null)
  3481. {
  3482. try
  3483. {
  3484. List<ScenePresence> presenceList = GetScenePresences();
  3485. foreach (ScenePresence presence in presenceList)
  3486. {
  3487. action(presence);
  3488. }
  3489. }
  3490. catch (Exception e)
  3491. {
  3492. m_log.Info("[BUG]: " + e.ToString());
  3493. }
  3494. }
  3495. }
  3496. /// <summary>
  3497. ///
  3498. /// </summary>
  3499. /// <param name="action"></param>
  3500. // public void ForEachObject(Action<SceneObjectGroup> action)
  3501. // {
  3502. // List<SceneObjectGroup> presenceList;
  3503. //
  3504. // lock (m_sceneObjects)
  3505. // {
  3506. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  3507. // }
  3508. //
  3509. // foreach (SceneObjectGroup presence in presenceList)
  3510. // {
  3511. // action(presence);
  3512. // }
  3513. // }
  3514. /// <summary>
  3515. /// Get a named prim contained in this scene (will return the first
  3516. /// found, if there are more than one prim with the same name)
  3517. /// </summary>
  3518. /// <param name="name"></param>
  3519. /// <returns></returns>
  3520. public SceneObjectPart GetSceneObjectPart(string name)
  3521. {
  3522. return m_sceneGraph.GetSceneObjectPart(name);
  3523. }
  3524. /// <summary>
  3525. /// Get a prim via its local id
  3526. /// </summary>
  3527. /// <param name="localID"></param>
  3528. /// <returns></returns>
  3529. public SceneObjectPart GetSceneObjectPart(uint localID)
  3530. {
  3531. return m_sceneGraph.GetSceneObjectPart(localID);
  3532. }
  3533. /// <summary>
  3534. /// Get a prim via its UUID
  3535. /// </summary>
  3536. /// <param name="fullID"></param>
  3537. /// <returns></returns>
  3538. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  3539. {
  3540. return m_sceneGraph.GetSceneObjectPart(fullID);
  3541. }
  3542. internal bool TryGetAvatar(UUID avatarId, out ScenePresence avatar)
  3543. {
  3544. return m_sceneGraph.TryGetAvatar(avatarId, out avatar);
  3545. }
  3546. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  3547. {
  3548. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  3549. }
  3550. public void ForEachClient(Action<IClientAPI> action)
  3551. {
  3552. m_sceneGraph.ForEachClient(action);
  3553. }
  3554. /// <summary>
  3555. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  3556. /// will not affect the original list of objects in the scene.
  3557. /// </summary>
  3558. /// <returns></returns>
  3559. public List<EntityBase> GetEntities()
  3560. {
  3561. return m_sceneGraph.GetEntities();
  3562. }
  3563. #endregion
  3564. #region BaseHTTPServer wrapper methods
  3565. public bool AddHTTPHandler(string method, GenericHTTPMethod handler)
  3566. {
  3567. return m_httpListener.AddHTTPHandler(method, handler);
  3568. }
  3569. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  3570. {
  3571. return m_httpListener.AddXmlRPCHandler(method, handler);
  3572. }
  3573. public void AddStreamHandler(IRequestHandler handler)
  3574. {
  3575. m_httpListener.AddStreamHandler(handler);
  3576. }
  3577. public bool AddLLSDHandler(string path, LLSDMethod handler)
  3578. {
  3579. return m_httpListener.AddLLSDHandler(path, handler);
  3580. }
  3581. public void RemoveStreamHandler(string httpMethod, string path)
  3582. {
  3583. m_httpListener.RemoveStreamHandler(httpMethod, path);
  3584. }
  3585. public void RemoveHTTPHandler(string httpMethod, string path)
  3586. {
  3587. m_httpListener.RemoveHTTPHandler(httpMethod, path);
  3588. }
  3589. public bool RemoveLLSDHandler(string path, LLSDMethod handler)
  3590. {
  3591. return m_httpListener.RemoveLLSDHandler(path, handler);
  3592. }
  3593. #endregion
  3594. #region Avatar Appearance Default
  3595. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  3596. {
  3597. visualParams = GetDefaultVisualParams();
  3598. wearables = AvatarWearable.DefaultWearables;
  3599. }
  3600. private static byte[] GetDefaultVisualParams()
  3601. {
  3602. byte[] visualParams;
  3603. visualParams = new byte[218];
  3604. for (int i = 0; i < 218; i++)
  3605. {
  3606. visualParams[i] = 100;
  3607. }
  3608. return visualParams;
  3609. }
  3610. #endregion
  3611. public void ParcelMediaSetTime(float time)
  3612. {
  3613. //should be doing this by parcel, but as its only for testing
  3614. // The use of Thread.Sleep here causes the following compiler error under mono 1.2.4
  3615. // OpenSim/Region/Environment/Scenes/Scene.cs(3675,17): error CS0103: The name `Thread' does not exist
  3616. // in the context of `<>c__CompilerGenerated17'
  3617. // MW said it was okay to comment the body of this method out for now since the code is experimental
  3618. // and will be replaced anyway
  3619. // ForEachClient(delegate(IClientAPI client)
  3620. // {
  3621. // client.SendParcelMediaCommand((uint)(2), ParcelMediaCommandEnum.Pause, 0);
  3622. // Thread.Sleep(10);
  3623. // client.SendParcelMediaCommand((uint)(64), ParcelMediaCommandEnum.Time, time);
  3624. // Thread.Sleep(200);
  3625. // client.SendParcelMediaCommand((uint)(4), ParcelMediaCommandEnum.Play, 0);
  3626. // });
  3627. }
  3628. public void RegionHandleRequest(IClientAPI client, UUID regionID)
  3629. {
  3630. RegionInfo info;
  3631. if (regionID == RegionInfo.RegionID)
  3632. info = RegionInfo;
  3633. else
  3634. info = CommsManager.GridService.RequestNeighbourInfo(regionID);
  3635. if (info != null)
  3636. client.SendRegionHandle(regionID, info.RegionHandle);
  3637. }
  3638. public void TerrainUnAcked(IClientAPI client, int patchX, int patchY)
  3639. {
  3640. //Console.WriteLine("Terrain packet unacked, resending patch: " + patchX + " , " + patchY);
  3641. client.SendLayerData(patchX, patchY, Heightmap.GetFloatsSerialised());
  3642. }
  3643. public void SetRootAgentScene(UUID agentID)
  3644. {
  3645. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3646. if (inv == null)
  3647. return;
  3648. inv.SetRootAgentScene(agentID, this);
  3649. EventManager.TriggerSetRootAgentScene(agentID, this);
  3650. }
  3651. public bool NeedSceneCacheClear(UUID agentID)
  3652. {
  3653. IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  3654. if (inv == null)
  3655. return true;
  3656. return inv.NeedSceneCacheClear(agentID, this);
  3657. }
  3658. public void ObjectSaleInfo(IClientAPI client, UUID agentID, UUID sessionID, uint localID, byte saleType, int salePrice)
  3659. {
  3660. SceneObjectPart part = GetSceneObjectPart(localID);
  3661. if (part == null || part.ParentGroup == null)
  3662. return;
  3663. if (part.ParentGroup.IsDeleted)
  3664. return;
  3665. part = part.ParentGroup.RootPart;
  3666. part.ObjectSaleType = saleType;
  3667. part.SalePrice = salePrice;
  3668. part.ParentGroup.HasGroupChanged = true;
  3669. part.GetProperties(client);
  3670. }
  3671. public bool PerformObjectBuy(IClientAPI remoteClient, UUID categoryID,
  3672. uint localID, byte saleType)
  3673. {
  3674. SceneObjectPart part = GetSceneObjectPart(localID);
  3675. if (part == null)
  3676. return false;
  3677. if (part.ParentGroup == null)
  3678. return false;
  3679. SceneObjectGroup group = part.ParentGroup;
  3680. switch (saleType)
  3681. {
  3682. case 1: // Sell as original (in-place sale)
  3683. uint effectivePerms=group.GetEffectivePermissions();
  3684. if ((effectivePerms & (uint)PermissionMask.Transfer) == 0)
  3685. {
  3686. remoteClient.SendAgentAlertMessage("This item doesn't appear to be for sale", false);
  3687. return false;
  3688. }
  3689. group.SetOwnerId(remoteClient.AgentId);
  3690. group.SetRootPartOwner(part, remoteClient.AgentId,
  3691. remoteClient.ActiveGroupId);
  3692. List<SceneObjectPart> partList =
  3693. new List<SceneObjectPart>(group.Children.Values);
  3694. if (Permissions.PropagatePermissions())
  3695. {
  3696. foreach (SceneObjectPart child in partList)
  3697. {
  3698. child.Inventory.ChangeInventoryOwner(remoteClient.AgentId);
  3699. child.ApplyNextOwnerPermissions();
  3700. }
  3701. }
  3702. part.ObjectSaleType = 0;
  3703. part.SalePrice = 10;
  3704. group.HasGroupChanged = true;
  3705. part.GetProperties(remoteClient);
  3706. part.ScheduleFullUpdate();
  3707. break;
  3708. case 2: // Sell a copy
  3709. string sceneObjectXml = group.ToXmlString();
  3710. CachedUserInfo userInfo =
  3711. CommsManager.UserProfileCacheService.GetUserDetails(remoteClient.AgentId);
  3712. if (userInfo != null)
  3713. {
  3714. uint perms=group.GetEffectivePermissions();
  3715. if ((perms & (uint)PermissionMask.Transfer) == 0)
  3716. {
  3717. remoteClient.SendAgentAlertMessage("This item doesn't appear to be for sale", false);
  3718. return false;
  3719. }
  3720. AssetBase asset = CreateAsset(
  3721. group.GetPartName(localID),
  3722. group.GetPartDescription(localID),
  3723. (sbyte)AssetType.Object,
  3724. Utils.StringToBytes(sceneObjectXml));
  3725. AssetCache.AddAsset(asset);
  3726. InventoryItemBase item = new InventoryItemBase();
  3727. item.Creator = part.CreatorID;
  3728. item.ID = UUID.Random();
  3729. item.Owner = remoteClient.AgentId;
  3730. item.AssetID = asset.FullID;
  3731. item.Description = asset.Description;
  3732. item.Name = asset.Name;
  3733. item.AssetType = asset.Type;
  3734. item.InvType = (int)InventoryType.Object;
  3735. item.Folder = categoryID;
  3736. uint nextPerms=(perms & 7) << 13;
  3737. if ((nextPerms & (uint)PermissionMask.Copy) == 0)
  3738. perms &= ~(uint)PermissionMask.Copy;
  3739. if ((nextPerms & (uint)PermissionMask.Transfer) == 0)
  3740. perms &= ~(uint)PermissionMask.Transfer;
  3741. if ((nextPerms & (uint)PermissionMask.Modify) == 0)
  3742. perms &= ~(uint)PermissionMask.Modify;
  3743. item.BasePermissions = perms & part.NextOwnerMask;
  3744. item.CurrentPermissions = perms & part.NextOwnerMask;
  3745. item.NextPermissions = part.NextOwnerMask;
  3746. item.EveryOnePermissions = part.EveryoneMask &
  3747. part.NextOwnerMask;
  3748. item.GroupPermissions = part.GroupMask &
  3749. part.NextOwnerMask;
  3750. item.CurrentPermissions |= 8; // Slam!
  3751. item.CreationDate = Util.UnixTimeSinceEpoch();
  3752. userInfo.AddItem(item);
  3753. remoteClient.SendInventoryItemCreateUpdate(item);
  3754. }
  3755. else
  3756. {
  3757. remoteClient.SendAgentAlertMessage("Cannot buy now. Your inventory is unavailable", false);
  3758. return false;
  3759. }
  3760. break;
  3761. case 3: // Sell contents
  3762. List<UUID> invList = part.Inventory.GetInventoryList();
  3763. bool okToSell = true;
  3764. foreach (UUID invID in invList)
  3765. {
  3766. TaskInventoryItem item = part.Inventory.GetInventoryItem(invID);
  3767. if ((item.CurrentPermissions &
  3768. (uint)PermissionMask.Transfer) == 0)
  3769. {
  3770. okToSell = false;
  3771. break;
  3772. }
  3773. }
  3774. if (!okToSell)
  3775. {
  3776. remoteClient.SendAgentAlertMessage("This item's inventory doesn't appear to be for sale", false);
  3777. return false;
  3778. }
  3779. if (invList.Count > 0)
  3780. MoveTaskInventoryItems(remoteClient.AgentId, part.Name,
  3781. part, invList);
  3782. break;
  3783. }
  3784. return true;
  3785. }
  3786. public void CleanTempObjects()
  3787. {
  3788. List<EntityBase> objs = GetEntities();
  3789. foreach (EntityBase obj in objs)
  3790. {
  3791. if (obj is SceneObjectGroup)
  3792. {
  3793. SceneObjectGroup grp = (SceneObjectGroup)obj;
  3794. if (!grp.IsDeleted)
  3795. {
  3796. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  3797. {
  3798. if (grp.RootPart.Expires <= DateTime.Now)
  3799. DeleteSceneObject(grp, false);
  3800. }
  3801. }
  3802. }
  3803. }
  3804. }
  3805. public void DeleteFromStorage(UUID uuid)
  3806. {
  3807. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  3808. }
  3809. public int GetHealth()
  3810. {
  3811. int health=1; // Start at 1, means we're up
  3812. // A login in the last 4 mins? We can't be doing too badly
  3813. //
  3814. if ((System.Environment.TickCount - m_LastLogin) < 240000)
  3815. health++;
  3816. return 0;
  3817. }
  3818. }
  3819. }