EntityTransferModule.cs 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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 OpenSim.Framework;
  33. using OpenSim.Framework.Capabilities;
  34. using OpenSim.Framework.Client;
  35. using OpenSim.Region.Framework.Interfaces;
  36. using OpenSim.Region.Framework.Scenes;
  37. using OpenSim.Services.Interfaces;
  38. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  39. using OpenMetaverse;
  40. using log4net;
  41. using Nini.Config;
  42. namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
  43. {
  44. public class EntityTransferModule : ISharedRegionModule, IEntityTransferModule
  45. {
  46. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  47. /// <summary>
  48. /// The maximum distance, in standard region units (256m) that an agent is allowed to transfer.
  49. /// </summary>
  50. private int m_MaxTransferDistance = 4095;
  51. public int MaxTransferDistance
  52. {
  53. get { return m_MaxTransferDistance; }
  54. set { m_MaxTransferDistance = value; }
  55. }
  56. protected bool m_Enabled = false;
  57. protected Scene m_aScene;
  58. protected List<Scene> m_Scenes = new List<Scene>();
  59. protected List<UUID> m_agentsInTransit;
  60. private ExpiringCache<UUID, ExpiringCache<ulong, DateTime>> m_bannedRegions =
  61. new ExpiringCache<UUID, ExpiringCache<ulong, DateTime>>();
  62. #region ISharedRegionModule
  63. public Type ReplaceableInterface
  64. {
  65. get { return null; }
  66. }
  67. public virtual string Name
  68. {
  69. get { return "BasicEntityTransferModule"; }
  70. }
  71. public virtual void Initialise(IConfigSource source)
  72. {
  73. IConfig moduleConfig = source.Configs["Modules"];
  74. if (moduleConfig != null)
  75. {
  76. string name = moduleConfig.GetString("EntityTransferModule", "");
  77. if (name == Name)
  78. {
  79. InitialiseCommon(source);
  80. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name);
  81. }
  82. }
  83. }
  84. /// <summary>
  85. /// Initialize config common for this module and any descendents.
  86. /// </summary>
  87. /// <param name="source"></param>
  88. protected virtual void InitialiseCommon(IConfigSource source)
  89. {
  90. IConfig transferConfig = source.Configs["EntityTransfer"];
  91. if (transferConfig != null)
  92. MaxTransferDistance = transferConfig.GetInt("max_distance", 4095);
  93. m_agentsInTransit = new List<UUID>();
  94. m_Enabled = true;
  95. }
  96. public virtual void PostInitialise()
  97. {
  98. }
  99. public virtual void AddRegion(Scene scene)
  100. {
  101. if (!m_Enabled)
  102. return;
  103. if (m_aScene == null)
  104. m_aScene = scene;
  105. m_Scenes.Add(scene);
  106. scene.RegisterModuleInterface<IEntityTransferModule>(this);
  107. scene.EventManager.OnNewClient += OnNewClient;
  108. }
  109. protected virtual void OnNewClient(IClientAPI client)
  110. {
  111. client.OnTeleportHomeRequest += TeleportHome;
  112. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  113. }
  114. public virtual void Close()
  115. {
  116. if (!m_Enabled)
  117. return;
  118. }
  119. public virtual void RemoveRegion(Scene scene)
  120. {
  121. if (!m_Enabled)
  122. return;
  123. if (scene == m_aScene)
  124. m_aScene = null;
  125. m_Scenes.Remove(scene);
  126. }
  127. public virtual void RegionLoaded(Scene scene)
  128. {
  129. if (!m_Enabled)
  130. return;
  131. }
  132. #endregion
  133. #region Agent Teleports
  134. public void Teleport(ScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags)
  135. {
  136. if (!sp.Scene.Permissions.CanTeleport(sp.UUID))
  137. return;
  138. IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
  139. // Reset animations; the viewer does that in teleports.
  140. sp.Animator.ResetAnimations();
  141. try
  142. {
  143. if (regionHandle == sp.Scene.RegionInfo.RegionHandle)
  144. {
  145. m_log.DebugFormat(
  146. "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation {0} within {1}",
  147. position, sp.Scene.RegionInfo.RegionName);
  148. // Teleport within the same region
  149. if (IsOutsideRegion(sp.Scene, position) || position.Z < 0)
  150. {
  151. Vector3 emergencyPos = new Vector3(128, 128, 128);
  152. m_log.WarnFormat(
  153. "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2}. Substituting {3}",
  154. position, sp.Name, sp.UUID, emergencyPos);
  155. position = emergencyPos;
  156. }
  157. // TODO: Get proper AVG Height
  158. float localAVHeight = 1.56f;
  159. float posZLimit = 22;
  160. // TODO: Check other Scene HeightField
  161. if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
  162. {
  163. posZLimit = (float)sp.Scene.Heightmap[(int)position.X, (int)position.Y];
  164. }
  165. float newPosZ = posZLimit + localAVHeight;
  166. if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  167. {
  168. position.Z = newPosZ;
  169. }
  170. sp.ControllingClient.SendTeleportStart(teleportFlags);
  171. sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  172. sp.Teleport(position);
  173. foreach (SceneObjectGroup grp in sp.GetAttachments())
  174. {
  175. if (grp.IsDeleted)
  176. sp.Scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT);
  177. }
  178. }
  179. else // Another region possibly in another simulator
  180. {
  181. uint x = 0, y = 0;
  182. Utils.LongToUInts(regionHandle, out x, out y);
  183. GridRegion reg = m_aScene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y);
  184. if (reg != null)
  185. {
  186. GridRegion finalDestination = GetFinalDestination(reg);
  187. if (finalDestination == null)
  188. {
  189. m_log.WarnFormat("[ENTITY TRANSFER MODULE]: Final destination is having problems. Unable to teleport agent.");
  190. sp.ControllingClient.SendTeleportFailed("Problem at destination");
  191. return;
  192. }
  193. uint curX = 0, curY = 0;
  194. Utils.LongToUInts(sp.Scene.RegionInfo.RegionHandle, out curX, out curY);
  195. int curCellX = (int)(curX / Constants.RegionSize);
  196. int curCellY = (int)(curY / Constants.RegionSize);
  197. int destCellX = (int)(finalDestination.RegionLocX / Constants.RegionSize);
  198. int destCellY = (int)(finalDestination.RegionLocY / Constants.RegionSize);
  199. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Source co-ords are x={0} y={1}", curRegionX, curRegionY);
  200. //
  201. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Final dest is x={0} y={1} {2}@{3}",
  202. // destRegionX, destRegionY, finalDestination.RegionID, finalDestination.ServerURI);
  203. // Check that these are not the same coordinates
  204. if (finalDestination.RegionLocX == sp.Scene.RegionInfo.RegionLocX &&
  205. finalDestination.RegionLocY == sp.Scene.RegionInfo.RegionLocY)
  206. {
  207. // Can't do. Viewer crashes
  208. sp.ControllingClient.SendTeleportFailed("Space warp! You would crash. Move to a different region and try again.");
  209. return;
  210. }
  211. if (Math.Abs(curCellX - destCellX) > MaxTransferDistance || Math.Abs(curCellY - destCellY) > MaxTransferDistance)
  212. {
  213. sp.ControllingClient.SendTeleportFailed(
  214. string.Format(
  215. "Can't teleport to {0} ({1},{2}) from {3} ({4},{5}), destination is more than {6} regions way",
  216. finalDestination.RegionName, destCellX, destCellY,
  217. sp.Scene.RegionInfo.RegionName, curCellX, curCellY,
  218. MaxTransferDistance));
  219. return;
  220. }
  221. //
  222. // This is it
  223. //
  224. DoTeleport(sp, reg, finalDestination, position, lookAt, teleportFlags, eq);
  225. //
  226. //
  227. //
  228. }
  229. else
  230. {
  231. // TP to a place that doesn't exist (anymore)
  232. // Inform the viewer about that
  233. sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
  234. // and set the map-tile to '(Offline)'
  235. uint regX, regY;
  236. Utils.LongToUInts(regionHandle, out regX, out regY);
  237. MapBlockData block = new MapBlockData();
  238. block.X = (ushort)(regX / Constants.RegionSize);
  239. block.Y = (ushort)(regY / Constants.RegionSize);
  240. block.Access = 254; // == not there
  241. List<MapBlockData> blocks = new List<MapBlockData>();
  242. blocks.Add(block);
  243. sp.ControllingClient.SendMapBlock(blocks, 0);
  244. }
  245. }
  246. }
  247. catch (Exception e)
  248. {
  249. m_log.WarnFormat("[ENTITY TRANSFER MODULE]: Exception on teleport: {0} {1}", e.Message, e.StackTrace);
  250. sp.ControllingClient.SendTeleportFailed("Internal error");
  251. }
  252. }
  253. public void DoTeleport(ScenePresence sp, GridRegion reg, GridRegion finalDestination, Vector3 position, Vector3 lookAt, uint teleportFlags, IEventQueue eq)
  254. {
  255. if (reg == null || finalDestination == null)
  256. {
  257. sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
  258. return;
  259. }
  260. m_log.DebugFormat(
  261. "[ENTITY TRANSFER MODULE]: Request Teleport to {0} ({1}) {2}/{3}",
  262. reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
  263. uint newRegionX = (uint)(reg.RegionHandle >> 40);
  264. uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
  265. uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
  266. uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);
  267. ulong destinationHandle = finalDestination.RegionHandle;
  268. // Let's do DNS resolution only once in this process, please!
  269. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  270. // it's actually doing a lot of work.
  271. IPEndPoint endPoint = finalDestination.ExternalEndPoint;
  272. if (endPoint.Address != null)
  273. {
  274. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  275. // both regions
  276. if (sp.ParentID != (uint)0)
  277. sp.StandUp();
  278. if (!sp.ValidateAttachments())
  279. m_log.DebugFormat(
  280. "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}. Continuing.",
  281. sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName);
  282. // if (!sp.ValidateAttachments())
  283. // {
  284. // sp.ControllingClient.SendTeleportFailed("Inconsistent attachment state");
  285. // return;
  286. // }
  287. string reason;
  288. string version;
  289. if (!m_aScene.SimulationService.QueryAccess(finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason))
  290. {
  291. sp.ControllingClient.SendTeleportFailed("Teleport failed: " + reason);
  292. return;
  293. }
  294. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Destination is running version {0}", version);
  295. sp.ControllingClient.SendTeleportStart(teleportFlags);
  296. // the avatar.Close below will clear the child region list. We need this below for (possibly)
  297. // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
  298. //List<ulong> childRegions = new List<ulong>(avatar.GetKnownRegionList());
  299. // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
  300. // failure at this point (unlike a border crossing failure). So perhaps this can never fail
  301. // once we reach here...
  302. //avatar.Scene.RemoveCapsHandler(avatar.UUID);
  303. string capsPath = String.Empty;
  304. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  305. AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
  306. agentCircuit.startpos = position;
  307. agentCircuit.child = true;
  308. agentCircuit.Appearance = sp.Appearance;
  309. if (currentAgentCircuit != null)
  310. {
  311. agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
  312. agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
  313. agentCircuit.Viewer = currentAgentCircuit.Viewer;
  314. agentCircuit.Channel = currentAgentCircuit.Channel;
  315. agentCircuit.Mac = currentAgentCircuit.Mac;
  316. agentCircuit.Id0 = currentAgentCircuit.Id0;
  317. }
  318. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  319. {
  320. // brand new agent, let's create a new caps seed
  321. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  322. }
  323. // Let's create an agent there if one doesn't exist yet.
  324. bool logout = false;
  325. if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
  326. {
  327. sp.ControllingClient.SendTeleportFailed(String.Format("Destination refused: {0}",
  328. reason));
  329. return;
  330. }
  331. // OK, it got this agent. Let's close some child agents
  332. sp.CloseChildAgents(newRegionX, newRegionY);
  333. IClientIPEndpoint ipepClient;
  334. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  335. {
  336. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
  337. #region IP Translation for NAT
  338. // Uses ipepClient above
  339. if (sp.ClientView.TryGet(out ipepClient))
  340. {
  341. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  342. }
  343. #endregion
  344. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  345. if (eq != null)
  346. {
  347. eq.EnableSimulator(destinationHandle, endPoint, sp.UUID);
  348. // ES makes the client send a UseCircuitCode message to the destination,
  349. // which triggers a bunch of things there.
  350. // So let's wait
  351. Thread.Sleep(200);
  352. eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
  353. }
  354. else
  355. {
  356. sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
  357. }
  358. }
  359. else
  360. {
  361. agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
  362. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  363. }
  364. SetInTransit(sp.UUID);
  365. // Let's send a full update of the agent. This is a synchronous call.
  366. AgentData agent = new AgentData();
  367. sp.CopyTo(agent);
  368. agent.Position = position;
  369. SetCallbackURL(agent, sp.Scene.RegionInfo);
  370. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Updating agent...");
  371. if (!UpdateAgent(reg, finalDestination, agent))
  372. {
  373. // Region doesn't take it
  374. m_log.WarnFormat(
  375. "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Returning avatar to source region.",
  376. sp.Name, finalDestination.RegionName);
  377. Fail(sp, finalDestination);
  378. return;
  379. }
  380. sp.ControllingClient.SendTeleportProgress(teleportFlags | (uint)TeleportFlags.DisableCancel, "sending_dest");
  381. m_log.DebugFormat(
  382. "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, sp.UUID);
  383. if (eq != null)
  384. {
  385. eq.TeleportFinishEvent(destinationHandle, 13, endPoint,
  386. 0, teleportFlags, capsPath, sp.UUID);
  387. }
  388. else
  389. {
  390. sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
  391. teleportFlags, capsPath);
  392. }
  393. // Let's set this to true tentatively. This does not trigger OnChildAgent
  394. sp.IsChildAgent = true;
  395. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  396. // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
  397. // that the client contacted the destination before we close things here.
  398. if (!WaitForCallback(sp.UUID))
  399. {
  400. m_log.WarnFormat(
  401. "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} failed due to no callback from destination region. Returning avatar to source region.",
  402. sp.Name, finalDestination.RegionName);
  403. Fail(sp, finalDestination);
  404. return;
  405. }
  406. // For backwards compatibility
  407. if (version == "Unknown" || version == string.Empty)
  408. {
  409. // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
  410. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one...");
  411. CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
  412. }
  413. // May need to logout or other cleanup
  414. AgentHasMovedAway(sp, logout);
  415. // Well, this is it. The agent is over there.
  416. KillEntity(sp.Scene, sp.LocalId);
  417. // Now let's make it officially a child agent
  418. sp.MakeChildAgent();
  419. // sp.Scene.CleanDroppedAttachments();
  420. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  421. if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
  422. {
  423. Thread.Sleep(5000);
  424. sp.Close();
  425. sp.Scene.IncomingCloseAgent(sp.UUID);
  426. }
  427. else
  428. // now we have a child agent in this region.
  429. sp.Reset();
  430. // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
  431. if (sp.Scene.NeedSceneCacheClear(sp.UUID))
  432. {
  433. m_log.DebugFormat(
  434. "[ENTITY TRANSFER MODULE]: User {0} is going to another region, profile cache removed",
  435. sp.UUID);
  436. }
  437. }
  438. else
  439. {
  440. sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
  441. }
  442. }
  443. private void Fail(ScenePresence sp, GridRegion finalDestination)
  444. {
  445. // Client never contacted destination. Let's restore everything back
  446. sp.ControllingClient.SendTeleportFailed("Problems connecting to destination.");
  447. // Fail. Reset it back
  448. sp.IsChildAgent = false;
  449. ReInstantiateScripts(sp);
  450. ResetFromTransit(sp.UUID);
  451. EnableChildAgents(sp);
  452. // Finally, kill the agent we just created at the destination.
  453. m_aScene.SimulationService.CloseAgent(finalDestination, sp.UUID);
  454. }
  455. protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout)
  456. {
  457. logout = false;
  458. return m_aScene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason);
  459. }
  460. protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent)
  461. {
  462. return m_aScene.SimulationService.UpdateAgent(finalDestination, agent);
  463. }
  464. protected virtual void SetCallbackURL(AgentData agent, RegionInfo region)
  465. {
  466. agent.CallbackURI = region.ServerURI + "agent/" + agent.AgentID.ToString() + "/" + region.RegionID.ToString() + "/release/";
  467. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Set callback URL to {0}", agent.CallbackURI);
  468. }
  469. protected virtual void AgentHasMovedAway(ScenePresence sp, bool logout)
  470. {
  471. sp.Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, true);
  472. }
  473. protected void KillEntity(Scene scene, uint localID)
  474. {
  475. scene.SendKillObject(localID);
  476. }
  477. protected virtual GridRegion GetFinalDestination(GridRegion region)
  478. {
  479. return region;
  480. }
  481. protected virtual bool NeedsNewAgent(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY)
  482. {
  483. return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
  484. }
  485. protected virtual bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
  486. {
  487. return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
  488. }
  489. protected virtual bool IsOutsideRegion(Scene s, Vector3 pos)
  490. {
  491. if (s.TestBorderCross(pos, Cardinals.N))
  492. return true;
  493. if (s.TestBorderCross(pos, Cardinals.S))
  494. return true;
  495. if (s.TestBorderCross(pos, Cardinals.E))
  496. return true;
  497. if (s.TestBorderCross(pos, Cardinals.W))
  498. return true;
  499. return false;
  500. }
  501. #endregion
  502. #region Landmark Teleport
  503. /// <summary>
  504. /// Tries to teleport agent to landmark.
  505. /// </summary>
  506. /// <param name="remoteClient"></param>
  507. /// <param name="regionHandle"></param>
  508. /// <param name="position"></param>
  509. public virtual void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  510. {
  511. GridRegion info = m_aScene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  512. if (info == null)
  513. {
  514. // can't find the region: Tell viewer and abort
  515. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  516. return;
  517. }
  518. ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
  519. Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  520. }
  521. #endregion
  522. #region Teleport Home
  523. public virtual void TeleportHome(UUID id, IClientAPI client)
  524. {
  525. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.FirstName, client.LastName);
  526. //OpenSim.Services.Interfaces.PresenceInfo pinfo = m_aScene.PresenceService.GetAgent(client.SessionId);
  527. GridUserInfo uinfo = m_aScene.GridUserService.GetGridUserInfo(client.AgentId.ToString());
  528. if (uinfo != null)
  529. {
  530. GridRegion regionInfo = m_aScene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
  531. if (regionInfo == null)
  532. {
  533. // can't find the Home region: Tell viewer and abort
  534. client.SendTeleportFailed("Your home region could not be found.");
  535. return;
  536. }
  537. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: User's home region is {0} {1} ({2}-{3})",
  538. regionInfo.RegionName, regionInfo.RegionID, regionInfo.RegionLocX / Constants.RegionSize, regionInfo.RegionLocY / Constants.RegionSize);
  539. // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point...
  540. ((Scene)(client.Scene)).RequestTeleportLocation(
  541. client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
  542. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  543. }
  544. }
  545. #endregion
  546. #region Agent Crossings
  547. public bool Cross(ScenePresence agent, bool isFlying)
  548. {
  549. Scene scene = agent.Scene;
  550. Vector3 pos = agent.AbsolutePosition;
  551. Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
  552. uint neighbourx = scene.RegionInfo.RegionLocX;
  553. uint neighboury = scene.RegionInfo.RegionLocY;
  554. const float boundaryDistance = 1.7f;
  555. Vector3 northCross = new Vector3(0, boundaryDistance, 0);
  556. Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
  557. Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
  558. Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
  559. // distance to edge that will trigger crossing
  560. // distance into new region to place avatar
  561. const float enterDistance = 0.5f;
  562. if (scene.TestBorderCross(pos + westCross, Cardinals.W))
  563. {
  564. if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  565. {
  566. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  567. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  568. }
  569. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  570. {
  571. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  572. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  573. {
  574. neighboury--;
  575. newpos.Y = Constants.RegionSize - enterDistance;
  576. }
  577. else
  578. {
  579. agent.InTransit();
  580. neighboury = b.TriggerRegionY;
  581. neighbourx = b.TriggerRegionX;
  582. Vector3 newposition = pos;
  583. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  584. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  585. agent.ControllingClient.SendAgentAlertMessage(
  586. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  587. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  588. return true;
  589. }
  590. }
  591. Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
  592. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  593. {
  594. neighbourx--;
  595. newpos.X = Constants.RegionSize - enterDistance;
  596. }
  597. else
  598. {
  599. agent.InTransit();
  600. neighboury = ba.TriggerRegionY;
  601. neighbourx = ba.TriggerRegionX;
  602. Vector3 newposition = pos;
  603. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  604. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  605. agent.ControllingClient.SendAgentAlertMessage(
  606. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  607. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  608. return true;
  609. }
  610. }
  611. else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
  612. {
  613. Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
  614. neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  615. newpos.X = enterDistance;
  616. if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  617. {
  618. Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  619. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  620. {
  621. neighboury--;
  622. newpos.Y = Constants.RegionSize - enterDistance;
  623. }
  624. else
  625. {
  626. agent.InTransit();
  627. neighboury = ba.TriggerRegionY;
  628. neighbourx = ba.TriggerRegionX;
  629. Vector3 newposition = pos;
  630. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  631. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  632. agent.ControllingClient.SendAgentAlertMessage(
  633. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  634. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  635. return true;
  636. }
  637. }
  638. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  639. {
  640. Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  641. neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
  642. newpos.Y = enterDistance;
  643. }
  644. }
  645. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  646. {
  647. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  648. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  649. {
  650. neighboury--;
  651. newpos.Y = Constants.RegionSize - enterDistance;
  652. }
  653. else
  654. {
  655. agent.InTransit();
  656. neighboury = b.TriggerRegionY;
  657. neighbourx = b.TriggerRegionX;
  658. Vector3 newposition = pos;
  659. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  660. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  661. agent.ControllingClient.SendAgentAlertMessage(
  662. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  663. InformClientToInitateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  664. return true;
  665. }
  666. }
  667. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  668. {
  669. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  670. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  671. newpos.Y = enterDistance;
  672. }
  673. /*
  674. if (pos.X < boundaryDistance) //West
  675. {
  676. neighbourx--;
  677. newpos.X = Constants.RegionSize - enterDistance;
  678. }
  679. else if (pos.X > Constants.RegionSize - boundaryDistance) // East
  680. {
  681. neighbourx++;
  682. newpos.X = enterDistance;
  683. }
  684. if (pos.Y < boundaryDistance) // South
  685. {
  686. neighboury--;
  687. newpos.Y = Constants.RegionSize - enterDistance;
  688. }
  689. else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
  690. {
  691. neighboury++;
  692. newpos.Y = enterDistance;
  693. }
  694. */
  695. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  696. int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
  697. ExpiringCache<ulong, DateTime> r;
  698. DateTime banUntil;
  699. if (m_bannedRegions.TryGetValue(agent.ControllingClient.AgentId, out r))
  700. {
  701. if (r.TryGetValue(neighbourHandle, out banUntil))
  702. {
  703. if (DateTime.Now < banUntil)
  704. return false;
  705. r.Remove(neighbourHandle);
  706. }
  707. }
  708. else
  709. {
  710. r = null;
  711. }
  712. GridRegion neighbourRegion = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
  713. string reason;
  714. string version;
  715. if (!scene.SimulationService.QueryAccess(neighbourRegion, agent.ControllingClient.AgentId, newpos, out version, out reason))
  716. {
  717. agent.ControllingClient.SendAlertMessage("Cannot region cross into banned parcel");
  718. if (r == null)
  719. {
  720. r = new ExpiringCache<ulong, DateTime>();
  721. r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
  722. m_bannedRegions.Add(agent.ControllingClient.AgentId, r, TimeSpan.FromSeconds(45));
  723. }
  724. else
  725. {
  726. r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
  727. }
  728. return false;
  729. }
  730. agent.InTransit();
  731. CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
  732. d.BeginInvoke(agent, newpos, neighbourx, neighboury, neighbourRegion, isFlying, version, CrossAgentToNewRegionCompleted, d);
  733. return true;
  734. }
  735. public delegate void InformClientToInitateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
  736. Vector3 position,
  737. Scene initiatingScene);
  738. private void InformClientToInitateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position, Scene initiatingScene)
  739. {
  740. // This assumes that we know what our neighbours are.
  741. InformClientToInitateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
  742. d.BeginInvoke(agent, regionX, regionY, position, initiatingScene,
  743. InformClientToInitiateTeleportToLocationCompleted,
  744. d);
  745. }
  746. public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
  747. Scene initiatingScene)
  748. {
  749. Thread.Sleep(10000);
  750. IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
  751. if (im != null)
  752. {
  753. UUID gotoLocation = Util.BuildFakeParcelID(
  754. Util.UIntsToLong(
  755. (regionX *
  756. (uint)Constants.RegionSize),
  757. (regionY *
  758. (uint)Constants.RegionSize)),
  759. (uint)(int)position.X,
  760. (uint)(int)position.Y,
  761. (uint)(int)position.Z);
  762. GridInstantMessage m = new GridInstantMessage(initiatingScene, UUID.Zero,
  763. "Region", agent.UUID,
  764. (byte)InstantMessageDialog.GodLikeRequestTeleport, false,
  765. "", gotoLocation, false, new Vector3(127, 0, 0),
  766. new Byte[0]);
  767. im.SendInstantMessage(m, delegate(bool success)
  768. {
  769. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Client Initiating Teleport sending IM success = {0}", success);
  770. });
  771. }
  772. }
  773. private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
  774. {
  775. InformClientToInitateTeleportToLocationDelegate icon =
  776. (InformClientToInitateTeleportToLocationDelegate)iar.AsyncState;
  777. icon.EndInvoke(iar);
  778. }
  779. public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion, bool isFlying, string version);
  780. /// <summary>
  781. /// This Closes child agents on neighbouring regions
  782. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  783. /// </summary>
  784. protected ScenePresence CrossAgentToNewRegionAsync(
  785. ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion,
  786. bool isFlying, string version)
  787. {
  788. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  789. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}", agent.Firstname, agent.Lastname, neighbourx, neighboury, version);
  790. Scene m_scene = agent.Scene;
  791. if (neighbourRegion != null)
  792. {
  793. if (!agent.ValidateAttachments())
  794. m_log.DebugFormat(
  795. "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for region crossing of {0} from {1} to {2}. Continuing.",
  796. agent.Name, agent.Scene.RegionInfo.RegionName, neighbourRegion.RegionName);
  797. pos = pos + (agent.Velocity);
  798. SetInTransit(agent.UUID);
  799. AgentData cAgent = new AgentData();
  800. agent.CopyTo(cAgent);
  801. cAgent.Position = pos;
  802. if (isFlying)
  803. cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  804. cAgent.CallbackURI = m_scene.RegionInfo.ServerURI +
  805. "agent/" + agent.UUID.ToString() + "/" + m_scene.RegionInfo.RegionID.ToString() + "/release/";
  806. if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent))
  807. {
  808. // region doesn't take it
  809. ReInstantiateScripts(agent);
  810. ResetFromTransit(agent.UUID);
  811. return agent;
  812. }
  813. // Next, let's close the child agent connections that are too far away.
  814. agent.CloseChildAgents(neighbourx, neighboury);
  815. //AgentCircuitData circuitdata = m_controllingClient.RequestClientInfo();
  816. agent.ControllingClient.RequestClientInfo();
  817. //m_log.Debug("BEFORE CROSS");
  818. //Scene.DumpChildrenSeeds(UUID);
  819. //DumpKnownRegions();
  820. string agentcaps;
  821. if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
  822. {
  823. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
  824. neighbourRegion.RegionHandle);
  825. return agent;
  826. }
  827. string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps);
  828. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
  829. IEventQueue eq = agent.Scene.RequestModuleInterface<IEventQueue>();
  830. if (eq != null)
  831. {
  832. eq.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  833. capsPath, agent.UUID, agent.ControllingClient.SessionId);
  834. }
  835. else
  836. {
  837. agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  838. capsPath);
  839. }
  840. if (!WaitForCallback(agent.UUID))
  841. {
  842. m_log.Debug("[ENTITY TRANSFER MODULE]: Callback never came in crossing agent");
  843. ReInstantiateScripts(agent);
  844. ResetFromTransit(agent.UUID);
  845. // Yikes! We should just have a ref to scene here.
  846. //agent.Scene.InformClientOfNeighbours(agent);
  847. EnableChildAgents(agent);
  848. return agent;
  849. }
  850. agent.MakeChildAgent();
  851. // now we have a child agent in this region. Request all interesting data about other (root) agents
  852. agent.SendOtherAgentsAvatarDataToMe();
  853. agent.SendOtherAgentsAppearanceToMe();
  854. // Backwards compatibility
  855. if (version == "Unknown" || version == string.Empty)
  856. {
  857. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old neighbor, passing attachments one by one...");
  858. CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
  859. }
  860. AgentHasMovedAway(agent, false);
  861. // the user may change their profile information in other region,
  862. // so the userinfo in UserProfileCache is not reliable any more, delete it
  863. // REFACTORING PROBLEM. Well, not a problem, but this method is HORRIBLE!
  864. if (agent.Scene.NeedSceneCacheClear(agent.UUID))
  865. {
  866. m_log.DebugFormat(
  867. "[ENTITY TRANSFER MODULE]: User {0} is going to another region", agent.UUID);
  868. }
  869. }
  870. //m_log.Debug("AFTER CROSS");
  871. //Scene.DumpChildrenSeeds(UUID);
  872. //DumpKnownRegions();
  873. return agent;
  874. }
  875. private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
  876. {
  877. CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
  878. ScenePresence agent = icon.EndInvoke(iar);
  879. // If the cross was successful, this agent is a child agent
  880. if (agent.IsChildAgent)
  881. agent.Reset();
  882. else // Not successful
  883. agent.RestoreInCurrentScene();
  884. // In any case
  885. agent.NotInTransit();
  886. //m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
  887. }
  888. #endregion
  889. #region Enable Child Agent
  890. /// <summary>
  891. /// This informs a single neighbouring region about agent "avatar".
  892. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  893. /// </summary>
  894. /// <param name="sp"></param>
  895. /// <param name="region"></param>
  896. public void EnableChildAgent(ScenePresence sp, GridRegion region)
  897. {
  898. m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName);
  899. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  900. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  901. agent.BaseFolder = UUID.Zero;
  902. agent.InventoryFolder = UUID.Zero;
  903. agent.startpos = new Vector3(128, 128, 70);
  904. agent.child = true;
  905. agent.Appearance = sp.Appearance;
  906. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  907. agent.ChildrenCapSeeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
  908. //m_log.DebugFormat("[XXX] Seeds 1 {0}", agent.ChildrenCapSeeds.Count);
  909. if (!agent.ChildrenCapSeeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
  910. agent.ChildrenCapSeeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
  911. //m_log.DebugFormat("[XXX] Seeds 2 {0}", agent.ChildrenCapSeeds.Count);
  912. sp.AddNeighbourRegion(region.RegionHandle, agent.CapsPath);
  913. //foreach (ulong h in agent.ChildrenCapSeeds.Keys)
  914. // m_log.DebugFormat("[XXX] --> {0}", h);
  915. //m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
  916. agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);
  917. if (sp.Scene.CapsModule != null)
  918. {
  919. sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, agent.ChildrenCapSeeds);
  920. }
  921. if (currentAgentCircuit != null)
  922. {
  923. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  924. agent.IPAddress = currentAgentCircuit.IPAddress;
  925. agent.Viewer = currentAgentCircuit.Viewer;
  926. agent.Channel = currentAgentCircuit.Channel;
  927. agent.Mac = currentAgentCircuit.Mac;
  928. agent.Id0 = currentAgentCircuit.Id0;
  929. }
  930. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  931. d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
  932. InformClientOfNeighbourCompleted,
  933. d);
  934. }
  935. #endregion
  936. #region Enable Child Agents
  937. private delegate void InformClientOfNeighbourDelegate(
  938. ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
  939. /// <summary>
  940. /// This informs all neighbouring regions about agent "avatar".
  941. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  942. /// </summary>
  943. /// <param name="sp"></param>
  944. public void EnableChildAgents(ScenePresence sp)
  945. {
  946. List<GridRegion> neighbours = new List<GridRegion>();
  947. RegionInfo m_regionInfo = sp.Scene.RegionInfo;
  948. if (m_regionInfo != null)
  949. {
  950. neighbours = RequestNeighbours(sp, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  951. }
  952. else
  953. {
  954. m_log.Debug("[ENTITY TRANSFER MODULE]: m_regionInfo was null in EnableChildAgents, is this a NPC?");
  955. }
  956. /// We need to find the difference between the new regions where there are no child agents
  957. /// and the regions where there are already child agents. We only send notification to the former.
  958. List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
  959. neighbourHandles.Add(sp.Scene.RegionInfo.RegionHandle); // add this region too
  960. List<ulong> previousRegionNeighbourHandles;
  961. if (sp.Scene.CapsModule != null)
  962. {
  963. previousRegionNeighbourHandles =
  964. new List<ulong>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID).Keys);
  965. }
  966. else
  967. {
  968. previousRegionNeighbourHandles = new List<ulong>();
  969. }
  970. List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  971. List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  972. //Dump("Current Neighbors", neighbourHandles);
  973. //Dump("Previous Neighbours", previousRegionNeighbourHandles);
  974. //Dump("New Neighbours", newRegions);
  975. //Dump("Old Neighbours", oldRegions);
  976. /// Update the scene presence's known regions here on this region
  977. sp.DropOldNeighbours(oldRegions);
  978. /// Collect as many seeds as possible
  979. Dictionary<ulong, string> seeds;
  980. if (sp.Scene.CapsModule != null)
  981. seeds
  982. = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
  983. else
  984. seeds = new Dictionary<ulong, string>();
  985. //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
  986. if (!seeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
  987. seeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
  988. /// Create the necessary child agents
  989. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  990. foreach (GridRegion neighbour in neighbours)
  991. {
  992. if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
  993. {
  994. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  995. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  996. agent.BaseFolder = UUID.Zero;
  997. agent.InventoryFolder = UUID.Zero;
  998. agent.startpos = new Vector3(128, 128, 70);
  999. agent.child = true;
  1000. agent.Appearance = sp.Appearance;
  1001. if (currentAgentCircuit != null)
  1002. {
  1003. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1004. agent.IPAddress = currentAgentCircuit.IPAddress;
  1005. agent.Viewer = currentAgentCircuit.Viewer;
  1006. agent.Channel = currentAgentCircuit.Channel;
  1007. agent.Mac = currentAgentCircuit.Mac;
  1008. agent.Id0 = currentAgentCircuit.Id0;
  1009. }
  1010. if (newRegions.Contains(neighbour.RegionHandle))
  1011. {
  1012. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1013. sp.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
  1014. seeds.Add(neighbour.RegionHandle, agent.CapsPath);
  1015. }
  1016. else
  1017. agent.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, neighbour.RegionHandle);
  1018. cagents.Add(agent);
  1019. }
  1020. }
  1021. /// Update all child agent with everyone's seeds
  1022. foreach (AgentCircuitData a in cagents)
  1023. {
  1024. a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  1025. }
  1026. if (sp.Scene.CapsModule != null)
  1027. {
  1028. sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, seeds);
  1029. }
  1030. sp.KnownRegions = seeds;
  1031. //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
  1032. //avatar.DumpKnownRegions();
  1033. bool newAgent = false;
  1034. int count = 0;
  1035. foreach (GridRegion neighbour in neighbours)
  1036. {
  1037. //m_log.WarnFormat("--> Going to send child agent to {0}", neighbour.RegionName);
  1038. // Don't do it if there's already an agent in that region
  1039. if (newRegions.Contains(neighbour.RegionHandle))
  1040. newAgent = true;
  1041. else
  1042. newAgent = false;
  1043. if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
  1044. {
  1045. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  1046. try
  1047. {
  1048. d.BeginInvoke(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
  1049. InformClientOfNeighbourCompleted,
  1050. d);
  1051. }
  1052. catch (ArgumentOutOfRangeException)
  1053. {
  1054. m_log.ErrorFormat(
  1055. "[ENTITY TRANSFER MODULE]: Neighbour Regions response included the current region in the neighbour list. The following region will not display to the client: {0} for region {1} ({2}, {3}).",
  1056. neighbour.ExternalHostName,
  1057. neighbour.RegionHandle,
  1058. neighbour.RegionLocX,
  1059. neighbour.RegionLocY);
  1060. }
  1061. catch (Exception e)
  1062. {
  1063. m_log.ErrorFormat(
  1064. "[ENTITY TRANSFER MODULE]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
  1065. neighbour.ExternalHostName,
  1066. neighbour.RegionHandle,
  1067. neighbour.RegionLocX,
  1068. neighbour.RegionLocY,
  1069. e);
  1070. // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
  1071. // since I don't know what will happen if we just let the client continue
  1072. // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
  1073. // throw e;
  1074. }
  1075. }
  1076. count++;
  1077. }
  1078. }
  1079. private void InformClientOfNeighbourCompleted(IAsyncResult iar)
  1080. {
  1081. InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate)iar.AsyncState;
  1082. icon.EndInvoke(iar);
  1083. //m_log.WarnFormat(" --> InformClientOfNeighbourCompleted");
  1084. }
  1085. /// <summary>
  1086. /// Async component for informing client of which neighbours exist
  1087. /// </summary>
  1088. /// <remarks>
  1089. /// This needs to run asynchronously, as a network timeout may block the thread for a long while
  1090. /// </remarks>
  1091. /// <param name="remoteClient"></param>
  1092. /// <param name="a"></param>
  1093. /// <param name="regionHandle"></param>
  1094. /// <param name="endPoint"></param>
  1095. private void InformClientOfNeighbourAsync(ScenePresence sp, AgentCircuitData a, GridRegion reg,
  1096. IPEndPoint endPoint, bool newAgent)
  1097. {
  1098. // Let's wait just a little to give time to originating regions to catch up with closing child agents
  1099. // after a cross here
  1100. Thread.Sleep(500);
  1101. Scene m_scene = sp.Scene;
  1102. uint x, y;
  1103. Utils.LongToUInts(reg.RegionHandle, out x, out y);
  1104. x = x / Constants.RegionSize;
  1105. y = y / Constants.RegionSize;
  1106. m_log.Debug("[ENTITY TRANSFER MODULE]: Starting to inform client about neighbour " + x + ", " + y + "(" + endPoint + ")");
  1107. string capsPath = reg.ServerURI + CapsUtil.GetCapsSeedPath(a.CapsPath);
  1108. string reason = String.Empty;
  1109. bool regionAccepted = m_scene.SimulationService.CreateAgent(reg, a, (uint)TeleportFlags.Default, out reason);
  1110. if (regionAccepted && newAgent)
  1111. {
  1112. IEventQueue eq = sp.Scene.RequestModuleInterface<IEventQueue>();
  1113. if (eq != null)
  1114. {
  1115. #region IP Translation for NAT
  1116. IClientIPEndpoint ipepClient;
  1117. if (sp.ClientView.TryGet(out ipepClient))
  1118. {
  1119. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  1120. }
  1121. #endregion
  1122. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} is sending {1} EnableSimulator for neighbour region {2} @ {3} " +
  1123. "and EstablishAgentCommunication with seed cap {4}",
  1124. m_scene.RegionInfo.RegionName, sp.Name, reg.RegionName, reg.RegionHandle, capsPath);
  1125. eq.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID);
  1126. eq.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
  1127. }
  1128. else
  1129. {
  1130. sp.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  1131. // TODO: make Event Queue disablable!
  1132. }
  1133. m_log.Debug("[ENTITY TRANSFER MODULE]: Completed inform client about neighbour " + endPoint.ToString());
  1134. }
  1135. if (!regionAccepted)
  1136. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Region {0} did not accept agent: {1}", reg.RegionName, reason);
  1137. }
  1138. /// <summary>
  1139. /// Return the list of regions that are considered to be neighbours to the given scene.
  1140. /// </summary>
  1141. /// <param name="pScene"></param>
  1142. /// <param name="pRegionLocX"></param>
  1143. /// <param name="pRegionLocY"></param>
  1144. /// <returns></returns>
  1145. protected List<GridRegion> RequestNeighbours(ScenePresence avatar, uint pRegionLocX, uint pRegionLocY)
  1146. {
  1147. Scene pScene = avatar.Scene;
  1148. RegionInfo m_regionInfo = pScene.RegionInfo;
  1149. Border[] northBorders = pScene.NorthBorders.ToArray();
  1150. Border[] southBorders = pScene.SouthBorders.ToArray();
  1151. Border[] eastBorders = pScene.EastBorders.ToArray();
  1152. Border[] westBorders = pScene.WestBorders.ToArray();
  1153. // Leaving this as a "megaregions" computation vs "non-megaregions" computation; it isn't
  1154. // clear what should be done with a "far view" given that megaregions already extended the
  1155. // view to include everything in the megaregion
  1156. if (northBorders.Length <= 1 && southBorders.Length <= 1 && eastBorders.Length <= 1 && westBorders.Length <= 1)
  1157. {
  1158. int dd = avatar.DrawDistance < Constants.RegionSize ? (int)Constants.RegionSize : (int)avatar.DrawDistance;
  1159. int startX = (int)pRegionLocX * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
  1160. int startY = (int)pRegionLocY * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
  1161. int endX = (int)pRegionLocX * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
  1162. int endY = (int)pRegionLocY * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
  1163. List<GridRegion> neighbours =
  1164. avatar.Scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
  1165. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  1166. return neighbours;
  1167. }
  1168. else
  1169. {
  1170. Vector2 extent = Vector2.Zero;
  1171. for (int i = 0; i < eastBorders.Length; i++)
  1172. {
  1173. extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
  1174. }
  1175. for (int i = 0; i < northBorders.Length; i++)
  1176. {
  1177. extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
  1178. }
  1179. // Loss of fraction on purpose
  1180. extent.X = ((int)extent.X / (int)Constants.RegionSize) + 1;
  1181. extent.Y = ((int)extent.Y / (int)Constants.RegionSize) + 1;
  1182. int startX = (int)(pRegionLocX - 1) * (int)Constants.RegionSize;
  1183. int startY = (int)(pRegionLocY - 1) * (int)Constants.RegionSize;
  1184. int endX = ((int)pRegionLocX + (int)extent.X) * (int)Constants.RegionSize;
  1185. int endY = ((int)pRegionLocY + (int)extent.Y) * (int)Constants.RegionSize;
  1186. List<GridRegion> neighbours = pScene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
  1187. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  1188. return neighbours;
  1189. }
  1190. }
  1191. private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1192. {
  1193. return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
  1194. }
  1195. // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1196. // {
  1197. // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
  1198. // }
  1199. private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1200. {
  1201. return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
  1202. }
  1203. private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
  1204. {
  1205. List<ulong> handles = new List<ulong>();
  1206. foreach (GridRegion reg in neighbours)
  1207. {
  1208. handles.Add(reg.RegionHandle);
  1209. }
  1210. return handles;
  1211. }
  1212. // private void Dump(string msg, List<ulong> handles)
  1213. // {
  1214. // m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
  1215. // foreach (ulong handle in handles)
  1216. // {
  1217. // uint x, y;
  1218. // Utils.LongToUInts(handle, out x, out y);
  1219. // x = x / Constants.RegionSize;
  1220. // y = y / Constants.RegionSize;
  1221. // m_log.InfoFormat("({0}, {1})", x, y);
  1222. // }
  1223. // }
  1224. #endregion
  1225. #region Agent Arrived
  1226. public void AgentArrivedAtDestination(UUID id)
  1227. {
  1228. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Agent {0} released", id);
  1229. ResetFromTransit(id);
  1230. }
  1231. #endregion
  1232. #region Object Transfers
  1233. /// <summary>
  1234. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1235. /// into.
  1236. ///
  1237. /// This method locates the new region handle and offsets the prim position for the new region
  1238. /// </summary>
  1239. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1240. /// <param name="grp">the scene object that we're crossing</param>
  1241. public void Cross(SceneObjectGroup grp, Vector3 attemptedPosition, bool silent)
  1242. {
  1243. if (grp == null)
  1244. return;
  1245. if (grp.IsDeleted)
  1246. return;
  1247. Scene scene = grp.Scene;
  1248. if (scene == null)
  1249. return;
  1250. if (grp.RootPart.DIE_AT_EDGE)
  1251. {
  1252. // We remove the object here
  1253. try
  1254. {
  1255. scene.DeleteSceneObject(grp, false);
  1256. }
  1257. catch (Exception)
  1258. {
  1259. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1260. }
  1261. return;
  1262. }
  1263. int thisx = (int)scene.RegionInfo.RegionLocX;
  1264. int thisy = (int)scene.RegionInfo.RegionLocY;
  1265. Vector3 EastCross = new Vector3(0.1f, 0, 0);
  1266. Vector3 WestCross = new Vector3(-0.1f, 0, 0);
  1267. Vector3 NorthCross = new Vector3(0, 0.1f, 0);
  1268. Vector3 SouthCross = new Vector3(0, -0.1f, 0);
  1269. // use this if no borders were crossed!
  1270. ulong newRegionHandle
  1271. = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
  1272. (uint)((thisy) * Constants.RegionSize));
  1273. Vector3 pos = attemptedPosition;
  1274. int changeX = 1;
  1275. int changeY = 1;
  1276. if (scene.TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
  1277. {
  1278. if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1279. {
  1280. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1281. if (crossedBorderx.BorderLine.Z > 0)
  1282. {
  1283. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1284. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1285. }
  1286. else
  1287. pos.X = ((pos.X + Constants.RegionSize));
  1288. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1289. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1290. if (crossedBordery.BorderLine.Z > 0)
  1291. {
  1292. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1293. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1294. }
  1295. else
  1296. pos.Y = ((pos.Y + Constants.RegionSize));
  1297. newRegionHandle
  1298. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1299. (uint)((thisy - changeY) * Constants.RegionSize));
  1300. // x - 1
  1301. // y - 1
  1302. }
  1303. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1304. {
  1305. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1306. if (crossedBorderx.BorderLine.Z > 0)
  1307. {
  1308. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1309. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1310. }
  1311. else
  1312. pos.X = ((pos.X + Constants.RegionSize));
  1313. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1314. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1315. if (crossedBordery.BorderLine.Z > 0)
  1316. {
  1317. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1318. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1319. }
  1320. else
  1321. pos.Y = ((pos.Y + Constants.RegionSize));
  1322. newRegionHandle
  1323. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1324. (uint)((thisy + changeY) * Constants.RegionSize));
  1325. // x - 1
  1326. // y + 1
  1327. }
  1328. else
  1329. {
  1330. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1331. if (crossedBorderx.BorderLine.Z > 0)
  1332. {
  1333. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1334. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1335. }
  1336. else
  1337. pos.X = ((pos.X + Constants.RegionSize));
  1338. newRegionHandle
  1339. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1340. (uint)(thisy * Constants.RegionSize));
  1341. // x - 1
  1342. }
  1343. }
  1344. else if (scene.TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
  1345. {
  1346. if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1347. {
  1348. pos.X = ((pos.X - Constants.RegionSize));
  1349. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1350. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1351. if (crossedBordery.BorderLine.Z > 0)
  1352. {
  1353. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1354. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1355. }
  1356. else
  1357. pos.Y = ((pos.Y + Constants.RegionSize));
  1358. newRegionHandle
  1359. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1360. (uint)((thisy - changeY) * Constants.RegionSize));
  1361. // x + 1
  1362. // y - 1
  1363. }
  1364. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1365. {
  1366. pos.X = ((pos.X - Constants.RegionSize));
  1367. pos.Y = ((pos.Y - Constants.RegionSize));
  1368. newRegionHandle
  1369. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1370. (uint)((thisy + changeY) * Constants.RegionSize));
  1371. // x + 1
  1372. // y + 1
  1373. }
  1374. else
  1375. {
  1376. pos.X = ((pos.X - Constants.RegionSize));
  1377. newRegionHandle
  1378. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  1379. (uint)(thisy * Constants.RegionSize));
  1380. // x + 1
  1381. }
  1382. }
  1383. else if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1384. {
  1385. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1386. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1387. if (crossedBordery.BorderLine.Z > 0)
  1388. {
  1389. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1390. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1391. }
  1392. else
  1393. pos.Y = ((pos.Y + Constants.RegionSize));
  1394. newRegionHandle
  1395. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
  1396. // y - 1
  1397. }
  1398. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1399. {
  1400. pos.Y = ((pos.Y - Constants.RegionSize));
  1401. newRegionHandle
  1402. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
  1403. // y + 1
  1404. }
  1405. // Offset the positions for the new region across the border
  1406. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  1407. grp.OffsetForNewRegion(pos);
  1408. // If we fail to cross the border, then reset the position of the scene object on that border.
  1409. uint x = 0, y = 0;
  1410. Utils.LongToUInts(newRegionHandle, out x, out y);
  1411. GridRegion destination = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
  1412. if (destination != null && !CrossPrimGroupIntoNewRegion(destination, grp, silent))
  1413. {
  1414. grp.OffsetForNewRegion(oldGroupPosition);
  1415. grp.ScheduleGroupForFullUpdate();
  1416. }
  1417. }
  1418. /// <summary>
  1419. /// Move the given scene object into a new region
  1420. /// </summary>
  1421. /// <param name="newRegionHandle"></param>
  1422. /// <param name="grp">Scene Object Group that we're crossing</param>
  1423. /// <returns>
  1424. /// true if the crossing itself was successful, false on failure
  1425. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  1426. /// </returns>
  1427. protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, SceneObjectGroup grp, bool silent)
  1428. {
  1429. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  1430. bool successYN = false;
  1431. grp.RootPart.UpdateFlag = 0;
  1432. //int primcrossingXMLmethod = 0;
  1433. if (destination != null)
  1434. {
  1435. //string objectState = grp.GetStateSnapshot();
  1436. //successYN
  1437. // = m_sceneGridService.PrimCrossToNeighboringRegion(
  1438. // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  1439. //if (successYN && (objectState != "") && m_allowScriptCrossings)
  1440. //{
  1441. // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  1442. // newRegionHandle, grp.UUID, objectState, 100);
  1443. //}
  1444. //// And the new channel...
  1445. //if (m_interregionCommsOut != null)
  1446. // successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
  1447. if (m_aScene.SimulationService != null)
  1448. successYN = m_aScene.SimulationService.CreateObject(destination, grp, true);
  1449. if (successYN)
  1450. {
  1451. // We remove the object here
  1452. try
  1453. {
  1454. grp.Scene.DeleteSceneObject(grp, silent);
  1455. }
  1456. catch (Exception e)
  1457. {
  1458. m_log.ErrorFormat(
  1459. "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  1460. grp, e);
  1461. }
  1462. }
  1463. else
  1464. {
  1465. if (!grp.IsDeleted)
  1466. {
  1467. if (grp.RootPart.PhysActor != null)
  1468. {
  1469. grp.RootPart.PhysActor.CrossingFailure();
  1470. }
  1471. }
  1472. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp);
  1473. }
  1474. }
  1475. else
  1476. {
  1477. m_log.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
  1478. }
  1479. return successYN;
  1480. }
  1481. protected bool CrossAttachmentsIntoNewRegion(GridRegion destination, ScenePresence sp, bool silent)
  1482. {
  1483. List<SceneObjectGroup> m_attachments = sp.GetAttachments();
  1484. // Validate
  1485. // foreach (SceneObjectGroup gobj in m_attachments)
  1486. // {
  1487. // if (gobj == null || gobj.IsDeleted)
  1488. // return false;
  1489. // }
  1490. foreach (SceneObjectGroup gobj in m_attachments)
  1491. {
  1492. // If the prim group is null then something must have happened to it!
  1493. if (gobj != null && !gobj.IsDeleted)
  1494. {
  1495. // Set the parent localID to 0 so it transfers over properly.
  1496. gobj.RootPart.SetParentLocalId(0);
  1497. gobj.AbsolutePosition = gobj.RootPart.AttachedPos;
  1498. gobj.IsAttachment = false;
  1499. //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
  1500. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending attachment {0} to region {1}", gobj.UUID, destination.RegionName);
  1501. CrossPrimGroupIntoNewRegion(destination, gobj, silent);
  1502. }
  1503. }
  1504. sp.ClearAttachments();
  1505. return true;
  1506. }
  1507. #endregion
  1508. #region Misc
  1509. protected bool WaitForCallback(UUID id)
  1510. {
  1511. int count = 200;
  1512. while (m_agentsInTransit.Contains(id) && count-- > 0)
  1513. {
  1514. //m_log.Debug(" >>> Waiting... " + count);
  1515. Thread.Sleep(100);
  1516. }
  1517. if (count > 0)
  1518. return true;
  1519. else
  1520. return false;
  1521. }
  1522. protected void SetInTransit(UUID id)
  1523. {
  1524. lock (m_agentsInTransit)
  1525. {
  1526. if (!m_agentsInTransit.Contains(id))
  1527. m_agentsInTransit.Add(id);
  1528. }
  1529. }
  1530. protected bool ResetFromTransit(UUID id)
  1531. {
  1532. lock (m_agentsInTransit)
  1533. {
  1534. if (m_agentsInTransit.Contains(id))
  1535. {
  1536. m_agentsInTransit.Remove(id);
  1537. return true;
  1538. }
  1539. }
  1540. return false;
  1541. }
  1542. protected void ReInstantiateScripts(ScenePresence sp)
  1543. {
  1544. int i = 0;
  1545. if (sp.InTransitScriptStates.Count > 0)
  1546. {
  1547. List<SceneObjectGroup> attachments = sp.GetAttachments();
  1548. foreach (SceneObjectGroup sog in attachments)
  1549. {
  1550. if (i < sp.InTransitScriptStates.Count)
  1551. {
  1552. sog.SetState(sp.InTransitScriptStates[i++], sp.Scene);
  1553. sog.CreateScriptInstances(0, false, sp.Scene.DefaultScriptEngine, 0);
  1554. sog.ResumeScripts();
  1555. }
  1556. else
  1557. m_log.ErrorFormat(
  1558. "[ENTITY TRANSFER MODULE]: InTransitScriptStates.Count={0} smaller than Attachments.Count={1}",
  1559. sp.InTransitScriptStates.Count, attachments.Count);
  1560. }
  1561. sp.InTransitScriptStates.Clear();
  1562. }
  1563. }
  1564. #endregion
  1565. }
  1566. }