SceneCommunicationService.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Net;
  30. using System.Reflection;
  31. using System.Threading;
  32. using OpenMetaverse;
  33. using OpenMetaverse.StructuredData;
  34. using log4net;
  35. using OpenSim.Framework;
  36. using OpenSim.Framework.Client;
  37. using OpenSim.Framework.Communications;
  38. using OpenSim.Framework.Communications.Cache;
  39. using OpenSim.Framework.Capabilities;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Services.Interfaces;
  42. using OSD = OpenMetaverse.StructuredData.OSD;
  43. namespace OpenSim.Region.Framework.Scenes
  44. {
  45. public delegate void KiPrimitiveDelegate(uint localID);
  46. public delegate void RemoveKnownRegionsFromAvatarList(UUID avatarID, List<ulong> regionlst);
  47. public class SceneCommunicationService //one instance per region
  48. {
  49. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  50. protected CommunicationsManager m_commsProvider;
  51. protected IInterregionCommsOut m_interregionCommsOut;
  52. protected RegionInfo m_regionInfo;
  53. protected RegionCommsListener regionCommsHost;
  54. protected List<UUID> m_agentsInTransit;
  55. public event AgentCrossing OnAvatarCrossingIntoRegion;
  56. public event ExpectUserDelegate OnExpectUser;
  57. public event ExpectPrimDelegate OnExpectPrim;
  58. public event CloseAgentConnection OnCloseAgentConnection;
  59. public event PrimCrossing OnPrimCrossingIntoRegion;
  60. public event RegionUp OnRegionUp;
  61. public event ChildAgentUpdate OnChildAgentUpdate;
  62. //public event RemoveKnownRegionsFromAvatarList OnRemoveKnownRegionFromAvatar;
  63. public event LogOffUser OnLogOffUser;
  64. public event GetLandData OnGetLandData;
  65. private AgentCrossing handlerAvatarCrossingIntoRegion = null; // OnAvatarCrossingIntoRegion;
  66. private ExpectUserDelegate handlerExpectUser = null; // OnExpectUser;
  67. private ExpectPrimDelegate handlerExpectPrim = null; // OnExpectPrim;
  68. private CloseAgentConnection handlerCloseAgentConnection = null; // OnCloseAgentConnection;
  69. private PrimCrossing handlerPrimCrossingIntoRegion = null; // OnPrimCrossingIntoRegion;
  70. private RegionUp handlerRegionUp = null; // OnRegionUp;
  71. private ChildAgentUpdate handlerChildAgentUpdate = null; // OnChildAgentUpdate;
  72. //private RemoveKnownRegionsFromAvatarList handlerRemoveKnownRegionFromAvatar = null; // OnRemoveKnownRegionFromAvatar;
  73. private LogOffUser handlerLogOffUser = null;
  74. private GetLandData handlerGetLandData = null; // OnGetLandData
  75. public KiPrimitiveDelegate KiPrimitive;
  76. public SceneCommunicationService(CommunicationsManager commsMan)
  77. {
  78. m_commsProvider = commsMan;
  79. m_agentsInTransit = new List<UUID>();
  80. }
  81. /// <summary>
  82. /// Register a region with the grid
  83. /// </summary>
  84. /// <param name="regionInfos"></param>
  85. /// <exception cref="System.Exception">Thrown if region registration fails.</exception>
  86. public void RegisterRegion(IInterregionCommsOut comms_out, RegionInfo regionInfos)
  87. {
  88. m_interregionCommsOut = comms_out;
  89. m_regionInfo = regionInfos;
  90. m_commsProvider.GridService.gdebugRegionName = regionInfos.RegionName;
  91. regionCommsHost = m_commsProvider.GridService.RegisterRegion(m_regionInfo);
  92. if (regionCommsHost != null)
  93. {
  94. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got" + regionCommsHost.ToString());
  95. regionCommsHost.debugRegionName = regionInfos.RegionName;
  96. regionCommsHost.OnExpectPrim += IncomingPrimCrossing;
  97. regionCommsHost.OnExpectUser += NewUserConnection;
  98. regionCommsHost.OnAvatarCrossingIntoRegion += AgentCrossing;
  99. regionCommsHost.OnCloseAgentConnection += CloseConnection;
  100. regionCommsHost.OnRegionUp += newRegionUp;
  101. regionCommsHost.OnChildAgentUpdate += ChildAgentUpdate;
  102. regionCommsHost.OnLogOffUser += GridLogOffUser;
  103. regionCommsHost.OnGetLandData += FetchLandData;
  104. }
  105. else
  106. {
  107. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: registered with gridservice and got null");
  108. }
  109. }
  110. public RegionInfo RequestClosestRegion(string name)
  111. {
  112. return m_commsProvider.GridService.RequestClosestRegion(name);
  113. }
  114. public void Close()
  115. {
  116. if (regionCommsHost != null)
  117. {
  118. regionCommsHost.OnLogOffUser -= GridLogOffUser;
  119. regionCommsHost.OnChildAgentUpdate -= ChildAgentUpdate;
  120. regionCommsHost.OnRegionUp -= newRegionUp;
  121. regionCommsHost.OnExpectUser -= NewUserConnection;
  122. regionCommsHost.OnExpectPrim -= IncomingPrimCrossing;
  123. regionCommsHost.OnAvatarCrossingIntoRegion -= AgentCrossing;
  124. regionCommsHost.OnCloseAgentConnection -= CloseConnection;
  125. regionCommsHost.OnGetLandData -= FetchLandData;
  126. try
  127. {
  128. m_commsProvider.GridService.DeregisterRegion(m_regionInfo);
  129. }
  130. catch (Exception e)
  131. {
  132. m_log.ErrorFormat(
  133. "[GRID]: Deregistration of region {0} from the grid failed - {1}. Continuing",
  134. m_regionInfo.RegionName, e);
  135. }
  136. regionCommsHost = null;
  137. }
  138. }
  139. #region CommsManager Event handlers
  140. /// <summary>
  141. ///
  142. /// </summary>
  143. /// <param name="regionHandle"></param>
  144. /// <param name="agent"></param>
  145. ///
  146. protected void NewUserConnection(AgentCircuitData agent)
  147. {
  148. handlerExpectUser = OnExpectUser;
  149. if (handlerExpectUser != null)
  150. {
  151. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: OnExpectUser Fired for User:" + agent.firstname + " " + agent.lastname);
  152. handlerExpectUser(agent);
  153. }
  154. }
  155. protected void GridLogOffUser(UUID AgentID, UUID RegionSecret, string message)
  156. {
  157. handlerLogOffUser = OnLogOffUser;
  158. if (handlerLogOffUser != null)
  159. {
  160. handlerLogOffUser(AgentID, RegionSecret, message);
  161. }
  162. }
  163. protected bool newRegionUp(RegionInfo region)
  164. {
  165. handlerRegionUp = OnRegionUp;
  166. if (handlerRegionUp != null)
  167. {
  168. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: newRegionUp Fired for User:" + region.RegionName);
  169. handlerRegionUp(region);
  170. }
  171. return true;
  172. }
  173. protected bool ChildAgentUpdate(ChildAgentDataUpdate cAgentData)
  174. {
  175. handlerChildAgentUpdate = OnChildAgentUpdate;
  176. if (handlerChildAgentUpdate != null)
  177. handlerChildAgentUpdate(cAgentData);
  178. return true;
  179. }
  180. protected void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  181. {
  182. handlerAvatarCrossingIntoRegion = OnAvatarCrossingIntoRegion;
  183. if (handlerAvatarCrossingIntoRegion != null)
  184. {
  185. handlerAvatarCrossingIntoRegion(agentID, position, isFlying);
  186. }
  187. }
  188. protected bool IncomingPrimCrossing(UUID primID, String objXMLData, int XMLMethod)
  189. {
  190. handlerExpectPrim = OnExpectPrim;
  191. if (handlerExpectPrim != null)
  192. {
  193. return handlerExpectPrim(primID, objXMLData, XMLMethod);
  194. }
  195. else
  196. {
  197. return false;
  198. }
  199. }
  200. protected void PrimCrossing(UUID primID, Vector3 position, bool isPhysical)
  201. {
  202. handlerPrimCrossingIntoRegion = OnPrimCrossingIntoRegion;
  203. if (handlerPrimCrossingIntoRegion != null)
  204. {
  205. handlerPrimCrossingIntoRegion(primID, position, isPhysical);
  206. }
  207. }
  208. protected bool CloseConnection(UUID agentID)
  209. {
  210. m_log.Debug("[INTERREGION]: Incoming Agent Close Request for agent: " + agentID);
  211. handlerCloseAgentConnection = OnCloseAgentConnection;
  212. if (handlerCloseAgentConnection != null)
  213. {
  214. return handlerCloseAgentConnection(agentID);
  215. }
  216. return false;
  217. }
  218. protected LandData FetchLandData(uint x, uint y)
  219. {
  220. handlerGetLandData = OnGetLandData;
  221. if (handlerGetLandData != null)
  222. {
  223. return handlerGetLandData(x, y);
  224. }
  225. return null;
  226. }
  227. #endregion
  228. #region Inform Client of Neighbours
  229. private delegate void InformClientOfNeighbourDelegate(
  230. ScenePresence avatar, AgentCircuitData a, SimpleRegionInfo reg, IPEndPoint endPoint, bool newAgent);
  231. private void InformClientOfNeighbourCompleted(IAsyncResult iar)
  232. {
  233. InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate) iar.AsyncState;
  234. icon.EndInvoke(iar);
  235. }
  236. /// <summary>
  237. /// Async component for informing client of which neighbours exist
  238. /// </summary>
  239. /// <remarks>
  240. /// This needs to run asynchronously, as a network timeout may block the thread for a long while
  241. /// </remarks>
  242. /// <param name="remoteClient"></param>
  243. /// <param name="a"></param>
  244. /// <param name="regionHandle"></param>
  245. /// <param name="endPoint"></param>
  246. private void InformClientOfNeighbourAsync(ScenePresence avatar, AgentCircuitData a, SimpleRegionInfo reg,
  247. IPEndPoint endPoint, bool newAgent)
  248. {
  249. // Let's wait just a little to give time to originating regions to catch up with closing child agents
  250. // after a cross here
  251. Thread.Sleep(500);
  252. uint x, y;
  253. Utils.LongToUInts(reg.RegionHandle, out x, out y);
  254. x = x / Constants.RegionSize;
  255. y = y / Constants.RegionSize;
  256. m_log.Info("[INTERGRID]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint.ToString() + ")");
  257. string capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  258. + "/CAPS/" + a.CapsPath + "0000/";
  259. string reason = String.Empty;
  260. //bool regionAccepted = m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, a);
  261. bool regionAccepted = m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, a, out reason);
  262. if (regionAccepted && newAgent)
  263. {
  264. IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
  265. if (eq != null)
  266. {
  267. #region IP Translation for NAT
  268. IClientIPEndpoint ipepClient;
  269. if (avatar.ClientView.TryGet(out ipepClient))
  270. {
  271. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  272. }
  273. #endregion
  274. eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
  275. eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
  276. m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1} in region {2}",
  277. capsPath, avatar.UUID, avatar.Scene.RegionInfo.RegionName);
  278. }
  279. else
  280. {
  281. avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  282. // TODO: make Event Queue disablable!
  283. }
  284. m_log.Info("[INTERGRID]: Completed inform client about neighbour " + endPoint.ToString());
  285. }
  286. }
  287. public void RequestNeighbors(RegionInfo region)
  288. {
  289. // List<SimpleRegionInfo> neighbours =
  290. m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  291. //IPEndPoint blah = new IPEndPoint();
  292. //blah.Address = region.RemotingAddress;
  293. //blah.Port = region.RemotingPort;
  294. }
  295. /// <summary>
  296. /// This informs all neighboring regions about agent "avatar".
  297. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  298. /// </summary>
  299. public void EnableNeighbourChildAgents(ScenePresence avatar, List<RegionInfo> lstneighbours)
  300. {
  301. List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
  302. //m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  303. for (int i = 0; i < lstneighbours.Count; i++)
  304. {
  305. // We don't want to keep sending to regions that consistently fail on comms.
  306. if (!(lstneighbours[i].commFailTF))
  307. {
  308. neighbours.Add(new SimpleRegionInfo(lstneighbours[i]));
  309. }
  310. }
  311. // we're going to be using the above code once neighbour cache is correct. Currently it doesn't appear to be
  312. // So we're temporarily going back to the old method of grabbing it from the Grid Server Every time :/
  313. if (m_regionInfo != null)
  314. {
  315. neighbours =
  316. m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  317. }
  318. else
  319. {
  320. m_log.Debug("[ENABLENEIGHBOURCHILDAGENTS]: m_regionInfo was null in EnableNeighbourChildAgents, is this a NPC?");
  321. }
  322. /// We need to find the difference between the new regions where there are no child agents
  323. /// and the regions where there are already child agents. We only send notification to the former.
  324. List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
  325. neighbourHandles.Add(avatar.Scene.RegionInfo.RegionHandle); // add this region too
  326. List<ulong> previousRegionNeighbourHandles ;
  327. if (avatar.Scene.CapsModule != null)
  328. {
  329. previousRegionNeighbourHandles =
  330. new List<ulong>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID).Keys);
  331. }
  332. else
  333. {
  334. previousRegionNeighbourHandles = new List<ulong>();
  335. }
  336. List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  337. List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  338. //Dump("Current Neighbors", neighbourHandles);
  339. //Dump("Previous Neighbours", previousRegionNeighbourHandles);
  340. //Dump("New Neighbours", newRegions);
  341. //Dump("Old Neighbours", oldRegions);
  342. /// Update the scene presence's known regions here on this region
  343. avatar.DropOldNeighbours(oldRegions);
  344. /// Collect as many seeds as possible
  345. Dictionary<ulong, string> seeds;
  346. if (avatar.Scene.CapsModule != null)
  347. seeds
  348. = new Dictionary<ulong, string>(avatar.Scene.CapsModule.GetChildrenSeeds(avatar.UUID));
  349. else
  350. seeds = new Dictionary<ulong, string>();
  351. //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
  352. if (!seeds.ContainsKey(avatar.Scene.RegionInfo.RegionHandle))
  353. seeds.Add(avatar.Scene.RegionInfo.RegionHandle, avatar.ControllingClient.RequestClientInfo().CapsPath);
  354. /// Create the necessary child agents
  355. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  356. foreach (SimpleRegionInfo neighbour in neighbours)
  357. {
  358. if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
  359. {
  360. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  361. agent.BaseFolder = UUID.Zero;
  362. agent.InventoryFolder = UUID.Zero;
  363. agent.startpos = new Vector3(128, 128, 70);
  364. agent.child = true;
  365. if (newRegions.Contains(neighbour.RegionHandle))
  366. {
  367. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  368. avatar.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
  369. seeds.Add(neighbour.RegionHandle, agent.CapsPath);
  370. }
  371. else
  372. agent.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, neighbour.RegionHandle);
  373. cagents.Add(agent);
  374. }
  375. }
  376. /// Update all child agent with everyone's seeds
  377. foreach (AgentCircuitData a in cagents)
  378. {
  379. a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  380. }
  381. if (avatar.Scene.CapsModule != null)
  382. {
  383. // These two are the same thing!
  384. avatar.Scene.CapsModule.SetChildrenSeed(avatar.UUID, seeds);
  385. }
  386. avatar.KnownRegions = seeds;
  387. //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
  388. //avatar.DumpKnownRegions();
  389. bool newAgent = false;
  390. int count = 0;
  391. foreach (SimpleRegionInfo neighbour in neighbours)
  392. {
  393. // Don't do it if there's already an agent in that region
  394. if (newRegions.Contains(neighbour.RegionHandle))
  395. newAgent = true;
  396. else
  397. newAgent = false;
  398. if (neighbour.RegionHandle != avatar.Scene.RegionInfo.RegionHandle)
  399. {
  400. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  401. try
  402. {
  403. d.BeginInvoke(avatar, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
  404. InformClientOfNeighbourCompleted,
  405. d);
  406. }
  407. catch (Exception e)
  408. {
  409. m_log.ErrorFormat(
  410. "[REGIONINFO]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
  411. neighbour.ExternalHostName,
  412. neighbour.RegionHandle,
  413. neighbour.RegionLocX,
  414. neighbour.RegionLocY,
  415. e);
  416. // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
  417. // since I don't know what will happen if we just let the client continue
  418. // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
  419. // throw e;
  420. }
  421. }
  422. count++;
  423. }
  424. }
  425. /// <summary>
  426. /// This informs a single neighboring region about agent "avatar".
  427. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  428. /// </summary>
  429. public void InformNeighborChildAgent(ScenePresence avatar, SimpleRegionInfo region)
  430. {
  431. AgentCircuitData agent = avatar.ControllingClient.RequestClientInfo();
  432. agent.BaseFolder = UUID.Zero;
  433. agent.InventoryFolder = UUID.Zero;
  434. agent.startpos = new Vector3(128, 128, 70);
  435. agent.child = true;
  436. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  437. d.BeginInvoke(avatar, agent, region, region.ExternalEndPoint, true,
  438. InformClientOfNeighbourCompleted,
  439. d);
  440. }
  441. #endregion
  442. public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle);
  443. private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar)
  444. {
  445. InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate) iar.AsyncState;
  446. icon.EndInvoke(iar);
  447. }
  448. /// <summary>
  449. /// Asynchronous call to information neighbouring regions that this region is up
  450. /// </summary>
  451. /// <param name="region"></param>
  452. /// <param name="regionhandle"></param>
  453. private void InformNeighboursThatRegionIsUpAsync(INeighbourService neighbourService, RegionInfo region, ulong regionhandle)
  454. {
  455. m_log.Info("[INTERGRID]: Starting to inform neighbors that I'm here");
  456. //RegionUpData regiondata = new RegionUpData(region.RegionLocX, region.RegionLocY, region.ExternalHostName, region.InternalEndPoint.Port);
  457. //bool regionAccepted =
  458. // m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region), regionhandle);
  459. //bool regionAccepted = m_interregionCommsOut.SendHelloNeighbour(regionhandle, region);
  460. bool regionAccepted = false;
  461. if (neighbourService != null)
  462. regionAccepted = neighbourService.HelloNeighbour(regionhandle, region);
  463. else
  464. m_log.DebugFormat("[SCS]: No neighbour service provided for informing neigbhours of this region");
  465. if (regionAccepted)
  466. {
  467. m_log.Info("[INTERGRID]: Completed informing neighbors that I'm here");
  468. handlerRegionUp = OnRegionUp;
  469. // yes, we're notifying ourselves.
  470. if (handlerRegionUp != null)
  471. handlerRegionUp(region);
  472. }
  473. else
  474. {
  475. m_log.Warn("[INTERGRID]: Failed to inform neighbors that I'm here.");
  476. }
  477. }
  478. /// <summary>
  479. /// Called by scene when region is initialized (not always when it's listening for agents)
  480. /// This is an inter-region message that informs the surrounding neighbors that the sim is up.
  481. /// </summary>
  482. public void InformNeighborsThatRegionisUp(INeighbourService neighbourService, RegionInfo region)
  483. {
  484. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending InterRegion Notification that region is up " + region.RegionName);
  485. List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
  486. // This stays uncached because we don't already know about our neighbors at this point.
  487. neighbours = m_commsProvider.GridService.RequestNeighbours(m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  488. if (neighbours != null)
  489. {
  490. for (int i = 0; i < neighbours.Count; i++)
  491. {
  492. InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync;
  493. d.BeginInvoke(neighbourService, region, neighbours[i].RegionHandle,
  494. InformNeighborsThatRegionisUpCompleted,
  495. d);
  496. }
  497. }
  498. //bool val = m_commsProvider.InterRegion.RegionUp(new SerializableRegionInfo(region));
  499. }
  500. public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, ulong regionHandle);
  501. /// <summary>
  502. /// This informs all neighboring regions about the settings of it's child agent.
  503. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  504. ///
  505. /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc.
  506. ///
  507. /// </summary>
  508. private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, ulong regionHandle)
  509. {
  510. //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName);
  511. try
  512. {
  513. //m_commsProvider.InterRegion.ChildAgentUpdate(regionHandle, cAgentData);
  514. m_interregionCommsOut.SendChildAgentUpdate(regionHandle, cAgentData);
  515. }
  516. catch
  517. {
  518. // Ignore; we did our best
  519. }
  520. //if (regionAccepted)
  521. //{
  522. // //m_log.Info("[INTERGRID]: Completed sending a neighbor an update about my agent");
  523. //}
  524. //else
  525. //{
  526. // //m_log.Info("[INTERGRID]: Failed sending a neighbor an update about my agent");
  527. //}
  528. }
  529. private void SendChildAgentDataUpdateCompleted(IAsyncResult iar)
  530. {
  531. SendChildAgentDataUpdateDelegate icon = (SendChildAgentDataUpdateDelegate) iar.AsyncState;
  532. icon.EndInvoke(iar);
  533. }
  534. public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence)
  535. {
  536. // This assumes that we know what our neighbors are.
  537. try
  538. {
  539. foreach (ulong regionHandle in presence.KnownChildRegionHandles)
  540. {
  541. if (regionHandle != m_regionInfo.RegionHandle)
  542. {
  543. SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync;
  544. d.BeginInvoke(cAgentData, regionHandle,
  545. SendChildAgentDataUpdateCompleted,
  546. d);
  547. }
  548. }
  549. }
  550. catch (InvalidOperationException)
  551. {
  552. // We're ignoring a collection was modified error because this data gets old and outdated fast.
  553. }
  554. }
  555. public delegate void SendCloseChildAgentDelegate(UUID agentID, ulong regionHandle);
  556. /// <summary>
  557. /// This Closes child agents on neighboring regions
  558. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  559. /// </summary>
  560. protected void SendCloseChildAgentAsync(UUID agentID, ulong regionHandle)
  561. {
  562. m_log.Debug("[INTERGRID]: Sending close agent to " + regionHandle);
  563. // let's do our best, but there's not much we can do if the neighbour doesn't accept.
  564. //m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID);
  565. m_interregionCommsOut.SendCloseAgent(regionHandle, agentID);
  566. }
  567. private void SendCloseChildAgentCompleted(IAsyncResult iar)
  568. {
  569. SendCloseChildAgentDelegate icon = (SendCloseChildAgentDelegate)iar.AsyncState;
  570. icon.EndInvoke(iar);
  571. }
  572. public void SendCloseChildAgentConnections(UUID agentID, List<ulong> regionslst)
  573. {
  574. foreach (ulong handle in regionslst)
  575. {
  576. SendCloseChildAgentDelegate d = SendCloseChildAgentAsync;
  577. d.BeginInvoke(agentID, handle,
  578. SendCloseChildAgentCompleted,
  579. d);
  580. }
  581. }
  582. /// <summary>
  583. /// Helper function to request neighbors from grid-comms
  584. /// </summary>
  585. /// <param name="regionHandle"></param>
  586. /// <returns></returns>
  587. public virtual RegionInfo RequestNeighbouringRegionInfo(ulong regionHandle)
  588. {
  589. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending Grid Services Request about neighbor " + regionHandle.ToString());
  590. return m_commsProvider.GridService.RequestNeighbourInfo(regionHandle);
  591. }
  592. /// <summary>
  593. /// Helper function to request neighbors from grid-comms
  594. /// </summary>
  595. /// <param name="regionID"></param>
  596. /// <returns></returns>
  597. public virtual RegionInfo RequestNeighbouringRegionInfo(UUID regionID)
  598. {
  599. //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending Grid Services Request about neighbor " + regionID);
  600. return m_commsProvider.GridService.RequestNeighbourInfo(regionID);
  601. }
  602. /// <summary>
  603. /// Requests map blocks in area of minX, maxX, minY, MaxY in world cordinates
  604. /// </summary>
  605. /// <param name="minX"></param>
  606. /// <param name="minY"></param>
  607. /// <param name="maxX"></param>
  608. /// <param name="maxY"></param>
  609. public virtual void RequestMapBlocks(IClientAPI remoteClient, int minX, int minY, int maxX, int maxY)
  610. {
  611. List<MapBlockData> mapBlocks;
  612. mapBlocks = m_commsProvider.GridService.RequestNeighbourMapBlocks(minX - 4, minY - 4, minX + 4, minY + 4);
  613. remoteClient.SendMapBlock(mapBlocks, 0);
  614. }
  615. /// <summary>
  616. /// Try to teleport an agent to a new region.
  617. /// </summary>
  618. /// <param name="remoteClient"></param>
  619. /// <param name="RegionHandle"></param>
  620. /// <param name="position"></param>
  621. /// <param name="lookAt"></param>
  622. /// <param name="flags"></param>
  623. public virtual void RequestTeleportToLocation(ScenePresence avatar, ulong regionHandle, Vector3 position,
  624. Vector3 lookAt, uint teleportFlags)
  625. {
  626. if (!avatar.Scene.Permissions.CanTeleport(avatar.UUID))
  627. return;
  628. bool destRegionUp = true;
  629. IEventQueue eq = avatar.Scene.RequestModuleInterface<IEventQueue>();
  630. // Reset animations; the viewer does that in teleports.
  631. avatar.ResetAnimations();
  632. if (regionHandle == m_regionInfo.RegionHandle)
  633. {
  634. m_log.DebugFormat(
  635. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation {0} within {1}",
  636. position, m_regionInfo.RegionName);
  637. // Teleport within the same region
  638. if (position.X < 0 || position.X > Constants.RegionSize || position.Y < 0 || position.Y > Constants.RegionSize || position.Z < 0)
  639. {
  640. Vector3 emergencyPos = new Vector3(128, 128, 128);
  641. m_log.WarnFormat(
  642. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
  643. position, avatar.Name, avatar.UUID, emergencyPos);
  644. position = emergencyPos;
  645. }
  646. // TODO: Get proper AVG Height
  647. float localAVHeight = 1.56f;
  648. float posZLimit = (float)avatar.Scene.Heightmap[(int)position.X, (int)position.Y];
  649. float newPosZ = posZLimit + localAVHeight;
  650. if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  651. {
  652. position.Z = newPosZ;
  653. }
  654. // Only send this if the event queue is null
  655. if (eq == null)
  656. avatar.ControllingClient.SendTeleportLocationStart();
  657. avatar.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  658. avatar.Teleport(position);
  659. }
  660. else
  661. {
  662. RegionInfo reg = RequestNeighbouringRegionInfo(regionHandle);
  663. if (reg != null)
  664. {
  665. m_log.DebugFormat(
  666. "[SCENE COMMUNICATION SERVICE]: RequestTeleportToLocation to {0} in {1}",
  667. position, reg.RegionName);
  668. if (eq == null)
  669. avatar.ControllingClient.SendTeleportLocationStart();
  670. // Let's do DNS resolution only once in this process, please!
  671. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  672. // it's actually doing a lot of work.
  673. IPEndPoint endPoint = reg.ExternalEndPoint;
  674. if (endPoint.Address == null)
  675. {
  676. // Couldn't resolve the name. Can't TP, because the viewer wants IP addresses.
  677. destRegionUp = false;
  678. }
  679. if (destRegionUp)
  680. {
  681. uint newRegionX = (uint)(reg.RegionHandle >> 40);
  682. uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
  683. uint oldRegionX = (uint)(m_regionInfo.RegionHandle >> 40);
  684. uint oldRegionY = (((uint)(m_regionInfo.RegionHandle)) >> 8);
  685. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  686. // both regions
  687. if (avatar.ParentID != (uint)0)
  688. avatar.StandUp();
  689. if (!avatar.ValidateAttachments())
  690. {
  691. avatar.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
  692. return;
  693. }
  694. // the avatar.Close below will clear the child region list. We need this below for (possibly)
  695. // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
  696. //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
  697. // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
  698. // failure at this point (unlike a border crossing failure). So perhaps this can never fail
  699. // once we reach here...
  700. //avatar.Scene.RemoveCapsHandler(avatar.UUID);
  701. string capsPath = String.Empty;
  702. AgentCircuitData agentCircuit = avatar.ControllingClient.RequestClientInfo();
  703. agentCircuit.BaseFolder = UUID.Zero;
  704. agentCircuit.InventoryFolder = UUID.Zero;
  705. agentCircuit.startpos = position;
  706. agentCircuit.child = true;
  707. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  708. {
  709. // brand new agent, let's create a new caps seed
  710. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  711. }
  712. string reason = String.Empty;
  713. // Let's create an agent there if one doesn't exist yet.
  714. //if (!m_commsProvider.InterRegion.InformRegionOfChildAgent(reg.RegionHandle, agentCircuit))
  715. if (!m_interregionCommsOut.SendCreateChildAgent(reg.RegionHandle, agentCircuit, out reason))
  716. {
  717. avatar.ControllingClient.SendTeleportFailed(String.Format("Destination is not accepting teleports: {0}",
  718. reason));
  719. return;
  720. }
  721. // OK, it got this agent. Let's close some child agents
  722. avatar.CloseChildAgents(newRegionX, newRegionY);
  723. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  724. {
  725. #region IP Translation for NAT
  726. IClientIPEndpoint ipepClient;
  727. if (avatar.ClientView.TryGet(out ipepClient))
  728. {
  729. capsPath
  730. = "http://"
  731. + NetworkUtil.GetHostFor(ipepClient.EndPoint, reg.ExternalHostName)
  732. + ":"
  733. + reg.HttpPort
  734. + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  735. }
  736. else
  737. {
  738. capsPath
  739. = "http://"
  740. + reg.ExternalHostName
  741. + ":"
  742. + reg.HttpPort
  743. + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  744. }
  745. #endregion
  746. if (eq != null)
  747. {
  748. #region IP Translation for NAT
  749. // Uses ipepClient above
  750. if (avatar.ClientView.TryGet(out ipepClient))
  751. {
  752. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  753. }
  754. #endregion
  755. eq.EnableSimulator(reg.RegionHandle, endPoint, avatar.UUID);
  756. // ES makes the client send a UseCircuitCode message to the destination,
  757. // which triggers a bunch of things there.
  758. // So let's wait
  759. Thread.Sleep(2000);
  760. eq.EstablishAgentCommunication(avatar.UUID, endPoint, capsPath);
  761. }
  762. else
  763. {
  764. avatar.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  765. }
  766. }
  767. else
  768. {
  769. agentCircuit.CapsPath = avatar.Scene.CapsModule.GetChildSeed(avatar.UUID, reg.RegionHandle);
  770. capsPath = "http://" + reg.ExternalHostName + ":" + reg.HttpPort
  771. + "/CAPS/" + agentCircuit.CapsPath + "0000/";
  772. }
  773. // Expect avatar crossing is a heavy-duty function at the destination.
  774. // That is where MakeRoot is called, which fetches appearance and inventory.
  775. // Plus triggers OnMakeRoot, which spawns a series of asynchronous updates.
  776. //m_commsProvider.InterRegion.ExpectAvatarCrossing(reg.RegionHandle, avatar.ControllingClient.AgentId,
  777. // position, false);
  778. //{
  779. // avatar.ControllingClient.SendTeleportFailed("Problem with destination.");
  780. // // We should close that agent we just created over at destination...
  781. // List<ulong> lst = new List<ulong>();
  782. // lst.Add(reg.RegionHandle);
  783. // SendCloseChildAgentAsync(avatar.UUID, lst);
  784. // return;
  785. //}
  786. SetInTransit(avatar.UUID);
  787. // Let's send a full update of the agent. This is a synchronous call.
  788. AgentData agent = new AgentData();
  789. avatar.CopyTo(agent);
  790. agent.Position = position;
  791. agent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
  792. "/agent/" + avatar.UUID.ToString() + "/" + avatar.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
  793. m_interregionCommsOut.SendChildAgentUpdate(reg.RegionHandle, agent);
  794. m_log.DebugFormat(
  795. "[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, avatar.UUID);
  796. if (eq != null)
  797. {
  798. eq.TeleportFinishEvent(reg.RegionHandle, 13, endPoint,
  799. 4, teleportFlags, capsPath, avatar.UUID);
  800. }
  801. else
  802. {
  803. avatar.ControllingClient.SendRegionTeleport(reg.RegionHandle, 13, endPoint, 4,
  804. teleportFlags, capsPath);
  805. }
  806. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  807. // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
  808. // that the client contacted the destination before we send the attachments and close things here.
  809. if (!WaitForCallback(avatar.UUID))
  810. {
  811. // Client never contacted destination. Let's restore everything back
  812. avatar.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
  813. ResetFromTransit(avatar.UUID);
  814. // Yikes! We should just have a ref to scene here.
  815. avatar.Scene.InformClientOfNeighbours(avatar);
  816. // Finally, kill the agent we just created at the destination.
  817. m_interregionCommsOut.SendCloseAgent(reg.RegionHandle, avatar.UUID);
  818. return;
  819. }
  820. // Can't go back from here
  821. if (KiPrimitive != null)
  822. {
  823. KiPrimitive(avatar.LocalId);
  824. }
  825. avatar.MakeChildAgent();
  826. // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
  827. avatar.CrossAttachmentsIntoNewRegion(reg.RegionHandle, true);
  828. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  829. if (Util.IsOutsideView(oldRegionX, newRegionX, oldRegionY, newRegionY))
  830. {
  831. Thread.Sleep(5000);
  832. avatar.Close();
  833. CloseConnection(avatar.UUID);
  834. }
  835. else
  836. // now we have a child agent in this region.
  837. avatar.Reset();
  838. // if (teleport success) // seems to be always success here
  839. // the user may change their profile information in other region,
  840. // so the userinfo in UserProfileCache is not reliable any more, delete it
  841. if (avatar.Scene.NeedSceneCacheClear(avatar.UUID))
  842. {
  843. m_commsProvider.UserProfileCacheService.RemoveUser(avatar.UUID);
  844. m_log.DebugFormat(
  845. "[SCENE COMMUNICATION SERVICE]: User {0} is going to another region, profile cache removed",
  846. avatar.UUID);
  847. }
  848. }
  849. else
  850. {
  851. avatar.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
  852. }
  853. }
  854. else
  855. {
  856. // TP to a place that doesn't exist (anymore)
  857. // Inform the viewer about that
  858. avatar.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
  859. // and set the map-tile to '(Offline)'
  860. uint regX, regY;
  861. Utils.LongToUInts(regionHandle, out regX, out regY);
  862. MapBlockData block = new MapBlockData();
  863. block.X = (ushort)(regX / Constants.RegionSize);
  864. block.Y = (ushort)(regY / Constants.RegionSize);
  865. block.Access = 254; // == not there
  866. List<MapBlockData> blocks = new List<MapBlockData>();
  867. blocks.Add(block);
  868. avatar.ControllingClient.SendMapBlock(blocks, 0);
  869. }
  870. }
  871. }
  872. public bool WaitForCallback(UUID id)
  873. {
  874. int count = 20;
  875. while (m_agentsInTransit.Contains(id) && count-- > 0)
  876. {
  877. //m_log.Debug(" >>> Waiting... " + count);
  878. Thread.Sleep(1000);
  879. }
  880. if (count > 0)
  881. return true;
  882. else
  883. return false;
  884. }
  885. public bool ReleaseAgent(UUID id)
  886. {
  887. //m_log.Debug(" >>> ReleaseAgent called <<< ");
  888. return ResetFromTransit(id);
  889. }
  890. public void SetInTransit(UUID id)
  891. {
  892. lock (m_agentsInTransit)
  893. {
  894. if (!m_agentsInTransit.Contains(id))
  895. m_agentsInTransit.Add(id);
  896. }
  897. }
  898. protected bool ResetFromTransit(UUID id)
  899. {
  900. lock (m_agentsInTransit)
  901. {
  902. if (m_agentsInTransit.Contains(id))
  903. {
  904. m_agentsInTransit.Remove(id);
  905. return true;
  906. }
  907. }
  908. return false;
  909. }
  910. private List<ulong> NeighbourHandles(List<SimpleRegionInfo> neighbours)
  911. {
  912. List<ulong> handles = new List<ulong>();
  913. foreach (SimpleRegionInfo reg in neighbours)
  914. {
  915. handles.Add(reg.RegionHandle);
  916. }
  917. return handles;
  918. }
  919. private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  920. {
  921. return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
  922. }
  923. // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  924. // {
  925. // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
  926. // }
  927. private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  928. {
  929. return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
  930. }
  931. public void CrossAgentToNewRegion(Scene scene, ScenePresence agent, bool isFlying)
  932. {
  933. Vector3 pos = agent.AbsolutePosition;
  934. Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
  935. uint neighbourx = m_regionInfo.RegionLocX;
  936. uint neighboury = m_regionInfo.RegionLocY;
  937. // distance to edge that will trigger crossing
  938. const float boundaryDistance = 1.7f;
  939. // distance into new region to place avatar
  940. const float enterDistance = 0.1f;
  941. if (pos.X < boundaryDistance)
  942. {
  943. neighbourx--;
  944. newpos.X = Constants.RegionSize - enterDistance;
  945. }
  946. else if (pos.X > Constants.RegionSize - boundaryDistance)
  947. {
  948. neighbourx++;
  949. newpos.X = enterDistance;
  950. }
  951. if (pos.Y < boundaryDistance)
  952. {
  953. neighboury--;
  954. newpos.Y = Constants.RegionSize - enterDistance;
  955. }
  956. else if (pos.Y > Constants.RegionSize - boundaryDistance)
  957. {
  958. neighboury++;
  959. newpos.Y = enterDistance;
  960. }
  961. CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
  962. d.BeginInvoke(agent, newpos, neighbourx, neighboury, isFlying, CrossAgentToNewRegionCompleted, d);
  963. }
  964. public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying);
  965. /// <summary>
  966. /// This Closes child agents on neighboring regions
  967. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  968. /// </summary>
  969. protected ScenePresence CrossAgentToNewRegionAsync(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, bool isFlying)
  970. {
  971. m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} to {2}-{3}", agent.Firstname, agent.Lastname, neighbourx, neighboury);
  972. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  973. SimpleRegionInfo neighbourRegion = RequestNeighbouringRegionInfo(neighbourHandle);
  974. if (neighbourRegion != null && agent.ValidateAttachments())
  975. {
  976. pos = pos + (agent.Velocity);
  977. CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
  978. if (userInfo != null)
  979. {
  980. userInfo.DropInventory();
  981. }
  982. else
  983. {
  984. m_log.WarnFormat("[SCENE COMM]: No cached user info found for {0} {1} on leaving region {2}",
  985. agent.Name, agent.UUID, agent.Scene.RegionInfo.RegionName);
  986. }
  987. //bool crossingSuccessful =
  988. // CrossToNeighbouringRegion(neighbourHandle, agent.ControllingClient.AgentId, pos,
  989. //isFlying);
  990. SetInTransit(agent.UUID);
  991. AgentData cAgent = new AgentData();
  992. agent.CopyTo(cAgent);
  993. cAgent.Position = pos;
  994. if (isFlying)
  995. cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  996. cAgent.CallbackURI = "http://" + m_regionInfo.ExternalHostName + ":" + m_regionInfo.HttpPort +
  997. "/agent/" + agent.UUID.ToString() + "/" + agent.Scene.RegionInfo.RegionHandle.ToString() + "/release/";
  998. m_interregionCommsOut.SendChildAgentUpdate(neighbourHandle, cAgent);
  999. // Next, let's close the child agent connections that are too far away.
  1000. agent.CloseChildAgents(neighbourx, neighboury);
  1001. //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
  1002. agent.ControllingClient.RequestClientInfo();
  1003. //m_log.Debug("BEFORE CROSS");
  1004. //Scene.DumpChildrenSeeds(UUID);
  1005. //DumpKnownRegions();
  1006. string agentcaps;
  1007. if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
  1008. {
  1009. m_log.ErrorFormat("[SCENE COMM]: No CAPS information for region handle {0}, exiting CrossToNewRegion.",
  1010. neighbourRegion.RegionHandle);
  1011. return agent;
  1012. }
  1013. // TODO Should construct this behind a method
  1014. string capsPath =
  1015. "http://" + neighbourRegion.ExternalHostName + ":" + neighbourRegion.HttpPort
  1016. + "/CAPS/" + agentcaps /*circuitdata.CapsPath*/ + "0000/";
  1017. m_log.DebugFormat("[CAPS]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
  1018. IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
  1019. if (eq != null)
  1020. {
  1021. eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  1022. capsPath, agent.UUID, agent.ControllingClient.SessionId);
  1023. }
  1024. else
  1025. {
  1026. agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  1027. capsPath);
  1028. }
  1029. if (!WaitForCallback(agent.UUID))
  1030. {
  1031. ResetFromTransit(agent.UUID);
  1032. // Yikes! We should just have a ref to scene here.
  1033. agent.Scene.InformClientOfNeighbours(agent);
  1034. return agent;
  1035. }
  1036. agent.MakeChildAgent();
  1037. // now we have a child agent in this region. Request all interesting data about other (root) agents
  1038. agent.SendInitialFullUpdateToAllClients();
  1039. agent.CrossAttachmentsIntoNewRegion(neighbourHandle, true);
  1040. // m_scene.SendKillObject(m_localId);
  1041. agent.Scene.NotifyMyCoarseLocationChange();
  1042. // the user may change their profile information in other region,
  1043. // so the userinfo in UserProfileCache is not reliable any more, delete it
  1044. if (agent.Scene.NeedSceneCacheClear(agent.UUID))
  1045. {
  1046. agent.Scene.CommsManager.UserProfileCacheService.RemoveUser(agent.UUID);
  1047. m_log.DebugFormat(
  1048. "[SCENE COMM]: User {0} is going to another region, profile cache removed", agent.UUID);
  1049. }
  1050. }
  1051. //m_log.Debug("AFTER CROSS");
  1052. //Scene.DumpChildrenSeeds(UUID);
  1053. //DumpKnownRegions();
  1054. return agent;
  1055. }
  1056. private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
  1057. {
  1058. CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
  1059. ScenePresence agent = icon.EndInvoke(iar);
  1060. // If the cross was successful, this agent is a child agent
  1061. if (agent.IsChildAgent)
  1062. {
  1063. agent.Reset();
  1064. }
  1065. else // Not successful
  1066. {
  1067. CachedUserInfo userInfo = m_commsProvider.UserProfileCacheService.GetUserDetails(agent.UUID);
  1068. if (userInfo != null)
  1069. {
  1070. userInfo.FetchInventory();
  1071. }
  1072. agent.RestoreInCurrentScene();
  1073. }
  1074. // In any case
  1075. agent.NotInTransit();
  1076. //m_log.DebugFormat("[SCENE COMM]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
  1077. }
  1078. public Dictionary<string, string> GetGridSettings()
  1079. {
  1080. return m_commsProvider.GridService.GetGridSettings();
  1081. }
  1082. public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat)
  1083. {
  1084. m_commsProvider.LogOffUser(userid, regionid, regionhandle, position, lookat);
  1085. }
  1086. // deprecated as of 2008-08-27
  1087. public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz)
  1088. {
  1089. m_commsProvider.LogOffUser(userid, regionid, regionhandle, posx, posy, posz);
  1090. }
  1091. public void ClearUserAgent(UUID avatarID)
  1092. {
  1093. m_commsProvider.UserService.ClearUserAgent(avatarID);
  1094. }
  1095. public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms)
  1096. {
  1097. m_commsProvider.AddNewUserFriend(friendlistowner, friend, perms);
  1098. }
  1099. public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms)
  1100. {
  1101. m_commsProvider.UpdateUserFriendPerms(friendlistowner, friend, perms);
  1102. }
  1103. public void RemoveUserFriend(UUID friendlistowner, UUID friend)
  1104. {
  1105. m_commsProvider.RemoveUserFriend(friendlistowner, friend);
  1106. }
  1107. public List<FriendListItem> GetUserFriendList(UUID friendlistowner)
  1108. {
  1109. return m_commsProvider.GetUserFriendList(friendlistowner);
  1110. }
  1111. public List<MapBlockData> RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY)
  1112. {
  1113. return m_commsProvider.GridService.RequestNeighbourMapBlocks(minX, minY, maxX, maxY);
  1114. }
  1115. public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query)
  1116. {
  1117. return m_commsProvider.GenerateAgentPickerRequestResponse(queryID, query);
  1118. }
  1119. public List<RegionInfo> RequestNamedRegions(string name, int maxNumber)
  1120. {
  1121. return m_commsProvider.GridService.RequestNamedRegions(name, maxNumber);
  1122. }
  1123. // private void Dump(string msg, List<ulong> handles)
  1124. // {
  1125. // m_log.Info"-------------- HANDLE DUMP ({0}) ---------", msg);
  1126. // foreach (ulong handle in handles)
  1127. // {
  1128. // uint x, y;
  1129. // Utils.LongToUInts(handle, out x, out y);
  1130. // x = x / Constants.RegionSize;
  1131. // y = y / Constants.RegionSize;
  1132. // m_log.Info("({0}, {1})", x, y);
  1133. // }
  1134. // }
  1135. }
  1136. }