EntityTransferModule.cs 118 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650
  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.Framework.Monitoring;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes;
  38. using OpenSim.Region.Physics.Manager;
  39. using OpenSim.Services.Interfaces;
  40. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  41. using OpenMetaverse;
  42. using log4net;
  43. using Nini.Config;
  44. using Mono.Addins;
  45. namespace OpenSim.Region.CoreModules.Framework.EntityTransfer
  46. {
  47. [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EntityTransferModule")]
  48. public class EntityTransferModule : INonSharedRegionModule, IEntityTransferModule
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. public const int DefaultMaxTransferDistance = 4095;
  52. public const bool WaitForAgentArrivedAtDestinationDefault = true;
  53. public string OutgoingTransferVersionName { get; set; }
  54. /// <summary>
  55. /// Determine the maximum entity transfer version we will use for teleports.
  56. /// </summary>
  57. public float MaxOutgoingTransferVersion { get; set; }
  58. /// <summary>
  59. /// The maximum distance, in standard region units (256m) that an agent is allowed to transfer.
  60. /// </summary>
  61. public int MaxTransferDistance { get; set; }
  62. /// <summary>
  63. /// If true then on a teleport, the source region waits for a callback from the destination region. If
  64. /// a callback fails to arrive within a set time then the user is pulled back into the source region.
  65. /// </summary>
  66. public bool WaitForAgentArrivedAtDestination { get; set; }
  67. /// <summary>
  68. /// If true then we ask the viewer to disable teleport cancellation and ignore teleport requests.
  69. /// </summary>
  70. /// <remarks>
  71. /// This is useful in situations where teleport is very likely to always succeed and we want to avoid a
  72. /// situation where avatars can be come 'stuck' due to a failed teleport cancellation. Unfortunately, the
  73. /// nature of the teleport protocol makes it extremely difficult (maybe impossible) to make teleport
  74. /// cancellation consistently suceed.
  75. /// </remarks>
  76. public bool DisableInterRegionTeleportCancellation { get; set; }
  77. /// <summary>
  78. /// Number of times inter-region teleport was attempted.
  79. /// </summary>
  80. private Stat m_interRegionTeleportAttempts;
  81. /// <summary>
  82. /// Number of times inter-region teleport was aborted (due to simultaneous client logout).
  83. /// </summary>
  84. private Stat m_interRegionTeleportAborts;
  85. /// <summary>
  86. /// Number of times inter-region teleport was successfully cancelled by the client.
  87. /// </summary>
  88. private Stat m_interRegionTeleportCancels;
  89. /// <summary>
  90. /// Number of times inter-region teleport failed due to server/client/network problems (e.g. viewer failed to
  91. /// connect with destination region).
  92. /// </summary>
  93. /// <remarks>
  94. /// This is not necessarily a problem for this simulator - in open-grid/hg conditions, viewer connectivity to
  95. /// destination simulator is unknown.
  96. /// </remarks>
  97. private Stat m_interRegionTeleportFailures;
  98. protected bool m_Enabled = false;
  99. public Scene Scene { get; private set; }
  100. /// <summary>
  101. /// Handles recording and manipulation of state for entities that are in transfer within or between regions
  102. /// (cross or teleport).
  103. /// </summary>
  104. private EntityTransferStateMachine m_entityTransferStateMachine;
  105. private ExpiringCache<UUID, ExpiringCache<ulong, DateTime>> m_bannedRegions =
  106. new ExpiringCache<UUID, ExpiringCache<ulong, DateTime>>();
  107. private IEventQueue m_eqModule;
  108. private IRegionCombinerModule m_regionCombinerModule;
  109. #region ISharedRegionModule
  110. public Type ReplaceableInterface
  111. {
  112. get { return null; }
  113. }
  114. public virtual string Name
  115. {
  116. get { return "BasicEntityTransferModule"; }
  117. }
  118. public virtual void Initialise(IConfigSource source)
  119. {
  120. IConfig moduleConfig = source.Configs["Modules"];
  121. if (moduleConfig != null)
  122. {
  123. string name = moduleConfig.GetString("EntityTransferModule", "");
  124. if (name == Name)
  125. {
  126. InitialiseCommon(source);
  127. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name);
  128. }
  129. }
  130. }
  131. /// <summary>
  132. /// Initialize config common for this module and any descendents.
  133. /// </summary>
  134. /// <param name="source"></param>
  135. protected virtual void InitialiseCommon(IConfigSource source)
  136. {
  137. string transferVersionName = "SIMULATION";
  138. float maxTransferVersion = 0.2f;
  139. IConfig transferConfig = source.Configs["EntityTransfer"];
  140. if (transferConfig != null)
  141. {
  142. string rawVersion
  143. = transferConfig.GetString(
  144. "MaxOutgoingTransferVersion",
  145. string.Format("{0}/{1}", transferVersionName, maxTransferVersion));
  146. string[] rawVersionComponents = rawVersion.Split(new char[] { '/' });
  147. bool versionValid = false;
  148. if (rawVersionComponents.Length >= 2)
  149. versionValid = float.TryParse(rawVersionComponents[1], out maxTransferVersion);
  150. if (!versionValid)
  151. {
  152. m_log.ErrorFormat(
  153. "[ENTITY TRANSFER MODULE]: MaxOutgoingTransferVersion {0} is invalid, using {1}",
  154. rawVersion, string.Format("{0}/{1}", transferVersionName, maxTransferVersion));
  155. }
  156. else
  157. {
  158. transferVersionName = rawVersionComponents[0];
  159. m_log.InfoFormat(
  160. "[ENTITY TRANSFER MODULE]: MaxOutgoingTransferVersion set to {0}",
  161. string.Format("{0}/{1}", transferVersionName, maxTransferVersion));
  162. }
  163. DisableInterRegionTeleportCancellation
  164. = transferConfig.GetBoolean("DisableInterRegionTeleportCancellation", false);
  165. WaitForAgentArrivedAtDestination
  166. = transferConfig.GetBoolean("wait_for_callback", WaitForAgentArrivedAtDestinationDefault);
  167. MaxTransferDistance = transferConfig.GetInt("max_distance", DefaultMaxTransferDistance);
  168. }
  169. else
  170. {
  171. MaxTransferDistance = DefaultMaxTransferDistance;
  172. }
  173. OutgoingTransferVersionName = transferVersionName;
  174. MaxOutgoingTransferVersion = maxTransferVersion;
  175. m_entityTransferStateMachine = new EntityTransferStateMachine(this);
  176. m_Enabled = true;
  177. }
  178. public virtual void PostInitialise()
  179. {
  180. }
  181. public virtual void AddRegion(Scene scene)
  182. {
  183. if (!m_Enabled)
  184. return;
  185. Scene = scene;
  186. m_interRegionTeleportAttempts =
  187. new Stat(
  188. "InterRegionTeleportAttempts",
  189. "Number of inter-region teleports attempted.",
  190. "This does not count attempts which failed due to pre-conditions (e.g. target simulator refused access).\n"
  191. + "You can get successfully teleports by subtracting aborts, cancels and teleport failures from this figure.",
  192. "",
  193. "entitytransfer",
  194. Scene.Name,
  195. StatType.Push,
  196. null,
  197. StatVerbosity.Debug);
  198. m_interRegionTeleportAborts =
  199. new Stat(
  200. "InterRegionTeleportAborts",
  201. "Number of inter-region teleports aborted due to client actions.",
  202. "The chief action is simultaneous logout whilst teleporting.",
  203. "",
  204. "entitytransfer",
  205. Scene.Name,
  206. StatType.Push,
  207. null,
  208. StatVerbosity.Debug);
  209. m_interRegionTeleportCancels =
  210. new Stat(
  211. "InterRegionTeleportCancels",
  212. "Number of inter-region teleports cancelled by the client.",
  213. null,
  214. "",
  215. "entitytransfer",
  216. Scene.Name,
  217. StatType.Push,
  218. null,
  219. StatVerbosity.Debug);
  220. m_interRegionTeleportFailures =
  221. new Stat(
  222. "InterRegionTeleportFailures",
  223. "Number of inter-region teleports that failed due to server/client/network issues.",
  224. "This number may not be very helpful in open-grid/hg situations as the network connectivity/quality of destinations is uncontrollable.",
  225. "",
  226. "entitytransfer",
  227. Scene.Name,
  228. StatType.Push,
  229. null,
  230. StatVerbosity.Debug);
  231. StatsManager.RegisterStat(m_interRegionTeleportAttempts);
  232. StatsManager.RegisterStat(m_interRegionTeleportAborts);
  233. StatsManager.RegisterStat(m_interRegionTeleportCancels);
  234. StatsManager.RegisterStat(m_interRegionTeleportFailures);
  235. scene.RegisterModuleInterface<IEntityTransferModule>(this);
  236. scene.EventManager.OnNewClient += OnNewClient;
  237. }
  238. protected virtual void OnNewClient(IClientAPI client)
  239. {
  240. client.OnTeleportHomeRequest += TriggerTeleportHome;
  241. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  242. if (!DisableInterRegionTeleportCancellation)
  243. client.OnTeleportCancel += OnClientCancelTeleport;
  244. client.OnConnectionClosed += OnConnectionClosed;
  245. }
  246. public virtual void Close() {}
  247. public virtual void RemoveRegion(Scene scene)
  248. {
  249. if (m_Enabled)
  250. {
  251. StatsManager.DeregisterStat(m_interRegionTeleportAttempts);
  252. StatsManager.DeregisterStat(m_interRegionTeleportAborts);
  253. StatsManager.DeregisterStat(m_interRegionTeleportCancels);
  254. StatsManager.DeregisterStat(m_interRegionTeleportFailures);
  255. }
  256. }
  257. public virtual void RegionLoaded(Scene scene)
  258. {
  259. if (!m_Enabled)
  260. return;
  261. m_eqModule = Scene.RequestModuleInterface<IEventQueue>();
  262. m_regionCombinerModule = Scene.RequestModuleInterface<IRegionCombinerModule>();
  263. }
  264. #endregion
  265. #region Agent Teleports
  266. private void OnConnectionClosed(IClientAPI client)
  267. {
  268. if (client.IsLoggingOut && m_entityTransferStateMachine.UpdateInTransit(client.AgentId, AgentTransferState.Aborting))
  269. {
  270. m_log.DebugFormat(
  271. "[ENTITY TRANSFER MODULE]: Aborted teleport request from {0} in {1} due to simultaneous logout",
  272. client.Name, Scene.Name);
  273. }
  274. }
  275. private void OnClientCancelTeleport(IClientAPI client)
  276. {
  277. m_entityTransferStateMachine.UpdateInTransit(client.AgentId, AgentTransferState.Cancelling);
  278. m_log.DebugFormat(
  279. "[ENTITY TRANSFER MODULE]: Received teleport cancel request from {0} in {1}", client.Name, Scene.Name);
  280. }
  281. public void Teleport(ScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags)
  282. {
  283. if (sp.Scene.Permissions.IsGridGod(sp.UUID))
  284. {
  285. // This user will be a God in the destination scene, too
  286. teleportFlags |= (uint)TeleportFlags.Godlike;
  287. }
  288. if (!sp.Scene.Permissions.CanTeleport(sp.UUID))
  289. return;
  290. string destinationRegionName = "(not found)";
  291. // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection
  292. // of whether the destination region completes the teleport.
  293. if (!m_entityTransferStateMachine.SetInTransit(sp.UUID))
  294. {
  295. m_log.DebugFormat(
  296. "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2}@{3} - agent is already in transit.",
  297. sp.Name, sp.UUID, position, regionHandle);
  298. sp.ControllingClient.SendTeleportFailed("Previous teleport process incomplete. Please retry shortly.");
  299. return;
  300. }
  301. try
  302. {
  303. // Reset animations; the viewer does that in teleports.
  304. sp.Animator.ResetAnimations();
  305. if (regionHandle == sp.Scene.RegionInfo.RegionHandle)
  306. {
  307. destinationRegionName = sp.Scene.RegionInfo.RegionName;
  308. TeleportAgentWithinRegion(sp, position, lookAt, teleportFlags);
  309. }
  310. else // Another region possibly in another simulator
  311. {
  312. GridRegion finalDestination = null;
  313. try
  314. {
  315. TeleportAgentToDifferentRegion(
  316. sp, regionHandle, position, lookAt, teleportFlags, out finalDestination);
  317. }
  318. finally
  319. {
  320. if (finalDestination != null)
  321. destinationRegionName = finalDestination.RegionName;
  322. }
  323. }
  324. }
  325. catch (Exception e)
  326. {
  327. m_log.ErrorFormat(
  328. "[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
  329. sp.Name, sp.AbsolutePosition, sp.Scene.RegionInfo.RegionName, position, destinationRegionName,
  330. e.Message, e.StackTrace);
  331. sp.ControllingClient.SendTeleportFailed("Internal error");
  332. }
  333. finally
  334. {
  335. m_entityTransferStateMachine.ResetFromTransit(sp.UUID);
  336. }
  337. }
  338. /// <summary>
  339. /// Teleports the agent within its current region.
  340. /// </summary>
  341. /// <param name="sp"></param>
  342. /// <param name="position"></param>
  343. /// <param name="lookAt"></param>
  344. /// <param name="teleportFlags"></param
  345. private void TeleportAgentWithinRegion(ScenePresence sp, Vector3 position, Vector3 lookAt, uint teleportFlags)
  346. {
  347. m_log.DebugFormat(
  348. "[ENTITY TRANSFER MODULE]: Teleport for {0} to {1} within {2}",
  349. sp.Name, position, sp.Scene.RegionInfo.RegionName);
  350. // Teleport within the same region
  351. if (IsOutsideRegion(sp.Scene, position) || position.Z < 0)
  352. {
  353. Vector3 emergencyPos = new Vector3(128, 128, 128);
  354. m_log.WarnFormat(
  355. "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2} in {3}. Substituting {4}",
  356. position, sp.Name, sp.UUID, Scene.Name, emergencyPos);
  357. position = emergencyPos;
  358. }
  359. // TODO: Get proper AVG Height
  360. float localAVHeight = 1.56f;
  361. float posZLimit = 22;
  362. // TODO: Check other Scene HeightField
  363. if (position.X > 0 && position.X <= (int)Constants.RegionSize && position.Y > 0 && position.Y <= (int)Constants.RegionSize)
  364. {
  365. posZLimit = (float)sp.Scene.Heightmap[(int)position.X, (int)position.Y];
  366. }
  367. float newPosZ = posZLimit + localAVHeight;
  368. if (posZLimit >= (position.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  369. {
  370. position.Z = newPosZ;
  371. }
  372. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.Transferring);
  373. sp.ControllingClient.SendTeleportStart(teleportFlags);
  374. sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  375. sp.Velocity = Vector3.Zero;
  376. sp.Teleport(position);
  377. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.ReceivedAtDestination);
  378. foreach (SceneObjectGroup grp in sp.GetAttachments())
  379. {
  380. sp.Scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT);
  381. }
  382. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
  383. }
  384. /// <summary>
  385. /// Teleports the agent to a different region.
  386. /// </summary>
  387. /// <param name='sp'></param>
  388. /// <param name='regionHandle'>/param>
  389. /// <param name='position'></param>
  390. /// <param name='lookAt'></param>
  391. /// <param name='teleportFlags'></param>
  392. /// <param name='finalDestination'></param>
  393. private void TeleportAgentToDifferentRegion(
  394. ScenePresence sp, ulong regionHandle, Vector3 position,
  395. Vector3 lookAt, uint teleportFlags, out GridRegion finalDestination)
  396. {
  397. uint x = 0, y = 0;
  398. Utils.LongToUInts(regionHandle, out x, out y);
  399. GridRegion reg = Scene.GridService.GetRegionByPosition(sp.Scene.RegionInfo.ScopeID, (int)x, (int)y);
  400. if (reg != null)
  401. {
  402. finalDestination = GetFinalDestination(reg);
  403. if (finalDestination == null)
  404. {
  405. m_log.WarnFormat(
  406. "[ENTITY TRANSFER MODULE]: Final destination is having problems. Unable to teleport {0} {1}",
  407. sp.Name, sp.UUID);
  408. sp.ControllingClient.SendTeleportFailed("Problem at destination");
  409. return;
  410. }
  411. // Check that these are not the same coordinates
  412. if (finalDestination.RegionLocX == sp.Scene.RegionInfo.RegionLocX &&
  413. finalDestination.RegionLocY == sp.Scene.RegionInfo.RegionLocY)
  414. {
  415. // Can't do. Viewer crashes
  416. sp.ControllingClient.SendTeleportFailed("Space warp! You would crash. Move to a different region and try again.");
  417. return;
  418. }
  419. // Validate assorted conditions
  420. string reason = string.Empty;
  421. if (!ValidateGenericConditions(sp, reg, finalDestination, teleportFlags, out reason))
  422. {
  423. sp.ControllingClient.SendTeleportFailed(reason);
  424. return;
  425. }
  426. //
  427. // This is it
  428. //
  429. DoTeleportInternal(sp, reg, finalDestination, position, lookAt, teleportFlags);
  430. //
  431. //
  432. //
  433. }
  434. else
  435. {
  436. finalDestination = null;
  437. // TP to a place that doesn't exist (anymore)
  438. // Inform the viewer about that
  439. sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to doesn't exist anymore");
  440. // and set the map-tile to '(Offline)'
  441. uint regX, regY;
  442. Utils.LongToUInts(regionHandle, out regX, out regY);
  443. MapBlockData block = new MapBlockData();
  444. block.X = (ushort)(regX / Constants.RegionSize);
  445. block.Y = (ushort)(regY / Constants.RegionSize);
  446. block.Access = 254; // == not there
  447. List<MapBlockData> blocks = new List<MapBlockData>();
  448. blocks.Add(block);
  449. sp.ControllingClient.SendMapBlock(blocks, 0);
  450. }
  451. }
  452. // Nothing to validate here
  453. protected virtual bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason)
  454. {
  455. reason = String.Empty;
  456. return true;
  457. }
  458. /// <summary>
  459. /// Determines whether this instance is within the max transfer distance.
  460. /// </summary>
  461. /// <param name="sourceRegion"></param>
  462. /// <param name="destRegion"></param>
  463. /// <returns>
  464. /// <c>true</c> if this instance is within max transfer distance; otherwise, <c>false</c>.
  465. /// </returns>
  466. private bool IsWithinMaxTeleportDistance(RegionInfo sourceRegion, GridRegion destRegion)
  467. {
  468. if(MaxTransferDistance == 0)
  469. return true;
  470. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Source co-ords are x={0} y={1}", curRegionX, curRegionY);
  471. //
  472. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Final dest is x={0} y={1} {2}@{3}",
  473. // destRegionX, destRegionY, finalDestination.RegionID, finalDestination.ServerURI);
  474. // Insanely, RegionLoc on RegionInfo is the 256m map co-ord whilst GridRegion.RegionLoc is the raw meters position.
  475. return Math.Abs(sourceRegion.RegionLocX - destRegion.RegionCoordX) <= MaxTransferDistance
  476. && Math.Abs(sourceRegion.RegionLocY - destRegion.RegionCoordY) <= MaxTransferDistance;
  477. }
  478. /// <summary>
  479. /// Wraps DoTeleportInternal() and manages the transfer state.
  480. /// </summary>
  481. public void DoTeleport(
  482. ScenePresence sp, GridRegion reg, GridRegion finalDestination,
  483. Vector3 position, Vector3 lookAt, uint teleportFlags)
  484. {
  485. // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection
  486. // of whether the destination region completes the teleport.
  487. if (!m_entityTransferStateMachine.SetInTransit(sp.UUID))
  488. {
  489. m_log.DebugFormat(
  490. "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2} ({3}) {4}/{5} - agent is already in transit.",
  491. sp.Name, sp.UUID, reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
  492. return;
  493. }
  494. try
  495. {
  496. DoTeleportInternal(sp, reg, finalDestination, position, lookAt, teleportFlags);
  497. }
  498. catch (Exception e)
  499. {
  500. m_log.ErrorFormat(
  501. "[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
  502. sp.Name, sp.AbsolutePosition, sp.Scene.RegionInfo.RegionName, position, finalDestination.RegionName,
  503. e.Message, e.StackTrace);
  504. sp.ControllingClient.SendTeleportFailed("Internal error");
  505. }
  506. finally
  507. {
  508. m_entityTransferStateMachine.ResetFromTransit(sp.UUID);
  509. }
  510. }
  511. /// <summary>
  512. /// Teleports the agent to another region.
  513. /// This method doesn't manage the transfer state; the caller must do that.
  514. /// </summary>
  515. private void DoTeleportInternal(
  516. ScenePresence sp, GridRegion reg, GridRegion finalDestination,
  517. Vector3 position, Vector3 lookAt, uint teleportFlags)
  518. {
  519. if (reg == null || finalDestination == null)
  520. {
  521. sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
  522. return;
  523. }
  524. m_log.DebugFormat(
  525. "[ENTITY TRANSFER MODULE]: Teleporting {0} {1} from {2} to {3} ({4}) {5}/{6}",
  526. sp.Name, sp.UUID, sp.Scene.RegionInfo.RegionName,
  527. reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
  528. RegionInfo sourceRegion = sp.Scene.RegionInfo;
  529. if (!IsWithinMaxTeleportDistance(sourceRegion, finalDestination))
  530. {
  531. sp.ControllingClient.SendTeleportFailed(
  532. string.Format(
  533. "Can't teleport to {0} ({1},{2}) from {3} ({4},{5}), destination is more than {6} regions way",
  534. finalDestination.RegionName, finalDestination.RegionCoordX, finalDestination.RegionCoordY,
  535. sourceRegion.RegionName, sourceRegion.RegionLocX, sourceRegion.RegionLocY,
  536. MaxTransferDistance));
  537. return;
  538. }
  539. uint newRegionX = (uint)(reg.RegionHandle >> 40);
  540. uint newRegionY = (((uint)(reg.RegionHandle)) >> 8);
  541. uint oldRegionX = (uint)(sp.Scene.RegionInfo.RegionHandle >> 40);
  542. uint oldRegionY = (((uint)(sp.Scene.RegionInfo.RegionHandle)) >> 8);
  543. ulong destinationHandle = finalDestination.RegionHandle;
  544. // Let's do DNS resolution only once in this process, please!
  545. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  546. // it's actually doing a lot of work.
  547. IPEndPoint endPoint = finalDestination.ExternalEndPoint;
  548. if (endPoint.Address == null)
  549. {
  550. sp.ControllingClient.SendTeleportFailed("Remote Region appears to be down");
  551. return;
  552. }
  553. if (!sp.ValidateAttachments())
  554. m_log.DebugFormat(
  555. "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}. Continuing.",
  556. sp.Name, sp.Scene.Name, finalDestination.RegionName);
  557. string reason;
  558. string version;
  559. if (!Scene.SimulationService.QueryAccess(
  560. finalDestination, sp.ControllingClient.AgentId, Vector3.Zero, out version, out reason))
  561. {
  562. sp.ControllingClient.SendTeleportFailed(reason);
  563. m_log.DebugFormat(
  564. "[ENTITY TRANSFER MODULE]: {0} was stopped from teleporting from {1} to {2} because {3}",
  565. sp.Name, sp.Scene.Name, finalDestination.RegionName, reason);
  566. return;
  567. }
  568. // Before this point, teleport 'failure' is due to checkable pre-conditions such as whether the target
  569. // simulator can be found and is explicitly prepared to allow access. Therefore, we will not count these
  570. // as server attempts.
  571. m_interRegionTeleportAttempts.Value++;
  572. m_log.DebugFormat(
  573. "[ENTITY TRANSFER MODULE]: {0} max transfer version is {1}/{2}, {3} max version is {4}",
  574. sp.Scene.Name, OutgoingTransferVersionName, MaxOutgoingTransferVersion, finalDestination.RegionName, version);
  575. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  576. // both regions
  577. if (sp.ParentID != (uint)0)
  578. sp.StandUp();
  579. if (DisableInterRegionTeleportCancellation)
  580. teleportFlags |= (uint)TeleportFlags.DisableCancel;
  581. // At least on LL 3.3.4, this is not strictly necessary - a teleport will succeed without sending this to
  582. // the viewer. However, it might mean that the viewer does not see the black teleport screen (untested).
  583. sp.ControllingClient.SendTeleportStart(teleportFlags);
  584. // the avatar.Close below will clear the child region list. We need this below for (possibly)
  585. // closing the child agents, so save it here (we need a copy as it is Clear()-ed).
  586. //List<ulong> childRegions = avatar.KnownRegionHandles;
  587. // Compared to ScenePresence.CrossToNewRegion(), there's no obvious code to handle a teleport
  588. // failure at this point (unlike a border crossing failure). So perhaps this can never fail
  589. // once we reach here...
  590. //avatar.Scene.RemoveCapsHandler(avatar.UUID);
  591. string capsPath = String.Empty;
  592. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  593. AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
  594. agentCircuit.startpos = position;
  595. agentCircuit.child = true;
  596. agentCircuit.Appearance = sp.Appearance;
  597. if (currentAgentCircuit != null)
  598. {
  599. agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
  600. agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
  601. agentCircuit.Viewer = currentAgentCircuit.Viewer;
  602. agentCircuit.Channel = currentAgentCircuit.Channel;
  603. agentCircuit.Mac = currentAgentCircuit.Mac;
  604. agentCircuit.Id0 = currentAgentCircuit.Id0;
  605. }
  606. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  607. {
  608. // brand new agent, let's create a new caps seed
  609. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  610. }
  611. // We're going to fallback to V1 if the destination gives us anything smaller than 0.2 or we're forcing
  612. // use of the earlier protocol
  613. float versionNumber = 0.1f;
  614. string[] versionComponents = version.Split(new char[] { '/' });
  615. if (versionComponents.Length >= 2)
  616. float.TryParse(versionComponents[1], out versionNumber);
  617. if (versionNumber == 0.2f && MaxOutgoingTransferVersion >= versionNumber)
  618. TransferAgent_V2(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, oldRegionX, newRegionX, oldRegionY, newRegionY, version, out reason);
  619. else
  620. TransferAgent_V1(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, oldRegionX, newRegionX, oldRegionY, newRegionY, version, out reason);
  621. }
  622. private void TransferAgent_V1(ScenePresence sp, AgentCircuitData agentCircuit, GridRegion reg, GridRegion finalDestination,
  623. IPEndPoint endPoint, uint teleportFlags, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, string version, out string reason)
  624. {
  625. ulong destinationHandle = finalDestination.RegionHandle;
  626. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  627. m_log.DebugFormat(
  628. "[ENTITY TRANSFER MODULE]: Using TP V1 for {0} going from {1} to {2}",
  629. sp.Name, Scene.Name, finalDestination.RegionName);
  630. // Let's create an agent there if one doesn't exist yet.
  631. // NOTE: logout will always be false for a non-HG teleport.
  632. bool logout = false;
  633. if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
  634. {
  635. m_interRegionTeleportFailures.Value++;
  636. sp.ControllingClient.SendTeleportFailed(String.Format("Teleport refused: {0}", reason));
  637. m_log.DebugFormat(
  638. "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}",
  639. sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason);
  640. return;
  641. }
  642. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Cancelling)
  643. {
  644. m_interRegionTeleportCancels.Value++;
  645. m_log.DebugFormat(
  646. "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after CreateAgent on client request",
  647. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  648. return;
  649. }
  650. else if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  651. {
  652. m_interRegionTeleportAborts.Value++;
  653. m_log.DebugFormat(
  654. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after CreateAgent due to previous client close.",
  655. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  656. return;
  657. }
  658. // Past this point we have to attempt clean up if the teleport fails, so update transfer state.
  659. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.Transferring);
  660. // OK, it got this agent. Let's close some child agents
  661. sp.CloseChildAgents(newRegionX, newRegionY);
  662. IClientIPEndpoint ipepClient;
  663. string capsPath = String.Empty;
  664. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  665. {
  666. m_log.DebugFormat(
  667. "[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} needs new child agent for incoming agent {3} from {4}",
  668. finalDestination.RegionName, newRegionX, newRegionY, sp.Name, Scene.Name);
  669. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
  670. #region IP Translation for NAT
  671. // Uses ipepClient above
  672. if (sp.ClientView.TryGet(out ipepClient))
  673. {
  674. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  675. }
  676. #endregion
  677. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  678. if (m_eqModule != null)
  679. {
  680. // The EnableSimulator message makes the client establish a connection with the destination
  681. // simulator by sending the initial UseCircuitCode UDP packet to the destination containing the
  682. // correct circuit code.
  683. m_eqModule.EnableSimulator(destinationHandle, endPoint, sp.UUID);
  684. // XXX: Is this wait necessary? We will always end up waiting on UpdateAgent for the destination
  685. // simulator to confirm that it has established communication with the viewer.
  686. Thread.Sleep(200);
  687. // At least on LL 3.3.4 for teleports between different regions on the same simulator this appears
  688. // unnecessary - teleport will succeed and SEED caps will be requested without it (though possibly
  689. // only on TeleportFinish). This is untested for region teleport between different simulators
  690. // though this probably also works.
  691. m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
  692. }
  693. else
  694. {
  695. // XXX: This is a little misleading since we're information the client of its avatar destination,
  696. // which may or may not be a neighbour region of the source region. This path is probably little
  697. // used anyway (with EQ being the one used). But it is currently being used for test code.
  698. sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
  699. }
  700. }
  701. else
  702. {
  703. agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
  704. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  705. }
  706. // Let's send a full update of the agent. This is a synchronous call.
  707. AgentData agent = new AgentData();
  708. sp.CopyTo(agent);
  709. agent.Position = agentCircuit.startpos;
  710. SetCallbackURL(agent, sp.Scene.RegionInfo);
  711. // We will check for an abort before UpdateAgent since UpdateAgent will require an active viewer to
  712. // establish th econnection to the destination which makes it return true.
  713. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  714. {
  715. m_interRegionTeleportAborts.Value++;
  716. m_log.DebugFormat(
  717. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} before UpdateAgent",
  718. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  719. return;
  720. }
  721. // A common teleport failure occurs when we can send CreateAgent to the
  722. // destination region but the viewer cannot establish the connection (e.g. due to network issues between
  723. // the viewer and the destination). In this case, UpdateAgent timesout after 10 seconds, although then
  724. // there's a further 10 second wait whilst we attempt to tell the destination to delete the agent in Fail().
  725. if (!UpdateAgent(reg, finalDestination, agent, sp))
  726. {
  727. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  728. {
  729. m_interRegionTeleportAborts.Value++;
  730. m_log.DebugFormat(
  731. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after UpdateAgent due to previous client close.",
  732. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  733. return;
  734. }
  735. m_log.WarnFormat(
  736. "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
  737. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  738. Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
  739. return;
  740. }
  741. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Cancelling)
  742. {
  743. m_interRegionTeleportCancels.Value++;
  744. m_log.DebugFormat(
  745. "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after UpdateAgent on client request",
  746. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  747. CleanupFailedInterRegionTeleport(sp, currentAgentCircuit.SessionID.ToString(), finalDestination);
  748. return;
  749. }
  750. m_log.DebugFormat(
  751. "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}",
  752. capsPath, sp.Scene.RegionInfo.RegionName, sp.Name);
  753. // We need to set this here to avoid an unlikely race condition when teleporting to a neighbour simulator,
  754. // where that neighbour simulator could otherwise request a child agent create on the source which then
  755. // closes our existing agent which is still signalled as root.
  756. sp.IsChildAgent = true;
  757. // OK, send TPFinish to the client, so that it starts the process of contacting the destination region
  758. if (m_eqModule != null)
  759. {
  760. m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, sp.UUID);
  761. }
  762. else
  763. {
  764. sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
  765. teleportFlags, capsPath);
  766. }
  767. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  768. // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
  769. // that the client contacted the destination before we close things here.
  770. if (!m_entityTransferStateMachine.WaitForAgentArrivedAtDestination(sp.UUID))
  771. {
  772. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  773. {
  774. m_interRegionTeleportAborts.Value++;
  775. m_log.DebugFormat(
  776. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after WaitForAgentArrivedAtDestination due to previous client close.",
  777. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  778. return;
  779. }
  780. m_log.WarnFormat(
  781. "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} from {2} failed due to no callback from destination region. Returning avatar to source region.",
  782. sp.Name, finalDestination.RegionName, sp.Scene.RegionInfo.RegionName);
  783. Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Destination region did not signal teleport completion.");
  784. return;
  785. }
  786. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
  787. // For backwards compatibility
  788. if (version == "Unknown" || version == string.Empty)
  789. {
  790. // CrossAttachmentsIntoNewRegion is a synchronous call. We shouldn't need to wait after it
  791. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Old simulator, sending attachments one by one...");
  792. CrossAttachmentsIntoNewRegion(finalDestination, sp, true);
  793. }
  794. // May need to logout or other cleanup
  795. AgentHasMovedAway(sp, logout);
  796. // Well, this is it. The agent is over there.
  797. KillEntity(sp.Scene, sp.LocalId);
  798. // Now let's make it officially a child agent
  799. sp.MakeChildAgent();
  800. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  801. if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
  802. {
  803. if (!sp.Scene.IncomingPreCloseClient(sp))
  804. return;
  805. // We need to delay here because Imprudence viewers, unlike v1 or v3, have a short (<200ms, <500ms) delay before
  806. // they regard the new region as the current region after receiving the AgentMovementComplete
  807. // response. If close is sent before then, it will cause the viewer to quit instead.
  808. //
  809. // This sleep can be increased if necessary. However, whilst it's active,
  810. // an agent cannot teleport back to this region if it has teleported away.
  811. Thread.Sleep(2000);
  812. sp.Scene.CloseAgent(sp.UUID, false);
  813. }
  814. else
  815. {
  816. // now we have a child agent in this region.
  817. sp.Reset();
  818. }
  819. }
  820. private void TransferAgent_V2(ScenePresence sp, AgentCircuitData agentCircuit, GridRegion reg, GridRegion finalDestination,
  821. IPEndPoint endPoint, uint teleportFlags, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, string version, out string reason)
  822. {
  823. ulong destinationHandle = finalDestination.RegionHandle;
  824. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  825. // Let's create an agent there if one doesn't exist yet.
  826. // NOTE: logout will always be false for a non-HG teleport.
  827. bool logout = false;
  828. if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, out reason, out logout))
  829. {
  830. m_interRegionTeleportFailures.Value++;
  831. sp.ControllingClient.SendTeleportFailed(String.Format("Teleport refused: {0}", reason));
  832. m_log.DebugFormat(
  833. "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}",
  834. sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason);
  835. return;
  836. }
  837. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Cancelling)
  838. {
  839. m_interRegionTeleportCancels.Value++;
  840. m_log.DebugFormat(
  841. "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after CreateAgent on client request",
  842. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  843. return;
  844. }
  845. else if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  846. {
  847. m_interRegionTeleportAborts.Value++;
  848. m_log.DebugFormat(
  849. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after CreateAgent due to previous client close.",
  850. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  851. return;
  852. }
  853. // Past this point we have to attempt clean up if the teleport fails, so update transfer state.
  854. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.Transferring);
  855. IClientIPEndpoint ipepClient;
  856. string capsPath = String.Empty;
  857. if (NeedsNewAgent(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY))
  858. {
  859. m_log.DebugFormat(
  860. "[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} needs new child agent for agent {3} from {4}",
  861. finalDestination.RegionName, newRegionX, newRegionY, sp.Name, Scene.Name);
  862. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
  863. #region IP Translation for NAT
  864. // Uses ipepClient above
  865. if (sp.ClientView.TryGet(out ipepClient))
  866. {
  867. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  868. }
  869. #endregion
  870. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  871. }
  872. else
  873. {
  874. agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
  875. capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  876. }
  877. // We need to set this here to avoid an unlikely race condition when teleporting to a neighbour simulator,
  878. // where that neighbour simulator could otherwise request a child agent create on the source which then
  879. // closes our existing agent which is still signalled as root.
  880. //sp.IsChildAgent = true;
  881. // New protocol: send TP Finish directly, without prior ES or EAC. That's what happens in the Linden grid
  882. if (m_eqModule != null)
  883. m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, sp.UUID);
  884. else
  885. sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
  886. teleportFlags, capsPath);
  887. m_log.DebugFormat(
  888. "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}",
  889. capsPath, sp.Scene.RegionInfo.RegionName, sp.Name);
  890. // Let's send a full update of the agent.
  891. AgentData agent = new AgentData();
  892. sp.CopyTo(agent);
  893. agent.Position = agentCircuit.startpos;
  894. agent.SenderWantsToWaitForRoot = true;
  895. //SetCallbackURL(agent, sp.Scene.RegionInfo);
  896. // Reset the do not close flag. This must be done before the destination opens child connections (here
  897. // triggered by UpdateAgent) to avoid race conditions. However, we also want to reset it as late as possible
  898. // to avoid a situation where an unexpectedly early call to Scene.NewUserConnection() wrongly results
  899. // in no close.
  900. sp.DoNotCloseAfterTeleport = false;
  901. // Send the Update. If this returns true, we know the client has contacted the destination
  902. // via CompleteMovementIntoRegion, so we can let go.
  903. // If it returns false, something went wrong, and we need to abort.
  904. if (!UpdateAgent(reg, finalDestination, agent, sp))
  905. {
  906. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  907. {
  908. m_interRegionTeleportAborts.Value++;
  909. m_log.DebugFormat(
  910. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after UpdateAgent due to previous client close.",
  911. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  912. return;
  913. }
  914. m_log.WarnFormat(
  915. "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
  916. sp.Name, finalDestination.RegionName, sp.Scene.Name);
  917. Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
  918. return;
  919. }
  920. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
  921. // Need to signal neighbours whether child agents may need closing irrespective of whether this
  922. // one needed closing. We also need to close child agents as quickly as possible to avoid complicated
  923. // race conditions with rapid agent releporting (e.g. from A1 to a non-neighbour B, back
  924. // to a neighbour A2 then off to a non-neighbour C). Closing child agents any later requires complex
  925. // distributed checks to avoid problems in rapid reteleporting scenarios and where child agents are
  926. // abandoned without proper close by viewer but then re-used by an incoming connection.
  927. sp.CloseChildAgents(newRegionX, newRegionY);
  928. // May need to logout or other cleanup
  929. AgentHasMovedAway(sp, logout);
  930. // Well, this is it. The agent is over there.
  931. KillEntity(sp.Scene, sp.LocalId);
  932. // Now let's make it officially a child agent
  933. sp.MakeChildAgent();
  934. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  935. if (NeedsClosing(sp.DrawDistance, oldRegionX, newRegionX, oldRegionY, newRegionY, reg))
  936. {
  937. if (!sp.Scene.IncomingPreCloseClient(sp))
  938. return;
  939. // RED ALERT!!!!
  940. // PLEASE DO NOT DECREASE THIS WAIT TIME UNDER ANY CIRCUMSTANCES.
  941. // THE VIEWERS SEEM TO NEED SOME TIME AFTER RECEIVING MoveAgentIntoRegion
  942. // BEFORE THEY SETTLE IN THE NEW REGION.
  943. // DECREASING THE WAIT TIME HERE WILL EITHER RESULT IN A VIEWER CRASH OR
  944. // IN THE AVIE BEING PLACED IN INFINITY FOR A COUPLE OF SECONDS.
  945. Thread.Sleep(15000);
  946. // OK, it got this agent. Let's close everything
  947. // If we shouldn't close the agent due to some other region renewing the connection
  948. // then this will be handled in IncomingCloseAgent under lock conditions
  949. m_log.DebugFormat(
  950. "[ENTITY TRANSFER MODULE]: Closing agent {0} in {1} after teleport", sp.Name, Scene.Name);
  951. sp.Scene.CloseAgent(sp.UUID, false);
  952. }
  953. else
  954. {
  955. // now we have a child agent in this region.
  956. sp.Reset();
  957. }
  958. }
  959. /// <summary>
  960. /// Clean up an inter-region teleport that did not complete, either because of simulator failure or cancellation.
  961. /// </summary>
  962. /// <remarks>
  963. /// All operations here must be idempotent so that we can call this method at any point in the teleport process
  964. /// up until we send the TeleportFinish event quene event to the viewer.
  965. /// <remarks>
  966. /// <param name='sp'> </param>
  967. /// <param name='finalDestination'></param>
  968. protected virtual void CleanupFailedInterRegionTeleport(ScenePresence sp, string auth_token, GridRegion finalDestination)
  969. {
  970. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
  971. if (sp.IsChildAgent) // We had set it to child before attempted TP (V1)
  972. {
  973. sp.IsChildAgent = false;
  974. ReInstantiateScripts(sp);
  975. EnableChildAgents(sp);
  976. }
  977. // Finally, kill the agent we just created at the destination.
  978. // XXX: Possibly this should be done asynchronously.
  979. Scene.SimulationService.CloseAgent(finalDestination, sp.UUID, auth_token);
  980. }
  981. /// <summary>
  982. /// Signal that the inter-region teleport failed and perform cleanup.
  983. /// </summary>
  984. /// <param name='sp'></param>
  985. /// <param name='finalDestination'></param>
  986. /// <param name='logout'></param>
  987. /// <param name='reason'>Human readable reason for teleport failure. Will be sent to client.</param>
  988. protected virtual void Fail(ScenePresence sp, GridRegion finalDestination, bool logout, string auth_code, string reason)
  989. {
  990. CleanupFailedInterRegionTeleport(sp, auth_code, finalDestination);
  991. m_interRegionTeleportFailures.Value++;
  992. sp.ControllingClient.SendTeleportFailed(
  993. string.Format(
  994. "Problems connecting to destination {0}, reason: {1}", finalDestination.RegionName, reason));
  995. sp.Scene.EventManager.TriggerTeleportFail(sp.ControllingClient, logout);
  996. }
  997. protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, out string reason, out bool logout)
  998. {
  999. logout = false;
  1000. bool success = Scene.SimulationService.CreateAgent(finalDestination, agentCircuit, teleportFlags, out reason);
  1001. if (success)
  1002. sp.Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
  1003. return success;
  1004. }
  1005. protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent, ScenePresence sp)
  1006. {
  1007. return Scene.SimulationService.UpdateAgent(finalDestination, agent);
  1008. }
  1009. protected virtual void SetCallbackURL(AgentData agent, RegionInfo region)
  1010. {
  1011. agent.CallbackURI = region.ServerURI + "agent/" + agent.AgentID.ToString() + "/" + region.RegionID.ToString() + "/release/";
  1012. m_log.DebugFormat(
  1013. "[ENTITY TRANSFER MODULE]: Set release callback URL to {0} in {1}",
  1014. agent.CallbackURI, region.RegionName);
  1015. }
  1016. /// <summary>
  1017. /// Clean up operations once an agent has moved away through cross or teleport.
  1018. /// </summary>
  1019. /// <param name='sp'></param>
  1020. /// <param name='logout'></param>
  1021. protected virtual void AgentHasMovedAway(ScenePresence sp, bool logout)
  1022. {
  1023. if (sp.Scene.AttachmentsModule != null)
  1024. sp.Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, true);
  1025. }
  1026. protected void KillEntity(Scene scene, uint localID)
  1027. {
  1028. scene.SendKillObject(new List<uint> { localID });
  1029. }
  1030. protected virtual GridRegion GetFinalDestination(GridRegion region)
  1031. {
  1032. return region;
  1033. }
  1034. protected virtual bool NeedsNewAgent(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY)
  1035. {
  1036. if (m_regionCombinerModule != null && m_regionCombinerModule.IsRootForMegaregion(Scene.RegionInfo.RegionID))
  1037. {
  1038. Vector2 swCorner, neCorner;
  1039. GetMegaregionViewRange(out swCorner, out neCorner);
  1040. m_log.DebugFormat(
  1041. "[ENTITY TRANSFER MODULE]: Megaregion view of {0} is from {1} to {2} with new agent check for {3},{4}",
  1042. Scene.Name, swCorner, neCorner, newRegionX, newRegionY);
  1043. return !(newRegionX >= swCorner.X && newRegionX <= neCorner.X && newRegionY >= swCorner.Y && newRegionY <= neCorner.Y);
  1044. }
  1045. else
  1046. {
  1047. return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
  1048. }
  1049. }
  1050. protected virtual bool NeedsClosing(float drawdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY, GridRegion reg)
  1051. {
  1052. return Util.IsOutsideView(drawdist, oldRegionX, newRegionX, oldRegionY, newRegionY);
  1053. }
  1054. protected virtual bool IsOutsideRegion(Scene s, Vector3 pos)
  1055. {
  1056. if (s.TestBorderCross(pos, Cardinals.N))
  1057. return true;
  1058. if (s.TestBorderCross(pos, Cardinals.S))
  1059. return true;
  1060. if (s.TestBorderCross(pos, Cardinals.E))
  1061. return true;
  1062. if (s.TestBorderCross(pos, Cardinals.W))
  1063. return true;
  1064. return false;
  1065. }
  1066. #endregion
  1067. #region Landmark Teleport
  1068. /// <summary>
  1069. /// Tries to teleport agent to landmark.
  1070. /// </summary>
  1071. /// <param name="remoteClient"></param>
  1072. /// <param name="regionHandle"></param>
  1073. /// <param name="position"></param>
  1074. public virtual void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  1075. {
  1076. GridRegion info = Scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  1077. if (info == null)
  1078. {
  1079. // can't find the region: Tell viewer and abort
  1080. remoteClient.SendTeleportFailed("The teleport destination could not be found.");
  1081. return;
  1082. }
  1083. ((Scene)(remoteClient.Scene)).RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
  1084. Vector3.Zero, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  1085. }
  1086. #endregion
  1087. #region Teleport Home
  1088. public virtual void TriggerTeleportHome(UUID id, IClientAPI client)
  1089. {
  1090. TeleportHome(id, client);
  1091. }
  1092. public virtual bool TeleportHome(UUID id, IClientAPI client)
  1093. {
  1094. m_log.DebugFormat(
  1095. "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, client.AgentId);
  1096. //OpenSim.Services.Interfaces.PresenceInfo pinfo = Scene.PresenceService.GetAgent(client.SessionId);
  1097. GridUserInfo uinfo = Scene.GridUserService.GetGridUserInfo(client.AgentId.ToString());
  1098. if (uinfo != null)
  1099. {
  1100. GridRegion regionInfo = Scene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
  1101. if (regionInfo == null)
  1102. {
  1103. // can't find the Home region: Tell viewer and abort
  1104. client.SendTeleportFailed("Your home region could not be found.");
  1105. return false;
  1106. }
  1107. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Home region of {0} is {1} ({2}-{3})",
  1108. client.Name, regionInfo.RegionName, regionInfo.RegionCoordX, regionInfo.RegionCoordY);
  1109. // a little eekie that this goes back to Scene and with a forced cast, will fix that at some point...
  1110. ((Scene)(client.Scene)).RequestTeleportLocation(
  1111. client, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
  1112. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  1113. return true;
  1114. }
  1115. else
  1116. {
  1117. m_log.ErrorFormat(
  1118. "[ENTITY TRANSFER MODULE]: No grid user information found for {0} {1}. Cannot send home.",
  1119. client.Name, client.AgentId);
  1120. }
  1121. return false;
  1122. }
  1123. #endregion
  1124. #region Agent Crossings
  1125. public bool Cross(ScenePresence agent, bool isFlying)
  1126. {
  1127. Scene scene = agent.Scene;
  1128. Vector3 pos = agent.AbsolutePosition;
  1129. // m_log.DebugFormat(
  1130. // "[ENTITY TRANSFER MODULE]: Crossing agent {0} at pos {1} in {2}", agent.Name, pos, scene.Name);
  1131. Vector3 newpos = new Vector3(pos.X, pos.Y, pos.Z);
  1132. uint neighbourx = scene.RegionInfo.RegionLocX;
  1133. uint neighboury = scene.RegionInfo.RegionLocY;
  1134. const float boundaryDistance = 1.7f;
  1135. Vector3 northCross = new Vector3(0, boundaryDistance, 0);
  1136. Vector3 southCross = new Vector3(0, -1 * boundaryDistance, 0);
  1137. Vector3 eastCross = new Vector3(boundaryDistance, 0, 0);
  1138. Vector3 westCross = new Vector3(-1 * boundaryDistance, 0, 0);
  1139. // distance into new region to place avatar
  1140. const float enterDistance = 0.5f;
  1141. if (scene.TestBorderCross(pos + westCross, Cardinals.W))
  1142. {
  1143. if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  1144. {
  1145. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  1146. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  1147. }
  1148. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  1149. {
  1150. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  1151. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  1152. {
  1153. neighboury--;
  1154. newpos.Y = Constants.RegionSize - enterDistance;
  1155. }
  1156. else
  1157. {
  1158. agent.IsInTransit = true;
  1159. neighboury = b.TriggerRegionY;
  1160. neighbourx = b.TriggerRegionX;
  1161. Vector3 newposition = pos;
  1162. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1163. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1164. agent.ControllingClient.SendAgentAlertMessage(
  1165. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1166. InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1167. return true;
  1168. }
  1169. }
  1170. Border ba = scene.GetCrossedBorder(pos + westCross, Cardinals.W);
  1171. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  1172. {
  1173. neighbourx--;
  1174. newpos.X = Constants.RegionSize - enterDistance;
  1175. }
  1176. else
  1177. {
  1178. agent.IsInTransit = true;
  1179. neighboury = ba.TriggerRegionY;
  1180. neighbourx = ba.TriggerRegionX;
  1181. Vector3 newposition = pos;
  1182. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1183. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1184. agent.ControllingClient.SendAgentAlertMessage(
  1185. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1186. InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1187. return true;
  1188. }
  1189. }
  1190. else if (scene.TestBorderCross(pos + eastCross, Cardinals.E))
  1191. {
  1192. Border b = scene.GetCrossedBorder(pos + eastCross, Cardinals.E);
  1193. neighbourx += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  1194. newpos.X = enterDistance;
  1195. if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  1196. {
  1197. Border ba = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  1198. if (ba.TriggerRegionX == 0 && ba.TriggerRegionY == 0)
  1199. {
  1200. neighboury--;
  1201. newpos.Y = Constants.RegionSize - enterDistance;
  1202. }
  1203. else
  1204. {
  1205. agent.IsInTransit = true;
  1206. neighboury = ba.TriggerRegionY;
  1207. neighbourx = ba.TriggerRegionX;
  1208. Vector3 newposition = pos;
  1209. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1210. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1211. agent.ControllingClient.SendAgentAlertMessage(
  1212. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1213. InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1214. return true;
  1215. }
  1216. }
  1217. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  1218. {
  1219. Border c = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  1220. neighboury += (uint)(int)(c.BorderLine.Z / (int)Constants.RegionSize);
  1221. newpos.Y = enterDistance;
  1222. }
  1223. }
  1224. else if (scene.TestBorderCross(pos + southCross, Cardinals.S))
  1225. {
  1226. Border b = scene.GetCrossedBorder(pos + southCross, Cardinals.S);
  1227. if (b.TriggerRegionX == 0 && b.TriggerRegionY == 0)
  1228. {
  1229. neighboury--;
  1230. newpos.Y = Constants.RegionSize - enterDistance;
  1231. }
  1232. else
  1233. {
  1234. agent.IsInTransit = true;
  1235. neighboury = b.TriggerRegionY;
  1236. neighbourx = b.TriggerRegionX;
  1237. Vector3 newposition = pos;
  1238. newposition.X += (scene.RegionInfo.RegionLocX - neighbourx) * Constants.RegionSize;
  1239. newposition.Y += (scene.RegionInfo.RegionLocY - neighboury) * Constants.RegionSize;
  1240. agent.ControllingClient.SendAgentAlertMessage(
  1241. String.Format("Moving you to region {0},{1}", neighbourx, neighboury), false);
  1242. InformClientToInitiateTeleportToLocation(agent, neighbourx, neighboury, newposition, scene);
  1243. return true;
  1244. }
  1245. }
  1246. else if (scene.TestBorderCross(pos + northCross, Cardinals.N))
  1247. {
  1248. Border b = scene.GetCrossedBorder(pos + northCross, Cardinals.N);
  1249. neighboury += (uint)(int)(b.BorderLine.Z / (int)Constants.RegionSize);
  1250. newpos.Y = enterDistance;
  1251. }
  1252. /*
  1253. if (pos.X < boundaryDistance) //West
  1254. {
  1255. neighbourx--;
  1256. newpos.X = Constants.RegionSize - enterDistance;
  1257. }
  1258. else if (pos.X > Constants.RegionSize - boundaryDistance) // East
  1259. {
  1260. neighbourx++;
  1261. newpos.X = enterDistance;
  1262. }
  1263. if (pos.Y < boundaryDistance) // South
  1264. {
  1265. neighboury--;
  1266. newpos.Y = Constants.RegionSize - enterDistance;
  1267. }
  1268. else if (pos.Y > Constants.RegionSize - boundaryDistance) // North
  1269. {
  1270. neighboury++;
  1271. newpos.Y = enterDistance;
  1272. }
  1273. */
  1274. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  1275. int x = (int)(neighbourx * Constants.RegionSize), y = (int)(neighboury * Constants.RegionSize);
  1276. ExpiringCache<ulong, DateTime> r;
  1277. DateTime banUntil;
  1278. if (m_bannedRegions.TryGetValue(agent.ControllingClient.AgentId, out r))
  1279. {
  1280. if (r.TryGetValue(neighbourHandle, out banUntil))
  1281. {
  1282. if (DateTime.Now < banUntil)
  1283. return false;
  1284. r.Remove(neighbourHandle);
  1285. }
  1286. }
  1287. else
  1288. {
  1289. r = null;
  1290. }
  1291. GridRegion neighbourRegion = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
  1292. string reason;
  1293. string version;
  1294. if (!scene.SimulationService.QueryAccess(neighbourRegion, agent.ControllingClient.AgentId, newpos, out version, out reason))
  1295. {
  1296. agent.ControllingClient.SendAlertMessage("Cannot region cross into banned parcel");
  1297. if (r == null)
  1298. {
  1299. r = new ExpiringCache<ulong, DateTime>();
  1300. r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
  1301. m_bannedRegions.Add(agent.ControllingClient.AgentId, r, TimeSpan.FromSeconds(45));
  1302. }
  1303. else
  1304. {
  1305. r.Add(neighbourHandle, DateTime.Now + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15));
  1306. }
  1307. return false;
  1308. }
  1309. agent.IsInTransit = true;
  1310. CrossAgentToNewRegionDelegate d = CrossAgentToNewRegionAsync;
  1311. d.BeginInvoke(agent, newpos, neighbourx, neighboury, neighbourRegion, isFlying, version, CrossAgentToNewRegionCompleted, d);
  1312. return true;
  1313. }
  1314. public delegate void InformClientToInitiateTeleportToLocationDelegate(ScenePresence agent, uint regionX, uint regionY,
  1315. Vector3 position,
  1316. Scene initiatingScene);
  1317. private void InformClientToInitiateTeleportToLocation(ScenePresence agent, uint regionX, uint regionY, Vector3 position, Scene initiatingScene)
  1318. {
  1319. // This assumes that we know what our neighbours are.
  1320. InformClientToInitiateTeleportToLocationDelegate d = InformClientToInitiateTeleportToLocationAsync;
  1321. d.BeginInvoke(agent, regionX, regionY, position, initiatingScene,
  1322. InformClientToInitiateTeleportToLocationCompleted,
  1323. d);
  1324. }
  1325. public void InformClientToInitiateTeleportToLocationAsync(ScenePresence agent, uint regionX, uint regionY, Vector3 position,
  1326. Scene initiatingScene)
  1327. {
  1328. Thread.Sleep(10000);
  1329. m_log.DebugFormat(
  1330. "[ENTITY TRANSFER MODULE]: Auto-reteleporting {0} to correct megaregion location {1},{2},{3} from {4}",
  1331. agent.Name, regionX, regionY, position, initiatingScene.Name);
  1332. agent.Scene.RequestTeleportLocation(
  1333. agent.ControllingClient,
  1334. Utils.UIntsToLong(regionX * (uint)Constants.RegionSize, regionY * (uint)Constants.RegionSize),
  1335. position,
  1336. agent.Lookat,
  1337. (uint)Constants.TeleportFlags.ViaLocation);
  1338. /*
  1339. IMessageTransferModule im = initiatingScene.RequestModuleInterface<IMessageTransferModule>();
  1340. if (im != null)
  1341. {
  1342. UUID gotoLocation = Util.BuildFakeParcelID(
  1343. Util.UIntsToLong(
  1344. (regionX *
  1345. (uint)Constants.RegionSize),
  1346. (regionY *
  1347. (uint)Constants.RegionSize)),
  1348. (uint)(int)position.X,
  1349. (uint)(int)position.Y,
  1350. (uint)(int)position.Z);
  1351. GridInstantMessage m
  1352. = new GridInstantMessage(
  1353. initiatingScene,
  1354. UUID.Zero,
  1355. "Region",
  1356. agent.UUID,
  1357. (byte)InstantMessageDialog.GodLikeRequestTeleport,
  1358. false,
  1359. "",
  1360. gotoLocation,
  1361. false,
  1362. new Vector3(127, 0, 0),
  1363. new Byte[0],
  1364. false);
  1365. im.SendInstantMessage(m, delegate(bool success)
  1366. {
  1367. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Client Initiating Teleport sending IM success = {0}", success);
  1368. });
  1369. }
  1370. */
  1371. }
  1372. private void InformClientToInitiateTeleportToLocationCompleted(IAsyncResult iar)
  1373. {
  1374. InformClientToInitiateTeleportToLocationDelegate icon =
  1375. (InformClientToInitiateTeleportToLocationDelegate)iar.AsyncState;
  1376. icon.EndInvoke(iar);
  1377. }
  1378. public delegate ScenePresence CrossAgentToNewRegionDelegate(ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion, bool isFlying, string version);
  1379. /// <summary>
  1380. /// This Closes child agents on neighbouring regions
  1381. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  1382. /// </summary>
  1383. protected ScenePresence CrossAgentToNewRegionAsync(
  1384. ScenePresence agent, Vector3 pos, uint neighbourx, uint neighboury, GridRegion neighbourRegion,
  1385. bool isFlying, string version)
  1386. {
  1387. if (neighbourRegion == null)
  1388. return agent;
  1389. if (!m_entityTransferStateMachine.SetInTransit(agent.UUID))
  1390. {
  1391. m_log.ErrorFormat(
  1392. "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2} - agent is already in transit",
  1393. agent.Name, neighbourRegion.RegionName, agent.Scene.RegionInfo.RegionName);
  1394. return agent;
  1395. }
  1396. bool transitWasReset = false;
  1397. try
  1398. {
  1399. ulong neighbourHandle = Utils.UIntsToLong((uint)(neighbourx * Constants.RegionSize), (uint)(neighboury * Constants.RegionSize));
  1400. m_log.DebugFormat(
  1401. "[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} to {2}-{3} running version {4}",
  1402. agent.Firstname, agent.Lastname, neighbourx, neighboury, version);
  1403. Scene m_scene = agent.Scene;
  1404. if (!agent.ValidateAttachments())
  1405. m_log.DebugFormat(
  1406. "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for region crossing of {0} from {1} to {2}. Continuing.",
  1407. agent.Name, agent.Scene.RegionInfo.RegionName, neighbourRegion.RegionName);
  1408. pos = pos + agent.Velocity;
  1409. Vector3 vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0);
  1410. agent.RemoveFromPhysicalScene();
  1411. AgentData cAgent = new AgentData();
  1412. agent.CopyTo(cAgent);
  1413. cAgent.Position = pos;
  1414. if (isFlying)
  1415. cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  1416. // We don't need the callback anymnore
  1417. cAgent.CallbackURI = String.Empty;
  1418. // Beyond this point, extra cleanup is needed beyond removing transit state
  1419. m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.Transferring);
  1420. if (!m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent))
  1421. {
  1422. // region doesn't take it
  1423. m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp);
  1424. m_log.WarnFormat(
  1425. "[ENTITY TRANSFER MODULE]: Region {0} would not accept update for agent {1} on cross attempt. Returning to original region.",
  1426. neighbourRegion.RegionName, agent.Name);
  1427. ReInstantiateScripts(agent);
  1428. agent.AddToPhysicalScene(isFlying);
  1429. return agent;
  1430. }
  1431. //m_log.Debug("BEFORE CROSS");
  1432. //Scene.DumpChildrenSeeds(UUID);
  1433. //DumpKnownRegions();
  1434. string agentcaps;
  1435. if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
  1436. {
  1437. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
  1438. neighbourRegion.RegionHandle);
  1439. return agent;
  1440. }
  1441. // No turning back
  1442. agent.IsChildAgent = true;
  1443. string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps);
  1444. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
  1445. if (m_eqModule != null)
  1446. {
  1447. m_eqModule.CrossRegion(
  1448. neighbourHandle, pos, vel2 /* agent.Velocity */, neighbourRegion.ExternalEndPoint,
  1449. capsPath, agent.UUID, agent.ControllingClient.SessionId);
  1450. }
  1451. else
  1452. {
  1453. agent.ControllingClient.CrossRegion(neighbourHandle, pos, agent.Velocity, neighbourRegion.ExternalEndPoint,
  1454. capsPath);
  1455. }
  1456. // SUCCESS!
  1457. m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.ReceivedAtDestination);
  1458. // Unlike a teleport, here we do not wait for the destination region to confirm the receipt.
  1459. m_entityTransferStateMachine.UpdateInTransit(agent.UUID, AgentTransferState.CleaningUp);
  1460. agent.MakeChildAgent();
  1461. // FIXME: Possibly this should occur lower down after other commands to close other agents,
  1462. // but not sure yet what the side effects would be.
  1463. m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
  1464. transitWasReset = true;
  1465. // now we have a child agent in this region. Request all interesting data about other (root) agents
  1466. agent.SendOtherAgentsAvatarDataToMe();
  1467. agent.SendOtherAgentsAppearanceToMe();
  1468. // Backwards compatibility. Best effort
  1469. if (version == "Unknown" || version == string.Empty)
  1470. {
  1471. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: neighbor with old version, passing attachments one by one...");
  1472. Thread.Sleep(3000); // wait a little now that we're not waiting for the callback
  1473. CrossAttachmentsIntoNewRegion(neighbourRegion, agent, true);
  1474. }
  1475. // Next, let's close the child agent connections that are too far away.
  1476. agent.CloseChildAgents(neighbourx, neighboury);
  1477. AgentHasMovedAway(agent, false);
  1478. //m_log.Debug("AFTER CROSS");
  1479. //Scene.DumpChildrenSeeds(UUID);
  1480. //DumpKnownRegions();
  1481. }
  1482. catch (Exception e)
  1483. {
  1484. m_log.ErrorFormat(
  1485. "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2}. Exception {3}{4}",
  1486. agent.Name, neighbourRegion.RegionName, agent.Scene.RegionInfo.RegionName, e.Message, e.StackTrace);
  1487. // TODO: Might be worth attempting other restoration here such as reinstantiation of scripts, etc.
  1488. }
  1489. finally
  1490. {
  1491. if (!transitWasReset)
  1492. m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
  1493. }
  1494. return agent;
  1495. }
  1496. private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
  1497. {
  1498. CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
  1499. ScenePresence agent = icon.EndInvoke(iar);
  1500. //// If the cross was successful, this agent is a child agent
  1501. //if (agent.IsChildAgent)
  1502. // agent.Reset();
  1503. //else // Not successful
  1504. // agent.RestoreInCurrentScene();
  1505. // In any case
  1506. agent.IsInTransit = false;
  1507. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
  1508. }
  1509. #endregion
  1510. #region Enable Child Agent
  1511. /// <summary>
  1512. /// This informs a single neighbouring region about agent "avatar".
  1513. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  1514. /// </summary>
  1515. /// <param name="sp"></param>
  1516. /// <param name="region"></param>
  1517. public void EnableChildAgent(ScenePresence sp, GridRegion region)
  1518. {
  1519. m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName);
  1520. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  1521. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  1522. agent.BaseFolder = UUID.Zero;
  1523. agent.InventoryFolder = UUID.Zero;
  1524. agent.startpos = new Vector3(128, 128, 70);
  1525. agent.child = true;
  1526. agent.Appearance = sp.Appearance;
  1527. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1528. agent.ChildrenCapSeeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
  1529. //m_log.DebugFormat("[XXX] Seeds 1 {0}", agent.ChildrenCapSeeds.Count);
  1530. if (!agent.ChildrenCapSeeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
  1531. agent.ChildrenCapSeeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
  1532. //m_log.DebugFormat("[XXX] Seeds 2 {0}", agent.ChildrenCapSeeds.Count);
  1533. sp.AddNeighbourRegion(region.RegionHandle, agent.CapsPath);
  1534. //foreach (ulong h in agent.ChildrenCapSeeds.Keys)
  1535. // m_log.DebugFormat("[XXX] --> {0}", h);
  1536. //m_log.DebugFormat("[XXX] Adding {0}", region.RegionHandle);
  1537. agent.ChildrenCapSeeds.Add(region.RegionHandle, agent.CapsPath);
  1538. if (sp.Scene.CapsModule != null)
  1539. {
  1540. sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, agent.ChildrenCapSeeds);
  1541. }
  1542. if (currentAgentCircuit != null)
  1543. {
  1544. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1545. agent.IPAddress = currentAgentCircuit.IPAddress;
  1546. agent.Viewer = currentAgentCircuit.Viewer;
  1547. agent.Channel = currentAgentCircuit.Channel;
  1548. agent.Mac = currentAgentCircuit.Mac;
  1549. agent.Id0 = currentAgentCircuit.Id0;
  1550. }
  1551. InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  1552. d.BeginInvoke(sp, agent, region, region.ExternalEndPoint, true,
  1553. InformClientOfNeighbourCompleted,
  1554. d);
  1555. }
  1556. #endregion
  1557. #region Enable Child Agents
  1558. private delegate void InformClientOfNeighbourDelegate(
  1559. ScenePresence avatar, AgentCircuitData a, GridRegion reg, IPEndPoint endPoint, bool newAgent);
  1560. /// <summary>
  1561. /// This informs all neighbouring regions about agent "avatar".
  1562. /// </summary>
  1563. /// <param name="sp"></param>
  1564. public void EnableChildAgents(ScenePresence sp)
  1565. {
  1566. List<GridRegion> neighbours = new List<GridRegion>();
  1567. RegionInfo m_regionInfo = sp.Scene.RegionInfo;
  1568. if (m_regionInfo != null)
  1569. {
  1570. neighbours = RequestNeighbours(sp, m_regionInfo.RegionLocX, m_regionInfo.RegionLocY);
  1571. }
  1572. else
  1573. {
  1574. m_log.Debug("[ENTITY TRANSFER MODULE]: m_regionInfo was null in EnableChildAgents, is this a NPC?");
  1575. }
  1576. /// We need to find the difference between the new regions where there are no child agents
  1577. /// and the regions where there are already child agents. We only send notification to the former.
  1578. List<ulong> neighbourHandles = NeighbourHandles(neighbours); // on this region
  1579. neighbourHandles.Add(sp.Scene.RegionInfo.RegionHandle); // add this region too
  1580. List<ulong> previousRegionNeighbourHandles;
  1581. if (sp.Scene.CapsModule != null)
  1582. {
  1583. previousRegionNeighbourHandles =
  1584. new List<ulong>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID).Keys);
  1585. }
  1586. else
  1587. {
  1588. previousRegionNeighbourHandles = new List<ulong>();
  1589. }
  1590. List<ulong> newRegions = NewNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  1591. List<ulong> oldRegions = OldNeighbours(neighbourHandles, previousRegionNeighbourHandles);
  1592. // Dump("Current Neighbors", neighbourHandles);
  1593. // Dump("Previous Neighbours", previousRegionNeighbourHandles);
  1594. // Dump("New Neighbours", newRegions);
  1595. // Dump("Old Neighbours", oldRegions);
  1596. /// Update the scene presence's known regions here on this region
  1597. sp.DropOldNeighbours(oldRegions);
  1598. /// Collect as many seeds as possible
  1599. Dictionary<ulong, string> seeds;
  1600. if (sp.Scene.CapsModule != null)
  1601. seeds = new Dictionary<ulong, string>(sp.Scene.CapsModule.GetChildrenSeeds(sp.UUID));
  1602. else
  1603. seeds = new Dictionary<ulong, string>();
  1604. //m_log.Debug(" !!! No. of seeds: " + seeds.Count);
  1605. if (!seeds.ContainsKey(sp.Scene.RegionInfo.RegionHandle))
  1606. seeds.Add(sp.Scene.RegionInfo.RegionHandle, sp.ControllingClient.RequestClientInfo().CapsPath);
  1607. /// Create the necessary child agents
  1608. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  1609. foreach (GridRegion neighbour in neighbours)
  1610. {
  1611. if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
  1612. {
  1613. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  1614. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  1615. agent.BaseFolder = UUID.Zero;
  1616. agent.InventoryFolder = UUID.Zero;
  1617. agent.startpos = sp.AbsolutePosition + CalculateOffset(sp, neighbour);
  1618. agent.child = true;
  1619. agent.Appearance = sp.Appearance;
  1620. if (currentAgentCircuit != null)
  1621. {
  1622. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1623. agent.IPAddress = currentAgentCircuit.IPAddress;
  1624. agent.Viewer = currentAgentCircuit.Viewer;
  1625. agent.Channel = currentAgentCircuit.Channel;
  1626. agent.Mac = currentAgentCircuit.Mac;
  1627. agent.Id0 = currentAgentCircuit.Id0;
  1628. }
  1629. if (newRegions.Contains(neighbour.RegionHandle))
  1630. {
  1631. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1632. sp.AddNeighbourRegion(neighbour.RegionHandle, agent.CapsPath);
  1633. seeds.Add(neighbour.RegionHandle, agent.CapsPath);
  1634. }
  1635. else
  1636. {
  1637. agent.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, neighbour.RegionHandle);
  1638. }
  1639. cagents.Add(agent);
  1640. }
  1641. }
  1642. /// Update all child agent with everyone's seeds
  1643. foreach (AgentCircuitData a in cagents)
  1644. {
  1645. a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  1646. }
  1647. if (sp.Scene.CapsModule != null)
  1648. {
  1649. sp.Scene.CapsModule.SetChildrenSeed(sp.UUID, seeds);
  1650. }
  1651. sp.KnownRegions = seeds;
  1652. //avatar.Scene.DumpChildrenSeeds(avatar.UUID);
  1653. //avatar.DumpKnownRegions();
  1654. bool newAgent = false;
  1655. int count = 0;
  1656. foreach (GridRegion neighbour in neighbours)
  1657. {
  1658. //m_log.WarnFormat("--> Going to send child agent to {0}", neighbour.RegionName);
  1659. // Don't do it if there's already an agent in that region
  1660. if (newRegions.Contains(neighbour.RegionHandle))
  1661. newAgent = true;
  1662. else
  1663. newAgent = false;
  1664. // continue;
  1665. if (neighbour.RegionHandle != sp.Scene.RegionInfo.RegionHandle)
  1666. {
  1667. try
  1668. {
  1669. // Let's put this back at sync, so that it doesn't clog
  1670. // the network, especially for regions in the same physical server.
  1671. // We're really not in a hurry here.
  1672. InformClientOfNeighbourAsync(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent);
  1673. //InformClientOfNeighbourDelegate d = InformClientOfNeighbourAsync;
  1674. //d.BeginInvoke(sp, cagents[count], neighbour, neighbour.ExternalEndPoint, newAgent,
  1675. // InformClientOfNeighbourCompleted,
  1676. // d);
  1677. }
  1678. catch (ArgumentOutOfRangeException)
  1679. {
  1680. m_log.ErrorFormat(
  1681. "[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}).",
  1682. neighbour.ExternalHostName,
  1683. neighbour.RegionHandle,
  1684. neighbour.RegionLocX,
  1685. neighbour.RegionLocY);
  1686. }
  1687. catch (Exception e)
  1688. {
  1689. m_log.ErrorFormat(
  1690. "[ENTITY TRANSFER MODULE]: Could not resolve external hostname {0} for region {1} ({2}, {3}). {4}",
  1691. neighbour.ExternalHostName,
  1692. neighbour.RegionHandle,
  1693. neighbour.RegionLocX,
  1694. neighbour.RegionLocY,
  1695. e);
  1696. // FIXME: Okay, even though we've failed, we're still going to throw the exception on,
  1697. // since I don't know what will happen if we just let the client continue
  1698. // XXX: Well, decided to swallow the exception instead for now. Let us see how that goes.
  1699. // throw e;
  1700. }
  1701. }
  1702. count++;
  1703. }
  1704. }
  1705. Vector3 CalculateOffset(ScenePresence sp, GridRegion neighbour)
  1706. {
  1707. int rRegionX = (int)sp.Scene.RegionInfo.RegionLocX;
  1708. int rRegionY = (int)sp.Scene.RegionInfo.RegionLocY;
  1709. int tRegionX = neighbour.RegionLocX / (int)Constants.RegionSize;
  1710. int tRegionY = neighbour.RegionLocY / (int)Constants.RegionSize;
  1711. int shiftx = (rRegionX - tRegionX) * (int)Constants.RegionSize;
  1712. int shifty = (rRegionY - tRegionY) * (int)Constants.RegionSize;
  1713. return new Vector3(shiftx, shifty, 0f);
  1714. }
  1715. private void InformClientOfNeighbourCompleted(IAsyncResult iar)
  1716. {
  1717. InformClientOfNeighbourDelegate icon = (InformClientOfNeighbourDelegate)iar.AsyncState;
  1718. icon.EndInvoke(iar);
  1719. //m_log.WarnFormat(" --> InformClientOfNeighbourCompleted");
  1720. }
  1721. /// <summary>
  1722. /// Async component for informing client of which neighbours exist
  1723. /// </summary>
  1724. /// <remarks>
  1725. /// This needs to run asynchronously, as a network timeout may block the thread for a long while
  1726. /// </remarks>
  1727. /// <param name="remoteClient"></param>
  1728. /// <param name="a"></param>
  1729. /// <param name="regionHandle"></param>
  1730. /// <param name="endPoint"></param>
  1731. private void InformClientOfNeighbourAsync(ScenePresence sp, AgentCircuitData a, GridRegion reg,
  1732. IPEndPoint endPoint, bool newAgent)
  1733. {
  1734. // Let's wait just a little to give time to originating regions to catch up with closing child agents
  1735. // after a cross here
  1736. Thread.Sleep(500);
  1737. Scene scene = sp.Scene;
  1738. m_log.DebugFormat(
  1739. "[ENTITY TRANSFER MODULE]: Informing {0} {1} about neighbour {2} {3} at ({4},{5})",
  1740. sp.Name, sp.UUID, reg.RegionName, endPoint, reg.RegionCoordX, reg.RegionCoordY);
  1741. string capsPath = reg.ServerURI + CapsUtil.GetCapsSeedPath(a.CapsPath);
  1742. string reason = String.Empty;
  1743. bool regionAccepted = scene.SimulationService.CreateAgent(reg, a, (uint)TeleportFlags.Default, out reason);
  1744. if (regionAccepted && newAgent)
  1745. {
  1746. if (m_eqModule != null)
  1747. {
  1748. #region IP Translation for NAT
  1749. IClientIPEndpoint ipepClient;
  1750. if (sp.ClientView.TryGet(out ipepClient))
  1751. {
  1752. endPoint.Address = NetworkUtil.GetIPFor(ipepClient.EndPoint, endPoint.Address);
  1753. }
  1754. #endregion
  1755. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} is sending {1} EnableSimulator for neighbour region {2} @ {3} " +
  1756. "and EstablishAgentCommunication with seed cap {4}",
  1757. scene.RegionInfo.RegionName, sp.Name, reg.RegionName, reg.RegionHandle, capsPath);
  1758. m_eqModule.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID);
  1759. m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath);
  1760. }
  1761. else
  1762. {
  1763. sp.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  1764. // TODO: make Event Queue disablable!
  1765. }
  1766. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Completed inform {0} {1} about neighbour {2}", sp.Name, sp.UUID, endPoint);
  1767. }
  1768. if (!regionAccepted)
  1769. m_log.WarnFormat(
  1770. "[ENTITY TRANSFER MODULE]: Region {0} did not accept {1} {2}: {3}",
  1771. reg.RegionName, sp.Name, sp.UUID, reason);
  1772. }
  1773. /// <summary>
  1774. /// Gets the range considered in view of this megaregion (assuming this is a megaregion).
  1775. /// </summary>
  1776. /// <remarks>Expressed in 256m units</remarks>
  1777. /// <param name='swCorner'></param>
  1778. /// <param name='neCorner'></param>
  1779. private void GetMegaregionViewRange(out Vector2 swCorner, out Vector2 neCorner)
  1780. {
  1781. Border[] northBorders = Scene.NorthBorders.ToArray();
  1782. Border[] eastBorders = Scene.EastBorders.ToArray();
  1783. Vector2 extent = Vector2.Zero;
  1784. for (int i = 0; i < eastBorders.Length; i++)
  1785. {
  1786. extent.X = (eastBorders[i].BorderLine.Z > extent.X) ? eastBorders[i].BorderLine.Z : extent.X;
  1787. }
  1788. for (int i = 0; i < northBorders.Length; i++)
  1789. {
  1790. extent.Y = (northBorders[i].BorderLine.Z > extent.Y) ? northBorders[i].BorderLine.Z : extent.Y;
  1791. }
  1792. // Loss of fraction on purpose
  1793. extent.X = ((int)extent.X / (int)Constants.RegionSize);
  1794. extent.Y = ((int)extent.Y / (int)Constants.RegionSize);
  1795. swCorner.X = Scene.RegionInfo.RegionLocX - 1;
  1796. swCorner.Y = Scene.RegionInfo.RegionLocY - 1;
  1797. neCorner.X = Scene.RegionInfo.RegionLocX + extent.X;
  1798. neCorner.Y = Scene.RegionInfo.RegionLocY + extent.Y;
  1799. }
  1800. /// <summary>
  1801. /// Return the list of regions that are considered to be neighbours to the given scene.
  1802. /// </summary>
  1803. /// <param name="pScene"></param>
  1804. /// <param name="pRegionLocX"></param>
  1805. /// <param name="pRegionLocY"></param>
  1806. /// <returns></returns>
  1807. protected List<GridRegion> RequestNeighbours(ScenePresence avatar, uint pRegionLocX, uint pRegionLocY)
  1808. {
  1809. Scene pScene = avatar.Scene;
  1810. RegionInfo m_regionInfo = pScene.RegionInfo;
  1811. // Leaving this as a "megaregions" computation vs "non-megaregions" computation; it isn't
  1812. // clear what should be done with a "far view" given that megaregions already extended the
  1813. // view to include everything in the megaregion
  1814. if (m_regionCombinerModule == null || !m_regionCombinerModule.IsRootForMegaregion(Scene.RegionInfo.RegionID))
  1815. {
  1816. int dd = avatar.DrawDistance < Constants.RegionSize ? (int)Constants.RegionSize : (int)avatar.DrawDistance;
  1817. int startX = (int)pRegionLocX * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
  1818. int startY = (int)pRegionLocY * (int)Constants.RegionSize - dd + (int)(Constants.RegionSize/2);
  1819. int endX = (int)pRegionLocX * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
  1820. int endY = (int)pRegionLocY * (int)Constants.RegionSize + dd + (int)(Constants.RegionSize/2);
  1821. List<GridRegion> neighbours =
  1822. avatar.Scene.GridService.GetRegionRange(m_regionInfo.ScopeID, startX, endX, startY, endY);
  1823. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  1824. return neighbours;
  1825. }
  1826. else
  1827. {
  1828. Vector2 swCorner, neCorner;
  1829. GetMegaregionViewRange(out swCorner, out neCorner);
  1830. List<GridRegion> neighbours
  1831. = pScene.GridService.GetRegionRange(
  1832. m_regionInfo.ScopeID,
  1833. (int)swCorner.X * (int)Constants.RegionSize,
  1834. (int)neCorner.X * (int)Constants.RegionSize,
  1835. (int)swCorner.Y * (int)Constants.RegionSize,
  1836. (int)neCorner.Y * (int)Constants.RegionSize);
  1837. neighbours.RemoveAll(delegate(GridRegion r) { return r.RegionID == m_regionInfo.RegionID; });
  1838. return neighbours;
  1839. }
  1840. }
  1841. private List<ulong> NewNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1842. {
  1843. return currentNeighbours.FindAll(delegate(ulong handle) { return !previousNeighbours.Contains(handle); });
  1844. }
  1845. // private List<ulong> CommonNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1846. // {
  1847. // return currentNeighbours.FindAll(delegate(ulong handle) { return previousNeighbours.Contains(handle); });
  1848. // }
  1849. private List<ulong> OldNeighbours(List<ulong> currentNeighbours, List<ulong> previousNeighbours)
  1850. {
  1851. return previousNeighbours.FindAll(delegate(ulong handle) { return !currentNeighbours.Contains(handle); });
  1852. }
  1853. private List<ulong> NeighbourHandles(List<GridRegion> neighbours)
  1854. {
  1855. List<ulong> handles = new List<ulong>();
  1856. foreach (GridRegion reg in neighbours)
  1857. {
  1858. handles.Add(reg.RegionHandle);
  1859. }
  1860. return handles;
  1861. }
  1862. // private void Dump(string msg, List<ulong> handles)
  1863. // {
  1864. // m_log.InfoFormat("-------------- HANDLE DUMP ({0}) ---------", msg);
  1865. // foreach (ulong handle in handles)
  1866. // {
  1867. // uint x, y;
  1868. // Utils.LongToUInts(handle, out x, out y);
  1869. // x = x / Constants.RegionSize;
  1870. // y = y / Constants.RegionSize;
  1871. // m_log.InfoFormat("({0}, {1})", x, y);
  1872. // }
  1873. // }
  1874. #endregion
  1875. #region Agent Arrived
  1876. public void AgentArrivedAtDestination(UUID id)
  1877. {
  1878. m_entityTransferStateMachine.SetAgentArrivedAtDestination(id);
  1879. }
  1880. #endregion
  1881. #region Object Transfers
  1882. /// <summary>
  1883. /// Move the given scene object into a new region depending on which region its absolute position has moved
  1884. /// into.
  1885. ///
  1886. /// This method locates the new region handle and offsets the prim position for the new region
  1887. /// </summary>
  1888. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  1889. /// <param name="grp">the scene object that we're crossing</param>
  1890. public void Cross(SceneObjectGroup grp, Vector3 attemptedPosition, bool silent)
  1891. {
  1892. if (grp == null)
  1893. return;
  1894. if (grp.IsDeleted)
  1895. return;
  1896. Scene scene = grp.Scene;
  1897. if (scene == null)
  1898. return;
  1899. if (grp.RootPart.DIE_AT_EDGE)
  1900. {
  1901. // We remove the object here
  1902. try
  1903. {
  1904. scene.DeleteSceneObject(grp, false);
  1905. }
  1906. catch (Exception)
  1907. {
  1908. m_log.Warn("[DATABASE]: exception when trying to remove the prim that crossed the border.");
  1909. }
  1910. return;
  1911. }
  1912. int thisx = (int)scene.RegionInfo.RegionLocX;
  1913. int thisy = (int)scene.RegionInfo.RegionLocY;
  1914. Vector3 EastCross = new Vector3(0.1f, 0, 0);
  1915. Vector3 WestCross = new Vector3(-0.1f, 0, 0);
  1916. Vector3 NorthCross = new Vector3(0, 0.1f, 0);
  1917. Vector3 SouthCross = new Vector3(0, -0.1f, 0);
  1918. // use this if no borders were crossed!
  1919. ulong newRegionHandle
  1920. = Util.UIntsToLong((uint)((thisx) * Constants.RegionSize),
  1921. (uint)((thisy) * Constants.RegionSize));
  1922. Vector3 pos = attemptedPosition;
  1923. int changeX = 1;
  1924. int changeY = 1;
  1925. if (scene.TestBorderCross(attemptedPosition + WestCross, Cardinals.W))
  1926. {
  1927. if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1928. {
  1929. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1930. if (crossedBorderx.BorderLine.Z > 0)
  1931. {
  1932. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1933. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1934. }
  1935. else
  1936. pos.X = ((pos.X + Constants.RegionSize));
  1937. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1938. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1939. if (crossedBordery.BorderLine.Z > 0)
  1940. {
  1941. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1942. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1943. }
  1944. else
  1945. pos.Y = ((pos.Y + Constants.RegionSize));
  1946. newRegionHandle
  1947. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1948. (uint)((thisy - changeY) * Constants.RegionSize));
  1949. // x - 1
  1950. // y - 1
  1951. }
  1952. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  1953. {
  1954. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1955. if (crossedBorderx.BorderLine.Z > 0)
  1956. {
  1957. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1958. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1959. }
  1960. else
  1961. pos.X = ((pos.X + Constants.RegionSize));
  1962. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1963. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  1964. if (crossedBordery.BorderLine.Z > 0)
  1965. {
  1966. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  1967. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  1968. }
  1969. else
  1970. pos.Y = ((pos.Y + Constants.RegionSize));
  1971. newRegionHandle
  1972. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1973. (uint)((thisy + changeY) * Constants.RegionSize));
  1974. // x - 1
  1975. // y + 1
  1976. }
  1977. else
  1978. {
  1979. Border crossedBorderx = scene.GetCrossedBorder(attemptedPosition + WestCross, Cardinals.W);
  1980. if (crossedBorderx.BorderLine.Z > 0)
  1981. {
  1982. pos.X = ((pos.X + crossedBorderx.BorderLine.Z));
  1983. changeX = (int)(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize);
  1984. }
  1985. else
  1986. pos.X = ((pos.X + Constants.RegionSize));
  1987. newRegionHandle
  1988. = Util.UIntsToLong((uint)((thisx - changeX) * Constants.RegionSize),
  1989. (uint)(thisy * Constants.RegionSize));
  1990. // x - 1
  1991. }
  1992. }
  1993. else if (scene.TestBorderCross(attemptedPosition + EastCross, Cardinals.E))
  1994. {
  1995. if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  1996. {
  1997. pos.X = ((pos.X - Constants.RegionSize));
  1998. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  1999. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  2000. if (crossedBordery.BorderLine.Z > 0)
  2001. {
  2002. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  2003. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  2004. }
  2005. else
  2006. pos.Y = ((pos.Y + Constants.RegionSize));
  2007. newRegionHandle
  2008. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  2009. (uint)((thisy - changeY) * Constants.RegionSize));
  2010. // x + 1
  2011. // y - 1
  2012. }
  2013. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  2014. {
  2015. pos.X = ((pos.X - Constants.RegionSize));
  2016. pos.Y = ((pos.Y - Constants.RegionSize));
  2017. newRegionHandle
  2018. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  2019. (uint)((thisy + changeY) * Constants.RegionSize));
  2020. // x + 1
  2021. // y + 1
  2022. }
  2023. else
  2024. {
  2025. pos.X = ((pos.X - Constants.RegionSize));
  2026. newRegionHandle
  2027. = Util.UIntsToLong((uint)((thisx + changeX) * Constants.RegionSize),
  2028. (uint)(thisy * Constants.RegionSize));
  2029. // x + 1
  2030. }
  2031. }
  2032. else if (scene.TestBorderCross(attemptedPosition + SouthCross, Cardinals.S))
  2033. {
  2034. Border crossedBordery = scene.GetCrossedBorder(attemptedPosition + SouthCross, Cardinals.S);
  2035. //(crossedBorderx.BorderLine.Z / (int)Constants.RegionSize)
  2036. if (crossedBordery.BorderLine.Z > 0)
  2037. {
  2038. pos.Y = ((pos.Y + crossedBordery.BorderLine.Z));
  2039. changeY = (int)(crossedBordery.BorderLine.Z / (int)Constants.RegionSize);
  2040. }
  2041. else
  2042. pos.Y = ((pos.Y + Constants.RegionSize));
  2043. newRegionHandle
  2044. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy - changeY) * Constants.RegionSize));
  2045. // y - 1
  2046. }
  2047. else if (scene.TestBorderCross(attemptedPosition + NorthCross, Cardinals.N))
  2048. {
  2049. pos.Y = ((pos.Y - Constants.RegionSize));
  2050. newRegionHandle
  2051. = Util.UIntsToLong((uint)(thisx * Constants.RegionSize), (uint)((thisy + changeY) * Constants.RegionSize));
  2052. // y + 1
  2053. }
  2054. // Offset the positions for the new region across the border
  2055. Vector3 oldGroupPosition = grp.RootPart.GroupPosition;
  2056. // If we fail to cross the border, then reset the position of the scene object on that border.
  2057. uint x = 0, y = 0;
  2058. Utils.LongToUInts(newRegionHandle, out x, out y);
  2059. GridRegion destination = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID, (int)x, (int)y);
  2060. if (destination == null || !CrossPrimGroupIntoNewRegion(destination, pos, grp, silent))
  2061. {
  2062. m_log.InfoFormat("[ENTITY TRANSFER MODULE] cross region transfer failed for object {0}",grp.UUID);
  2063. // We are going to move the object back to the old position so long as the old position
  2064. // is in the region
  2065. oldGroupPosition.X = Util.Clamp<float>(oldGroupPosition.X,1.0f,(float)Constants.RegionSize-1);
  2066. oldGroupPosition.Y = Util.Clamp<float>(oldGroupPosition.Y,1.0f,(float)Constants.RegionSize-1);
  2067. oldGroupPosition.Z = Util.Clamp<float>(oldGroupPosition.Z,1.0f,4096.0f);
  2068. grp.RootPart.GroupPosition = oldGroupPosition;
  2069. // Need to turn off the physics flags, otherwise the object will continue to attempt to
  2070. // move out of the region creating an infinite loop of failed attempts to cross
  2071. grp.UpdatePrimFlags(grp.RootPart.LocalId,false,grp.IsTemporary,grp.IsPhantom,false);
  2072. if (grp.RootPart.KeyframeMotion != null)
  2073. grp.RootPart.KeyframeMotion.CrossingFailure();
  2074. grp.ScheduleGroupForFullUpdate();
  2075. }
  2076. }
  2077. /// <summary>
  2078. /// Move the given scene object into a new region
  2079. /// </summary>
  2080. /// <param name="newRegionHandle"></param>
  2081. /// <param name="grp">Scene Object Group that we're crossing</param>
  2082. /// <returns>
  2083. /// true if the crossing itself was successful, false on failure
  2084. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  2085. /// </returns>
  2086. protected bool CrossPrimGroupIntoNewRegion(GridRegion destination, Vector3 newPosition, SceneObjectGroup grp, bool silent)
  2087. {
  2088. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  2089. bool successYN = false;
  2090. grp.RootPart.ClearUpdateSchedule();
  2091. //int primcrossingXMLmethod = 0;
  2092. if (destination != null)
  2093. {
  2094. //string objectState = grp.GetStateSnapshot();
  2095. //successYN
  2096. // = m_sceneGridService.PrimCrossToNeighboringRegion(
  2097. // newRegionHandle, grp.UUID, m_serialiser.SaveGroupToXml2(grp), primcrossingXMLmethod);
  2098. //if (successYN && (objectState != "") && m_allowScriptCrossings)
  2099. //{
  2100. // successYN = m_sceneGridService.PrimCrossToNeighboringRegion(
  2101. // newRegionHandle, grp.UUID, objectState, 100);
  2102. //}
  2103. //// And the new channel...
  2104. //if (m_interregionCommsOut != null)
  2105. // successYN = m_interregionCommsOut.SendCreateObject(newRegionHandle, grp, true);
  2106. if (Scene.SimulationService != null)
  2107. successYN = Scene.SimulationService.CreateObject(destination, newPosition, grp, true);
  2108. if (successYN)
  2109. {
  2110. // We remove the object here
  2111. try
  2112. {
  2113. grp.Scene.DeleteSceneObject(grp, silent);
  2114. }
  2115. catch (Exception e)
  2116. {
  2117. m_log.ErrorFormat(
  2118. "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  2119. grp, e);
  2120. }
  2121. }
  2122. else
  2123. {
  2124. if (!grp.IsDeleted)
  2125. {
  2126. PhysicsActor pa = grp.RootPart.PhysActor;
  2127. if (pa != null)
  2128. pa.CrossingFailure();
  2129. }
  2130. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: Prim crossing failed for {0}", grp);
  2131. }
  2132. }
  2133. else
  2134. {
  2135. m_log.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
  2136. }
  2137. return successYN;
  2138. }
  2139. /// <summary>
  2140. /// Cross the attachments for an avatar into the destination region.
  2141. /// </summary>
  2142. /// <remarks>
  2143. /// This is only invoked for simulators released prior to April 2011. Versions of OpenSimulator since then
  2144. /// transfer attachments in one go as part of the ChildAgentDataUpdate data passed in the update agent call.
  2145. /// </remarks>
  2146. /// <param name='destination'></param>
  2147. /// <param name='sp'></param>
  2148. /// <param name='silent'></param>
  2149. protected void CrossAttachmentsIntoNewRegion(GridRegion destination, ScenePresence sp, bool silent)
  2150. {
  2151. List<SceneObjectGroup> attachments = sp.GetAttachments();
  2152. // m_log.DebugFormat(
  2153. // "[ENTITY TRANSFER MODULE]: Crossing {0} attachments into {1} for {2}",
  2154. // m_attachments.Count, destination.RegionName, sp.Name);
  2155. foreach (SceneObjectGroup gobj in attachments)
  2156. {
  2157. // If the prim group is null then something must have happened to it!
  2158. if (gobj != null && !gobj.IsDeleted)
  2159. {
  2160. SceneObjectGroup clone = (SceneObjectGroup)gobj.CloneForNewScene();
  2161. clone.RootPart.GroupPosition = gobj.RootPart.AttachedPos;
  2162. clone.IsAttachment = false;
  2163. //gobj.RootPart.LastOwnerID = gobj.GetFromAssetID();
  2164. m_log.DebugFormat(
  2165. "[ENTITY TRANSFER MODULE]: Sending attachment {0} to region {1}",
  2166. clone.UUID, destination.RegionName);
  2167. CrossPrimGroupIntoNewRegion(destination, Vector3.Zero, clone, silent);
  2168. }
  2169. }
  2170. sp.ClearAttachments();
  2171. }
  2172. #endregion
  2173. #region Misc
  2174. public bool IsInTransit(UUID id)
  2175. {
  2176. return m_entityTransferStateMachine.GetAgentTransferState(id) != null;
  2177. }
  2178. protected void ReInstantiateScripts(ScenePresence sp)
  2179. {
  2180. int i = 0;
  2181. if (sp.InTransitScriptStates.Count > 0)
  2182. {
  2183. List<SceneObjectGroup> attachments = sp.GetAttachments();
  2184. foreach (SceneObjectGroup sog in attachments)
  2185. {
  2186. if (i < sp.InTransitScriptStates.Count)
  2187. {
  2188. sog.SetState(sp.InTransitScriptStates[i++], sp.Scene);
  2189. sog.CreateScriptInstances(0, false, sp.Scene.DefaultScriptEngine, 0);
  2190. sog.ResumeScripts();
  2191. }
  2192. else
  2193. m_log.ErrorFormat(
  2194. "[ENTITY TRANSFER MODULE]: InTransitScriptStates.Count={0} smaller than Attachments.Count={1}",
  2195. sp.InTransitScriptStates.Count, attachments.Count);
  2196. }
  2197. sp.InTransitScriptStates.Clear();
  2198. }
  2199. }
  2200. #endregion
  2201. }
  2202. }