Scene.cs 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the 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.Threading;
  32. using System.Timers;
  33. using Axiom.Math;
  34. using libsecondlife;
  35. using libsecondlife.Packets;
  36. using OpenJPEGNet;
  37. using OpenSim.Framework;
  38. using OpenSim.Framework.Communications;
  39. using OpenSim.Framework.Communications.Cache;
  40. using OpenSim.Framework.Servers;
  41. using OpenSim.Region.Environment.Interfaces;
  42. using OpenSim.Region.Environment.Modules.World.Archiver;
  43. using OpenSim.Region.Environment.Modules.World.Terrain;
  44. using OpenSim.Region.Environment.Scenes.Scripting;
  45. using OpenSim.Region.Physics.Manager;
  46. using Nini.Config;
  47. using Caps=OpenSim.Framework.Communications.Capabilities.Caps;
  48. using Image=System.Drawing.Image;
  49. using Timer=System.Timers.Timer;
  50. namespace OpenSim.Region.Environment.Scenes
  51. {
  52. public delegate bool FilterAvatarList(ScenePresence avatar);
  53. public partial class Scene : SceneBase
  54. {
  55. public delegate void SynchronizeSceneHandler(Scene scene);
  56. public SynchronizeSceneHandler SynchronizeScene = null;
  57. public int splitID = 0;
  58. #region Fields
  59. protected Timer m_heartbeatTimer = new Timer();
  60. protected Timer m_restartWaitTimer = new Timer();
  61. protected SimStatsReporter m_statsReporter;
  62. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  63. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  64. public InnerScene m_innerScene;
  65. private Random Rand = new Random();
  66. private uint _primCount = 720000;
  67. private readonly Mutex _primAllocateMutex = new Mutex(false);
  68. private int m_timePhase = 24;
  69. private readonly Mutex updateLock;
  70. public bool m_physicalPrim;
  71. public bool m_seeIntoRegionFromNeighbor;
  72. public int MaxUndoCount = 5;
  73. private int m_RestartTimerCounter;
  74. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  75. private int m_incrementsof15seconds = 0;
  76. private volatile bool m_backingup = false;
  77. protected string m_simulatorVersion = "unknown";
  78. protected ModuleLoader m_moduleLoader;
  79. protected StorageManager m_storageManager;
  80. protected AgentCircuitManager m_authenticateHandler;
  81. public CommunicationsManager CommsManager;
  82. protected SceneCommunicationService m_sceneGridService;
  83. protected SceneXmlLoader m_sceneXmlLoader;
  84. /// <summary>
  85. /// Each agent has its own capabilities handler.
  86. /// </summary>
  87. protected Dictionary<LLUUID, Caps> m_capsHandlers = new Dictionary<LLUUID, Caps>();
  88. protected BaseHttpServer m_httpListener;
  89. protected Dictionary<string, IRegionModule> Modules = new Dictionary<string, IRegionModule>();
  90. protected Dictionary<Type, object> ModuleInterfaces = new Dictionary<Type, object>();
  91. protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
  92. protected Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
  93. //API module interfaces
  94. public IXfer XferManager;
  95. protected IHttpRequests m_httpRequestModule;
  96. protected IXMLRPC m_xmlrpcModule;
  97. protected IWorldComm m_worldCommModule;
  98. protected IAvatarFactory m_AvatarFactory;
  99. protected IConfigSource m_config;
  100. // Central Update Loop
  101. protected int m_fps = 10;
  102. protected int m_frame = 0;
  103. protected float m_timespan = 0.089f;
  104. protected DateTime m_lastupdate = DateTime.Now;
  105. protected float m_timedilation = 1.0f;
  106. private int m_update_physics = 1;
  107. private int m_update_entitymovement = 1;
  108. private int m_update_entities = 1; // Run through all objects checking for updates
  109. private int m_update_entitiesquick = 200; // Run through objects that have scheduled updates checking for updates
  110. private int m_update_presences = 1; // Update scene presence movements
  111. private int m_update_events = 1;
  112. private int m_update_backup = 200;
  113. private int m_update_terrain = 50;
  114. private int m_update_land = 1;
  115. private int frameMS = 0;
  116. private int physicsMS2 = 0;
  117. private int physicsMS = 0;
  118. private int otherMS = 0;
  119. private bool m_physics_enabled = true;
  120. private bool m_scripts_enabled = true;
  121. #endregion
  122. #region Properties
  123. public AgentCircuitManager AuthenticateHandler
  124. {
  125. get { return m_authenticateHandler; }
  126. }
  127. // an instance to the physics plugin's Scene object.
  128. public PhysicsScene PhysicsScene
  129. {
  130. set { m_innerScene.PhysicsScene = value; }
  131. get { return (m_innerScene.PhysicsScene); }
  132. }
  133. // This gets locked so things stay thread safe.
  134. public object SyncRoot
  135. {
  136. get { return m_innerScene.m_syncRoot; }
  137. }
  138. public float TimeDilation
  139. {
  140. get { return m_timedilation; }
  141. }
  142. public int TimePhase
  143. {
  144. get { return m_timePhase; }
  145. }
  146. // Local reference to the objects in the scene (which are held in innerScene)
  147. // public Dictionary<LLUUID, SceneObjectGroup> Objects
  148. // {
  149. // get { return m_innerScene.SceneObjects; }
  150. // }
  151. // Reference to all of the agents in the scene (root and child)
  152. protected Dictionary<LLUUID, ScenePresence> m_scenePresences
  153. {
  154. get { return m_innerScene.ScenePresences; }
  155. set { m_innerScene.ScenePresences = value; }
  156. }
  157. // protected Dictionary<LLUUID, SceneObjectGroup> m_sceneObjects
  158. // {
  159. // get { return m_innerScene.SceneObjects; }
  160. // set { m_innerScene.SceneObjects = value; }
  161. // }
  162. /// <summary>
  163. /// The dictionary of all entities in this scene. The contents of this dictionary may be changed at any time.
  164. /// If you wish to add or remove entities, please use the appropriate method for that entity rather than
  165. /// editing this dictionary directly.
  166. ///
  167. /// If you want a list of entities where the list itself is guaranteed not to change, please use
  168. /// GetEntities()
  169. /// </summary>
  170. public Dictionary<LLUUID, EntityBase> Entities
  171. {
  172. get { return m_innerScene.Entities; }
  173. set { m_innerScene.Entities = value; }
  174. }
  175. public Dictionary<LLUUID, ScenePresence> m_restorePresences
  176. {
  177. get { return m_innerScene.RestorePresences; }
  178. set { m_innerScene.RestorePresences = value; }
  179. }
  180. public int objectCapacity = 45000;
  181. #endregion
  182. #region Constructors
  183. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  184. CommunicationsManager commsMan, SceneCommunicationService sceneGridService,
  185. AssetCache assetCach, StorageManager storeManager, BaseHttpServer httpServer,
  186. ModuleLoader moduleLoader, bool dumpAssetsToFile, bool physicalPrim,
  187. bool SeeIntoRegionFromNeighbor, IConfigSource config, string simulatorVersion)
  188. {
  189. m_config = config;
  190. updateLock = new Mutex(false);
  191. m_moduleLoader = moduleLoader;
  192. m_authenticateHandler = authen;
  193. CommsManager = commsMan;
  194. m_sceneGridService = sceneGridService;
  195. m_sceneGridService.debugRegionName = regInfo.RegionName;
  196. m_storageManager = storeManager;
  197. AssetCache = assetCach;
  198. m_regInfo = regInfo;
  199. m_regionHandle = m_regInfo.RegionHandle;
  200. m_regionName = m_regInfo.RegionName;
  201. m_datastore = m_regInfo.DataStore;
  202. m_physicalPrim = physicalPrim;
  203. m_seeIntoRegionFromNeighbor = SeeIntoRegionFromNeighbor;
  204. m_eventManager = new EventManager();
  205. m_externalChecks = new SceneExternalChecks(this);
  206. //Bind Storage Manager functions to some land manager functions for this scene
  207. EventManager.OnLandObjectAdded +=
  208. new EventManager.LandObjectAdded(m_storageManager.DataStore.StoreLandObject);
  209. EventManager.OnLandObjectRemoved +=
  210. new EventManager.LandObjectRemoved(m_storageManager.DataStore.RemoveLandObject);
  211. m_innerScene = new InnerScene(this, m_regInfo);
  212. // If the Inner scene has an Unrecoverable error, restart this sim.
  213. // Currently the only thing that causes it to happen is two kinds of specific
  214. // Physics based crashes.
  215. //
  216. // Out of memory
  217. // Operating system has killed the plugin
  218. m_innerScene.UnRecoverableError += RestartNow;
  219. m_sceneXmlLoader = new SceneXmlLoader(this, m_innerScene, m_regInfo);
  220. RegisterDefaultSceneEvents();
  221. m_httpListener = httpServer;
  222. m_dumpAssetsToFile = dumpAssetsToFile;
  223. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipScripts) == Simulator.RegionFlags.SkipScripts)
  224. {
  225. m_scripts_enabled = false;
  226. }
  227. else
  228. {
  229. m_scripts_enabled = true;
  230. }
  231. if ((RegionInfo.EstateSettings.regionFlags & Simulator.RegionFlags.SkipPhysics) == Simulator.RegionFlags.SkipPhysics)
  232. {
  233. m_physics_enabled = false;
  234. }
  235. else
  236. {
  237. m_physics_enabled = true;
  238. }
  239. m_statsReporter = new SimStatsReporter(regInfo);
  240. m_statsReporter.OnSendStatsResult += SendSimStatsPackets;
  241. m_statsReporter.SetObjectCapacity(objectCapacity);
  242. m_simulatorVersion = simulatorVersion
  243. + " ChilTasks:" + m_seeIntoRegionFromNeighbor.ToString()
  244. + " PhysPrim:" + m_physicalPrim.ToString();
  245. }
  246. #endregion
  247. #region Startup / Close Methods
  248. protected virtual void RegisterDefaultSceneEvents()
  249. {
  250. m_eventManager.OnPermissionError += SendPermissionAlert;
  251. }
  252. public override string GetSimulatorVersion()
  253. {
  254. return m_simulatorVersion;
  255. }
  256. public override bool OtherRegionUp(RegionInfo otherRegion)
  257. {
  258. // Another region is up.
  259. // Gets called from Grid Comms (SceneCommunicationService<---RegionListener<----LocalBackEnd<----OGS1)
  260. // We have to tell all our ScenePresences about it..
  261. // and add it to the neighbor list.
  262. // We only add it to the neighbor list if it's within 1 region from here.
  263. // Agents may have draw distance values that cross two regions though, so
  264. // we add it to the notify list regardless of distance.
  265. // We'll check the agent's draw distance before notifying them though.
  266. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  267. {
  268. for (int i = 0; i < m_neighbours.Count; i++)
  269. {
  270. // The purpose of this loop is to re-update the known neighbors
  271. // when another region comes up on top of another one.
  272. // The latest region in that location ends up in the
  273. // 'known neighbors list'
  274. // Additionally, the commFailTF property gets reset to false.
  275. if (m_neighbours[i].RegionHandle == otherRegion.RegionHandle)
  276. {
  277. lock (m_neighbours)
  278. {
  279. m_neighbours[i] = otherRegion;
  280. }
  281. }
  282. }
  283. // If the value isn't in the neighbours, add it.
  284. // If the RegionInfo isn't exact but is for the same XY World location,
  285. // then the above loop will fix that.
  286. if (!(CheckNeighborRegion(otherRegion)))
  287. {
  288. lock (m_neighbours)
  289. {
  290. m_neighbours.Add(otherRegion);
  291. //m_log.Info("[UP]: " + otherRegion.RegionHandle.ToString());
  292. }
  293. }
  294. // If these are cast to INT because long + negative values + abs returns invalid data
  295. int resultX = Math.Abs((int)otherRegion.RegionLocX - (int)RegionInfo.RegionLocX);
  296. int resultY = Math.Abs((int)otherRegion.RegionLocY - (int)RegionInfo.RegionLocY);
  297. if ((resultX <= 1) &&
  298. (resultY <= 1))
  299. {
  300. try
  301. {
  302. ForEachScenePresence(delegate(ScenePresence agent)
  303. {
  304. // If agent is a root agent.
  305. if (!agent.IsChildAgent)
  306. {
  307. //agent.ControllingClient.new
  308. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  309. InformClientOfNeighbor(agent, otherRegion);
  310. }
  311. }
  312. );
  313. }
  314. catch (NullReferenceException)
  315. {
  316. // This means that we're not booted up completely yet.
  317. // This shouldn't happen too often anymore.
  318. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  319. }
  320. }
  321. else
  322. {
  323. m_log.Info("[INTERGRID]: Got notice about far away Region: " + otherRegion.RegionName.ToString() +
  324. " at (" + otherRegion.RegionLocX.ToString() + ", " +
  325. otherRegion.RegionLocY.ToString() + ")");
  326. }
  327. }
  328. return true;
  329. }
  330. // Given float seconds, this will restart the region.
  331. public void AddNeighborRegion(RegionInfo region)
  332. {
  333. lock (m_neighbours)
  334. {
  335. if (!CheckNeighborRegion(region))
  336. {
  337. m_neighbours.Add(region);
  338. }
  339. }
  340. }
  341. public bool CheckNeighborRegion(RegionInfo region)
  342. {
  343. bool found = false;
  344. lock (m_neighbours)
  345. {
  346. foreach (RegionInfo reg in m_neighbours)
  347. {
  348. if (reg.RegionHandle == region.RegionHandle)
  349. {
  350. found = true;
  351. break;
  352. }
  353. }
  354. }
  355. return found;
  356. }
  357. public virtual void Restart(float seconds)
  358. {
  359. // notifications are done in 15 second increments
  360. // so .. if the number of seconds is less then 15 seconds, it's not really a restart request
  361. // It's a 'Cancel restart' request.
  362. // RestartNow() does immediate restarting.
  363. if (seconds < 15)
  364. {
  365. m_restartTimer.Stop();
  366. SendGeneralAlert("Restart Aborted");
  367. }
  368. else
  369. {
  370. // Now we figure out what to set the timer to that does the notifications and calls, RestartNow()
  371. m_restartTimer.Interval = 15000;
  372. m_incrementsof15seconds = (int)seconds / 15;
  373. m_RestartTimerCounter = 0;
  374. m_restartTimer.AutoReset = true;
  375. m_restartTimer.Elapsed += new ElapsedEventHandler(RestartTimer_Elapsed);
  376. m_log.Error("[REGION]: Restarting Region in " + (seconds / 60) + " minutes");
  377. m_restartTimer.Start();
  378. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in 2 Minutes");
  379. //SendGeneralAlert(RegionInfo.RegionName + ": Restarting in 2 Minutes");
  380. }
  381. }
  382. // The Restart timer has occured.
  383. // We have to figure out if this is a notification or if the number of seconds specified in Restart
  384. // have elapsed.
  385. // If they have elapsed, call RestartNow()
  386. public void RestartTimer_Elapsed(object sender, ElapsedEventArgs e)
  387. {
  388. m_RestartTimerCounter++;
  389. if (m_RestartTimerCounter <= m_incrementsof15seconds)
  390. {
  391. if (m_RestartTimerCounter == 4 || m_RestartTimerCounter == 6 || m_RestartTimerCounter == 7)
  392. SendRegionMessageFromEstateTools(LLUUID.Random(), LLUUID.Random(), String.Empty, RegionInfo.RegionName + ": Restarting in " +
  393. ((8 - m_RestartTimerCounter) * 15) + " seconds");
  394. // SendGeneralAlert(RegionInfo.RegionName + ": Restarting in " + ((8 - m_RestartTimerCounter)*15) +
  395. //" seconds");
  396. }
  397. else
  398. {
  399. m_restartTimer.Stop();
  400. m_restartTimer.AutoReset = false;
  401. RestartNow();
  402. }
  403. }
  404. // This causes the region to restart immediatley.
  405. public void RestartNow()
  406. {
  407. if (PhysicsScene != null)
  408. {
  409. PhysicsScene.Dispose();
  410. }
  411. m_log.Error("[REGION]: Closing");
  412. Close();
  413. m_log.Error("[REGION]: Firing Region Restart Message");
  414. base.Restart(0);
  415. }
  416. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  417. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  418. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  419. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  420. // subsequently the agent will never see the region come back online.
  421. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  422. {
  423. m_restartWaitTimer.Stop();
  424. lock (m_regionRestartNotifyList)
  425. {
  426. foreach (RegionInfo region in m_regionRestartNotifyList)
  427. {
  428. try
  429. {
  430. ForEachScenePresence(delegate(ScenePresence agent)
  431. {
  432. // If agent is a root agent.
  433. if (!agent.IsChildAgent)
  434. {
  435. //agent.ControllingClient.new
  436. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  437. InformClientOfNeighbor(agent, region);
  438. }
  439. }
  440. );
  441. }
  442. catch (NullReferenceException)
  443. {
  444. // This means that we're not booted up completely yet.
  445. // This shouldn't happen too often anymore.
  446. }
  447. }
  448. // Reset list to nothing.
  449. m_regionRestartNotifyList.Clear();
  450. }
  451. }
  452. public void SetSceneCoreDebug(bool ScriptEngine, bool CollisionEvents, bool PhysicsEngine)
  453. {
  454. if (m_scripts_enabled != !ScriptEngine)
  455. {
  456. // Tedd! Here's the method to disable the scripting engine!
  457. if (ScriptEngine)
  458. {
  459. m_log.Info("Stopping all Scripts in Scene");
  460. lock (Entities)
  461. {
  462. foreach (EntityBase ent in Entities.Values)
  463. {
  464. if (ent is SceneObjectGroup)
  465. {
  466. ((SceneObjectGroup)ent).StopScripts();
  467. }
  468. }
  469. }
  470. }
  471. else
  472. {
  473. m_log.Info("Starting all Scripts in Scene");
  474. lock (Entities)
  475. {
  476. foreach (EntityBase ent in Entities.Values)
  477. {
  478. if (ent is SceneObjectGroup)
  479. {
  480. ((SceneObjectGroup)ent).StartScripts();
  481. }
  482. }
  483. }
  484. }
  485. m_scripts_enabled = !ScriptEngine;
  486. m_log.Info("[TOTEDD]: Here is the method to trigger disabling of the scripting engine");
  487. }
  488. if (m_physics_enabled != !PhysicsEngine)
  489. {
  490. m_physics_enabled = !PhysicsEngine;
  491. }
  492. }
  493. public int GetInaccurateNeighborCount()
  494. {
  495. lock (m_neighbours)
  496. return m_neighbours.Count;
  497. }
  498. // This is the method that shuts down the scene.
  499. public override void Close()
  500. {
  501. m_log.Warn("[SCENE]: Closing down the single simulator: " + RegionInfo.RegionName);
  502. // Kick all ROOT agents with the message, 'The simulator is going down'
  503. ForEachScenePresence(delegate(ScenePresence avatar)
  504. {
  505. if (avatar.KnownChildRegions.Contains(RegionInfo.RegionHandle))
  506. avatar.KnownChildRegions.Remove(RegionInfo.RegionHandle);
  507. if (!avatar.IsChildAgent)
  508. avatar.ControllingClient.Kick("The simulator is going down.");
  509. avatar.ControllingClient.SendShutdownConnectionNotice();
  510. });
  511. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  512. Thread.Sleep(500);
  513. // Stop all client threads.
  514. ForEachScenePresence(delegate(ScenePresence avatar) { avatar.ControllingClient.Close(true); });
  515. // Stop updating the scene objects and agents.
  516. m_heartbeatTimer.Close();
  517. // close the inner scene
  518. m_innerScene.Close();
  519. // De-register with region communications (events cleanup)
  520. UnRegisterReginWithComms();
  521. // Shut down all non shared modules.
  522. foreach (IRegionModule module in Modules.Values)
  523. {
  524. if (!module.IsSharedModule)
  525. {
  526. module.Close();
  527. }
  528. }
  529. Modules.Clear();
  530. // call the base class Close method.
  531. base.Close();
  532. }
  533. /// <summary>
  534. /// Start the timer which triggers regular scene updates
  535. /// </summary>
  536. public void StartTimer()
  537. {
  538. m_log.Debug("[SCENE]: Starting timer");
  539. m_heartbeatTimer.Enabled = true;
  540. m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  541. m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  542. }
  543. /// <summary>
  544. /// Sets up references to modules required by the scene
  545. /// </summary>
  546. public void SetModuleInterfaces()
  547. {
  548. m_httpRequestModule = RequestModuleInterface<IHttpRequests>();
  549. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  550. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  551. XferManager = RequestModuleInterface<IXfer>();
  552. m_AvatarFactory = RequestModuleInterface<IAvatarFactory>();
  553. }
  554. #endregion
  555. #region Update Methods
  556. /// <summary>
  557. /// Performs per-frame updates regularly
  558. /// </summary>
  559. /// <param name="sender"></param>
  560. /// <param name="e"></param>
  561. private void Heartbeat(object sender, EventArgs e)
  562. {
  563. Update();
  564. }
  565. /// <summary>
  566. /// Performs per-frame updates on the scene, this should be the central scene loop
  567. /// </summary>
  568. public override void Update()
  569. {
  570. TimeSpan SinceLastFrame = DateTime.Now - m_lastupdate;
  571. // Aquire a lock so only one update call happens at once
  572. updateLock.WaitOne();
  573. float physicsFPS = 0;
  574. //m_log.Info("sadfadf" + m_neighbours.Count.ToString());
  575. int agentsInScene = m_innerScene.GetRootAgentCount() + m_innerScene.GetChildAgentCount();
  576. if (agentsInScene > 21)
  577. {
  578. if (m_update_entities == 1)
  579. {
  580. m_update_entities = 5;
  581. m_statsReporter.SetUpdateMS(6000);
  582. }
  583. }
  584. else
  585. {
  586. if (m_update_entities == 5)
  587. {
  588. m_update_entities = 1;
  589. m_statsReporter.SetUpdateMS(3000);
  590. }
  591. }
  592. frameMS = System.Environment.TickCount;
  593. try
  594. {
  595. // Increment the frame counter
  596. m_frame++;
  597. // Loop it
  598. if (m_frame == Int32.MaxValue)
  599. m_frame = 0;
  600. physicsMS2 = System.Environment.TickCount;
  601. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  602. m_innerScene.UpdatePreparePhysics();
  603. physicsMS2 = System.Environment.TickCount - physicsMS2;
  604. if (m_frame % m_update_entitymovement == 0)
  605. m_innerScene.UpdateEntityMovement();
  606. physicsMS = System.Environment.TickCount;
  607. if ((m_frame % m_update_physics == 0) && m_physics_enabled)
  608. physicsFPS = m_innerScene.UpdatePhysics(
  609. Math.Max(SinceLastFrame.TotalSeconds, m_timespan)
  610. );
  611. if (m_frame % m_update_physics == 0 && SynchronizeScene != null)
  612. SynchronizeScene(this);
  613. physicsMS = System.Environment.TickCount - physicsMS;
  614. physicsMS += physicsMS2;
  615. otherMS = System.Environment.TickCount;
  616. // run through all entities looking for updates (slow)
  617. if (m_frame % m_update_entities == 0)
  618. m_innerScene.UpdateEntities();
  619. // run through entities that have scheduled themselves for
  620. // updates looking for updates(faster)
  621. if (m_frame % m_update_entitiesquick == 0)
  622. m_innerScene.ProcessUpdates();
  623. // Run through scenepresences looking for updates
  624. if (m_frame % m_update_presences == 0)
  625. m_innerScene.UpdatePresences();
  626. if (Region_Status != RegionStatus.SlaveScene)
  627. {
  628. if (m_frame % m_update_events == 0)
  629. UpdateEvents();
  630. if (m_frame % m_update_backup == 0)
  631. UpdateStorageBackup();
  632. if (m_frame % m_update_terrain == 0)
  633. UpdateTerrain();
  634. if (m_frame % m_update_land == 0)
  635. UpdateLand();
  636. otherMS = System.Environment.TickCount - otherMS;
  637. // if (m_frame%m_update_avatars == 0)
  638. // UpdateInWorldTime();
  639. m_statsReporter.AddPhysicsFPS(physicsFPS);
  640. m_statsReporter.AddTimeDilation(m_timedilation);
  641. m_statsReporter.AddFPS(1);
  642. m_statsReporter.AddInPackets(0);
  643. m_statsReporter.SetRootAgents(m_innerScene.GetRootAgentCount());
  644. m_statsReporter.SetChildAgents(m_innerScene.GetChildAgentCount());
  645. m_statsReporter.SetObjects(m_innerScene.GetTotalObjects());
  646. m_statsReporter.SetActiveObjects(m_innerScene.GetActiveObjects());
  647. frameMS = System.Environment.TickCount - frameMS;
  648. m_statsReporter.addFrameMS(frameMS);
  649. m_statsReporter.addPhysicsMS(physicsMS);
  650. m_statsReporter.addOtherMS(otherMS);
  651. m_statsReporter.SetActiveScripts(m_innerScene.GetActiveScripts());
  652. m_statsReporter.addScriptLines(m_innerScene.GetScriptLPS());
  653. }
  654. }
  655. catch (NotImplementedException)
  656. {
  657. throw;
  658. }
  659. catch (AccessViolationException e)
  660. {
  661. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  662. }
  663. catch (NullReferenceException e)
  664. {
  665. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  666. }
  667. catch (InvalidOperationException e)
  668. {
  669. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  670. }
  671. catch (Exception e)
  672. {
  673. m_log.Error("[Scene]: Failed with exception " + e.ToString() + " On Region: " + RegionInfo.RegionName);
  674. }
  675. finally
  676. {
  677. updateLock.ReleaseMutex();
  678. // Get actual time dilation
  679. float tmpval = (m_timespan / (float)SinceLastFrame.TotalSeconds);
  680. // If actual time dilation is greater then one, we're catching up, so subtract
  681. // the amount that's greater then 1 from the time dilation
  682. if (tmpval > 1.0)
  683. {
  684. tmpval = tmpval - (tmpval - 1.0f);
  685. }
  686. m_timedilation = tmpval;
  687. m_lastupdate = DateTime.Now;
  688. }
  689. }
  690. private void SendSimStatsPackets(SimStatsPacket pack)
  691. {
  692. List<ScenePresence> StatSendAgents = GetScenePresences();
  693. foreach (ScenePresence agent in StatSendAgents)
  694. {
  695. if (!agent.IsChildAgent)
  696. {
  697. agent.ControllingClient.SendSimStats(pack);
  698. }
  699. }
  700. }
  701. private void UpdateLand()
  702. {
  703. if (LandChannel != null)
  704. {
  705. if (LandChannel.IsLandPrimCountTainted())
  706. {
  707. EventManager.TriggerParcelPrimCountUpdate();
  708. }
  709. }
  710. }
  711. private void UpdateTerrain()
  712. {
  713. EventManager.TriggerTerrainTick();
  714. }
  715. private void UpdateStorageBackup()
  716. {
  717. if (!m_backingup)
  718. {
  719. m_backingup = true;
  720. Thread backupthread = new Thread(Backup);
  721. backupthread.Name = "BackupWriter";
  722. backupthread.IsBackground = true;
  723. backupthread.Start();
  724. }
  725. }
  726. private void UpdateEvents()
  727. {
  728. m_eventManager.TriggerOnFrame();
  729. }
  730. /// <summary>
  731. /// Perform delegate action on all clients subscribing to updates from this region.
  732. /// </summary>
  733. /// <returns></returns>
  734. internal void Broadcast(Action<IClientAPI> whatToDo)
  735. {
  736. ForEachScenePresence(delegate(ScenePresence presence) { whatToDo(presence.ControllingClient); });
  737. }
  738. /// <summary>
  739. ///
  740. /// </summary>
  741. /// <returns></returns>
  742. public void Backup()
  743. {
  744. EventManager.TriggerOnBackup(m_storageManager.DataStore);
  745. m_backingup = false;
  746. //return true;
  747. }
  748. #endregion
  749. #region Load Terrain
  750. public void ExportWorldMap(string fileName)
  751. {
  752. List<MapBlockData> mapBlocks =
  753. m_sceneGridService.RequestNeighbourMapBlocks((int)(RegionInfo.RegionLocX - 9),
  754. (int)(RegionInfo.RegionLocY - 9),
  755. (int)(RegionInfo.RegionLocX + 9),
  756. (int)(RegionInfo.RegionLocY + 9));
  757. List<AssetBase> textures = new List<AssetBase>();
  758. List<Image> bitImages = new List<Image>();
  759. foreach (MapBlockData mapBlock in mapBlocks)
  760. {
  761. AssetBase texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  762. if (texAsset != null)
  763. {
  764. textures.Add(texAsset);
  765. }
  766. else
  767. {
  768. texAsset = AssetCache.GetAsset(mapBlock.MapImageId, true);
  769. if (texAsset != null)
  770. {
  771. textures.Add(texAsset);
  772. }
  773. }
  774. }
  775. foreach (AssetBase asset in textures)
  776. {
  777. Image image = OpenJPEG.DecodeToImage(asset.Data);
  778. bitImages.Add(image);
  779. }
  780. Bitmap mapTexture = new Bitmap(2560, 2560);
  781. Graphics g = Graphics.FromImage(mapTexture);
  782. SolidBrush sea = new SolidBrush(Color.DarkBlue);
  783. g.FillRectangle(sea, 0, 0, 2560, 2560);
  784. for (int i = 0; i < mapBlocks.Count; i++)
  785. {
  786. ushort x = (ushort)((mapBlocks[i].X - RegionInfo.RegionLocX) + 10);
  787. ushort y = (ushort)((mapBlocks[i].Y - RegionInfo.RegionLocY) + 10);
  788. g.DrawImage(bitImages[i], (x * 128), (y * 128), 128, 128);
  789. }
  790. mapTexture.Save(fileName, ImageFormat.Jpeg);
  791. }
  792. public void SaveTerrain()
  793. {
  794. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  795. }
  796. /// <summary>
  797. /// Loads the World heightmap
  798. /// </summary>
  799. ///
  800. public override void LoadWorldMap()
  801. {
  802. try
  803. {
  804. double[,] map = m_storageManager.DataStore.LoadTerrain(RegionInfo.RegionID);
  805. if (map == null)
  806. {
  807. m_log.Info("[TERRAIN]: No default terrain. Generating a new terrain.");
  808. Heightmap = new TerrainChannel();
  809. m_storageManager.DataStore.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  810. }
  811. else
  812. {
  813. Heightmap = new TerrainChannel(map);
  814. }
  815. }
  816. catch (Exception e)
  817. {
  818. m_log.Warn("[terrain]: Scene.cs: LoadWorldMap() - Failed with exception " + e.ToString());
  819. }
  820. }
  821. /// <summary>
  822. /// Register this region with a grid service
  823. /// </summary>
  824. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  825. public void RegisterRegionWithGrid()
  826. {
  827. RegisterCommsEvents();
  828. // These two 'commands' *must be* next to each other or sim rebooting fails.
  829. m_sceneGridService.RegisterRegion(RegionInfo);
  830. m_sceneGridService.InformNeighborsThatRegionisUp(RegionInfo);
  831. Dictionary<string, string> dGridSettings = m_sceneGridService.GetGridSettings();
  832. if (dGridSettings.ContainsKey("allow_forceful_banlines"))
  833. {
  834. if (dGridSettings["allow_forceful_banlines"] != "TRUE")
  835. {
  836. m_log.Info("[GRID]: Grid is disabling forceful parcel banlists");
  837. EventManager.TriggerSetAllowForcefulBan(false);
  838. }
  839. else
  840. {
  841. m_log.Info("[GRID]: Grid is allowing forceful parcel banlists");
  842. EventManager.TriggerSetAllowForcefulBan(true);
  843. }
  844. }
  845. }
  846. /// <summary>
  847. ///
  848. /// </summary>
  849. public void CreateTerrainTexture(bool temporary)
  850. {
  851. //create a texture asset of the terrain
  852. IMapImageGenerator terrain = RequestModuleInterface<IMapImageGenerator>();
  853. // Cannot create a map for a nonexistant heightmap yet.
  854. if (Heightmap == null)
  855. return;
  856. if (terrain == null)
  857. {
  858. Bitmap mapbmp = new Bitmap(256, 256);
  859. double[,] hm = Heightmap.GetDoubles();
  860. //Color prim = Color.FromArgb(120, 120, 120);
  861. //LLVector3 RayEnd = new LLVector3(0, 0, 0);
  862. //LLVector3 RayStart = new LLVector3(0, 0, 0);
  863. //LLVector3 direction = new LLVector3(0, 0, -1);
  864. //Vector3 AXOrigin = new Vector3();
  865. //Vector3 AXdirection = new Vector3();
  866. //Ray testRay = new Ray();
  867. //EntityIntersection rt = new EntityIntersection();
  868. float low = 255;
  869. float high = 0;
  870. for (int x = 0; x < 256; x++)
  871. {
  872. for (int y = 0; y < 256; y++)
  873. {
  874. float hmval = (float)hm[x, y];
  875. if (hmval < low)
  876. low = hmval;
  877. if (hmval > high)
  878. high = hmval;
  879. }
  880. }
  881. float mid = (high + low) * 0.5f;
  882. for (int x = 0; x < 256; x++)
  883. {
  884. //int tc = System.Environment.TickCount;
  885. for (int y = 0; y < 256; y++)
  886. {
  887. //RayEnd = new LLVector3(x, y, 0);
  888. //RayStart = new LLVector3(x, y, 255);
  889. //direction = LLVector3.Norm(RayEnd - RayStart);
  890. //AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  891. //AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  892. //testRay = new Ray(AXOrigin, AXdirection);
  893. //rt = m_innerScene.GetClosestIntersectingPrim(testRay);
  894. //if (rt.HitTF)
  895. //{
  896. //mapbmp.SetPixel(x, y, prim);
  897. //}
  898. //else
  899. //{
  900. //float tmpval = (float)hm[x, y];
  901. float heightvalue = (float)hm[x, y];
  902. if ((float)heightvalue > m_regInfo.EstateSettings.waterHeight)
  903. {
  904. // scale height value
  905. heightvalue = low + mid * (heightvalue - low) / mid;
  906. if (heightvalue > 255)
  907. heightvalue = 255;
  908. if (heightvalue < 0)
  909. heightvalue = 0;
  910. Color green = Color.FromArgb((int)heightvalue, 100, (int)heightvalue);
  911. // Y flip the cordinates
  912. mapbmp.SetPixel(x, (256 - y) - 1, green);
  913. }
  914. else
  915. {
  916. // Y flip the cordinates
  917. heightvalue = m_regInfo.EstateSettings.waterHeight - heightvalue;
  918. if (heightvalue > 19)
  919. heightvalue = 19;
  920. if (heightvalue < 0)
  921. heightvalue = 0;
  922. heightvalue = 100 - (heightvalue * 100) / 19;
  923. if (heightvalue > 255)
  924. heightvalue = 255;
  925. if (heightvalue < 0)
  926. heightvalue = 0;
  927. Color water = Color.FromArgb((int)heightvalue, (int)heightvalue, 255);
  928. mapbmp.SetPixel(x, (256 - y) - 1, water);
  929. }
  930. //}
  931. }
  932. //tc = System.Environment.TickCount - tc;
  933. //m_log.Info("[MAPTILE]: Completed One row in " + tc + " ms");
  934. }
  935. byte[] data;
  936. try
  937. {
  938. data = OpenJPEG.EncodeFromImage(mapbmp, false);
  939. }
  940. catch (Exception)
  941. {
  942. return;
  943. }
  944. m_regInfo.EstateSettings.terrainImageID = LLUUID.Random();
  945. AssetBase asset = new AssetBase();
  946. asset.FullID = m_regInfo.EstateSettings.terrainImageID;
  947. asset.Data = data;
  948. asset.Name = "terrainImage";
  949. asset.Description = RegionInfo.RegionName;
  950. asset.Type = 0;
  951. asset.Temporary = temporary;
  952. AssetCache.AddAsset(asset);
  953. }
  954. else
  955. {
  956. byte[] data = terrain.WriteJpeg2000Image("defaultstripe.png");
  957. if (data != null)
  958. {
  959. m_regInfo.EstateSettings.terrainImageID = LLUUID.Random();
  960. AssetBase asset = new AssetBase();
  961. asset.FullID = m_regInfo.EstateSettings.terrainImageID;
  962. asset.Data = data;
  963. asset.Name = "terrainImage";
  964. asset.Description = RegionInfo.RegionName;
  965. asset.Type = 0;
  966. asset.Temporary = temporary;
  967. AssetCache.AddAsset(asset);
  968. }
  969. }
  970. }
  971. #endregion
  972. #region Load Land
  973. public void loadAllLandObjectsFromStorage(LLUUID regionID)
  974. {
  975. m_log.Info("[SCENE]: Loading land objects from storage");
  976. List<LandData> landData = m_storageManager.DataStore.LoadLandObjects(regionID);
  977. if (LandChannel != null)
  978. {
  979. if (landData.Count == 0)
  980. {
  981. EventManager.TriggerNoticeNoLandDataFromStorage();
  982. }
  983. else
  984. {
  985. EventManager.TriggerIncomingLandDataFromStorage(landData);
  986. }
  987. }
  988. else
  989. {
  990. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  991. }
  992. }
  993. #endregion
  994. #region Primitives Methods
  995. /// <summary>
  996. /// Loads the World's objects
  997. /// </summary>
  998. public virtual void LoadPrimsFromStorage(LLUUID regionID)
  999. {
  1000. m_log.Info("[SCENE]: Loading objects from datastore");
  1001. List<SceneObjectGroup> PrimsFromDB = m_storageManager.DataStore.LoadObjects(regionID);
  1002. foreach (SceneObjectGroup group in PrimsFromDB)
  1003. {
  1004. AddSceneObjectFromStorage(group);
  1005. SceneObjectPart rootPart = group.GetChildPart(group.UUID);
  1006. rootPart.ObjectFlags &= ~(uint)LLObject.ObjectFlags.Scripted;
  1007. rootPart.TrimPermissions();
  1008. group.CheckSculptAndLoad();
  1009. group.ApplyPhysics(m_physicalPrim);
  1010. //rootPart.DoPhysicsPropertyUpdate(UsePhysics, true);
  1011. }
  1012. m_log.Info("[SCENE]: Loaded " + PrimsFromDB.Count.ToString() + " SceneObject(s)");
  1013. }
  1014. /// <summary>
  1015. /// Returns a new unallocated primitive ID
  1016. /// </summary>
  1017. /// <returns>A brand new primitive ID</returns>
  1018. public uint PrimIDAllocate()
  1019. {
  1020. uint myID;
  1021. _primAllocateMutex.WaitOne();
  1022. ++_primCount;
  1023. myID = _primCount;
  1024. _primAllocateMutex.ReleaseMutex();
  1025. return myID;
  1026. }
  1027. public LLVector3 GetNewRezLocation(LLVector3 RayStart, LLVector3 RayEnd, LLUUID RayTargetID, LLQuaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, LLVector3 scale, bool FaceCenter)
  1028. {
  1029. LLVector3 pos = LLVector3.Zero;
  1030. if (RayEndIsIntersection == (byte)1)
  1031. {
  1032. pos = RayEnd;
  1033. return pos;
  1034. }
  1035. if (RayTargetID != LLUUID.Zero)
  1036. {
  1037. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1038. LLVector3 direction = LLVector3.Norm(RayEnd - RayStart);
  1039. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1040. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1041. if (target != null)
  1042. {
  1043. pos = target.AbsolutePosition;
  1044. //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());
  1045. // TODO: Raytrace better here
  1046. //EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1047. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1048. // Ray Trace against target here
  1049. EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1,0,0,0), frontFacesOnly, FaceCenter);
  1050. // Un-comment out the following line to Get Raytrace results printed to the console.
  1051. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1052. float ScaleOffset = 0.5f;
  1053. // If we hit something
  1054. if (ei.HitTF)
  1055. {
  1056. LLVector3 scaleComponent = new LLVector3(ei.AAfaceNormal.x, ei.AAfaceNormal.y, ei.AAfaceNormal.z);
  1057. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1058. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1059. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1060. ScaleOffset = Math.Abs(ScaleOffset);
  1061. LLVector3 intersectionpoint = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  1062. LLVector3 normal = new LLVector3(ei.normal.x, ei.normal.y, ei.normal.z);
  1063. // Set the position to the intersection point
  1064. LLVector3 offset = (normal * (ScaleOffset / 2f));
  1065. pos = (intersectionpoint + offset);
  1066. // Un-offset the prim (it gets offset later by the consumer method)
  1067. pos.Z -= 0.25F;
  1068. }
  1069. return pos;
  1070. }
  1071. else
  1072. {
  1073. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1074. EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1075. // Un-comment the following line to print the raytrace results to the console.
  1076. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1077. if (ei.HitTF)
  1078. {
  1079. pos = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  1080. }
  1081. return pos;
  1082. }
  1083. }
  1084. else
  1085. {
  1086. // fall back to our stupid functionality
  1087. pos = RayEnd;
  1088. return pos;
  1089. }
  1090. }
  1091. public virtual void AddNewPrim(LLUUID ownerID, LLVector3 RayEnd, LLQuaternion rot, PrimitiveBaseShape shape,
  1092. byte bypassRaycast, LLVector3 RayStart, LLUUID RayTargetID,
  1093. byte RayEndIsIntersection)
  1094. {
  1095. LLVector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new LLVector3(0.5f, 0.5f, 0.5f), false);
  1096. if (ExternalChecks.ExternalChecksCanRezObject(1, ownerID, pos))
  1097. {
  1098. // rez ON the ground, not IN the ground
  1099. pos.Z += 0.25F;
  1100. AddNewPrim(ownerID, pos, rot, shape);
  1101. }
  1102. }
  1103. public virtual SceneObjectGroup AddNewPrim(LLUUID ownerID, LLVector3 pos, LLQuaternion rot, PrimitiveBaseShape shape)
  1104. {
  1105. SceneObjectGroup sceneOb =
  1106. new SceneObjectGroup(this, m_regionHandle, ownerID, PrimIDAllocate(), pos, rot, shape);
  1107. AddSceneObject(sceneOb);
  1108. SceneObjectPart rootPart = sceneOb.GetChildPart(sceneOb.UUID);
  1109. // if grass or tree, make phantom
  1110. //rootPart.TrimPermissions();
  1111. if ((rootPart.Shape.PCode == (byte)PCode.Grass) || (rootPart.Shape.PCode == (byte)PCode.Tree) || (rootPart.Shape.PCode == (byte)PCode.NewTree))
  1112. {
  1113. rootPart.AddFlag(LLObject.ObjectFlags.Phantom);
  1114. //rootPart.ObjectFlags += (uint)LLObject.ObjectFlags.Phantom;
  1115. }
  1116. // if not phantom, add to physics
  1117. sceneOb.ApplyPhysics(m_physicalPrim);
  1118. m_innerScene.AddToUpdateList(sceneOb);
  1119. return sceneOb;
  1120. }
  1121. public SceneObjectGroup AddTree(LLVector3 scale, LLQuaternion rotation, LLVector3 position,
  1122. Tree treeType, bool newTree)
  1123. {
  1124. LLUUID uuid = this.RegionInfo.MasterAvatarAssignedUUID;
  1125. PrimitiveBaseShape treeShape = new PrimitiveBaseShape();
  1126. treeShape.PathCurve = 16;
  1127. treeShape.PathEnd = 49900;
  1128. treeShape.PCode = newTree ? (byte)PCode.NewTree : (byte)PCode.Tree;
  1129. treeShape.Scale = scale;
  1130. treeShape.State = (byte)treeType;
  1131. return AddNewPrim(uuid, position, rotation, treeShape);
  1132. }
  1133. /// <summary>
  1134. /// Add an object into the scene that has come from storage
  1135. /// </summary>
  1136. /// <param name="sceneObject"></param>
  1137. public void AddSceneObjectFromStorage(SceneObjectGroup sceneObject)
  1138. {
  1139. m_innerScene.AddSceneObjectFromStorage(sceneObject);
  1140. }
  1141. /// <summary>
  1142. /// Add an object to the scene
  1143. /// </summary>
  1144. /// <param name="sceneObject"></param>
  1145. public void AddSceneObject(SceneObjectGroup sceneObject)
  1146. {
  1147. m_innerScene.AddSceneObject(sceneObject);
  1148. }
  1149. /// <summary>
  1150. /// Delete this object from the scene.
  1151. /// </summary>
  1152. /// <param name="group"></param>
  1153. public void DeleteSceneObject(SceneObjectGroup group)
  1154. {
  1155. SceneObjectPart rootPart = (group).GetChildPart(group.UUID);
  1156. if (rootPart.PhysActor != null)
  1157. {
  1158. PhysicsScene.RemovePrim(rootPart.PhysActor);
  1159. rootPart.PhysActor = null;
  1160. }
  1161. if (UnlinkSceneObject(group.UUID))
  1162. {
  1163. EventManager.TriggerObjectBeingRemovedFromScene(group);
  1164. EventManager.TriggerParcelPrimCountTainted();
  1165. }
  1166. group.DeleteGroup();
  1167. group.DeleteParts();
  1168. // In case anybody else retains a reference to this group, signal deletion by changing the name
  1169. // to null. We can't zero out the UUID because this is taken from the root part, which has already
  1170. // been removed.
  1171. // FIXME: This is a really poor temporary solution, since it still leaves plenty of scope for race
  1172. // conditions where a user deletes an entity while it is being stored. Really, the update
  1173. // code needs a redesign.
  1174. group.Name = null;
  1175. }
  1176. /// <summary>
  1177. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  1178. /// object itself is not destroyed.
  1179. /// </summary>
  1180. /// <param name="uuid"></param>
  1181. /// <returns>true if the object was in the scene, false if it was not</returns>
  1182. public bool UnlinkSceneObject(LLUUID uuid)
  1183. {
  1184. if (m_innerScene.DeleteSceneObject(uuid))
  1185. {
  1186. m_storageManager.DataStore.RemoveObject(uuid, m_regInfo.RegionID);
  1187. return true;
  1188. }
  1189. return false;
  1190. }
  1191. public void LoadPrimsFromXml(string fileName, bool newIdsFlag, LLVector3 loadOffset)
  1192. {
  1193. m_sceneXmlLoader.LoadPrimsFromXml(fileName, newIdsFlag, loadOffset);
  1194. }
  1195. public void SavePrimsToXml(string fileName)
  1196. {
  1197. m_sceneXmlLoader.SavePrimsToXml(fileName);
  1198. }
  1199. public void LoadPrimsFromXml2(string fileName)
  1200. {
  1201. m_sceneXmlLoader.LoadPrimsFromXml2(fileName);
  1202. }
  1203. public void SavePrimsToXml2(string fileName)
  1204. {
  1205. m_sceneXmlLoader.SavePrimsToXml2(fileName);
  1206. }
  1207. /// <summary>
  1208. /// Load a prim archive into the scene. This loads both prims and their assets.
  1209. /// </summary>
  1210. /// <param name="filePath"></param>
  1211. public void LoadPrimsFromArchive(string filePath)
  1212. {
  1213. IRegionArchiver archiver = RequestModuleInterface<IRegionArchiver>();
  1214. archiver.DearchiveRegion(filePath);
  1215. }
  1216. /// <summary>
  1217. /// Save the prims in the scene to an archive. This saves both prims and their assets.
  1218. /// </summary>
  1219. /// <param name="filePath"></param>
  1220. public void SavePrimsToArchive(string filePath)
  1221. {
  1222. IRegionArchiver archiver = RequestModuleInterface<IRegionArchiver>();
  1223. archiver.ArchiveRegion(filePath);
  1224. }
  1225. /// <summary>
  1226. /// Locate New region Handle and offset the prim position for the new region
  1227. ///
  1228. /// </summary>
  1229. /// <param name="position">current position of Group</param>
  1230. /// <param name="grp">Scene Object Group that we're crossing</param>
  1231. public void CrossPrimGroupIntoNewRegion(LLVector3 position, SceneObjectGroup grp)
  1232. {
  1233. if (grp == null)
  1234. return;
  1235. if (grp.RootPart == null)
  1236. return;
  1237. if (grp.RootPart.DIE_AT_EDGE)
  1238. {
  1239. // We remove the object here
  1240. try
  1241. {
  1242. DeleteSceneObject(grp);
  1243. }
  1244. catch (Exception)
  1245. {
  1246. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1247. }
  1248. return;
  1249. }
  1250. m_log.Warn("Prim crossing: " + grp.UUID.ToString());
  1251. int thisx = (int)RegionInfo.RegionLocX;
  1252. int thisy = (int)RegionInfo.RegionLocY;
  1253. ulong newRegionHandle = 0;
  1254. LLVector3 pos = position;
  1255. if (position.X > Constants.RegionSize + 0.1f)
  1256. {
  1257. pos.X = ((pos.X - Constants.RegionSize));
  1258. newRegionHandle = Util.UIntsToLong((uint)((thisx + 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1259. // x + 1
  1260. }
  1261. else if (position.X < -0.1f)
  1262. {
  1263. pos.X = ((pos.X + Constants.RegionSize));
  1264. newRegionHandle = Util.UIntsToLong((uint)((thisx - 1) * Constants.RegionSize), (uint)(thisy * Constants.RegionSize));
  1265. // x - 1
  1266. }
  1267. if (position.Y > Constants.RegionSize + 0.1f)
  1268. {
  1269. pos.Y = ((pos.Y - Constants.RegionSize));
  1270. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + 1) * Constants.RegionSize));
  1271. // y + 1
  1272. }
  1273. else if (position.Y < -1f)
  1274. {
  1275. pos.Y = ((pos.Y + Constants.RegionSize));
  1276. newRegionHandle = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - 1) * Constants.RegionSize));
  1277. // y - 1
  1278. }
  1279. // Offset the positions for the new region across the border
  1280. grp.OffsetForNewRegion(pos);
  1281. CrossPrimGroupIntoNewRegion(newRegionHandle, grp);
  1282. }
  1283. public void CrossPrimGroupIntoNewRegion(ulong newRegionHandle, SceneObjectGroup grp)
  1284. {
  1285. int primcrossingXMLmethod = 0;
  1286. if (newRegionHandle != 0)
  1287. {
  1288. bool successYN = false;
  1289. successYN = m_sceneGridService.PrimCrossToNeighboringRegion(newRegionHandle, grp.UUID, m_sceneXmlLoader.SavePrimGroupToXML2String(grp), primcrossingXMLmethod);
  1290. if (successYN)
  1291. {
  1292. // We remove the object here
  1293. try
  1294. {
  1295. DeleteSceneObject(grp);
  1296. }
  1297. catch (Exception)
  1298. {
  1299. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1300. }
  1301. }
  1302. else
  1303. {
  1304. m_log.Warn("[INTERREGION]: Prim Crossing Failed!");
  1305. if (grp.RootPart != null)
  1306. {
  1307. if (grp.RootPart.PhysActor != null)
  1308. {
  1309. grp.RootPart.PhysActor.CrossingFailure();
  1310. }
  1311. }
  1312. }
  1313. }
  1314. }
  1315. public bool IncomingInterRegionPrimGroup(ulong regionHandle, LLUUID primID, string objXMLData, int XMLMethod)
  1316. {
  1317. m_log.Warn("{[INTERREGION]: A new prim arrived from a neighbor");
  1318. if (XMLMethod == 0)
  1319. {
  1320. m_sceneXmlLoader.LoadGroupFromXml2String(objXMLData);
  1321. SceneObjectPart RootPrim = GetSceneObjectPart(primID);
  1322. if (RootPrim != null)
  1323. {
  1324. if (RootPrim.Shape.PCode == (byte)PCode.Prim)
  1325. {
  1326. SceneObjectGroup grp = RootPrim.ParentGroup;
  1327. if (grp != null)
  1328. {
  1329. if (RootPrim.Shape.State != 0)
  1330. {
  1331. // Attachment
  1332. ScenePresence sp = GetScenePresence(grp.OwnerID);
  1333. if (sp != null)
  1334. {
  1335. // hack assetID until we get assetID into the XML format.
  1336. // LastOwnerID is used for group deeding, so when you do stuff
  1337. // with the deeded object, it goes back to them
  1338. grp.SetFromAssetID(grp.RootPart.LastOwnerID);
  1339. m_innerScene.AttachObject(sp.ControllingClient, grp.LocalId, (uint)0, grp.GroupRotation, grp.AbsolutePosition);
  1340. }
  1341. }
  1342. }
  1343. }
  1344. }
  1345. return true;
  1346. }
  1347. else
  1348. {
  1349. return false;
  1350. }
  1351. }
  1352. #endregion
  1353. #region Add/Remove Avatar Methods
  1354. /// <summary>
  1355. ///
  1356. /// </summary>
  1357. /// <param name="client"></param
  1358. /// <param name="child"></param>
  1359. public override void AddNewClient(IClientAPI client, bool child)
  1360. {
  1361. m_log.DebugFormat(
  1362. "[CONNECTION DEBUGGING]: Creating new client for {0} at {1}",
  1363. client.AgentId, RegionInfo.RegionName);
  1364. SubscribeToClientEvents(client);
  1365. ScenePresence presence;
  1366. if (m_restorePresences.ContainsKey(client.AgentId))
  1367. {
  1368. m_log.Info("[REGION]: Restore Scene Presence");
  1369. presence = m_restorePresences[client.AgentId];
  1370. m_restorePresences.Remove(client.AgentId);
  1371. // This is one of two paths to create avatars that are
  1372. // used. This tends to get called more in standalone
  1373. // than grid, not really sure why, but as such needs
  1374. // an explicity appearance lookup here.
  1375. AvatarAppearance appearance = null;
  1376. GetAvatarAppearance(client, out appearance);
  1377. presence.Appearance = appearance;
  1378. presence.initializeScenePresence(client, RegionInfo, this);
  1379. m_innerScene.AddScenePresence(presence);
  1380. lock (m_restorePresences)
  1381. {
  1382. Monitor.PulseAll(m_restorePresences);
  1383. }
  1384. }
  1385. else
  1386. {
  1387. m_log.Info("[REGION]: Add New Scene Presence");
  1388. CreateAndAddScenePresence(client, child);
  1389. CommsManager.UserProfileCacheService.AddNewUser(client.AgentId);
  1390. }
  1391. EventManager.TriggerOnNewClient(client);
  1392. }
  1393. protected virtual void SubscribeToClientEvents(IClientAPI client)
  1394. {
  1395. client.OnRegionHandShakeReply += SendLayerData;
  1396. //remoteClient.OnRequestWearables += new GenericCall(this.GetInitialPrims);
  1397. // client.OnRequestWearables += InformClientOfNeighbours;
  1398. client.OnAddPrim += AddNewPrim;
  1399. client.OnUpdatePrimGroupPosition += m_innerScene.UpdatePrimPosition;
  1400. client.OnUpdatePrimSinglePosition += m_innerScene.UpdatePrimSinglePosition;
  1401. client.OnUpdatePrimGroupRotation += m_innerScene.UpdatePrimRotation;
  1402. client.OnUpdatePrimGroupMouseRotation += m_innerScene.UpdatePrimRotation;
  1403. client.OnUpdatePrimSingleRotation += m_innerScene.UpdatePrimSingleRotation;
  1404. client.OnUpdatePrimScale += m_innerScene.UpdatePrimScale;
  1405. client.OnUpdatePrimGroupScale += m_innerScene.UpdatePrimGroupScale;
  1406. client.OnUpdateExtraParams += m_innerScene.UpdateExtraParam;
  1407. client.OnUpdatePrimShape += m_innerScene.UpdatePrimShape;
  1408. client.OnRequestMapBlocks += RequestMapBlocks;
  1409. client.OnUpdatePrimTexture += m_innerScene.UpdatePrimTexture;
  1410. client.OnTeleportLocationRequest += RequestTeleportLocation;
  1411. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  1412. client.OnObjectSelect += SelectPrim;
  1413. client.OnObjectDeselect += DeselectPrim;
  1414. client.OnGrabUpdate += m_innerScene.MoveObject;
  1415. client.OnDeRezObject += DeRezObject;
  1416. client.OnRezObject += RezObject;
  1417. client.OnRezSingleAttachmentFromInv += m_innerScene.RezSingleAttachment;
  1418. client.OnDetachAttachmentIntoInv += m_innerScene.DetachSingleAttachmentToInv;
  1419. client.OnObjectAttach += m_innerScene.AttachObject;
  1420. client.OnObjectDetach += m_innerScene.DetachObject;
  1421. client.OnNameFromUUIDRequest += CommsManager.HandleUUIDNameRequest;
  1422. client.OnObjectDescription += m_innerScene.PrimDescription;
  1423. client.OnObjectName += m_innerScene.PrimName;
  1424. client.OnLinkObjects += m_innerScene.LinkObjects;
  1425. client.OnDelinkObjects += m_innerScene.DelinkObjects;
  1426. client.OnObjectDuplicate += m_innerScene.DuplicateObject;
  1427. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  1428. client.OnUpdatePrimFlags += m_innerScene.UpdatePrimFlags;
  1429. client.OnRequestObjectPropertiesFamily += m_innerScene.RequestObjectPropertiesFamily;
  1430. client.OnRequestGodlikePowers += handleRequestGodlikePowers;
  1431. client.OnGodKickUser += HandleGodlikeKickUser;
  1432. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  1433. client.OnCreateNewInventoryItem += CreateNewInventoryItem;
  1434. client.OnCreateNewInventoryFolder += CommsManager.UserProfileCacheService.HandleCreateInventoryFolder;
  1435. client.OnUpdateInventoryFolder += CommsManager.UserProfileCacheService.HandleUpdateInventoryFolder;
  1436. client.OnMoveInventoryFolder += CommsManager.UserProfileCacheService.HandleMoveInventoryFolder;
  1437. client.OnFetchInventoryDescendents += CommsManager.UserProfileCacheService.HandleFetchInventoryDescendents;
  1438. client.OnPurgeInventoryDescendents += CommsManager.UserProfileCacheService.HandlePurgeInventoryDescendents;
  1439. client.OnFetchInventory += CommsManager.UserProfileCacheService.HandleFetchInventory;
  1440. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  1441. client.OnCopyInventoryItem += CopyInventoryItem;
  1442. client.OnMoveInventoryItem += MoveInventoryItem;
  1443. client.OnRemoveInventoryItem += RemoveInventoryItem;
  1444. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  1445. client.OnRezScript += RezScript;
  1446. client.OnRequestTaskInventory += RequestTaskInventory;
  1447. client.OnRemoveTaskItem += RemoveTaskInventory;
  1448. client.OnUpdateTaskInventory += UpdateTaskInventory;
  1449. client.OnMoveTaskItem += MoveTaskInventoryItem;
  1450. client.OnGrabObject += ProcessObjectGrab;
  1451. client.OnDeGrabObject += ProcessObjectDeGrab;
  1452. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  1453. client.OnParcelBuy += ProcessParcelBuy;
  1454. client.OnAvatarPickerRequest += ProcessAvatarPickerRequest;
  1455. client.OnPacketStats += AddPacketStats;
  1456. client.OnObjectIncludeInSearch += m_innerScene.MakeObjectSearchable;
  1457. client.OnTeleportHomeRequest += TeleportClientHome;
  1458. client.OnSetStartLocationRequest += SetHomeRezPoint;
  1459. client.OnUndo += m_innerScene.HandleUndo;
  1460. client.OnObjectGroupRequest += m_innerScene.HandleObjectGroupUpdate;
  1461. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  1462. client.OnScriptReset += ProcessScriptReset;
  1463. // EventManager.TriggerOnNewClient(client);
  1464. }
  1465. public virtual void TeleportClientHome(LLUUID AgentId, IClientAPI client)
  1466. {
  1467. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(AgentId);
  1468. if (UserProfile != null)
  1469. {
  1470. ulong homeRegion = UserProfile.HomeRegion;
  1471. LLVector3 homePostion = new LLVector3(UserProfile.HomeLocationX,UserProfile.HomeLocationY,UserProfile.HomeLocationZ);
  1472. LLVector3 homeLookat = new LLVector3(UserProfile.HomeLookAt);
  1473. RequestTeleportLocation(client, homeRegion, homePostion,homeLookat,(uint)0);
  1474. }
  1475. }
  1476. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, LLUUID AgentID, LLUUID GroupID,
  1477. LLUUID RayTargetObj, LLVector3 RayEnd, LLVector3 RayStart,
  1478. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  1479. {
  1480. LLVector3 pos;
  1481. const bool frontFacesOnly = true;
  1482. SceneObjectPart target = GetSceneObjectPart(localID);
  1483. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  1484. if (target != null && target2 != null)
  1485. {
  1486. LLVector3 direction = LLVector3.Norm(RayEnd - RayStart);
  1487. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1488. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1489. if (target2.ParentGroup != null)
  1490. {
  1491. pos = target2.AbsolutePosition;
  1492. //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());
  1493. // TODO: Raytrace better here
  1494. //EntityIntersection ei = m_innerScene.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1495. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1496. // Ray Trace against target here
  1497. EntityIntersection ei = target.TestIntersectionOBB(NewRay, new Quaternion(1, 0, 0, 0), frontFacesOnly, false);
  1498. // Un-comment out the following line to Get Raytrace results printed to the console.
  1499. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1500. float ScaleOffset = 0.5f;
  1501. // If we hit something
  1502. if (ei.HitTF)
  1503. {
  1504. LLVector3 scale = target.Scale;
  1505. LLVector3 scaleComponent = new LLVector3(ei.AAfaceNormal.x, ei.AAfaceNormal.y, ei.AAfaceNormal.z);
  1506. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1507. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1508. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1509. ScaleOffset = Math.Abs(ScaleOffset);
  1510. LLVector3 intersectionpoint = new LLVector3(ei.ipoint.x, ei.ipoint.y, ei.ipoint.z);
  1511. LLVector3 normal = new LLVector3(ei.normal.x, ei.normal.y, ei.normal.z);
  1512. LLVector3 offset = (normal * (ScaleOffset / 2f));
  1513. pos = (intersectionpoint + offset);
  1514. if (CopyCenters)
  1515. {
  1516. // now we cast a ray from inside the prim(absolute position) to one of it's faces along the face normal.
  1517. LLVector3 direction2 = LLVector3.Norm(pos - target2.AbsolutePosition);
  1518. Vector3 AXOrigin2 = new Vector3(target2.AbsolutePosition.X, target2.AbsolutePosition.Y, target2.AbsolutePosition.Z);
  1519. Vector3 AXdirection2 = new Vector3(direction2.X, direction2.Y, direction2.Z); //ei.AAfaceNormal;
  1520. Ray NewRay2 = new Ray(AXOrigin2, AXdirection2);
  1521. EntityIntersection ei2 = target.TestIntersectionOBB(NewRay2, new Quaternion(1, 0, 0, 0), false, CopyCenters);
  1522. if (ei2.HitTF)
  1523. {
  1524. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei2.HitTF.ToString() + " Point: " + ei2.ipoint.ToString() + " Normal: " + ei2.normal.ToString());
  1525. pos = new LLVector3(ei2.ipoint.x,ei2.ipoint.y,ei2.ipoint.z);
  1526. normal.X = ei2.normal.x;
  1527. normal.Y = ei2.normal.y;
  1528. normal.Z = ei2.normal.z;
  1529. }
  1530. }
  1531. // Set the position to the intersection point
  1532. offset = (normal * (ScaleOffset / 2f));
  1533. pos = (intersectionpoint + offset);
  1534. // stick in offset format from the original prim
  1535. pos = pos - target2.ParentGroup.AbsolutePosition;
  1536. m_innerScene.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID);
  1537. }
  1538. return;
  1539. }
  1540. return;
  1541. }
  1542. }
  1543. public virtual void SetHomeRezPoint(IClientAPI remoteClient, ulong regionHandle, LLVector3 position, LLVector3 lookAt, uint flags)
  1544. {
  1545. UserProfileData UserProfile = CommsManager.UserService.GetUserProfile(remoteClient.AgentId);
  1546. if (UserProfile != null)
  1547. {
  1548. // I know I'm ignoring the regionHandle provided by the teleport location request.
  1549. // reusing the TeleportLocationRequest delegate, so regionHandle isn't valid
  1550. UserProfile.HomeRegion = RegionInfo.RegionHandle;
  1551. // We cast these to an int so as not to cause a breaking change with old regions
  1552. // Newer regions treat this as a float on the ExpectUser method.. so we need to wait a few
  1553. // releases before setting these to floats. (r4257)
  1554. UserProfile.HomeLocationX = (int)position.X;
  1555. UserProfile.HomeLocationY = (int)position.Y;
  1556. UserProfile.HomeLocationZ = (int)position.Z;
  1557. UserProfile.HomeLookAtX = (int)lookAt.X;
  1558. UserProfile.HomeLookAtY = (int)lookAt.Y;
  1559. UserProfile.HomeLookAtZ = (int)lookAt.Z;
  1560. CommsManager.UserService.UpdateUserProfileProperties(UserProfile);
  1561. remoteClient.SendAgentAlertMessage("Set home to here if supported by login service",false);
  1562. }
  1563. else
  1564. {
  1565. remoteClient.SendAgentAlertMessage("Set Home request Failed",false);
  1566. }
  1567. }
  1568. protected virtual ScenePresence CreateAndAddScenePresence(IClientAPI client, bool child)
  1569. {
  1570. AvatarAppearance appearance = null;
  1571. GetAvatarAppearance(client, out appearance);
  1572. ScenePresence avatar = m_innerScene.CreateAndAddScenePresence(client, child, appearance);
  1573. return avatar;
  1574. }
  1575. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  1576. {
  1577. appearance = null; // VS needs this line, mono doesn't
  1578. if (m_AvatarFactory == null ||
  1579. !m_AvatarFactory.TryGetAvatarAppearance(client.AgentId, out appearance))
  1580. {
  1581. m_log.Warn("[APPEARANCE]: Appearance not found, creating default");
  1582. }
  1583. }
  1584. /// <summary>
  1585. /// Remove the given client from the scene.
  1586. /// </summary>
  1587. /// <param name="agentID"></param>
  1588. public override void RemoveClient(LLUUID agentID)
  1589. {
  1590. bool childagentYN = false;
  1591. ScenePresence avatar = GetScenePresence(agentID);
  1592. if (avatar != null)
  1593. {
  1594. childagentYN = avatar.IsChildAgent;
  1595. }
  1596. try
  1597. {
  1598. if (avatar.IsChildAgent)
  1599. {
  1600. m_innerScene.removeUserCount(false);
  1601. }
  1602. else
  1603. {
  1604. m_innerScene.removeUserCount(true);
  1605. m_sceneGridService.LogOffUser(agentID, RegionInfo.RegionID, RegionInfo.RegionHandle,
  1606. avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y,
  1607. avatar.AbsolutePosition.Z);
  1608. List<ulong> childknownRegions = new List<ulong>();
  1609. List<ulong> ckn = avatar.GetKnownRegionList();
  1610. for (int i = 0; i < ckn.Count; i++)
  1611. {
  1612. childknownRegions.Add(ckn[i]);
  1613. }
  1614. m_sceneGridService.SendCloseChildAgentConnections(agentID, childknownRegions);
  1615. RemoveCapsHandler(agentID);
  1616. CommsManager.UserProfileCacheService.RemoveUser(agentID);
  1617. }
  1618. m_eventManager.TriggerClientClosed(agentID);
  1619. }
  1620. catch (NullReferenceException)
  1621. {
  1622. // We don't know which count to remove it from
  1623. // Avatar is already disposed :/
  1624. }
  1625. m_eventManager.TriggerOnRemovePresence(agentID);
  1626. Broadcast(delegate(IClientAPI client)
  1627. {
  1628. try
  1629. {
  1630. client.SendKillObject(avatar.RegionHandle, avatar.LocalId);
  1631. }
  1632. catch (NullReferenceException)
  1633. {
  1634. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1635. }
  1636. });
  1637. ForEachScenePresence(
  1638. delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1639. IAgentAssetTransactions agentTransactions = this.RequestModuleInterface<IAgentAssetTransactions>();
  1640. if (agentTransactions != null)
  1641. {
  1642. agentTransactions.RemoveAgentAssetTransactions(agentID);
  1643. }
  1644. m_innerScene.RemoveScenePresence(agentID);
  1645. try
  1646. {
  1647. avatar.Close();
  1648. }
  1649. catch (NullReferenceException)
  1650. {
  1651. //We can safely ignore null reference exceptions. It means the avatar are dead and cleaned up anyway.
  1652. }
  1653. catch (Exception e)
  1654. {
  1655. m_log.Error("[SCENE] Scene.cs:RemoveClient exception: " + e.ToString());
  1656. }
  1657. // Remove client agent from profile, so new logins will work
  1658. if (!childagentYN)
  1659. {
  1660. m_sceneGridService.ClearUserAgent(agentID);
  1661. }
  1662. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  1663. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  1664. }
  1665. public void HandleRemoveKnownRegionsFromAvatar(LLUUID avatarID, List<ulong> regionslst)
  1666. {
  1667. ScenePresence av = GetScenePresence(avatarID);
  1668. if (av != null)
  1669. {
  1670. lock (av)
  1671. {
  1672. for (int i = 0; i < regionslst.Count; i++)
  1673. {
  1674. av.KnownChildRegions.Remove(regionslst[i]);
  1675. }
  1676. }
  1677. }
  1678. }
  1679. public override void CloseAllAgents(uint circuitcode)
  1680. {
  1681. // Called by ClientView to kill all circuit codes
  1682. ClientManager.CloseAllAgents(circuitcode);
  1683. }
  1684. public void NotifyMyCoarseLocationChange()
  1685. {
  1686. ForEachScenePresence(delegate(ScenePresence presence) { presence.CoarseLocationChange(); });
  1687. }
  1688. #endregion
  1689. #region Entities
  1690. public void SendKillObject(uint localID)
  1691. {
  1692. Broadcast(delegate(IClientAPI client) { client.SendKillObject(m_regionHandle, localID); });
  1693. }
  1694. #endregion
  1695. #region RegionComms
  1696. /// <summary>
  1697. ///
  1698. /// </summary>
  1699. public void RegisterCommsEvents()
  1700. {
  1701. m_sceneGridService.OnExpectUser += NewUserConnection;
  1702. m_sceneGridService.OnAvatarCrossingIntoRegion += AgentCrossing;
  1703. m_sceneGridService.OnCloseAgentConnection += CloseConnection;
  1704. m_sceneGridService.OnRegionUp += OtherRegionUp;
  1705. m_sceneGridService.OnChildAgentUpdate += IncomingChildAgentDataUpdate;
  1706. m_sceneGridService.OnExpectPrim += IncomingInterRegionPrimGroup;
  1707. m_sceneGridService.OnRemoveKnownRegionFromAvatar += HandleRemoveKnownRegionsFromAvatar;
  1708. m_sceneGridService.KillObject = SendKillObject;
  1709. }
  1710. /// <summary>
  1711. ///
  1712. /// </summary>
  1713. public void UnRegisterReginWithComms()
  1714. {
  1715. m_sceneGridService.OnRemoveKnownRegionFromAvatar -= HandleRemoveKnownRegionsFromAvatar;
  1716. m_sceneGridService.OnExpectPrim -= IncomingInterRegionPrimGroup;
  1717. m_sceneGridService.OnChildAgentUpdate -= IncomingChildAgentDataUpdate;
  1718. m_sceneGridService.OnRegionUp -= OtherRegionUp;
  1719. m_sceneGridService.OnExpectUser -= NewUserConnection;
  1720. m_sceneGridService.OnAvatarCrossingIntoRegion -= AgentCrossing;
  1721. m_sceneGridService.OnCloseAgentConnection -= CloseConnection;
  1722. m_sceneGridService.Close();
  1723. }
  1724. /// <summary>
  1725. /// Do the work necessary to initiate a new user connection.
  1726. /// At the moment, this consists of setting up the caps infrastructure
  1727. /// </summary>
  1728. /// <param name="regionHandle"></param>
  1729. /// <param name="agent"></param>
  1730. public void NewUserConnection(ulong regionHandle, AgentCircuitData agent)
  1731. {
  1732. if (regionHandle == m_regInfo.RegionHandle)
  1733. {
  1734. capsPaths[agent.AgentID] = agent.CapsPath;
  1735. if (!agent.child)
  1736. {
  1737. AddCapsHandler(agent.AgentID);
  1738. // Honor parcel landing type and position.
  1739. ILandObject land = LandChannel.GetLandObject(agent.startpos.X, agent.startpos.Y);
  1740. if (land != null)
  1741. {
  1742. if (land.landData.landingType == (byte)1 && land.landData.userLocation != LLVector3.Zero)
  1743. {
  1744. agent.startpos = land.landData.userLocation;
  1745. }
  1746. }
  1747. }
  1748. m_log.DebugFormat(
  1749. "[CONNECTION DEBUGGING]: Creating new circuit code ({0}) for avatar {1} at {2}",
  1750. agent.circuitcode, agent.AgentID, RegionInfo.RegionName);
  1751. m_authenticateHandler.AddNewCircuit(agent.circuitcode, agent);
  1752. }
  1753. else
  1754. {
  1755. m_log.WarnFormat(
  1756. "[CONNECTION DEBUGGING]: Skipping this region for welcoming avatar {0} [{1}] at {2}",
  1757. agent.AgentID, regionHandle, RegionInfo.RegionName);
  1758. }
  1759. }
  1760. /// <summary>
  1761. /// Add a caps handler for the given agent. If the CAPS handler already exists for this agent,
  1762. /// then it is replaced by a new CAPS handler.
  1763. ///
  1764. /// FIXME: On login this is called twice, once for the login and once when the connection is made.
  1765. /// This is somewhat innefficient and should be fixed. The initial login creation is necessary
  1766. /// since the client asks for capabilities immediately after being informed of the seed.
  1767. /// </summary>
  1768. /// <param name="agentId"></param>
  1769. /// <param name="capsObjectPath"></param>
  1770. public void AddCapsHandler(LLUUID agentId)
  1771. {
  1772. String capsObjectPath = GetCapsPath(agentId);
  1773. m_log.DebugFormat(
  1774. "[CAPS]: Setting up CAPS handler for root agent {0} in {1}",
  1775. agentId, RegionInfo.RegionName);
  1776. Caps cap =
  1777. new Caps(AssetCache, m_httpListener, m_regInfo.ExternalHostName, m_httpListener.Port,
  1778. capsObjectPath, agentId, m_dumpAssetsToFile, RegionInfo.RegionName);
  1779. cap.RegisterHandlers();
  1780. EventManager.TriggerOnRegisterCaps(agentId, cap);
  1781. cap.AddNewInventoryItem = AddUploadedInventoryItem;
  1782. cap.ItemUpdatedCall = CapsUpdateInventoryItemAsset;
  1783. cap.TaskScriptUpdatedCall = CapsUpdateTaskInventoryScriptAsset;
  1784. cap.CAPSFetchInventoryDescendents = CommsManager.UserProfileCacheService.HandleFetchInventoryDescendentsCAPS;
  1785. cap.GetClient = m_innerScene.GetControllingClient;
  1786. m_capsHandlers[agentId] = cap;
  1787. }
  1788. /// <summary>
  1789. /// Remove the caps handler for a given agent.
  1790. /// </summary>
  1791. /// <param name="agentId"></param>
  1792. public void RemoveCapsHandler(LLUUID agentId)
  1793. {
  1794. lock (m_capsHandlers)
  1795. {
  1796. if (m_capsHandlers.ContainsKey(agentId))
  1797. {
  1798. m_log.DebugFormat(
  1799. "[CAPS]: Removing CAPS handler for root agent {0} in {1}",
  1800. agentId, RegionInfo.RegionName);
  1801. m_capsHandlers[agentId].DeregisterHandlers();
  1802. EventManager.TriggerOnDeregisterCaps(agentId, m_capsHandlers[agentId]);
  1803. m_capsHandlers.Remove(agentId);
  1804. }
  1805. else
  1806. {
  1807. m_log.WarnFormat(
  1808. "[CAPS]: Received request to remove CAPS handler for root agent {0} in {1}, but no such CAPS handler found!",
  1809. agentId, RegionInfo.RegionName);
  1810. }
  1811. }
  1812. }
  1813. /// <summary>
  1814. ///
  1815. /// </summary>
  1816. /// <param name="regionHandle"></param>
  1817. /// <param name="agentID"></param>
  1818. /// <param name="position"></param>
  1819. /// <param name="isFlying"></param>
  1820. public virtual void AgentCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1821. {
  1822. if (regionHandle == m_regInfo.RegionHandle)
  1823. {
  1824. lock (m_scenePresences)
  1825. {
  1826. if (m_scenePresences.ContainsKey(agentID))
  1827. {
  1828. try
  1829. {
  1830. m_scenePresences[agentID].MakeRootAgent(position, isFlying);
  1831. }
  1832. catch (Exception e)
  1833. {
  1834. m_log.Info("[SCENE]: Unable to do Agent Crossing.");
  1835. m_log.Debug("[SCENE]: " + e.ToString());
  1836. }
  1837. //m_innerScene.SwapRootChildAgent(false);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. public virtual bool IncomingChildAgentDataUpdate(ulong regionHandle, ChildAgentDataUpdate cAgentData)
  1843. {
  1844. ScenePresence childAgentUpdate = GetScenePresence(new LLUUID(cAgentData.AgentID));
  1845. if (childAgentUpdate != null)
  1846. {
  1847. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  1848. // however to avoid a race condition crossing borders..
  1849. if (childAgentUpdate.IsChildAgent)
  1850. {
  1851. uint rRegionX = (uint)(cAgentData.regionHandle >> 40);
  1852. uint rRegionY = (((uint)(cAgentData.regionHandle)) >> 8);
  1853. uint tRegionX = RegionInfo.RegionLocX;
  1854. uint tRegionY = RegionInfo.RegionLocY;
  1855. //Send Data to ScenePresence
  1856. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  1857. // Not Implemented:
  1858. //TODO: Do we need to pass the message on to one of our neighbors?
  1859. }
  1860. return true;
  1861. }
  1862. return false;
  1863. }
  1864. /// <summary>
  1865. /// Tell a single agent to disconnect from the region.
  1866. /// </summary>
  1867. /// <param name="regionHandle"></param>
  1868. /// <param name="agentID"></param>
  1869. public bool CloseConnection(ulong regionHandle, LLUUID agentID)
  1870. {
  1871. if (regionHandle == m_regionHandle)
  1872. {
  1873. ScenePresence presence = m_innerScene.GetScenePresence(agentID);
  1874. if (presence != null)
  1875. {
  1876. if (presence.IsChildAgent)
  1877. {
  1878. m_innerScene.removeUserCount(false);
  1879. }
  1880. else
  1881. {
  1882. m_innerScene.removeUserCount(true);
  1883. }
  1884. // Tell a single agent to disconnect from the region.
  1885. presence.ControllingClient.SendShutdownConnectionNotice();
  1886. presence.ControllingClient.Close(true);
  1887. }
  1888. }
  1889. return true;
  1890. }
  1891. /// <summary>
  1892. /// Tell neighboring regions about this agent
  1893. /// When the regions respond with a true value,
  1894. /// tell the agents about the region.
  1895. ///
  1896. /// We have to tell the regions about the agents first otherwise it'll deny them access
  1897. ///
  1898. /// </summary>
  1899. /// <param name="presence"></param>
  1900. public void InformClientOfNeighbours(ScenePresence presence)
  1901. {
  1902. m_sceneGridService.EnableNeighbourChildAgents(presence, m_neighbours);
  1903. }
  1904. /// <summary>
  1905. /// Tell a neighboring region about this agent
  1906. /// </summary>
  1907. /// <param name="presence"></param>
  1908. /// <param name="region"></param>
  1909. public void InformClientOfNeighbor(ScenePresence presence, RegionInfo region)
  1910. {
  1911. m_sceneGridService.InformNeighborChildAgent(presence, region, m_neighbours);
  1912. }
  1913. /// <summary>
  1914. /// Requests information about this region from gridcomms
  1915. /// </summary>
  1916. /// <param name="regionHandle"></param>
  1917. /// <returns></returns>
  1918. public RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  1919. {
  1920. return m_sceneGridService.RequestNeighbouringRegionInfo(regionHandle);
  1921. }
  1922. /// <summary>
  1923. /// Requests textures for map from minimum region to maximum region in world cordinates
  1924. /// </summary>
  1925. /// <param name="remoteClient"></param>
  1926. /// <param name="minX"></param>
  1927. /// <param name="minY"></param>
  1928. /// <param name="maxX"></param>
  1929. /// <param name="maxY"></param>
  1930. public void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  1931. {
  1932. m_sceneGridService.RequestMapBlocks(remoteClient, minX, minY, maxX, maxX);
  1933. }
  1934. /// <summary>
  1935. /// Tries to teleport agent to other region.
  1936. /// </summary>
  1937. /// <param name="remoteClient"></param>
  1938. /// <param name="regionHandle"></param>
  1939. /// <param name="position"></param>
  1940. /// <param name="lookAt"></param>
  1941. /// <param name="flags"></param>
  1942. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, LLVector3 position,
  1943. LLVector3 lookAt, uint flags)
  1944. {
  1945. lock (m_scenePresences)
  1946. {
  1947. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  1948. {
  1949. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  1950. position, lookAt, flags);
  1951. }
  1952. }
  1953. }
  1954. /// <summary>
  1955. /// Tries to teleport agent to landmark.
  1956. /// </summary>
  1957. /// <param name="remoteClient"></param>
  1958. /// <param name="regionHandle"></param>
  1959. /// <param name="position"></param>
  1960. public void RequestTeleportLandmark(IClientAPI remoteClient, ulong regionHandle, LLVector3 position)
  1961. {
  1962. lock (m_scenePresences)
  1963. {
  1964. if (m_scenePresences.ContainsKey(remoteClient.AgentId))
  1965. {
  1966. m_sceneGridService.RequestTeleportToLocation(m_scenePresences[remoteClient.AgentId], regionHandle,
  1967. position, LLVector3.Zero, 0);
  1968. }
  1969. }
  1970. }
  1971. /// <summary>
  1972. /// Agent is crossing the border into a neighbouring region. Tell the neighbour about it!
  1973. /// </summary>
  1974. /// <param name="regionHandle"></param>
  1975. /// <param name="agentID"></param>
  1976. /// <param name="position"></param>
  1977. /// <param name="isFlying"></param>
  1978. /// <returns></returns>
  1979. public bool InformNeighbourOfCrossing(ulong regionHandle, LLUUID agentID, LLVector3 position, bool isFlying)
  1980. {
  1981. return m_sceneGridService.CrossToNeighbouringRegion(regionHandle, agentID, position, isFlying);
  1982. }
  1983. public void SendOutChildAgentUpdates(ChildAgentDataUpdate cadu, ScenePresence presence)
  1984. {
  1985. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  1986. }
  1987. #endregion
  1988. #region Module Methods
  1989. /// <summary>
  1990. ///
  1991. /// </summary>
  1992. /// <param name="name"></param>
  1993. /// <param name="module"></param>
  1994. public void AddModule(string name, IRegionModule module)
  1995. {
  1996. if (!Modules.ContainsKey(name))
  1997. {
  1998. Modules.Add(name, module);
  1999. }
  2000. }
  2001. public void RegisterModuleCommander(string name, ICommander commander)
  2002. {
  2003. lock (m_moduleCommanders)
  2004. {
  2005. m_moduleCommanders.Add(name, commander);
  2006. }
  2007. }
  2008. public ICommander GetCommander(string name)
  2009. {
  2010. lock (m_moduleCommanders)
  2011. {
  2012. return m_moduleCommanders[name];
  2013. }
  2014. }
  2015. public Dictionary<string, ICommander> GetCommanders()
  2016. {
  2017. return m_moduleCommanders;
  2018. }
  2019. /// <summary>
  2020. /// Register an interface to a region module. This allows module methods to be called directly as
  2021. /// well as via events. If there is already a module registered for this interface, it is not replaced
  2022. /// (is this the best behaviour?)
  2023. /// </summary>
  2024. /// <param name="mod"></param>
  2025. public void RegisterModuleInterface<M>(M mod)
  2026. {
  2027. if (!ModuleInterfaces.ContainsKey(typeof(M)))
  2028. {
  2029. ModuleInterfaces.Add(typeof(M), mod);
  2030. }
  2031. }
  2032. /// <summary>
  2033. /// For the given interface, retrieve the region module which implements it.
  2034. /// </summary>
  2035. /// <returns>null if there is no module implementing that interface</returns>
  2036. public T RequestModuleInterface<T>()
  2037. {
  2038. if (ModuleInterfaces.ContainsKey(typeof(T)))
  2039. {
  2040. return (T)ModuleInterfaces[typeof(T)];
  2041. }
  2042. else
  2043. {
  2044. return default(T);
  2045. }
  2046. }
  2047. public void SetObjectCapacity(int objects)
  2048. {
  2049. if (m_statsReporter != null)
  2050. {
  2051. m_statsReporter.SetObjectCapacity(objects);
  2052. }
  2053. objectCapacity = objects;
  2054. }
  2055. public List<FriendListItem> GetFriendList(LLUUID avatarID)
  2056. {
  2057. return CommsManager.GetUserFriendList(avatarID);
  2058. }
  2059. #endregion
  2060. #region Other Methods
  2061. /// <summary>
  2062. ///
  2063. /// </summary>
  2064. /// <param name="phase"></param>
  2065. public void SetTimePhase(int phase)
  2066. {
  2067. m_timePhase = phase;
  2068. }
  2069. /// <summary>
  2070. ///
  2071. /// </summary>
  2072. /// <param name="avatarID"></param>
  2073. /// <param name="objectName"></param>
  2074. /// <param name="objectID"></param>
  2075. /// <param name="ownerID"></param>
  2076. /// <param name="groupOwned"></param>
  2077. /// <param name="message"></param>
  2078. /// <param name="url"></param>
  2079. public void SendUrlToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, bool groupOwned,
  2080. string message, string url)
  2081. {
  2082. lock (m_scenePresences)
  2083. {
  2084. if (m_scenePresences.ContainsKey(avatarID))
  2085. {
  2086. m_scenePresences[avatarID].ControllingClient.SendLoadURL(objectName, objectID, ownerID, groupOwned,
  2087. message, url);
  2088. }
  2089. }
  2090. }
  2091. public void SendDialogToUser(LLUUID avatarID, string objectName, LLUUID objectID, LLUUID ownerID, string message, LLUUID TextureID, int ch, string[] buttonlabels)
  2092. {
  2093. lock (m_scenePresences)
  2094. {
  2095. if (m_scenePresences.ContainsKey(avatarID))
  2096. {
  2097. m_scenePresences[avatarID].ControllingClient.SendDialog(
  2098. objectName, objectID, ownerID, message, TextureID, ch, buttonlabels);
  2099. }
  2100. }
  2101. }
  2102. /// <summary>
  2103. ///
  2104. /// </summary>
  2105. /// <param name="url"></param>
  2106. /// <param name="type"></param>
  2107. /// <param name="body"></param>
  2108. /// <returns></returns>
  2109. public LLUUID MakeHttpRequest(string url, string type, string body)
  2110. {
  2111. if (m_httpRequestModule != null)
  2112. {
  2113. return m_httpRequestModule.MakeHttpRequest(url, type, body);
  2114. }
  2115. return LLUUID.Zero;
  2116. }
  2117. /// <summary>
  2118. /// This method is a way for the Friends Module to create an instant
  2119. /// message to the avatar and for Instant Messages that travel across
  2120. /// gridcomms to make it to the Instant Message Module.
  2121. ///
  2122. /// Friendship establishment and groups are unfortunately tied with instant messaging and
  2123. /// there's no way to separate them completely.
  2124. /// </summary>
  2125. /// <param name="message">object containing the instant message data</param>
  2126. /// <returns>void</returns>
  2127. public void TriggerGridInstantMessage(GridInstantMessage message, InstantMessageReceiver options)
  2128. {
  2129. m_eventManager.TriggerGridInstantMessage(message, options);
  2130. }
  2131. public virtual void StoreAddFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  2132. {
  2133. // TODO: m_sceneGridService.DoStuff;
  2134. m_sceneGridService.AddNewUserFriend(ownerID, friendID, perms);
  2135. }
  2136. public virtual void StoreUpdateFriendship(LLUUID ownerID, LLUUID friendID, uint perms)
  2137. {
  2138. // TODO: m_sceneGridService.DoStuff;
  2139. m_sceneGridService.UpdateUserFriendPerms(ownerID, friendID, perms);
  2140. }
  2141. public virtual void StoreRemoveFriendship(LLUUID ownerID, LLUUID ExfriendID)
  2142. {
  2143. // TODO: m_sceneGridService.DoStuff;
  2144. m_sceneGridService.RemoveUserFriend(ownerID, ExfriendID);
  2145. }
  2146. public virtual List<FriendListItem> StoreGetFriendsForUser(LLUUID ownerID)
  2147. {
  2148. // TODO: m_sceneGridService.DoStuff;
  2149. return m_sceneGridService.GetUserFriendList(ownerID);
  2150. }
  2151. public void AddPacketStats(int inPackets, int outPackets, int unAckedBytes)
  2152. {
  2153. m_statsReporter.AddInPackets(inPackets);
  2154. m_statsReporter.AddOutPackets(outPackets);
  2155. m_statsReporter.AddunAckedBytes(unAckedBytes);
  2156. }
  2157. public void AddAgentTime(int ms)
  2158. {
  2159. m_statsReporter.addFrameMS(ms);
  2160. m_statsReporter.addAgentMS(ms);
  2161. }
  2162. public void AddAgentUpdates(int count)
  2163. {
  2164. m_statsReporter.AddAgentUpdates(count);
  2165. }
  2166. public void AddPendingDownloads(int count)
  2167. {
  2168. m_statsReporter.addPendingDownload(count);
  2169. }
  2170. #endregion
  2171. #region Console Commands
  2172. #region Alert Methods
  2173. private void SendPermissionAlert(LLUUID user, string reason)
  2174. {
  2175. SendAlertToUser(user, reason, false);
  2176. }
  2177. /// <summary>
  2178. ///
  2179. /// </summary>
  2180. /// <param name="message"></param>
  2181. public void SendGeneralAlert(string message)
  2182. {
  2183. List<ScenePresence> presenceList = GetScenePresences();
  2184. foreach (ScenePresence presence in presenceList)
  2185. {
  2186. presence.ControllingClient.SendAlertMessage(message);
  2187. }
  2188. }
  2189. /// <summary>
  2190. ///
  2191. /// </summary>
  2192. /// <param name="agentID"></param>
  2193. /// <param name="message"></param>
  2194. /// <param name="modal"></param>
  2195. public void SendAlertToUser(LLUUID agentID, string message, bool modal)
  2196. {
  2197. lock (m_scenePresences)
  2198. {
  2199. if (m_scenePresences.ContainsKey(agentID))
  2200. {
  2201. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage(message, modal);
  2202. }
  2203. }
  2204. }
  2205. /// <summary>
  2206. ///
  2207. /// </summary>
  2208. /// <param name="agentID"></param>
  2209. /// <param name="sessionID"></param>
  2210. /// <param name="token"></param>
  2211. /// <param name="controllingClient"></param>
  2212. public void handleRequestGodlikePowers(LLUUID agentID, LLUUID sessionID, LLUUID token, bool godLike,
  2213. IClientAPI controllingClient)
  2214. {
  2215. lock (m_scenePresences)
  2216. {
  2217. // User needs to be logged into this sim
  2218. if (m_scenePresences.ContainsKey(agentID))
  2219. {
  2220. // First check that this is the sim owner
  2221. if (ExternalChecks.ExternalChecksCanBeGodLike(agentID))
  2222. {
  2223. // Next we check for spoofing.....
  2224. LLUUID testSessionID = m_scenePresences[agentID].ControllingClient.SessionId;
  2225. if (sessionID == testSessionID)
  2226. {
  2227. if (sessionID == controllingClient.SessionId)
  2228. {
  2229. //m_log.Info("godlike: " + godLike.ToString());
  2230. m_scenePresences[agentID].GrantGodlikePowers(agentID, testSessionID, token, godLike);
  2231. }
  2232. }
  2233. }
  2234. else
  2235. {
  2236. m_scenePresences[agentID].ControllingClient.SendAgentAlertMessage("Request for god powers denied", false);
  2237. }
  2238. }
  2239. }
  2240. }
  2241. /// <summary>
  2242. /// Sends a Big Blue Box message on the upper right of the screen to the client
  2243. /// for all agents in the region
  2244. /// </summary>
  2245. /// <param name="FromAvatarID">The person sending the message</param>
  2246. /// <param name="fromSessionID">The session of the person sending the message</param>
  2247. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  2248. /// <param name="Message">The Message being sent to the user</param>
  2249. public void SendRegionMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  2250. {
  2251. List<ScenePresence> presenceList = GetScenePresences();
  2252. foreach (ScenePresence presence in presenceList)
  2253. {
  2254. if (!presence.IsChildAgent)
  2255. presence.ControllingClient.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  2256. }
  2257. }
  2258. /// <summary>
  2259. /// Sends a Big Blue Box message on the upper right of the screen to the client
  2260. /// for all agents in the estate
  2261. /// </summary>
  2262. /// <param name="FromAvatarID">The person sending the message</param>
  2263. /// <param name="fromSessionID">The session of the person sending the message</param>
  2264. /// <param name="FromAvatarName">The name of the person doing the sending</param>
  2265. /// <param name="Message">The Message being sent to the user</param>
  2266. public void SendEstateMessageFromEstateTools(LLUUID FromAvatarID, LLUUID fromSessionID, String FromAvatarName, String Message)
  2267. {
  2268. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2269. {
  2270. controller.SendBlueBoxMessage(FromAvatarID, fromSessionID, FromAvatarName, Message);
  2271. }
  2272. );
  2273. }
  2274. /// <summary>
  2275. /// Kicks User specified from the simulator. This logs them off of the grid
  2276. /// If the client gets the UUID: 44e87126e7944ded05b37c42da3d5cdb it assumes
  2277. /// that you're kicking it even if the avatar's UUID isn't the UUID that the
  2278. /// agent is assigned
  2279. /// </summary>
  2280. /// <param name="godID">The person doing the kicking</param>
  2281. /// <param name="sessionID">The session of the person doing the kicking</param>
  2282. /// <param name="agentID">the person that is being kicked</param>
  2283. /// <param name="kickflags">This isn't used apparently</param>
  2284. /// <param name="reason">The message to send to the user after it's been turned into a field</param>
  2285. public void HandleGodlikeKickUser(LLUUID godID, LLUUID sessionID, LLUUID agentID, uint kickflags, byte[] reason)
  2286. {
  2287. // For some reason the client sends this seemingly hard coded UUID for kicking everyone. Dun-know.
  2288. LLUUID kickUserID = new LLUUID("44e87126e7944ded05b37c42da3d5cdb");
  2289. lock (m_scenePresences)
  2290. {
  2291. if (m_scenePresences.ContainsKey(agentID) || agentID == kickUserID)
  2292. {
  2293. if (ExternalChecks.ExternalChecksCanBeGodLike(godID))
  2294. {
  2295. if (agentID == kickUserID)
  2296. {
  2297. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2298. {
  2299. if (controller.AgentId != godID)
  2300. controller.Kick(Helpers.FieldToUTF8String(reason));
  2301. }
  2302. );
  2303. // This is a bit crude. It seems the client will be null before it actually stops the thread
  2304. // The thread will kill itself eventually :/
  2305. // Is there another way to make sure *all* clients get this 'inter region' message?
  2306. ClientManager.ForEachClient(delegate(IClientAPI controller)
  2307. {
  2308. ScenePresence p = GetScenePresence(controller.AgentId);
  2309. bool childagent = p != null && p.IsChildAgent;
  2310. if (controller.AgentId != godID && !childagent)
  2311. // Do we really want to kick the initiator of this madness?
  2312. {
  2313. controller.Close(true);
  2314. }
  2315. }
  2316. );
  2317. }
  2318. else
  2319. {
  2320. m_innerScene.removeUserCount(!m_scenePresences[agentID].IsChildAgent);
  2321. m_scenePresences[agentID].ControllingClient.Kick(Helpers.FieldToUTF8String(reason));
  2322. m_scenePresences[agentID].ControllingClient.Close(true);
  2323. }
  2324. }
  2325. else
  2326. {
  2327. if (m_scenePresences.ContainsKey(godID))
  2328. m_scenePresences[godID].ControllingClient.SendAgentAlertMessage("Kick request denied", false);
  2329. }
  2330. }
  2331. }
  2332. }
  2333. public void HandleObjectPermissionsUpdate(IClientAPI controller, LLUUID agentID, LLUUID sessionID, byte field, uint localId, uint mask, byte set)
  2334. {
  2335. // Check for spoofing.. since this is permissions we're talking about here!
  2336. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  2337. {
  2338. // Tell the object to do permission update
  2339. if (localId != 0)
  2340. {
  2341. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  2342. if (chObjectGroup != null)
  2343. {
  2344. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  2345. }
  2346. }
  2347. }
  2348. }
  2349. /// <summary>
  2350. ///
  2351. /// </summary>
  2352. /// <param name="firstName"></param>
  2353. /// <param name="lastName"></param>
  2354. /// <param name="message"></param>
  2355. /// <param name="modal"></param>
  2356. public void SendAlertToUser(string firstName, string lastName, string message, bool modal)
  2357. {
  2358. List<ScenePresence> presenceList = GetScenePresences();
  2359. foreach (ScenePresence presence in presenceList)
  2360. {
  2361. if ((presence.Firstname == firstName) && (presence.Lastname == lastName))
  2362. {
  2363. presence.ControllingClient.SendAgentAlertMessage(message, modal);
  2364. break;
  2365. }
  2366. }
  2367. }
  2368. /// <summary>
  2369. ///
  2370. /// </summary>
  2371. /// <param name="commandParams"></param>
  2372. public void HandleAlertCommand(string[] commandParams)
  2373. {
  2374. if (commandParams[0] == "general")
  2375. {
  2376. string message = CombineParams(commandParams, 1);
  2377. SendGeneralAlert(message);
  2378. }
  2379. else
  2380. {
  2381. string message = CombineParams(commandParams, 2);
  2382. SendAlertToUser(commandParams[0], commandParams[1], message, false);
  2383. }
  2384. }
  2385. private string CombineParams(string[] commandParams, int pos)
  2386. {
  2387. string result = String.Empty;
  2388. for (int i = pos; i < commandParams.Length; i++)
  2389. {
  2390. result += commandParams[i] + " ";
  2391. }
  2392. return result;
  2393. }
  2394. #endregion
  2395. /// <summary>
  2396. /// Causes all clients to get a full object update on all of the objects in the scene.
  2397. /// </summary>
  2398. public void ForceClientUpdate()
  2399. {
  2400. List<EntityBase> EntityList = GetEntities();
  2401. foreach (EntityBase ent in EntityList)
  2402. {
  2403. if (ent is SceneObjectGroup)
  2404. {
  2405. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  2406. }
  2407. }
  2408. }
  2409. /// <summary>
  2410. /// This is currently only used for scale (to scale to MegaPrim size)
  2411. /// There is a console command that calls this in OpenSimMain
  2412. /// </summary>
  2413. /// <param name="cmdparams"></param>
  2414. public void HandleEditCommand(string[] cmdparams)
  2415. {
  2416. Console.WriteLine("Searching for Primitive: '" + cmdparams[0] + "'");
  2417. List<EntityBase> EntityList = GetEntities();
  2418. foreach (EntityBase ent in EntityList)
  2419. {
  2420. if (ent is SceneObjectGroup)
  2421. {
  2422. SceneObjectPart part = ((SceneObjectGroup)ent).GetChildPart(((SceneObjectGroup)ent).UUID);
  2423. if (part != null)
  2424. {
  2425. if (part.Name == cmdparams[0])
  2426. {
  2427. part.Resize(
  2428. new LLVector3(Convert.ToSingle(cmdparams[1]), Convert.ToSingle(cmdparams[2]),
  2429. Convert.ToSingle(cmdparams[3])));
  2430. Console.WriteLine("Edited scale of Primitive: " + part.Name);
  2431. }
  2432. }
  2433. }
  2434. }
  2435. }
  2436. /// <summary>
  2437. /// Shows various details about the sim based on the parameters supplied by the console command in openSimMain.
  2438. /// </summary>
  2439. /// <param name="showWhat"></param>
  2440. public void Show(string showWhat)
  2441. {
  2442. switch (showWhat)
  2443. {
  2444. case "users":
  2445. m_log.Error("Current Region: " + RegionInfo.RegionName);
  2446. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16}{5,-16}{6,-16}", "Firstname", "Lastname",
  2447. "Agent ID", "Session ID", "Circuit", "IP", "World");
  2448. foreach (ScenePresence scenePresence in GetAvatars())
  2449. {
  2450. m_log.ErrorFormat("{0,-16}{1,-16}{2,-25}{3,-25}{4,-16},{5,-16}{6,-16}",
  2451. scenePresence.Firstname,
  2452. scenePresence.Lastname,
  2453. scenePresence.UUID,
  2454. scenePresence.ControllingClient.AgentId,
  2455. "Unknown",
  2456. "Unknown",
  2457. RegionInfo.RegionName);
  2458. }
  2459. break;
  2460. case "modules":
  2461. m_log.Error("The currently loaded modules in " + RegionInfo.RegionName + " are:");
  2462. foreach (IRegionModule module in Modules.Values)
  2463. {
  2464. if (!module.IsSharedModule)
  2465. {
  2466. m_log.Error("Region Module: " + module.Name);
  2467. }
  2468. }
  2469. break;
  2470. }
  2471. }
  2472. #endregion
  2473. #region Script Handling Methods
  2474. /// <summary>
  2475. /// Console command handler to send script command to script engine.
  2476. /// </summary>
  2477. /// <param name="args"></param>
  2478. public void SendCommandToPlugins(string[] args)
  2479. {
  2480. m_eventManager.TriggerOnPluginConsole(args);
  2481. }
  2482. public double GetLandHeight(int x, int y)
  2483. {
  2484. return Heightmap[x, y];
  2485. }
  2486. public LLUUID GetLandOwner(float x, float y)
  2487. {
  2488. ILandObject land = LandChannel.GetLandObject(x, y);
  2489. if (land == null)
  2490. {
  2491. return LLUUID.Zero;
  2492. }
  2493. else
  2494. {
  2495. return land.landData.ownerID;
  2496. }
  2497. }
  2498. public LandData GetLandData(float x, float y)
  2499. {
  2500. return LandChannel.GetLandObject(x, y).landData;
  2501. }
  2502. public void SetLandMusicURL(float x, float y, string url)
  2503. {
  2504. ILandObject land = LandChannel.GetLandObject(x, y);
  2505. if (land == null)
  2506. {
  2507. return;
  2508. }
  2509. else
  2510. {
  2511. land.landData.musicURL = url;
  2512. return;
  2513. }
  2514. }
  2515. public void SetLandMediaURL(float x, float y, string url)
  2516. {
  2517. ILandObject land = LandChannel.GetLandObject(x, y);
  2518. if (land == null)
  2519. {
  2520. return;
  2521. }
  2522. else
  2523. {
  2524. land.landData.mediaURL = url;
  2525. return;
  2526. }
  2527. }
  2528. public RegionInfo RequestClosestRegion(string name)
  2529. {
  2530. return m_sceneGridService.RequestClosestRegion(name);
  2531. }
  2532. #endregion
  2533. #region Script Engine
  2534. private List<ScriptEngineInterface> ScriptEngines = new List<ScriptEngineInterface>();
  2535. private bool m_dumpAssetsToFile;
  2536. /// <summary>
  2537. ///
  2538. /// </summary>
  2539. /// <param name="scriptEngine"></param>
  2540. public void AddScriptEngine(ScriptEngineInterface scriptEngine)
  2541. {
  2542. ScriptEngines.Add(scriptEngine);
  2543. scriptEngine.InitializeEngine(this);
  2544. }
  2545. public void TriggerObjectChanged(uint localID, uint change)
  2546. {
  2547. m_eventManager.TriggerOnScriptChangedEvent(localID, change);
  2548. }
  2549. public void TriggerAtTargetEvent(uint localID, uint handle, LLVector3 targetpos, LLVector3 currentpos)
  2550. {
  2551. m_eventManager.TriggerAtTargetEvent(localID, handle, targetpos, currentpos);
  2552. }
  2553. public void TriggerNotAtTargetEvent(uint localID)
  2554. {
  2555. m_eventManager.TriggerNotAtTargetEvent(localID);
  2556. }
  2557. private bool scriptDanger(SceneObjectPart part,LLVector3 pos)
  2558. {
  2559. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  2560. if (part != null)
  2561. {
  2562. if (parcel != null)
  2563. {
  2564. if ((parcel.landData.landFlags & (uint)Parcel.ParcelFlags.AllowOtherScripts) != 0)
  2565. {
  2566. return true;
  2567. }
  2568. else if ((parcel.landData.landFlags & (uint)Parcel.ParcelFlags.AllowGroupScripts) != 0)
  2569. {
  2570. if (part.OwnerID == parcel.landData.ownerID || (parcel.landData.isGroupOwned && part.GroupID == parcel.landData.groupID) || ExternalChecks.ExternalChecksCanBeGodLike(part.OwnerID))
  2571. {
  2572. return true;
  2573. }
  2574. else
  2575. {
  2576. return false;
  2577. }
  2578. }
  2579. else
  2580. {
  2581. if (part.OwnerID == parcel.landData.ownerID)
  2582. {
  2583. return true;
  2584. }
  2585. else
  2586. {
  2587. return false;
  2588. }
  2589. }
  2590. }
  2591. else
  2592. {
  2593. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  2594. {
  2595. // The only time parcel != null when an object is inside a region is when
  2596. // there is nothing behind the landchannel. IE, no land plugin loaded.
  2597. return true;
  2598. }
  2599. else
  2600. {
  2601. // The object is outside of this region. Stop piping events to it.
  2602. return false;
  2603. }
  2604. }
  2605. }
  2606. else
  2607. {
  2608. return false;
  2609. }
  2610. }
  2611. public bool scriptDanger(uint localID, LLVector3 pos)
  2612. {
  2613. SceneObjectPart part = GetSceneObjectPart(localID);
  2614. if (part != null)
  2615. {
  2616. return scriptDanger(part, pos);
  2617. }
  2618. else
  2619. {
  2620. return false;
  2621. }
  2622. }
  2623. public bool pipeEventsForScript(uint localID)
  2624. {
  2625. SceneObjectPart part = GetSceneObjectPart(localID);
  2626. if (part != null)
  2627. {
  2628. LLVector3 pos = part.GetWorldPosition();
  2629. return scriptDanger(part, pos);
  2630. }
  2631. else
  2632. {
  2633. return false;
  2634. }
  2635. }
  2636. #endregion
  2637. #region InnerScene wrapper methods
  2638. /// <summary>
  2639. ///
  2640. /// </summary>
  2641. /// <param name="localID"></param>
  2642. /// <returns></returns>
  2643. public LLUUID ConvertLocalIDToFullID(uint localID)
  2644. {
  2645. return m_innerScene.ConvertLocalIDToFullID(localID);
  2646. }
  2647. public void SwapRootAgentCount(bool rootChildChildRootTF)
  2648. {
  2649. m_innerScene.SwapRootChildAgent(rootChildChildRootTF);
  2650. }
  2651. public void AddPhysicalPrim(int num)
  2652. {
  2653. m_innerScene.AddPhysicalPrim(num);
  2654. }
  2655. public void RemovePhysicalPrim(int num)
  2656. {
  2657. m_innerScene.RemovePhysicalPrim(num);
  2658. }
  2659. /// <summary>
  2660. ///
  2661. /// </summary>
  2662. /// <param name="presence"></param>
  2663. public void SendAllSceneObjectsToClient(ScenePresence presence)
  2664. {
  2665. m_innerScene.SendAllSceneObjectsToClient(presence);
  2666. }
  2667. //The idea is to have a group of method that return a list of avatars meeting some requirement
  2668. // ie it could be all m_scenePresences within a certain range of the calling prim/avatar.
  2669. /// <summary>
  2670. /// Return a list of all avatars in this region.
  2671. /// This list is a new object, so it can be iterated over without locking.
  2672. /// </summary>
  2673. /// <returns></returns>
  2674. public List<ScenePresence> GetAvatars()
  2675. {
  2676. return m_innerScene.GetAvatars();
  2677. }
  2678. /// <summary>
  2679. /// Return a list of all ScenePresences in this region. This returns child agents as well as root agents.
  2680. /// This list is a new object, so it can be iterated over without locking.
  2681. /// </summary>
  2682. /// <returns></returns>
  2683. public List<ScenePresence> GetScenePresences()
  2684. {
  2685. return m_innerScene.GetScenePresences();
  2686. }
  2687. /// <summary>
  2688. /// Request a filtered list of ScenePresences in this region.
  2689. /// This list is a new object, so it can be iterated over without locking.
  2690. /// </summary>
  2691. /// <param name="filter"></param>
  2692. /// <returns></returns>
  2693. public List<ScenePresence> GetScenePresences(FilterAvatarList filter)
  2694. {
  2695. return m_innerScene.GetScenePresences(filter);
  2696. }
  2697. /// <summary>
  2698. /// Request a scene presence by UUID
  2699. /// </summary>
  2700. /// <param name="avatarID"></param>
  2701. /// <returns></returns>
  2702. public ScenePresence GetScenePresence(LLUUID avatarID)
  2703. {
  2704. return m_innerScene.GetScenePresence(avatarID);
  2705. }
  2706. /// <summary>
  2707. /// Request an Avatar's Child Status - used by ClientView when a 'kick everyone' or 'estate message' occurs
  2708. /// </summary>
  2709. /// <param name="avatarID">AvatarID to lookup</param>
  2710. /// <returns></returns>
  2711. public override bool PresenceChildStatus(LLUUID avatarID)
  2712. {
  2713. ScenePresence cp = GetScenePresence(avatarID);
  2714. return cp.IsChildAgent;
  2715. }
  2716. /// <summary>
  2717. ///
  2718. /// </summary>
  2719. /// <param name="action"></param>
  2720. public void ForEachScenePresence(Action<ScenePresence> action)
  2721. {
  2722. // We don't want to try to send messages if there are no avatars.
  2723. if (m_scenePresences != null)
  2724. {
  2725. try
  2726. {
  2727. List<ScenePresence> presenceList = GetScenePresences();
  2728. foreach (ScenePresence presence in presenceList)
  2729. {
  2730. action(presence);
  2731. }
  2732. }
  2733. catch (Exception e)
  2734. {
  2735. m_log.Info("[BUG]: " + e.ToString());
  2736. }
  2737. }
  2738. }
  2739. /// <summary>
  2740. ///
  2741. /// </summary>
  2742. /// <param name="action"></param>
  2743. // public void ForEachObject(Action<SceneObjectGroup> action)
  2744. // {
  2745. // List<SceneObjectGroup> presenceList;
  2746. //
  2747. // lock (m_sceneObjects)
  2748. // {
  2749. // presenceList = new List<SceneObjectGroup>(m_sceneObjects.Values);
  2750. // }
  2751. //
  2752. // foreach (SceneObjectGroup presence in presenceList)
  2753. // {
  2754. // action(presence);
  2755. // }
  2756. // }
  2757. /// <summary>
  2758. ///
  2759. /// </summary>
  2760. /// <param name="localID"></param>
  2761. /// <returns></returns>
  2762. public SceneObjectPart GetSceneObjectPart(uint localID)
  2763. {
  2764. return m_innerScene.GetSceneObjectPart(localID);
  2765. }
  2766. /// <summary>
  2767. ///
  2768. /// </summary>
  2769. /// <param name="fullID"></param>
  2770. /// <returns></returns>
  2771. public SceneObjectPart GetSceneObjectPart(LLUUID fullID)
  2772. {
  2773. return m_innerScene.GetSceneObjectPart(fullID);
  2774. }
  2775. internal bool TryGetAvatar(LLUUID avatarId, out ScenePresence avatar)
  2776. {
  2777. return m_innerScene.TryGetAvatar(avatarId, out avatar);
  2778. }
  2779. internal bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  2780. {
  2781. return m_innerScene.TryGetAvatarByName(avatarName, out avatar);
  2782. }
  2783. internal void ForEachClient(Action<IClientAPI> action)
  2784. {
  2785. m_innerScene.ForEachClient(action);
  2786. }
  2787. /// <summary>
  2788. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  2789. /// will not affect the original list of objects in the scene.
  2790. /// </summary>
  2791. /// <returns></returns>
  2792. public List<EntityBase> GetEntities()
  2793. {
  2794. return m_innerScene.GetEntities();
  2795. }
  2796. #endregion
  2797. #region BaseHTTPServer wrapper methods
  2798. public bool AddHTTPHandler(string method, GenericHTTPMethod handler)
  2799. {
  2800. return m_httpListener.AddHTTPHandler(method, handler);
  2801. }
  2802. public bool AddXmlRPCHandler(string method, XmlRpcMethod handler)
  2803. {
  2804. return m_httpListener.AddXmlRPCHandler(method, handler);
  2805. }
  2806. public void AddStreamHandler(IRequestHandler handler)
  2807. {
  2808. m_httpListener.AddStreamHandler(handler);
  2809. }
  2810. public void RemoveStreamHandler(string httpMethod, string path)
  2811. {
  2812. m_httpListener.RemoveStreamHandler(httpMethod, path);
  2813. }
  2814. public void RemoveHTTPHandler(string httpMethod, string path)
  2815. {
  2816. m_httpListener.RemoveHTTPHandler(httpMethod, path);
  2817. }
  2818. #endregion
  2819. #region Avatar Appearance Default
  2820. public static void GetDefaultAvatarAppearance(out AvatarWearable[] wearables, out byte[] visualParams)
  2821. {
  2822. visualParams = GetDefaultVisualParams();
  2823. wearables = AvatarWearable.DefaultWearables;
  2824. }
  2825. private static byte[] GetDefaultVisualParams()
  2826. {
  2827. byte[] visualParams;
  2828. visualParams = new byte[218];
  2829. for (int i = 0; i < 218; i++)
  2830. {
  2831. visualParams[i] = 100;
  2832. }
  2833. return visualParams;
  2834. }
  2835. #endregion
  2836. }
  2837. }