EntityTransferModule.cs 116 KB

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