EntityTransferModule.cs 91 KB

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