EntityTransferModule.cs 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884
  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.PhysicsModules.SharedBase;
  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, IDisposable
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  51. private static readonly string LogHeader = "[ENTITY TRANSFER MODULE]";
  52. private static readonly string OutfitTPError = "destination region does not support the Outfit you are wearing. Please retry with a simpler one";
  53. public EntityTransferModule()
  54. {
  55. }
  56. ~EntityTransferModule()
  57. {
  58. Dispose(false);
  59. }
  60. public void Dispose()
  61. {
  62. if (!disposed)
  63. {
  64. Dispose(true);
  65. GC.SuppressFinalize(this);
  66. }
  67. }
  68. bool disposed;
  69. private void Dispose(bool disposing)
  70. {
  71. if (!disposed)
  72. {
  73. disposed = true;
  74. m_bannedRegionCache?.Dispose();
  75. m_bannedRegionCache = null;
  76. }
  77. }
  78. /// <summary>
  79. /// If true then on a teleport, the source region waits for a callback from the destination region. If
  80. /// a callback fails to arrive within a set time then the user is pulled back into the source region.
  81. /// </summary>
  82. public bool WaitForAgentArrivedAtDestination { get; set; } = true;
  83. /// <summary>
  84. /// If true then we ask the viewer to disable teleport cancellation and ignore teleport requests.
  85. /// </summary>
  86. /// <remarks>
  87. /// This is useful in situations where teleport is very likely to always succeed and we want to avoid a
  88. /// situation where avatars can be come 'stuck' due to a failed teleport cancellation. Unfortunately, the
  89. /// nature of the teleport protocol makes it extremely difficult (maybe impossible) to make teleport
  90. /// cancellation consistently suceed.
  91. /// </remarks>
  92. public bool DisableInterRegionTeleportCancellation { get; set; }
  93. /// <summary>
  94. /// Number of times inter-region teleport was attempted.
  95. /// </summary>
  96. private Stat m_interRegionTeleportAttempts;
  97. /// <summary>
  98. /// Number of times inter-region teleport was aborted (due to simultaneous client logout).
  99. /// </summary>
  100. private Stat m_interRegionTeleportAborts;
  101. /// <summary>
  102. /// Number of times inter-region teleport was successfully cancelled by the client.
  103. /// </summary>
  104. private Stat m_interRegionTeleportCancels;
  105. /// <summary>
  106. /// Number of times inter-region teleport failed due to server/client/network problems (e.g. viewer failed to
  107. /// connect with destination region).
  108. /// </summary>
  109. /// <remarks>
  110. /// This is not necessarily a problem for this simulator - in open-grid/hg conditions, viewer connectivity to
  111. /// destination simulator is unknown.
  112. /// </remarks>
  113. private Stat m_interRegionTeleportFailures;
  114. protected GridInfo m_thisGridInfo;
  115. protected bool m_Enabled = false;
  116. protected Scene m_scene;
  117. public Scene Scene
  118. {
  119. get
  120. {
  121. return m_scene;
  122. }
  123. }
  124. protected string m_sceneName;
  125. protected RegionInfo m_sceneRegionInfo;
  126. protected ulong m_sceneRegionHandler;
  127. /// <summary>
  128. /// Handles recording and manipulation of state for entities that are in transfer within or between regions
  129. /// (cross or teleport).
  130. /// </summary>
  131. private EntityTransferStateMachine m_entityTransferStateMachine;
  132. // For performance, we keed a cached of banned regions so we don't keep going
  133. // to the grid service.
  134. private class BannedRegionCache
  135. {
  136. private ExpiringCacheOS<ulong, Dictionary<UUID, double>> m_bannedRegions =
  137. new ExpiringCacheOS<ulong, Dictionary<UUID, double>>(15000);
  138. public BannedRegionCache()
  139. {
  140. }
  141. ~BannedRegionCache()
  142. {
  143. Dispose(false);
  144. }
  145. public void Dispose()
  146. {
  147. Dispose(true);
  148. GC.SuppressFinalize(this);
  149. }
  150. private void Dispose(bool disposing)
  151. {
  152. if (m_bannedRegions != null)
  153. {
  154. m_bannedRegions.Dispose();
  155. m_bannedRegions = null;
  156. }
  157. }
  158. // Return 'true' if there is a valid ban entry for this agent in this region
  159. public bool IfBanned(ulong pRegionHandle, UUID pAgentID)
  160. {
  161. if (m_bannedRegions.TryGetValue(pRegionHandle, out Dictionary<UUID, double> idCache))
  162. {
  163. lock(idCache)
  164. {
  165. if (idCache.TryGetValue(pAgentID, out double exp))
  166. {
  167. if(exp < Util.GetTimeStamp())
  168. return true;
  169. else
  170. idCache.Remove(pAgentID);
  171. }
  172. }
  173. }
  174. return false;
  175. }
  176. public void Add(ulong pRegionHandle, UUID pAgentID, double newTime)
  177. {
  178. if (m_bannedRegions.TryGetValue(pRegionHandle, out Dictionary<UUID, double> idCache))
  179. {
  180. lock (idCache)
  181. {
  182. idCache[pAgentID] = Util.GetTimeStamp() + newTime;
  183. m_bannedRegions.AddOrUpdate(pRegionHandle, idCache, newTime);
  184. }
  185. }
  186. else
  187. {
  188. idCache = new Dictionary<UUID, double>();
  189. idCache[pAgentID] = Util.GetTimeStamp() + newTime;
  190. m_bannedRegions.AddOrUpdate(pRegionHandle, idCache, newTime);
  191. }
  192. }
  193. // Remove the agent from the region's banned list
  194. public void Remove(ulong pRegionHandle, UUID pAgentID)
  195. {
  196. if (m_bannedRegions.TryGetValue(pRegionHandle, out Dictionary<UUID, double> idCache))
  197. {
  198. lock (idCache)
  199. idCache.Remove(pAgentID);
  200. }
  201. }
  202. }
  203. private BannedRegionCache m_bannedRegionCache = new BannedRegionCache();
  204. private IEventQueue m_eqModule;
  205. #region ISharedRegionModule
  206. public Type ReplaceableInterface
  207. {
  208. get { return null; }
  209. }
  210. public virtual string Name
  211. {
  212. get { return "BasicEntityTransferModule"; }
  213. }
  214. public virtual void Initialise(IConfigSource source)
  215. {
  216. IConfig moduleConfig = source.Configs["Modules"];
  217. if (moduleConfig != null)
  218. {
  219. string name = moduleConfig.GetString("EntityTransferModule", "");
  220. if (name == Name)
  221. {
  222. InitialiseCommon(source);
  223. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: {0} enabled.", Name);
  224. }
  225. }
  226. }
  227. /// <summary>
  228. /// Initialize config common for this module and any descendents.
  229. /// </summary>
  230. /// <param name="source"></param>
  231. protected virtual void InitialiseCommon(IConfigSource source)
  232. {
  233. IConfig transferConfig = source.Configs["EntityTransfer"];
  234. if (transferConfig != null)
  235. {
  236. DisableInterRegionTeleportCancellation
  237. = transferConfig.GetBoolean("DisableInterRegionTeleportCancellation", false);
  238. WaitForAgentArrivedAtDestination
  239. = transferConfig.GetBoolean("wait_for_callback", WaitForAgentArrivedAtDestination);
  240. }
  241. m_entityTransferStateMachine = new EntityTransferStateMachine(this);
  242. m_Enabled = true;
  243. }
  244. public virtual void PostInitialise()
  245. {
  246. }
  247. public virtual void AddRegion(Scene scene)
  248. {
  249. if (!m_Enabled)
  250. return;
  251. m_scene = scene;
  252. m_sceneName = scene.Name;
  253. m_sceneRegionInfo = scene.RegionInfo;
  254. m_sceneRegionHandler = m_sceneRegionInfo.RegionHandle;
  255. m_thisGridInfo = scene.SceneGridInfo;
  256. m_interRegionTeleportAttempts =
  257. new Stat(
  258. "InterRegionTeleportAttempts",
  259. "Number of inter-region teleports attempted.",
  260. "This does not count attempts which failed due to pre-conditions (e.g. target simulator refused access).\n"
  261. + "You can get successfully teleports by subtracting aborts, cancels and teleport failures from this figure.",
  262. "",
  263. "entitytransfer",
  264. m_sceneName,
  265. StatType.Push,
  266. null,
  267. StatVerbosity.Debug);
  268. m_interRegionTeleportAborts =
  269. new Stat(
  270. "InterRegionTeleportAborts",
  271. "Number of inter-region teleports aborted due to client actions.",
  272. "The chief action is simultaneous logout whilst teleporting.",
  273. "",
  274. "entitytransfer",
  275. m_sceneName,
  276. StatType.Push,
  277. null,
  278. StatVerbosity.Debug);
  279. m_interRegionTeleportCancels =
  280. new Stat(
  281. "InterRegionTeleportCancels",
  282. "Number of inter-region teleports cancelled by the client.",
  283. null,
  284. "",
  285. "entitytransfer",
  286. m_sceneName,
  287. StatType.Push,
  288. null,
  289. StatVerbosity.Debug);
  290. m_interRegionTeleportFailures =
  291. new Stat(
  292. "InterRegionTeleportFailures",
  293. "Number of inter-region teleports that failed due to server/client/network issues.",
  294. "This number may not be very helpful in open-grid/hg situations as the network connectivity/quality of destinations is uncontrollable.",
  295. "",
  296. "entitytransfer",
  297. m_sceneName,
  298. StatType.Push,
  299. null,
  300. StatVerbosity.Debug);
  301. StatsManager.RegisterStat(m_interRegionTeleportAttempts);
  302. StatsManager.RegisterStat(m_interRegionTeleportAborts);
  303. StatsManager.RegisterStat(m_interRegionTeleportCancels);
  304. StatsManager.RegisterStat(m_interRegionTeleportFailures);
  305. scene.RegisterModuleInterface<IEntityTransferModule>(this);
  306. scene.EventManager.OnNewClient += OnNewClient;
  307. }
  308. protected virtual void OnNewClient(IClientAPI client)
  309. {
  310. client.OnTeleportHomeRequest += TriggerTeleportHome;
  311. client.OnTeleportLandmarkRequest += RequestTeleportLandmark;
  312. if (!DisableInterRegionTeleportCancellation)
  313. client.OnTeleportCancel += OnClientCancelTeleport;
  314. client.OnConnectionClosed += OnConnectionClosed;
  315. }
  316. public virtual void Close()
  317. {
  318. Dispose();
  319. }
  320. public virtual void RemoveRegion(Scene scene)
  321. {
  322. if (m_Enabled)
  323. {
  324. StatsManager.DeregisterStat(m_interRegionTeleportAttempts);
  325. StatsManager.DeregisterStat(m_interRegionTeleportAborts);
  326. StatsManager.DeregisterStat(m_interRegionTeleportCancels);
  327. StatsManager.DeregisterStat(m_interRegionTeleportFailures);
  328. scene.EventManager.OnNewClient -= OnNewClient;
  329. m_thisGridInfo = null;
  330. }
  331. }
  332. public virtual void RegionLoaded(Scene scene)
  333. {
  334. if (!m_Enabled)
  335. return;
  336. m_eqModule = m_scene.RequestModuleInterface<IEventQueue>();
  337. }
  338. #endregion
  339. #region Agent Teleports
  340. public virtual void OnConnectionClosed(IClientAPI client)
  341. {
  342. if (client.IsLoggingOut && m_entityTransferStateMachine.UpdateInTransit(client.AgentId, AgentTransferState.Aborting))
  343. {
  344. m_log.DebugFormat(
  345. "[ENTITY TRANSFER MODULE]: Aborted teleport request from {0} in {1} due to simultaneous logout",
  346. client.Name, m_sceneName);
  347. }
  348. }
  349. private void OnClientCancelTeleport(IClientAPI client)
  350. {
  351. m_entityTransferStateMachine.UpdateInTransit(client.AgentId, AgentTransferState.Cancelling);
  352. m_log.DebugFormat(
  353. "[ENTITY TRANSFER MODULE]: Received teleport cancel request from {0} in {1}", client.Name, m_sceneName);
  354. }
  355. // Attempt to teleport the ScenePresence to the specified position in the specified region (spec'ed by its handle).
  356. public void Teleport(ScenePresence sp, ulong regionHandle, Vector3 position, Vector3 lookAt, uint teleportFlags)
  357. {
  358. UUID spUUID = sp.UUID;
  359. if (m_scene.Permissions.IsGridGod(spUUID))
  360. {
  361. // This user will be a God in the destination scene, too
  362. teleportFlags |= (uint)TeleportFlags.Godlike;
  363. }
  364. else if (!m_scene.Permissions.CanTeleport(spUUID))
  365. return;
  366. string destinationRegionName = "(not found)";
  367. // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection
  368. // of whether the destination region completes the teleport.
  369. if (!m_entityTransferStateMachine.SetInTransit(spUUID))
  370. {
  371. m_log.DebugFormat(
  372. "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2}@{3} - agent is already in transit.",
  373. sp.Name, spUUID, position, regionHandle);
  374. sp.ControllingClient.SendTeleportFailed("Previous teleport process incomplete. Please retry shortly.");
  375. return;
  376. }
  377. try
  378. {
  379. if (Util.CompareRegionHandles(regionHandle, position, m_sceneRegionInfo, out Vector3 roffset))
  380. {
  381. if(!sp.AllowMovement)
  382. {
  383. sp.ControllingClient.SendTeleportFailed("You are frozen");
  384. m_entityTransferStateMachine.ResetFromTransit(spUUID);
  385. return;
  386. }
  387. destinationRegionName = m_sceneName;
  388. TeleportAgentWithinRegion(sp, roffset, lookAt, teleportFlags);
  389. }
  390. else // Another region possibly in another simulator
  391. {
  392. GridRegion finalDestination = null;
  393. try
  394. {
  395. TeleportAgentToDifferentRegion(sp, regionHandle, position, lookAt, teleportFlags, out finalDestination);
  396. }
  397. finally
  398. {
  399. if (finalDestination != null)
  400. destinationRegionName = finalDestination.RegionName;
  401. }
  402. }
  403. }
  404. catch (Exception e)
  405. {
  406. m_log.ErrorFormat(
  407. "[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
  408. sp.Name, sp.AbsolutePosition, m_sceneName, position, destinationRegionName,
  409. e.Message, e.StackTrace);
  410. if(sp != null && sp.ControllingClient != null && !sp.IsDeleted)
  411. sp.ControllingClient.SendTeleportFailed("Internal error");
  412. }
  413. finally
  414. {
  415. m_entityTransferStateMachine.ResetFromTransit(spUUID);
  416. }
  417. }
  418. /// <summary>
  419. /// Teleports the agent within its current region.
  420. /// </summary>
  421. /// <param name="sp"></param>
  422. /// <param name="position"></param>
  423. /// <param name="lookAt"></param>
  424. /// <param name="teleportFlags"></param>
  425. private void TeleportAgentWithinRegion(ScenePresence sp, Vector3 position, Vector3 lookAt, uint teleportFlags)
  426. {
  427. m_log.DebugFormat(
  428. "[ENTITY TRANSFER MODULE]: Teleport for {0} to {1} within {2}",
  429. sp.Name, position, m_sceneName);
  430. // Teleport within the same region
  431. if (!m_scene.PositionIsInCurrentRegion(position) || position.Z < 0)
  432. {
  433. Vector3 emergencyPos = new Vector3(128, 128, 128);
  434. m_log.WarnFormat(
  435. "[ENTITY TRANSFER MODULE]: RequestTeleportToLocation() was given an illegal position of {0} for avatar {1}, {2} in {3}. Substituting {4}",
  436. position, sp.Name, sp.UUID, m_sceneName, emergencyPos);
  437. position = emergencyPos;
  438. }
  439. // Check Default Location (Also See ScenePresence.CompleteMovement)
  440. if (position.X == 128f && position.Y == 128f && position.Z == 22.5f)
  441. position = m_sceneRegionInfo.DefaultLandingPoint;
  442. // TODO: Get proper AVG Height
  443. float localHalfAVHeight = 0.8f;
  444. if (sp.Appearance != null)
  445. localHalfAVHeight = sp.Appearance.AvatarHeight / 2;
  446. float posZLimit = 22;
  447. // TODO: Check other Scene HeightField
  448. posZLimit = m_scene.Heightmap[(int)position.X, (int)position.Y];
  449. posZLimit += localHalfAVHeight + 0.1f;
  450. if ((position.Z < posZLimit) && !(Single.IsInfinity(posZLimit) || Single.IsNaN(posZLimit)))
  451. {
  452. position.Z = posZLimit;
  453. }
  454. /*
  455. if(!sp.CheckLocalTPLandingPoint(ref position))
  456. {
  457. sp.ControllingClient.SendTeleportFailed("Not allowed at destination");
  458. return;
  459. }
  460. */
  461. if (sp.Flying)
  462. teleportFlags |= (uint)TeleportFlags.IsFlying;
  463. UUID spUUID = sp.UUID;
  464. m_entityTransferStateMachine.UpdateInTransit(spUUID, AgentTransferState.Transferring);
  465. sp.ControllingClient.SendTeleportStart(teleportFlags);
  466. lookAt.Z = 0f;
  467. if(Math.Abs(lookAt.X) < 0.01f && Math.Abs(lookAt.Y) < 0.01f)
  468. {
  469. lookAt.X = 1.0f;
  470. lookAt.Y = 0;
  471. }
  472. sp.ControllingClient.SendLocalTeleport(position, lookAt, teleportFlags);
  473. sp.TeleportFlags = (Constants.TeleportFlags)teleportFlags;
  474. sp.RotateToLookAt(lookAt);
  475. sp.Velocity = Vector3.Zero;
  476. sp.Teleport(position);
  477. m_entityTransferStateMachine.UpdateInTransit(spUUID, AgentTransferState.ReceivedAtDestination);
  478. foreach (SceneObjectGroup grp in sp.GetAttachments())
  479. {
  480. if ((grp.ScriptEvents & scriptEvents.changed) != 0)
  481. m_scene.EventManager.TriggerOnScriptChangedEvent(grp.LocalId, (uint)Changed.TELEPORT);
  482. }
  483. m_entityTransferStateMachine.UpdateInTransit(spUUID, AgentTransferState.CleaningUp);
  484. }
  485. /// <summary>
  486. /// Teleports the agent to a different region.
  487. /// </summary>
  488. /// <param name='sp'></param>
  489. /// <param name='regionHandle'>/param>
  490. /// <param name='position'></param>
  491. /// <param name='lookAt'></param>
  492. /// <param name='teleportFlags'></param>
  493. /// <param name='finalDestination'></param>
  494. private void TeleportAgentToDifferentRegion(
  495. ScenePresence sp, ulong regionHandle, Vector3 position,
  496. Vector3 lookAt, uint teleportFlags, out GridRegion finalDestination)
  497. {
  498. // Get destination region taking into account that the address could be an offset
  499. // region inside a varregion.
  500. GridRegion reg = GetTeleportDestinationRegion(m_scene.GridService, m_sceneRegionInfo.ScopeID, regionHandle, ref position);
  501. if( reg == null)
  502. {
  503. finalDestination = null;
  504. // TP to a place that doesn't exist (anymore)
  505. // Inform the viewer about that
  506. sp.ControllingClient.SendTeleportFailed("The region you tried to teleport to was not found");
  507. // and set the map-tile to '(Offline)'
  508. uint regX, regY;
  509. Util.RegionHandleToRegionLoc(regionHandle, out regX, out regY);
  510. MapBlockData block = new MapBlockData();
  511. block.X = (ushort)(regX);
  512. block.Y = (ushort)(regY);
  513. block.Access = (byte)SimAccess.Down; // == not there
  514. List<MapBlockData> blocks = new List<MapBlockData>();
  515. blocks.Add(block);
  516. sp.ControllingClient.SendMapBlock(blocks, 0);
  517. return;
  518. }
  519. string homeURI = m_scene.GetAgentHomeURI(sp.ControllingClient.AgentId);
  520. string reason = String.Empty;
  521. finalDestination = GetFinalDestination(reg, sp.ControllingClient.AgentId, homeURI, out reason);
  522. if (finalDestination == null)
  523. {
  524. m_log.WarnFormat( "{0} Unable to teleport {1} {2}: {3}",
  525. LogHeader, sp.Name, sp.UUID, reason);
  526. sp.ControllingClient.SendTeleportFailed(reason);
  527. return;
  528. }
  529. if (!ValidateGenericConditions(sp, reg, finalDestination, teleportFlags, out reason))
  530. {
  531. sp.ControllingClient.SendTeleportFailed(reason);
  532. return;
  533. }
  534. //
  535. // This is it
  536. //
  537. DoTeleportInternal(sp, reg, finalDestination, position, lookAt, teleportFlags);
  538. }
  539. // The teleport address could be an address in a subregion of a larger varregion.
  540. // Find the real base region and adjust the teleport location to account for the
  541. // larger region.
  542. private GridRegion GetTeleportDestinationRegion(IGridService gridService, UUID scope, ulong regionHandle, ref Vector3 position)
  543. {
  544. uint x = 0, y = 0;
  545. Util.RegionHandleToWorldLoc(regionHandle, out x, out y);
  546. GridRegion reg;
  547. // handle legacy HG. linked regions are mapped into y = 0 and have no size information
  548. // so we can only search by base handle
  549. if( y == 0)
  550. {
  551. reg = gridService.GetRegionByPosition(scope, (int)x, (int)y);
  552. return reg;
  553. }
  554. // Compute the world location we're teleporting to
  555. double worldX = (double)x + position.X;
  556. double worldY = (double)y + position.Y;
  557. // Find the region that contains the position
  558. reg = GetRegionContainingWorldLocation(gridService, scope, worldX, worldY);
  559. if (reg != null)
  560. {
  561. // modify the position for the offset into the actual region returned
  562. position.X += x - reg.RegionLocX;
  563. position.Y += y - reg.RegionLocY;
  564. }
  565. return reg;
  566. }
  567. // Nothing to validate here
  568. protected virtual bool ValidateGenericConditions(ScenePresence sp, GridRegion reg, GridRegion finalDestination, uint teleportFlags, out string reason)
  569. {
  570. reason = string.Empty;
  571. return true;
  572. }
  573. /// <summary>
  574. /// Wraps DoTeleportInternal() and manages the transfer state.
  575. /// </summary>
  576. public void DoTeleport(
  577. ScenePresence sp, GridRegion reg, GridRegion finalDestination,
  578. Vector3 position, Vector3 lookAt, uint teleportFlags)
  579. {
  580. // Record that this agent is in transit so that we can prevent simultaneous requests and do later detection
  581. // of whether the destination region completes the teleport.
  582. if (!m_entityTransferStateMachine.SetInTransit(sp.UUID))
  583. {
  584. m_log.DebugFormat(
  585. "[ENTITY TRANSFER MODULE]: Ignoring teleport request of {0} {1} to {2} ({3}) {4}/{5} - agent is already in transit.",
  586. sp.Name, sp.UUID, reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
  587. sp.ControllingClient.SendTeleportFailed("Agent is already in transit.");
  588. return;
  589. }
  590. try
  591. {
  592. DoTeleportInternal(sp, reg, finalDestination, position, lookAt, teleportFlags);
  593. }
  594. catch (Exception e)
  595. {
  596. m_log.ErrorFormat(
  597. "[ENTITY TRANSFER MODULE]: Exception on teleport of {0} from {1}@{2} to {3}@{4}: {5}{6}",
  598. sp.Name, sp.AbsolutePosition, m_sceneName, position, finalDestination.RegionName,
  599. e.Message, e.StackTrace);
  600. sp.ControllingClient.SendTeleportFailed("Internal error");
  601. }
  602. finally
  603. {
  604. m_entityTransferStateMachine.ResetFromTransit(sp.UUID);
  605. }
  606. }
  607. /// <summary>
  608. /// Teleports the agent to another region.
  609. /// This method doesn't manage the transfer state; the caller must do that.
  610. /// </summary>
  611. private void DoTeleportInternal(
  612. ScenePresence sp, GridRegion reg, GridRegion finalDestination,
  613. Vector3 position, Vector3 lookAt, uint teleportFlags)
  614. {
  615. if (reg == null || finalDestination == null)
  616. {
  617. sp.ControllingClient.SendTeleportFailed("Unable to locate destination");
  618. return;
  619. }
  620. string homeURI = m_scene.GetAgentHomeURI(sp.ControllingClient.AgentId);
  621. m_log.DebugFormat(
  622. "[ENTITY TRANSFER MODULE]: Teleporting {0} {1} from {2} to {3} ({4}) {5}/{6}",
  623. sp.Name, sp.UUID, m_sceneName,
  624. reg.ServerURI, finalDestination.ServerURI, finalDestination.RegionName, position);
  625. ulong destinationHandle = finalDestination.RegionHandle;
  626. if(destinationHandle == m_sceneRegionHandler)
  627. {
  628. sp.ControllingClient.SendTeleportFailed("Can't teleport to a region on same map position. Try going to another region first, then retry from there");
  629. return;
  630. }
  631. // Let's do DNS resolution only once in this process, please!
  632. // This may be a costly operation. The reg.ExternalEndPoint field is not a passive field,
  633. // it's actually doing a lot of work.
  634. IPEndPoint endPoint = finalDestination.ExternalEndPoint;
  635. if (endPoint == null || endPoint.Address == null)
  636. {
  637. sp.ControllingClient.SendTeleportFailed("Could not resolve destination Address");
  638. return;
  639. }
  640. if (!sp.ValidateAttachments())
  641. m_log.DebugFormat(
  642. "[ENTITY TRANSFER MODULE]: Failed validation of all attachments for teleport of {0} from {1} to {2}. Continuing.",
  643. sp.Name, sp.Scene.Name, finalDestination.RegionName);
  644. string reason;
  645. EntityTransferContext ctx = new EntityTransferContext();
  646. if (!m_scene.SimulationService.QueryAccess(
  647. finalDestination, sp.UUID, homeURI, true, position, m_scene.GetFormatsOffered(), ctx, out reason))
  648. {
  649. sp.ControllingClient.SendTeleportFailed(reason);
  650. m_log.DebugFormat(
  651. "[ENTITY TRANSFER MODULE]: {0} was stopped from teleporting from {1} to {2} because: {3}",
  652. sp.Name, sp.Scene.Name, finalDestination.RegionName, reason);
  653. return;
  654. }
  655. if (!sp.Appearance.CanTeleport(ctx.OutboundVersion))
  656. {
  657. sp.ControllingClient.SendTeleportFailed(OutfitTPError);
  658. m_log.DebugFormat(
  659. "[ENTITY TRANSFER MODULE]: {0} was stopped from teleporting from {1} to {2} because: {3}",
  660. sp.Name, sp.Scene.Name, finalDestination.RegionName, "incompatible wearable");
  661. return;
  662. }
  663. // Before this point, teleport 'failure' is due to checkable pre-conditions such as whether the target
  664. // simulator can be found and is explicitly prepared to allow access. Therefore, we will not count these
  665. // as server attempts.
  666. m_interRegionTeleportAttempts.Value++;
  667. m_log.DebugFormat(
  668. "[ENTITY TRANSFER MODULE]: {0} transfer protocol version to {1} is {2} / {3}",
  669. sp.Scene.Name, finalDestination.RegionName, ctx.OutboundVersion, ctx.InboundVersion);
  670. // Fixing a bug where teleporting while sitting results in the avatar ending up removed from
  671. // both regions
  672. if (sp.IsSitting)
  673. sp.StandUp();
  674. else if (sp.Flying)
  675. teleportFlags |= (uint)TeleportFlags.IsFlying;
  676. sp.IsInLocalTransit = reg.RegionLocY != 0; // HG
  677. sp.IsInTransit = true;
  678. if (DisableInterRegionTeleportCancellation)
  679. teleportFlags |= (uint)TeleportFlags.DisableCancel;
  680. // At least on LL 3.3.4, this is not strictly necessary - a teleport will succeed without sending this to
  681. // the viewer. However, it might mean that the viewer does not see the black teleport screen (untested).
  682. sp.ControllingClient.SendTeleportStart(teleportFlags);
  683. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  684. AgentCircuitData agentCircuit = sp.ControllingClient.RequestClientInfo();
  685. agentCircuit.startpos = position;
  686. agentCircuit.child = true;
  687. agentCircuit.Appearance = new AvatarAppearance();
  688. agentCircuit.Appearance.AvatarHeight = sp.Appearance.AvatarHeight;
  689. if (currentAgentCircuit != null)
  690. {
  691. agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
  692. agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
  693. agentCircuit.Viewer = currentAgentCircuit.Viewer;
  694. agentCircuit.Channel = currentAgentCircuit.Channel;
  695. agentCircuit.Mac = currentAgentCircuit.Mac;
  696. agentCircuit.Id0 = currentAgentCircuit.Id0;
  697. }
  698. uint newRegionX, newRegionY;
  699. Util.RegionHandleToRegionLoc(destinationHandle, out newRegionX, out newRegionY);
  700. int oldSizeX = (int)m_sceneRegionInfo.RegionSizeX;
  701. int oldSizeY = (int)m_sceneRegionInfo.RegionSizeY;
  702. int newSizeX = finalDestination.RegionSizeX;
  703. int newSizeY = finalDestination.RegionSizeY;
  704. bool OutSideViewRange = !sp.IsInLocalTransit || NeedsNewAgent(sp.RegionViewDistance,
  705. m_sceneRegionInfo.RegionLocX, newRegionX, m_sceneRegionInfo.RegionLocY, newRegionY,
  706. oldSizeX, oldSizeY, newSizeX, newSizeY);
  707. if (OutSideViewRange)
  708. {
  709. m_log.DebugFormat(
  710. "[ENTITY TRANSFER MODULE]: Determined that region {0} at {1},{2} size {3},{4} needs new child agent for agent {5} from {6}",
  711. finalDestination.RegionName, newRegionX, newRegionY,newSizeX, newSizeY, sp.Name, m_sceneName);
  712. //sp.ControllingClient.SendTeleportProgress(teleportFlags, "Creating agent...");
  713. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  714. }
  715. else
  716. {
  717. agentCircuit.CapsPath = sp.Scene.CapsModule.GetChildSeed(sp.UUID, reg.RegionHandle);
  718. if (agentCircuit.CapsPath == null)
  719. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  720. }
  721. // We're going to fallback to V1 if the destination gives us anything smaller than 0.2
  722. if (ctx.OutboundVersion >= 0.2f)
  723. TransferAgent_V2(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, OutSideViewRange, lookAt, ctx, out reason);
  724. else
  725. TransferAgent_V1(sp, agentCircuit, reg, finalDestination, endPoint, teleportFlags, OutSideViewRange, lookAt, ctx, out reason);
  726. }
  727. private void TransferAgent_V1(ScenePresence sp, AgentCircuitData agentCircuit, GridRegion reg, GridRegion finalDestination,
  728. IPEndPoint endPoint, uint teleportFlags, bool OutSideViewRange, Vector3 lookAt, EntityTransferContext ctx, out string reason)
  729. {
  730. ulong destinationHandle = finalDestination.RegionHandle;
  731. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  732. m_log.DebugFormat(
  733. "[ENTITY TRANSFER MODULE]: Using TP V1 for {0} going from {1} to {2}",
  734. sp.Name, m_sceneName, finalDestination.RegionName);
  735. string capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  736. List<ulong> childRegionsToClose = sp.GetChildAgentsToClose(destinationHandle, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  737. if(agentCircuit.ChildrenCapSeeds != null)
  738. {
  739. foreach(ulong handler in childRegionsToClose)
  740. {
  741. agentCircuit.ChildrenCapSeeds.Remove(handler);
  742. }
  743. }
  744. // Let's create an agent there if one doesn't exist yet.
  745. // NOTE: logout will always be false for a non-HG teleport.
  746. bool logout = false;
  747. if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, ctx, out reason, out logout))
  748. {
  749. m_interRegionTeleportFailures.Value++;
  750. m_log.DebugFormat(
  751. "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}",
  752. sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason);
  753. sp.ControllingClient.SendTeleportFailed(reason);
  754. sp.IsInTransit = false;
  755. return;
  756. }
  757. UUID spUUID = sp.UUID;
  758. if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Cancelling)
  759. {
  760. m_interRegionTeleportCancels.Value++;
  761. m_log.DebugFormat(
  762. "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after CreateAgent on client request",
  763. sp.Name, finalDestination.RegionName, m_sceneName);
  764. sp.IsInTransit = false;
  765. return;
  766. }
  767. else if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Aborting)
  768. {
  769. m_interRegionTeleportAborts.Value++;
  770. m_log.DebugFormat(
  771. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after CreateAgent due to previous client close.",
  772. sp.Name, finalDestination.RegionName, m_sceneName);
  773. sp.IsInTransit = false;
  774. return;
  775. }
  776. // Past this point we have to attempt clean up if the teleport fails, so update transfer state.
  777. m_entityTransferStateMachine.UpdateInTransit(spUUID, AgentTransferState.Transferring);
  778. // OK, it got this agent. Let's close some child agents
  779. if (OutSideViewRange)
  780. {
  781. if (m_eqModule != null)
  782. {
  783. // The EnableSimulator message makes the client establish a connection with the destination
  784. // simulator by sending the initial UseCircuitCode UDP packet to the destination containing the
  785. // correct circuit code.
  786. m_eqModule.EnableSimulator(destinationHandle, endPoint, spUUID,
  787. finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  788. m_log.DebugFormat("{0} Sent EnableSimulator. regName={1}, size=<{2},{3}>", LogHeader,
  789. finalDestination.RegionName, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  790. // XXX: Is this wait necessary? We will always end up waiting on UpdateAgent for the destination
  791. // simulator to confirm that it has established communication with the viewer.
  792. Thread.Sleep(200);
  793. // At least on LL 3.3.4 for teleports between different regions on the same simulator this appears
  794. // unnecessary - teleport will succeed and SEED caps will be requested without it (though possibly
  795. // only on TeleportFinish). This is untested for region teleport between different simulators
  796. // though this probably also works.
  797. m_eqModule.EstablishAgentCommunication(spUUID, endPoint, capsPath, finalDestination.RegionHandle,
  798. finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  799. }
  800. else
  801. {
  802. // XXX: This is a little misleading since we're information the client of its avatar destination,
  803. // which may or may not be a neighbour region of the source region. This path is probably little
  804. // used anyway (with EQ being the one used). But it is currently being used for test code.
  805. sp.ControllingClient.InformClientOfNeighbour(destinationHandle, endPoint);
  806. }
  807. }
  808. // Let's send a full update of the agent. This is a synchronous call.
  809. AgentData agent = new AgentData();
  810. sp.CopyTo(agent,false);
  811. agent.SetLookAt(lookAt);
  812. if ((teleportFlags & (uint)TeleportFlags.IsFlying) != 0)
  813. agent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  814. agent.Position = agentCircuit.startpos;
  815. SetCallbackURL(agent);
  816. // We will check for an abort before UpdateAgent since UpdateAgent will require an active viewer to
  817. // establish th econnection to the destination which makes it return true.
  818. if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Aborting)
  819. {
  820. m_interRegionTeleportAborts.Value++;
  821. m_log.DebugFormat(
  822. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} before UpdateAgent",
  823. sp.Name, finalDestination.RegionName, m_sceneName);
  824. sp.IsInTransit = false;
  825. return;
  826. }
  827. // A common teleport failure occurs when we can send CreateAgent to the
  828. // destination region but the viewer cannot establish the connection (e.g. due to network issues between
  829. // the viewer and the destination). In this case, UpdateAgent timesout after 10 seconds, although then
  830. // there's a further 10 second wait whilst we attempt to tell the destination to delete the agent in Fail().
  831. if (!UpdateAgent(reg, finalDestination, agent, sp, ctx))
  832. {
  833. if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Aborting)
  834. {
  835. m_interRegionTeleportAborts.Value++;
  836. m_log.DebugFormat(
  837. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after UpdateAgent due to previous client close.",
  838. sp.Name, finalDestination.RegionName, m_sceneName);
  839. sp.IsInTransit = false;
  840. return;
  841. }
  842. m_log.WarnFormat(
  843. "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
  844. sp.Name, finalDestination.RegionName, m_sceneName);
  845. Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
  846. sp.IsInTransit = false;
  847. return;
  848. }
  849. if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Cancelling)
  850. {
  851. m_interRegionTeleportCancels.Value++;
  852. m_log.DebugFormat(
  853. "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after UpdateAgent on client request",
  854. sp.Name, finalDestination.RegionName, m_sceneName);
  855. CleanupFailedInterRegionTeleport(sp, currentAgentCircuit.SessionID.ToString(), finalDestination);
  856. sp.IsInTransit = false;
  857. return;
  858. }
  859. m_log.DebugFormat(
  860. "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}",
  861. capsPath, m_sceneName, sp.Name);
  862. // We need to set this here to avoid an unlikely race condition when teleporting to a neighbour simulator,
  863. // where that neighbour simulator could otherwise request a child agent create on the source which then
  864. // closes our existing agent which is still signalled as root.
  865. sp.IsChildAgent = true;
  866. // OK, send TPFinish to the client, so that it starts the process of contacting the destination region
  867. if (m_eqModule != null)
  868. {
  869. m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, spUUID,
  870. finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  871. }
  872. else
  873. {
  874. sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
  875. teleportFlags, capsPath);
  876. }
  877. // TeleportFinish makes the client send CompleteMovementIntoRegion (at the destination), which
  878. // trigers a whole shebang of things there, including MakeRoot. So let's wait for confirmation
  879. // that the client contacted the destination before we close things here.
  880. if (!m_entityTransferStateMachine.WaitForAgentArrivedAtDestination(spUUID))
  881. {
  882. if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Aborting)
  883. {
  884. m_interRegionTeleportAborts.Value++;
  885. m_log.DebugFormat(
  886. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after WaitForAgentArrivedAtDestination due to previous client close.",
  887. sp.Name, finalDestination.RegionName, m_sceneName);
  888. sp.IsInTransit = false;
  889. return;
  890. }
  891. m_log.WarnFormat(
  892. "[ENTITY TRANSFER MODULE]: Teleport of {0} to {1} from {2} failed due to no callback from destination region. Returning avatar to source region.",
  893. sp.Name, finalDestination.RegionName, m_sceneName);
  894. Fail(sp, finalDestination, logout, currentAgentCircuit.SessionID.ToString(), "Destination region did not signal teleport completion.");
  895. sp.IsInTransit = false;
  896. return;
  897. }
  898. m_entityTransferStateMachine.UpdateInTransit(spUUID, AgentTransferState.CleaningUp);
  899. if(logout)
  900. sp.closeAllChildAgents();
  901. else
  902. sp.CloseChildAgents(childRegionsToClose);
  903. // call HG hook
  904. AgentHasMovedAway(sp, logout);
  905. sp.HasMovedAway(!(OutSideViewRange || logout));
  906. // Now let's make it officially a child agent
  907. sp.MakeChildAgent(destinationHandle);
  908. // Finally, let's close this previously-known-as-root agent, when the jump is outside the view zone
  909. if (NeedsClosing(reg, OutSideViewRange))
  910. {
  911. if (!m_scene.IncomingPreCloseClient(sp))
  912. return;
  913. // We need to delay here because Imprudence viewers, unlike v1 or v3, have a short (<200ms, <500ms) delay before
  914. // they regard the new region as the current region after receiving the AgentMovementComplete
  915. // response. If close is sent before then, it will cause the viewer to quit instead.
  916. //
  917. // This sleep can be increased if necessary. However, whilst it's active,
  918. // an agent cannot teleport back to this region if it has teleported away.
  919. Thread.Sleep(2000);
  920. m_scene.CloseAgent(sp.UUID, false);
  921. }
  922. sp.IsInTransit = false;
  923. }
  924. private void TransferAgent_V2(ScenePresence sp, AgentCircuitData agentCircuit, GridRegion reg, GridRegion finalDestination,
  925. IPEndPoint endPoint, uint teleportFlags, bool OutSideViewRange, Vector3 lookAt, EntityTransferContext ctx, out string reason)
  926. {
  927. ulong destinationHandle = finalDestination.RegionHandle;
  928. List<ulong> childRegionsToClose = null;
  929. // HG needs a deeper change
  930. bool localclose = (ctx.OutboundVersion < 0.7f || !sp.IsInLocalTransit);
  931. if (localclose)
  932. {
  933. childRegionsToClose = sp.GetChildAgentsToClose(destinationHandle, finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  934. if(agentCircuit.ChildrenCapSeeds != null)
  935. {
  936. foreach(ulong handler in childRegionsToClose)
  937. {
  938. agentCircuit.ChildrenCapSeeds.Remove(handler);
  939. }
  940. }
  941. }
  942. if (OutSideViewRange && agentCircuit.ChildrenCapSeeds != null)
  943. agentCircuit.ChildrenCapSeeds.Remove(sp.RegionHandle);
  944. string capsPath = finalDestination.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);;
  945. // Let's create an agent there if one doesn't exist yet.
  946. // NOTE: logout will always be false for a non-HG teleport.
  947. bool logout = false;
  948. if (!CreateAgent(sp, reg, finalDestination, agentCircuit, teleportFlags, ctx, out reason, out logout))
  949. {
  950. m_interRegionTeleportFailures.Value++;
  951. m_log.DebugFormat(
  952. "[ENTITY TRANSFER MODULE]: Teleport of {0} from {1} to {2} was refused because {3}",
  953. sp.Name, sp.Scene.RegionInfo.RegionName, finalDestination.RegionName, reason);
  954. sp.ControllingClient.SendTeleportFailed(reason);
  955. sp.IsInTransit = false;
  956. return;
  957. }
  958. UUID spUUID = sp.UUID;
  959. if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Cancelling)
  960. {
  961. m_interRegionTeleportCancels.Value++;
  962. m_log.DebugFormat(
  963. "[ENTITY TRANSFER MODULE]: Cancelled teleport of {0} to {1} from {2} after CreateAgent on client request",
  964. sp.Name, finalDestination.RegionName, m_sceneName);
  965. sp.IsInTransit = false;
  966. return;
  967. }
  968. else if (m_entityTransferStateMachine.GetAgentTransferState(spUUID) == AgentTransferState.Aborting)
  969. {
  970. m_interRegionTeleportAborts.Value++;
  971. m_log.DebugFormat(
  972. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after CreateAgent due to previous client close.",
  973. sp.Name, finalDestination.RegionName, m_sceneName);
  974. sp.IsInTransit = false;
  975. return;
  976. }
  977. // Past this point we have to attempt clean up if the teleport fails, so update transfer state.
  978. m_entityTransferStateMachine.UpdateInTransit(spUUID, AgentTransferState.Transferring);
  979. // We need to set this here to avoid an unlikely race condition when teleporting to a neighbour simulator,
  980. // where that neighbour simulator could otherwise request a child agent create on the source which then
  981. // closes our existing agent which is still signalled as root.
  982. //sp.IsChildAgent = true;
  983. // New protocol: send TP Finish directly, without prior ES or EAC. That's what happens in the Linden grid
  984. if (m_eqModule != null)
  985. m_eqModule.TeleportFinishEvent(destinationHandle, 13, endPoint, 0, teleportFlags, capsPath, sp.UUID,
  986. finalDestination.RegionSizeX, finalDestination.RegionSizeY);
  987. else
  988. sp.ControllingClient.SendRegionTeleport(destinationHandle, 13, endPoint, 4,
  989. teleportFlags, capsPath);
  990. m_log.DebugFormat(
  991. "[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} from {1} to {2}",
  992. capsPath, m_sceneName, sp.Name);
  993. // Let's send a full update of the agent.
  994. AgentData agent = new AgentData();
  995. sp.CopyTo(agent,false);
  996. agent.SetLookAt(lookAt);
  997. agent.Position = agentCircuit.startpos;
  998. if ((teleportFlags & (uint)TeleportFlags.IsFlying) != 0)
  999. agent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  1000. agent.SenderWantsToWaitForRoot = true;
  1001. if(OutSideViewRange)
  1002. SetNewCallbackURL(agent);
  1003. // Reset the do not close flag. This must be done before the destination opens child connections (here
  1004. // triggered by UpdateAgent) to avoid race conditions. However, we also want to reset it as late as possible
  1005. // to avoid a situation where an unexpectedly early call to Scene.NewUserConnection() wrongly results
  1006. // in no close.
  1007. sp.DoNotCloseAfterTeleport = false;
  1008. // we still need to flag this as child here
  1009. // a close from receiving region seems possible to happen before we reach sp.MakeChildAgent below
  1010. // causing the agent to be loggout out from grid incorrectly
  1011. sp.IsChildAgent = true;
  1012. // Send the Update. If this returns true, we know the client has contacted the destination
  1013. // via CompleteMovementIntoRegion, so we can let go.
  1014. // If it returns false, something went wrong, and we need to abort.
  1015. if (!UpdateAgent(reg, finalDestination, agent, sp, ctx))
  1016. {
  1017. sp.IsChildAgent = false;
  1018. if (m_entityTransferStateMachine.GetAgentTransferState(sp.UUID) == AgentTransferState.Aborting)
  1019. {
  1020. m_interRegionTeleportAborts.Value++;
  1021. m_log.DebugFormat(
  1022. "[ENTITY TRANSFER MODULE]: Aborted teleport of {0} to {1} from {2} after UpdateAgent due to previous client close.",
  1023. sp.Name, finalDestination.RegionName, m_sceneName);
  1024. sp.IsInTransit = false;
  1025. return;
  1026. }
  1027. m_log.WarnFormat(
  1028. "[ENTITY TRANSFER MODULE]: UpdateAgent failed on teleport of {0} to {1}. Keeping avatar in {2}",
  1029. sp.Name, finalDestination.RegionName, m_sceneName);
  1030. Fail(sp, finalDestination, logout, agentCircuit.SessionID.ToString(), "Connection between viewer and destination region could not be established.");
  1031. sp.IsInTransit = false;
  1032. return;
  1033. }
  1034. //shut this up for now
  1035. m_entityTransferStateMachine.ResetFromTransit(spUUID);
  1036. //m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
  1037. sp.HasMovedAway(!(OutSideViewRange || logout));
  1038. //HG hook
  1039. AgentHasMovedAway(sp, logout);
  1040. // Now let's make it officially a child agent
  1041. sp.MakeChildAgent(destinationHandle);
  1042. if(localclose)
  1043. {
  1044. if (logout)
  1045. sp.closeAllChildAgents();
  1046. else
  1047. sp.CloseChildAgents(childRegionsToClose);
  1048. }
  1049. // if far jump we do need to close anyways
  1050. if (NeedsClosing(reg, OutSideViewRange))
  1051. {
  1052. int count = 60;
  1053. do
  1054. {
  1055. Thread.Sleep(250);
  1056. if(sp.IsDeleted)
  1057. return;
  1058. if(!sp.IsInTransit)
  1059. break;
  1060. } while (--count > 0);
  1061. if (!sp.IsDeleted)
  1062. {
  1063. m_log.DebugFormat(
  1064. "[ENTITY TRANSFER MODULE]: Closing agent {0} in {1} after teleport {2}", sp.Name, m_sceneName, sp.IsInTransit?"timeout":"");
  1065. m_scene.CloseAgent(spUUID, false);
  1066. }
  1067. return;
  1068. }
  1069. // otherwise keep child
  1070. sp.IsInTransit = false;
  1071. }
  1072. /// <summary>
  1073. /// Clean up an inter-region teleport that did not complete, either because of simulator failure or cancellation.
  1074. /// </summary>
  1075. /// <remarks>
  1076. /// All operations here must be idempotent so that we can call this method at any point in the teleport process
  1077. /// up until we send the TeleportFinish event quene event to the viewer.
  1078. /// <remarks>
  1079. /// <param name='sp'> </param>
  1080. /// <param name='finalDestination'></param>
  1081. protected virtual void CleanupFailedInterRegionTeleport(ScenePresence sp, string auth_token, GridRegion finalDestination)
  1082. {
  1083. m_entityTransferStateMachine.UpdateInTransit(sp.UUID, AgentTransferState.CleaningUp);
  1084. if (sp.IsChildAgent) // We had set it to child before attempted TP (V1)
  1085. {
  1086. sp.IsChildAgent = false;
  1087. ReInstantiateScripts(sp);
  1088. EnableChildAgents(sp);
  1089. }
  1090. // Finally, kill the agent we just created at the destination.
  1091. // XXX: Possibly this should be done asynchronously.
  1092. Scene.SimulationService.CloseAgent(finalDestination, sp.UUID, auth_token);
  1093. }
  1094. /// <summary>
  1095. /// Signal that the inter-region teleport failed and perform cleanup.
  1096. /// </summary>
  1097. /// <param name='sp'></param>
  1098. /// <param name='finalDestination'></param>
  1099. /// <param name='logout'></param>
  1100. /// <param name='reason'>Human readable reason for teleport failure. Will be sent to client.</param>
  1101. protected virtual void Fail(ScenePresence sp, GridRegion finalDestination, bool logout, string auth_code, string reason)
  1102. {
  1103. CleanupFailedInterRegionTeleport(sp, auth_code, finalDestination);
  1104. m_interRegionTeleportFailures.Value++;
  1105. sp.ControllingClient.SendTeleportFailed(
  1106. string.Format(
  1107. "Problems connecting to destination {0}, reason: {1}", finalDestination.RegionName, reason));
  1108. sp.Scene.EventManager.TriggerTeleportFail(sp.ControllingClient, logout);
  1109. }
  1110. protected virtual bool CreateAgent(ScenePresence sp, GridRegion reg, GridRegion finalDestination, AgentCircuitData agentCircuit, uint teleportFlags, EntityTransferContext ctx, out string reason, out bool logout)
  1111. {
  1112. GridRegion source = new GridRegion(m_sceneRegionInfo);
  1113. source.RawServerURI = m_thisGridInfo.GateKeeperURL;
  1114. logout = false;
  1115. bool success = m_scene.SimulationService.CreateAgent(source, finalDestination, agentCircuit, teleportFlags, ctx, out reason);
  1116. if (success)
  1117. sp.Scene.EventManager.TriggerTeleportStart(sp.ControllingClient, reg, finalDestination, teleportFlags, logout);
  1118. return success;
  1119. }
  1120. protected virtual bool UpdateAgent(GridRegion reg, GridRegion finalDestination, AgentData agent, ScenePresence sp, EntityTransferContext ctx)
  1121. {
  1122. return m_scene.SimulationService.UpdateAgent(finalDestination, agent, ctx);
  1123. }
  1124. protected virtual void SetCallbackURL(AgentData agent)
  1125. {
  1126. agent.CallbackURI = m_sceneRegionInfo.ServerURI + "agent/" + agent.AgentID.ToString() + "/" + m_sceneRegionInfo.RegionID.ToString() + "/release/";
  1127. //m_log.DebugFormat(
  1128. // "[ENTITY TRANSFER MODULE]: Set release callback URL to {0} in {1}",
  1129. // agent.CallbackURI, region.RegionName);
  1130. }
  1131. protected virtual void SetNewCallbackURL(AgentData agent)
  1132. {
  1133. agent.NewCallbackURI = m_sceneRegionInfo.ServerURI + "agent/" + agent.AgentID.ToString() + "/" + m_sceneRegionInfo.RegionID.ToString() + "/release/";
  1134. m_log.DebugFormat(
  1135. "[ENTITY TRANSFER MODULE]: Set release callback URL to {0} in {1}",
  1136. agent.NewCallbackURI, m_sceneName);
  1137. }
  1138. /// <summary>
  1139. /// Clean up operations once an agent has moved away through cross or teleport.
  1140. /// </summary>
  1141. /// <param name='sp'></param>
  1142. /// <param name='logout'></param>
  1143. ///
  1144. /// now just a HG hook
  1145. protected virtual void AgentHasMovedAway(ScenePresence sp, bool logout)
  1146. {
  1147. // if (sp.Scene.AttachmentsModule != null)
  1148. // sp.Scene.AttachmentsModule.DeleteAttachmentsFromScene(sp, logout);
  1149. }
  1150. protected void KillEntity(Scene scene, uint localID)
  1151. {
  1152. scene.SendKillObject(new List<uint> { localID });
  1153. }
  1154. // HG hook
  1155. protected virtual GridRegion GetFinalDestination(GridRegion region, UUID agentID, string agentHomeURI, out string message)
  1156. {
  1157. message = null;
  1158. return region;
  1159. }
  1160. // This returns 'true' if the new region already has a child agent for our
  1161. // incoming agent. The implication is that, if 'false', we have to create the
  1162. // child and then teleport into the region.
  1163. protected virtual bool NeedsNewAgent(float viewdist, uint oldRegionX, uint newRegionX, uint oldRegionY, uint newRegionY,
  1164. int oldsizeX, int oldsizeY, int newsizeX, int newsizeY)
  1165. {
  1166. return Util.IsOutsideView(viewdist, oldRegionX, newRegionX, oldRegionY, newRegionY,
  1167. oldsizeX, oldsizeY, newsizeX, newsizeY);
  1168. }
  1169. // HG Hook
  1170. protected virtual bool NeedsClosing(GridRegion reg, bool OutViewRange)
  1171. {
  1172. return OutViewRange;
  1173. }
  1174. #endregion
  1175. #region Landmark Teleport
  1176. /// <summary>
  1177. /// Tries to teleport agent to landmark.
  1178. /// </summary>
  1179. /// <param name="remoteClient"></param>
  1180. /// <param name="regionHandle"></param>
  1181. /// <param name="position"></param>
  1182. public void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm)
  1183. {
  1184. RequestTeleportLandmark(remoteClient, lm, Vector3.Zero);
  1185. }
  1186. public virtual void RequestTeleportLandmark(IClientAPI remoteClient, AssetLandmark lm, Vector3 lookAt)
  1187. {
  1188. if (lm == null || lm.Data == null || lm.Data.Length == 0)
  1189. return;
  1190. ScenePresence sp = m_scene.GetScenePresence(remoteClient.AgentId);
  1191. if (sp == null || sp.IsDeleted || sp.IsInTransit || sp.IsChildAgent || sp.IsNPC)
  1192. return;
  1193. GridRegion info = m_scene.GridService.GetRegionByUUID(UUID.Zero, lm.RegionID);
  1194. if (info == null)
  1195. {
  1196. // can't find the region: Tell viewer and abort
  1197. remoteClient.SendTeleportFailed("Landmark region not found");
  1198. return;
  1199. }
  1200. //check if region on same position and fix local offset
  1201. if (Util.CompareRegionHandles(lm.RegionHandle, lm.Position, info.RegionLocX, info.RegionLocY, info.RegionSizeX, info.RegionSizeY, out Vector3 offset))
  1202. {
  1203. m_scene.RequestTeleportLocation(remoteClient, info.RegionHandle, offset,
  1204. lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  1205. }
  1206. else //region may had move to other grid slot. assume the lm position is good
  1207. m_scene.RequestTeleportLocation(remoteClient, info.RegionHandle, lm.Position,
  1208. lookAt, (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaLandmark));
  1209. }
  1210. #endregion
  1211. #region Teleport Home
  1212. public virtual void TriggerTeleportHome(UUID id, IClientAPI client)
  1213. {
  1214. TeleportHome(id, client);
  1215. }
  1216. public virtual bool TeleportHome(UUID id, IClientAPI client)
  1217. {
  1218. bool notsame = false;
  1219. if (client == null)
  1220. {
  1221. m_log.DebugFormat(
  1222. "[ENTITY TRANSFER MODULE]: Request to teleport {0} home", id);
  1223. }
  1224. else
  1225. {
  1226. if (id.Equals(client.AgentId))
  1227. {
  1228. m_log.DebugFormat(
  1229. "[ENTITY TRANSFER MODULE]: Request to teleport {0} {1} home", client.Name, id);
  1230. }
  1231. else
  1232. {
  1233. notsame = true;
  1234. m_log.DebugFormat(
  1235. "[ENTITY TRANSFER MODULE]: Request to teleport {0} home by {1} {2}", id, client.Name, client.AgentId);
  1236. }
  1237. }
  1238. ScenePresence sp = ((Scene)(client.Scene)).GetScenePresence(id);
  1239. if (sp == null || sp.IsDeleted || sp.IsChildAgent || sp.ControllingClient == null || !sp.ControllingClient.IsActive)
  1240. {
  1241. if (notsame)
  1242. client.SendAlertMessage("TeleportHome: Agent not found in the scene");
  1243. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Agent not found in the scene where it is supposed to be");
  1244. return false;
  1245. }
  1246. IClientAPI targetClient = sp.ControllingClient;
  1247. if (sp.IsInTransit)
  1248. {
  1249. if (notsame)
  1250. client.SendAlertMessage("TeleportHome: Agent already processing a teleport");
  1251. targetClient.SendTeleportFailed("Already processing a teleport");
  1252. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Agent still in teleport");
  1253. return false;
  1254. }
  1255. //OpenSim.Services.Interfaces.PresenceInfo pinfo = Scene.PresenceService.GetAgent(client.SessionId);
  1256. GridUserInfo uinfo = m_scene.GridUserService.GetGridUserInfo(id.ToString());
  1257. if(uinfo == null)
  1258. {
  1259. m_log.ErrorFormat("[ENTITY TRANSFER MODULE] Griduser info not found for {1}. Cannot send home.", id);
  1260. if (notsame)
  1261. client.SendAlertMessage("TeleportHome: Agent home region not found");
  1262. targetClient.SendTeleportFailed("Your home region not found");
  1263. return false;
  1264. }
  1265. if (uinfo.HomeRegionID.IsZero())
  1266. {
  1267. // can't find the Home region: Tell viewer and abort
  1268. m_log.ErrorFormat("[ENTITY TRANSFER MODULE] no home set {0}", id);
  1269. if (notsame)
  1270. client.SendAlertMessage("TeleportHome: Agent home not set");
  1271. targetClient.SendTeleportFailed("Home set not");
  1272. return false;
  1273. }
  1274. GridRegion regionInfo = m_scene.GridService.GetRegionByUUID(UUID.Zero, uinfo.HomeRegionID);
  1275. if (regionInfo == null)
  1276. {
  1277. // can't find the Home region: Tell viewer and abort
  1278. m_log.ErrorFormat("[ENTITY TRANSFER MODULE] {0} home region {1} not found", id, uinfo.HomeRegionID);
  1279. if (notsame)
  1280. client.SendAlertMessage("TeleportHome: Agent home region not found");
  1281. targetClient.SendTeleportFailed("Home region not found");
  1282. return false;
  1283. }
  1284. Teleport(sp, regionInfo.RegionHandle, uinfo.HomePosition, uinfo.HomeLookAt,
  1285. (uint)(Constants.TeleportFlags.SetLastToTarget | Constants.TeleportFlags.ViaHome));
  1286. return true;
  1287. }
  1288. #endregion
  1289. #region Agent Crossings
  1290. public bool checkAgentAccessToRegion(ScenePresence agent, GridRegion destiny, Vector3 position,
  1291. EntityTransferContext ctx, out string reason)
  1292. {
  1293. reason = string.Empty;
  1294. UUID agentID = agent.UUID;
  1295. ulong destinyHandle = destiny.RegionHandle;
  1296. if (m_bannedRegionCache.IfBanned(destinyHandle, agentID))
  1297. return false;
  1298. string homeURI = m_scene.GetAgentHomeURI(agentID);
  1299. if (!m_scene.SimulationService.QueryAccess(destiny, agentID, homeURI, false, position,
  1300. m_scene.GetFormatsOffered(), ctx, out reason))
  1301. {
  1302. m_bannedRegionCache.Add(destinyHandle, agentID, 60.0);
  1303. return false;
  1304. }
  1305. if (!agent.Appearance.CanTeleport(ctx.OutboundVersion))
  1306. {
  1307. reason = OutfitTPError;
  1308. m_bannedRegionCache.Add(destinyHandle, agentID, 60.0);
  1309. return false;
  1310. }
  1311. return true;
  1312. }
  1313. // Given a position relative to the current region and outside of it
  1314. // find the new region that the point is actually in
  1315. // returns 'null' if new region not found or if agent as no access
  1316. // else also returns new target position in the new region local coords
  1317. // now only works for crossings
  1318. public GridRegion GetDestination(UUID agentID, Vector3 pos,
  1319. EntityTransferContext ctx, out Vector3 newpos, out string failureReason)
  1320. {
  1321. newpos = pos;
  1322. failureReason = string.Empty;
  1323. // m_log.DebugFormat(
  1324. // "[ENTITY TRANSFER MODULE]: Crossing agent {0} at pos {1} in {2}", agent.Name, pos, scene.Name);
  1325. // Compute world location of the agent's position
  1326. double presenceWorldX = (double)m_sceneRegionInfo.WorldLocX + pos.X;
  1327. double presenceWorldY = (double)m_sceneRegionInfo.WorldLocY + pos.Y;
  1328. // Call the grid service to lookup the region containing the new position.
  1329. GridRegion neighbourRegion = GetRegionContainingWorldLocation(
  1330. m_scene.GridService, m_sceneRegionInfo.ScopeID,
  1331. presenceWorldX, presenceWorldY);
  1332. if (neighbourRegion == null)
  1333. return null;
  1334. if(neighbourRegion.RegionFlags != null && (neighbourRegion.RegionFlags & OpenSim.Framework.RegionFlags.RegionOnline) == 0)
  1335. return null;
  1336. if (m_bannedRegionCache.IfBanned(neighbourRegion.RegionHandle, agentID))
  1337. {
  1338. failureReason = "Access Denied or Temporary not possible";
  1339. return null;
  1340. }
  1341. // Compute the entity's position relative to the new region
  1342. newpos = new Vector3((float)(presenceWorldX - neighbourRegion.RegionLocX),
  1343. (float)(presenceWorldY - neighbourRegion.RegionLocY),
  1344. pos.Z);
  1345. string homeURI = m_scene.GetAgentHomeURI(agentID);
  1346. if (!m_scene.SimulationService.QueryAccess(
  1347. neighbourRegion, agentID, homeURI, false, newpos,
  1348. m_scene.GetFormatsOffered(), ctx, out failureReason))
  1349. {
  1350. // remember the fail
  1351. m_bannedRegionCache.Add(neighbourRegion.RegionHandle, agentID, 60);
  1352. if(string.IsNullOrWhiteSpace(failureReason))
  1353. failureReason = "Access Denied";
  1354. return null;
  1355. }
  1356. return neighbourRegion;
  1357. }
  1358. public bool Cross(ScenePresence agent, bool isFlying)
  1359. {
  1360. ScenePresence ag = agent;
  1361. ag.IsInLocalTransit = true;
  1362. ag.IsInTransit = true;
  1363. WorkManager.RunInThreadPool(delegate
  1364. {
  1365. CrossAsync(ag, isFlying);
  1366. if (ag.IsDeleted)
  1367. return;
  1368. if (!ag.IsChildAgent)
  1369. {
  1370. // crossing failed
  1371. ag.CrossToNewRegionFail();
  1372. }
  1373. else
  1374. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", ag.Firstname, ag.Lastname);
  1375. ag.IsInTransit = false;
  1376. }, null,"AgentRegionCross-"+ag.UUID.ToString());
  1377. return true;
  1378. }
  1379. public ScenePresence CrossAsync(ScenePresence agent, bool isFlying)
  1380. {
  1381. if(agent.RegionViewDistance == 0)
  1382. return agent;
  1383. Vector3 newpos;
  1384. EntityTransferContext ctx = new EntityTransferContext();
  1385. string failureReason;
  1386. // We need this because of decimal number parsing of the protocols.
  1387. Culture.SetCurrentCulture();
  1388. Vector3 pos = agent.AbsolutePosition + agent.Velocity * 0.2f;
  1389. GridRegion neighbourRegion = GetDestination(agent.UUID, pos,
  1390. ctx, out newpos, out failureReason);
  1391. if (neighbourRegion == null)
  1392. {
  1393. if (!agent.IsDeleted && failureReason != String.Empty && agent.ControllingClient != null)
  1394. agent.ControllingClient.SendAlertMessage(failureReason);
  1395. return agent;
  1396. }
  1397. if (!agent.Appearance.CanTeleport(ctx.OutboundVersion))
  1398. {
  1399. if (agent.ControllingClient != null)
  1400. agent.ControllingClient.SendAlertMessage(OutfitTPError);
  1401. return agent;
  1402. }
  1403. //agent.IsInTransit = true;
  1404. CrossAgentToNewRegionAsync(agent, newpos, neighbourRegion, isFlying, ctx);
  1405. agent.IsInTransit = false;
  1406. return agent;
  1407. }
  1408. public bool CrossAgentCreateFarChild(ScenePresence agent, GridRegion neighbourRegion, Vector3 pos, EntityTransferContext ctx)
  1409. {
  1410. ulong regionhandler = neighbourRegion.RegionHandle;
  1411. if(agent.knowsNeighbourRegion(regionhandler))
  1412. return true;
  1413. string reason;
  1414. GridRegion source = new GridRegion(m_sceneRegionInfo);
  1415. AgentCircuitData currentAgentCircuit =
  1416. m_scene.AuthenticateHandler.GetAgentCircuitData(agent.ControllingClient.CircuitCode);
  1417. AgentCircuitData agentCircuit = agent.ControllingClient.RequestClientInfo();
  1418. agentCircuit.startpos = pos;
  1419. agentCircuit.child = true;
  1420. agentCircuit.Appearance = new AvatarAppearance();
  1421. agentCircuit.Appearance.AvatarHeight = agent.Appearance.AvatarHeight;
  1422. if (currentAgentCircuit != null)
  1423. {
  1424. agentCircuit.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1425. agentCircuit.IPAddress = currentAgentCircuit.IPAddress;
  1426. agentCircuit.Viewer = currentAgentCircuit.Viewer;
  1427. agentCircuit.Channel = currentAgentCircuit.Channel;
  1428. agentCircuit.Mac = currentAgentCircuit.Mac;
  1429. agentCircuit.Id0 = currentAgentCircuit.Id0;
  1430. }
  1431. agentCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1432. agent.AddNeighbourRegion(neighbourRegion, agentCircuit.CapsPath);
  1433. IPEndPoint endPoint = neighbourRegion.ExternalEndPoint;
  1434. if(endPoint == null)
  1435. {
  1436. m_log.DebugFormat("CrossAgentCreateFarChild failed to resolve neighbour address {0}", neighbourRegion.ExternalHostName);
  1437. return false;
  1438. }
  1439. if (!m_scene.SimulationService.CreateAgent(source, neighbourRegion, agentCircuit, (int)TeleportFlags.Default, ctx, out reason))
  1440. {
  1441. agent.RemoveNeighbourRegion(regionhandler);
  1442. return false;
  1443. }
  1444. string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentCircuit.CapsPath);
  1445. int newSizeX = neighbourRegion.RegionSizeX;
  1446. int newSizeY = neighbourRegion.RegionSizeY;
  1447. if (m_eqModule != null)
  1448. {
  1449. m_log.DebugFormat("{0} {1} is sending {2} EnableSimulator for neighbour region {3}(loc=<{4},{5}>,siz=<{6},{7}>) " +
  1450. "and EstablishAgentCommunication with seed cap {8}", LogHeader,
  1451. source.RegionName, agent.Name,
  1452. neighbourRegion.RegionName, neighbourRegion.RegionLocX, neighbourRegion.RegionLocY, newSizeX, newSizeY , capsPath);
  1453. m_eqModule.EnableSimulator(regionhandler,
  1454. endPoint, agent.UUID, newSizeX, newSizeY);
  1455. m_eqModule.EstablishAgentCommunication(agent.UUID, endPoint, capsPath,
  1456. regionhandler, newSizeX, newSizeY);
  1457. }
  1458. else
  1459. {
  1460. agent.ControllingClient.InformClientOfNeighbour(regionhandler, endPoint);
  1461. }
  1462. return true;
  1463. }
  1464. /// <summary>
  1465. /// This Closes child agents on neighbouring regions
  1466. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  1467. /// </summary>
  1468. public ScenePresence CrossAgentToNewRegionAsync(
  1469. ScenePresence agent, Vector3 pos, GridRegion neighbourRegion,
  1470. bool isFlying, EntityTransferContext ctx)
  1471. {
  1472. try
  1473. {
  1474. m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: new region={1} at <{2},{3}>. newpos={4}",
  1475. LogHeader, neighbourRegion.RegionName, neighbourRegion.RegionLocX, neighbourRegion.RegionLocY, pos);
  1476. if (neighbourRegion == null)
  1477. {
  1478. m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: invalid destiny", LogHeader);
  1479. return agent;
  1480. }
  1481. IPEndPoint endpoint = neighbourRegion.ExternalEndPoint;
  1482. if(endpoint == null)
  1483. {
  1484. m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: failed to resolve neighbour address {0} ",neighbourRegion.ExternalHostName);
  1485. return agent;
  1486. }
  1487. m_entityTransferStateMachine.SetInTransit(agent.UUID);
  1488. agent.RemoveFromPhysicalScene();
  1489. if (!CrossAgentIntoNewRegionMain(agent, pos, neighbourRegion, endpoint, isFlying, ctx))
  1490. {
  1491. m_log.DebugFormat("{0}: CrossAgentToNewRegionAsync: cross main failed. Resetting transfer state", LogHeader);
  1492. m_entityTransferStateMachine.ResetFromTransit(agent.UUID);
  1493. }
  1494. }
  1495. catch (Exception e)
  1496. {
  1497. m_log.Error(string.Format("{0}: CrossAgentToNewRegionAsync: failed with exception ", LogHeader), e);
  1498. }
  1499. return agent;
  1500. }
  1501. public bool CrossAgentIntoNewRegionMain(ScenePresence agent, Vector3 pos, GridRegion neighbourRegion,
  1502. IPEndPoint endpoint, bool isFlying, EntityTransferContext ctx)
  1503. {
  1504. int ts = Util.EnvironmentTickCount();
  1505. bool sucess = true;
  1506. string reason = String.Empty;
  1507. List<ulong> childRegionsToClose = null;
  1508. UUID agentUUID = agent.UUID;
  1509. try
  1510. {
  1511. AgentData cAgent = new AgentData();
  1512. agent.CopyTo(cAgent,true);
  1513. cAgent.Position = pos;
  1514. cAgent.ChildrenCapSeeds = agent.KnownRegions;
  1515. if(ctx.OutboundVersion < 0.7f)
  1516. {
  1517. childRegionsToClose = agent.GetChildAgentsToClose(neighbourRegion.RegionHandle, neighbourRegion.RegionSizeX, neighbourRegion.RegionSizeY);
  1518. if(cAgent.ChildrenCapSeeds != null)
  1519. {
  1520. foreach(ulong regh in childRegionsToClose)
  1521. cAgent.ChildrenCapSeeds.Remove(regh);
  1522. }
  1523. }
  1524. if (isFlying)
  1525. cAgent.ControlFlags |= (uint)AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  1526. // We don't need the callback anymnore
  1527. cAgent.CallbackURI = String.Empty;
  1528. // Beyond this point, extra cleanup is needed beyond removing transit state
  1529. m_entityTransferStateMachine.UpdateInTransit(agentUUID, AgentTransferState.Transferring);
  1530. if (sucess && !m_scene.SimulationService.UpdateAgent(neighbourRegion, cAgent, ctx))
  1531. {
  1532. sucess = false;
  1533. reason = "agent update failed";
  1534. }
  1535. if(!sucess)
  1536. {
  1537. // region doesn't take it
  1538. m_entityTransferStateMachine.UpdateInTransit(agentUUID, AgentTransferState.CleaningUp);
  1539. m_log.WarnFormat(
  1540. "[ENTITY TRANSFER MODULE]: agent {0} crossing to {1} failed: {2}",
  1541. agent.Name, neighbourRegion.RegionName, reason);
  1542. ReInstantiateScripts(agent);
  1543. if(agent.ParentID == 0 && agent.ParentUUID.IsZero())
  1544. {
  1545. agent.AddToPhysicalScene(isFlying);
  1546. }
  1547. return false;
  1548. }
  1549. m_log.DebugFormat("[CrossAgentIntoNewRegionMain] ok, time {0}ms",Util.EnvironmentTickCountSubtract(ts));
  1550. }
  1551. catch (Exception e)
  1552. {
  1553. m_log.ErrorFormat(
  1554. "[ENTITY TRANSFER MODULE]: Problem crossing user {0} to new region {1} from {2}. Exception {3}{4}",
  1555. agent.Name, neighbourRegion.RegionName, m_sceneName, e.Message, e.StackTrace);
  1556. // TODO: Might be worth attempting other restoration here such as reinstantiation of scripts, etc.
  1557. return false;
  1558. }
  1559. string agentcaps;
  1560. if (!agent.KnownRegions.TryGetValue(neighbourRegion.RegionHandle, out agentcaps))
  1561. {
  1562. m_log.ErrorFormat("[ENTITY TRANSFER MODULE]: No ENTITY TRANSFER MODULE information for region handle {0}, exiting CrossToNewRegion.",
  1563. neighbourRegion.RegionHandle);
  1564. return false;
  1565. }
  1566. // No turning back
  1567. agent.IsChildAgent = true;
  1568. string capsPath = neighbourRegion.ServerURI + CapsUtil.GetCapsSeedPath(agentcaps);
  1569. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Sending new CAPS seed url {0} to client {1}", capsPath, agent.UUID);
  1570. Vector3 vel2 = Vector3.Zero;
  1571. if((agent.m_crossingFlags & 2) != 0)
  1572. vel2 = new Vector3(agent.Velocity.X, agent.Velocity.Y, 0);
  1573. if (m_eqModule != null)
  1574. {
  1575. m_eqModule.CrossRegion(
  1576. neighbourRegion.RegionHandle, pos, vel2 /* agent.Velocity */,
  1577. endpoint, capsPath, agentUUID, agent.ControllingClient.SessionId,
  1578. neighbourRegion.RegionSizeX, neighbourRegion.RegionSizeY);
  1579. }
  1580. else
  1581. {
  1582. m_log.ErrorFormat("{0} Using old CrossRegion packet. Varregion will not work!!", LogHeader);
  1583. agent.ControllingClient.CrossRegion(neighbourRegion.RegionHandle, pos, agent.Velocity,
  1584. endpoint,capsPath);
  1585. }
  1586. // SUCCESS!
  1587. m_entityTransferStateMachine.UpdateInTransit(agentUUID, AgentTransferState.ReceivedAtDestination);
  1588. // Unlike a teleport, here we do not wait for the destination region to confirm the receipt.
  1589. m_entityTransferStateMachine.UpdateInTransit(agentUUID, AgentTransferState.CleaningUp);
  1590. if(childRegionsToClose != null)
  1591. agent.CloseChildAgents(childRegionsToClose);
  1592. if((agent.m_crossingFlags & 8) == 0)
  1593. agent.ClearControls(); // don't let attachments delete (called in HasMovedAway) disturb taken controls on viewers
  1594. agent.HasMovedAway((agent.m_crossingFlags & 8) == 0);
  1595. agent.MakeChildAgent(neighbourRegion.RegionHandle);
  1596. // FIXME: Possibly this should occur lower down after other commands to close other agents,
  1597. // but not sure yet what the side effects would be.
  1598. m_entityTransferStateMachine.ResetFromTransit(agentUUID);
  1599. return true;
  1600. }
  1601. private void CrossAgentToNewRegionCompleted(IAsyncResult iar)
  1602. {
  1603. CrossAgentToNewRegionDelegate icon = (CrossAgentToNewRegionDelegate)iar.AsyncState;
  1604. ScenePresence agent = icon.EndInvoke(iar);
  1605. //// If the cross was successful, this agent is a child agent
  1606. //if (agent.IsChildAgent)
  1607. // agent.Reset();
  1608. //else // Not successful
  1609. // agent.RestoreInCurrentScene();
  1610. // In any case
  1611. agent.IsInTransit = false;
  1612. // m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Crossing agent {0} {1} completed.", agent.Firstname, agent.Lastname);
  1613. }
  1614. #endregion
  1615. #region Enable Child Agent
  1616. /// <summary>
  1617. /// This informs a single neighbouring region about agent "avatar", and avatar about it
  1618. /// Calls an asynchronous method to do so.. so it doesn't lag the sim.
  1619. /// </summary>
  1620. /// <param name="sp"></param>
  1621. /// <param name="region"></param>
  1622. public void EnableChildAgent(ScenePresence sp, GridRegion region)
  1623. {
  1624. int viewrange = (int)sp.RegionViewDistance;
  1625. if(viewrange == 0)
  1626. return;
  1627. ICapabilitiesModule capsModule = m_scene.CapsModule;
  1628. if (capsModule == null)
  1629. return;
  1630. Vector3 pos = sp.AbsolutePosition;
  1631. int rtmp = region.RegionLocX - (int)m_sceneRegionInfo.WorldLocX - (int)pos.X;
  1632. if ( rtmp > viewrange || rtmp < -(viewrange + region.RegionSizeX))
  1633. return;
  1634. rtmp = region.RegionLocY - (int)m_sceneRegionInfo.WorldLocY - (int)pos.Y;
  1635. if (rtmp > viewrange || rtmp < -(viewrange + region.RegionSizeY))
  1636. return;
  1637. m_log.DebugFormat("[ENTITY TRANSFER]: Enabling child agent in new neighbour {0}", region.RegionName);
  1638. ulong regionhandler = region.RegionHandle;
  1639. Dictionary<ulong, string> seeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(sp.UUID));
  1640. if (seeds.ContainsKey(regionhandler))
  1641. seeds.Remove(regionhandler);
  1642. if (!seeds.ContainsKey(m_sceneRegionHandler))
  1643. seeds.Add(m_sceneRegionHandler, sp.ControllingClient.RequestClientInfo().CapsPath);
  1644. AgentCircuitData currentAgentCircuit = sp.Scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  1645. AgentCircuitData agent = sp.ControllingClient.RequestClientInfo();
  1646. agent.BaseFolder = UUID.Zero;
  1647. agent.InventoryFolder = UUID.Zero;
  1648. agent.startpos = sp.AbsolutePosition + CalculateOffset(sp, region);
  1649. agent.startfar = sp.DrawDistance;
  1650. agent.child = true;
  1651. agent.Appearance = new AvatarAppearance();
  1652. agent.Appearance.AvatarHeight = sp.Appearance.AvatarHeight;
  1653. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1654. seeds.Add(regionhandler, agent.CapsPath);
  1655. agent.ChildrenCapSeeds = null;
  1656. capsModule.SetChildrenSeed(sp.UUID, seeds);
  1657. sp.KnownRegions = seeds;
  1658. sp.AddNeighbourRegionSizeInfo(region);
  1659. if (currentAgentCircuit != null)
  1660. {
  1661. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1662. agent.IPAddress = currentAgentCircuit.IPAddress;
  1663. agent.Viewer = currentAgentCircuit.Viewer;
  1664. agent.Channel = currentAgentCircuit.Channel;
  1665. agent.Mac = currentAgentCircuit.Mac;
  1666. agent.Id0 = currentAgentCircuit.Id0;
  1667. }
  1668. IPEndPoint external = region.ExternalEndPoint;
  1669. if (external != null)
  1670. {
  1671. ScenePresence avatar = sp;
  1672. GridRegion reg = region;
  1673. WorkManager.RunInThreadPool(delegate
  1674. {
  1675. InformClientOfNeighbourAsync(avatar, agent, reg, external, true);
  1676. },"InformClientOfNeighbourAsync" + avatar.UUID.ToString());
  1677. }
  1678. }
  1679. #endregion
  1680. #region Enable Child Agents
  1681. List<GridRegion> RegionsInView(Vector3 pos, RegionInfo curregion, List<GridRegion> fullneighbours, float viewrange)
  1682. {
  1683. if (fullneighbours.Count == 0 || viewrange == 0)
  1684. return new List<GridRegion>();
  1685. int itmp = (int)curregion.WorldLocX + (int)pos.X;
  1686. int minX = itmp - (int)viewrange;
  1687. int maxX = itmp + (int)viewrange;
  1688. itmp = (int)curregion.WorldLocY + (int)pos.Y;
  1689. int minY = itmp - (int)viewrange;
  1690. int maxY = itmp + (int)viewrange;
  1691. List<GridRegion> ret = new List<GridRegion>(fullneighbours.Count);
  1692. foreach (GridRegion r in fullneighbours)
  1693. {
  1694. OpenSim.Framework.RegionFlags? regionFlags = r.RegionFlags;
  1695. if (regionFlags != null)
  1696. {
  1697. if ((regionFlags & OpenSim.Framework.RegionFlags.RegionOnline) == 0)
  1698. continue;
  1699. }
  1700. itmp = r.RegionLocX;
  1701. if (maxX < itmp)
  1702. continue;
  1703. if (minX > itmp + r.RegionSizeX)
  1704. continue;
  1705. itmp = r.RegionLocY;
  1706. if (maxY < itmp)
  1707. continue;
  1708. if (minY > itmp + r.RegionSizeY)
  1709. continue;
  1710. ret.Add(r);
  1711. }
  1712. return ret;
  1713. }
  1714. List<GridRegion> RegionsInSPView(ScenePresence sp)
  1715. {
  1716. int viewrange = (int)sp.RegionViewDistance;
  1717. if (viewrange == 0)
  1718. return new List<GridRegion>();
  1719. List<GridRegion> fullneighbours = GetNeighbors(sp);
  1720. if (fullneighbours.Count == 0)
  1721. return new List<GridRegion>();
  1722. Vector3 pos = sp.AbsolutePosition;
  1723. int itmp = (int)m_sceneRegionInfo.WorldLocX + (int)pos.X;
  1724. int minX = itmp - viewrange;
  1725. int maxX = itmp + viewrange;
  1726. itmp = (int)m_sceneRegionInfo.WorldLocY + (int)pos.Y;
  1727. int minY = itmp - viewrange;
  1728. int maxY = itmp + viewrange;
  1729. List<GridRegion> ret = new List<GridRegion>(fullneighbours.Count);
  1730. foreach (GridRegion r in fullneighbours)
  1731. {
  1732. OpenSim.Framework.RegionFlags? regionFlags = r.RegionFlags;
  1733. if (regionFlags != null)
  1734. {
  1735. if ((regionFlags & OpenSim.Framework.RegionFlags.RegionOnline) == 0)
  1736. continue;
  1737. }
  1738. itmp = r.RegionLocX;
  1739. if (maxX < itmp)
  1740. continue;
  1741. if (minX > itmp + r.RegionSizeX)
  1742. continue;
  1743. itmp = r.RegionLocY;
  1744. if (maxY < itmp)
  1745. continue;
  1746. if (minY > itmp + r.RegionSizeY)
  1747. continue;
  1748. ret.Add(r);
  1749. }
  1750. return ret;
  1751. }
  1752. /// <summary>
  1753. /// This informs all neighbouring regions about agent "avatar".
  1754. /// and as important informs the avatar about then
  1755. /// </summary>
  1756. /// <param name="sp"></param>
  1757. public void EnableChildAgents(ScenePresence sp)
  1758. {
  1759. // assumes that out of view range regions are disconnected by the previous region
  1760. ICapabilitiesModule capsModule = m_scene.CapsModule;
  1761. if (capsModule == null)
  1762. return;
  1763. List<GridRegion> neighbours = RegionsInSPView(sp);
  1764. LinkedList<ulong> previousRegionNeighbourHandles;
  1765. Dictionary<ulong, string> seeds;
  1766. seeds = new Dictionary<ulong, string>(capsModule.GetChildrenSeeds(sp.UUID));
  1767. previousRegionNeighbourHandles = new LinkedList<ulong>(seeds.Keys);
  1768. IClientAPI spClient = sp.ControllingClient;
  1769. // This will fail if the user aborts login
  1770. try
  1771. {
  1772. if (!seeds.ContainsKey(m_sceneRegionHandler))
  1773. seeds.Add(m_sceneRegionHandler, spClient.RequestClientInfo().CapsPath);
  1774. }
  1775. catch
  1776. {
  1777. return;
  1778. }
  1779. AgentCircuitData currentAgentCircuit =
  1780. m_scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
  1781. List<AgentCircuitData> cagents = new List<AgentCircuitData>();
  1782. List<ulong> newneighbours = new List<ulong>();
  1783. foreach (GridRegion neighbour in neighbours)
  1784. {
  1785. ulong handler = neighbour.RegionHandle;
  1786. if (previousRegionNeighbourHandles.Contains(handler))
  1787. {
  1788. // agent already knows this region
  1789. previousRegionNeighbourHandles.Remove(handler);
  1790. continue;
  1791. }
  1792. if (handler == m_sceneRegionHandler)
  1793. continue;
  1794. // a new region to add
  1795. AgentCircuitData agent = spClient.RequestClientInfo();
  1796. agent.BaseFolder = UUID.Zero;
  1797. agent.InventoryFolder = UUID.Zero;
  1798. agent.startpos = sp.AbsolutePosition + CalculateOffset(sp, neighbour);
  1799. agent.child = true;
  1800. agent.Appearance = new AvatarAppearance();
  1801. agent.Appearance.AvatarHeight = sp.Appearance.AvatarHeight;
  1802. agent.startfar = sp.DrawDistance;
  1803. if (currentAgentCircuit != null)
  1804. {
  1805. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1806. agent.IPAddress = currentAgentCircuit.IPAddress;
  1807. agent.Viewer = currentAgentCircuit.Viewer;
  1808. agent.Channel = currentAgentCircuit.Channel;
  1809. agent.Mac = currentAgentCircuit.Mac;
  1810. agent.Id0 = currentAgentCircuit.Id0;
  1811. }
  1812. newneighbours.Add(handler);
  1813. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1814. seeds.Add(handler, agent.CapsPath);
  1815. agent.ChildrenCapSeeds = null;
  1816. cagents.Add(agent);
  1817. }
  1818. List<ulong> toclose;
  1819. // previousRegionNeighbourHandles now contains regions to forget
  1820. if (previousRegionNeighbourHandles.Count > 0)
  1821. {
  1822. if (previousRegionNeighbourHandles.Contains(m_sceneRegionHandler))
  1823. previousRegionNeighbourHandles.Remove(m_sceneRegionHandler);
  1824. foreach (ulong handler in previousRegionNeighbourHandles)
  1825. seeds.Remove(handler);
  1826. toclose = new List<ulong>(previousRegionNeighbourHandles);
  1827. }
  1828. else
  1829. toclose = new List<ulong>();
  1830. /// Update all child agent with everyone's seeds
  1831. // foreach (AgentCircuitData a in cagents)
  1832. // a.ChildrenCapSeeds = new Dictionary<ulong, string>(seeds);
  1833. if (capsModule != null)
  1834. capsModule.SetChildrenSeed(sp.UUID, seeds);
  1835. sp.KnownRegions = seeds;
  1836. sp.SetNeighbourRegionSizeInfo(neighbours);
  1837. if (neighbours.Count > 0 || toclose.Count > 0)
  1838. {
  1839. AgentPosition agentpos = new AgentPosition();
  1840. agentpos.AgentID = new UUID(sp.UUID.Guid);
  1841. agentpos.SessionID = spClient.SessionId;
  1842. agentpos.Size = sp.Appearance.AvatarSize;
  1843. agentpos.Center = sp.CameraPosition;
  1844. agentpos.Far = sp.DrawDistance;
  1845. agentpos.Position = sp.AbsolutePosition;
  1846. agentpos.Velocity = sp.Velocity;
  1847. agentpos.RegionHandle = m_sceneRegionHandler;
  1848. //agentpos.GodLevel = sp.GodLevel;
  1849. agentpos.GodData = sp.GodController.State();
  1850. agentpos.Throttles = spClient.GetThrottlesPacked(1);
  1851. // agentpos.ChildrenCapSeeds = seeds;
  1852. Util.FireAndForget(delegate
  1853. {
  1854. int count = 0;
  1855. IPEndPoint ipe;
  1856. if(toclose.Count > 0)
  1857. sp.CloseChildAgents(toclose);
  1858. foreach (GridRegion neighbour in neighbours)
  1859. {
  1860. ulong handler = neighbour.RegionHandle;
  1861. try
  1862. {
  1863. if (newneighbours.Contains(handler))
  1864. {
  1865. ipe = neighbour.ExternalEndPoint;
  1866. if (ipe != null)
  1867. InformClientOfNeighbourAsync(sp, cagents[count], neighbour, ipe, true);
  1868. else
  1869. {
  1870. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: lost DNS resolution for neighbour {0}", neighbour.ExternalHostName);
  1871. }
  1872. count++;
  1873. }
  1874. else if (!previousRegionNeighbourHandles.Contains(handler))
  1875. {
  1876. m_scene.SimulationService.UpdateAgent(neighbour, agentpos);
  1877. }
  1878. if (sp.IsDeleted)
  1879. return;
  1880. }
  1881. catch (Exception e)
  1882. {
  1883. m_log.ErrorFormat(
  1884. "[ENTITY TRANSFER MODULE]: Error creating child agent at {0} ({1} ({2}, {3}). {4}",
  1885. neighbour.ExternalHostName,
  1886. neighbour.RegionHandle,
  1887. neighbour.RegionLocX,
  1888. neighbour.RegionLocY,
  1889. e);
  1890. }
  1891. }
  1892. });
  1893. }
  1894. }
  1895. public void CheckChildAgents(ScenePresence sp)
  1896. {
  1897. List<GridRegion> neighbours = RegionsInSPView(sp);
  1898. Dictionary<ulong, string> previousRegionNeighbour = sp.KnownRegions;
  1899. previousRegionNeighbour.Remove(m_sceneRegionHandler);
  1900. IClientAPI spClient = sp.ControllingClient;
  1901. AgentCircuitData currentAgentCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(spClient.CircuitCode);
  1902. List<AgentCircuitData> cagents = new List<AgentCircuitData>(neighbours.Count);
  1903. List<GridRegion> newneighbours = new List<GridRegion>(neighbours.Count);
  1904. foreach (GridRegion neighbour in neighbours)
  1905. {
  1906. ulong handler = neighbour.RegionHandle;
  1907. if (previousRegionNeighbour.Remove(handler))
  1908. {
  1909. // agent already knows this region
  1910. continue;
  1911. }
  1912. if (handler == m_sceneRegionHandler)
  1913. continue;
  1914. // a new region to add
  1915. AgentCircuitData agent = spClient.RequestClientInfo();
  1916. agent.BaseFolder = UUID.Zero;
  1917. agent.InventoryFolder = UUID.Zero;
  1918. agent.startpos = sp.AbsolutePosition + CalculateOffset(sp, neighbour);
  1919. agent.child = true;
  1920. agent.Appearance = new AvatarAppearance();
  1921. agent.Appearance.AvatarHeight = sp.Appearance.AvatarHeight;
  1922. agent.startfar = sp.DrawDistance;
  1923. if (currentAgentCircuit != null)
  1924. {
  1925. agent.ServiceURLs = currentAgentCircuit.ServiceURLs;
  1926. agent.IPAddress = currentAgentCircuit.IPAddress;
  1927. agent.Viewer = currentAgentCircuit.Viewer;
  1928. agent.Channel = currentAgentCircuit.Channel;
  1929. agent.Mac = currentAgentCircuit.Mac;
  1930. agent.Id0 = currentAgentCircuit.Id0;
  1931. }
  1932. newneighbours.Add(neighbour);
  1933. agent.CapsPath = CapsUtil.GetRandomCapsObjectPath();
  1934. sp.AddNeighbourRegion(neighbour, agent.CapsPath);
  1935. agent.ChildrenCapSeeds = null;
  1936. cagents.Add(agent);
  1937. }
  1938. // previousRegionNeighbourHandles now contains regions to forget
  1939. if (previousRegionNeighbour.Count > 0)
  1940. {
  1941. List<ulong> toclose = new List<ulong>(previousRegionNeighbour.Keys);
  1942. sp.CloseChildAgents(toclose);
  1943. }
  1944. ICapabilitiesModule capsModule = m_scene.CapsModule;
  1945. if (capsModule != null)
  1946. capsModule.SetChildrenSeed(sp.UUID, sp.KnownRegions);
  1947. if (newneighbours.Count > 0)
  1948. {
  1949. int count = 0;
  1950. IPEndPoint ipe;
  1951. foreach (GridRegion neighbour in newneighbours)
  1952. {
  1953. try
  1954. {
  1955. ipe = neighbour.ExternalEndPoint;
  1956. if (ipe != null)
  1957. InformClientOfNeighbourAsync(sp, cagents[count], neighbour, ipe, true);
  1958. else
  1959. {
  1960. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: lost DNS resolution for neighbour {0}", neighbour.ExternalHostName);
  1961. }
  1962. count++;
  1963. if (sp.IsDeleted)
  1964. return;
  1965. }
  1966. catch (Exception e)
  1967. {
  1968. m_log.ErrorFormat(
  1969. "[ENTITY TRANSFER MODULE]: Error creating child agent at {0} ({1} ({2}, {3}). {4}",
  1970. neighbour.ExternalHostName,
  1971. neighbour.RegionHandle,
  1972. neighbour.RegionLocX,
  1973. neighbour.RegionLocY,
  1974. e);
  1975. }
  1976. }
  1977. }
  1978. }
  1979. public void CloseOldChildAgents(ScenePresence sp)
  1980. {
  1981. Dictionary<ulong, string> seeds = sp.KnownRegions;
  1982. if (seeds.Count == 0)
  1983. return;
  1984. seeds.Remove(m_sceneRegionHandler);
  1985. if (seeds.Count == 0)
  1986. return;
  1987. List<GridRegion> neighbours = RegionsInSPView(sp);
  1988. sp.SetNeighbourRegionSizeInfo(neighbours);
  1989. foreach (GridRegion neighbour in neighbours)
  1990. seeds.Remove(neighbour.RegionHandle);
  1991. // seeds now contains regions to forget
  1992. if (seeds.Count == 0)
  1993. return;
  1994. List<ulong> toclose = new List<ulong>(seeds.Keys);
  1995. Util.FireAndForget(delegate
  1996. {
  1997. sp.CloseChildAgents(toclose);
  1998. });
  1999. }
  2000. // Computes the difference between two region bases.
  2001. // Returns a vector of world coordinates (meters) from base of first region to the second.
  2002. // The first region is the home region of the passed scene presence.
  2003. Vector3 CalculateOffset(ScenePresence sp, GridRegion neighbour)
  2004. {
  2005. return new Vector3(sp.Scene.RegionInfo.WorldLocX - neighbour.RegionLocX,
  2006. sp.Scene.RegionInfo.WorldLocY - neighbour.RegionLocY,
  2007. 0f);
  2008. }
  2009. #endregion
  2010. #region NotFoundLocationCache class
  2011. // A collection of not found locations to make future lookups 'not found' lookups quick.
  2012. // A simple expiring cache that keeps not found locations for some number of seconds.
  2013. // A 'not found' location is presumed to be anywhere in the minimum sized region that
  2014. // contains that point. A conservitive estimate.
  2015. private class NotFoundLocationCache
  2016. {
  2017. private Dictionary<ulong, DateTime> m_notFoundLocations = new Dictionary<ulong, DateTime>();
  2018. public NotFoundLocationCache()
  2019. {
  2020. }
  2021. // just use normal regions handlers and sizes
  2022. public void Add(double pX, double pY)
  2023. {
  2024. ulong psh = (ulong)pX & 0xffffff00ul;
  2025. psh <<= 32;
  2026. psh |= (ulong)pY & 0xffffff00ul;
  2027. lock (m_notFoundLocations)
  2028. m_notFoundLocations[psh] = DateTime.UtcNow + TimeSpan.FromSeconds(30);
  2029. }
  2030. // Test to see of this point is in any of the 'not found' areas.
  2031. // Return 'true' if the point is found inside the 'not found' areas.
  2032. public bool Contains(double pX, double pY)
  2033. {
  2034. ulong psh = (ulong)pX & 0xffffff00ul;
  2035. psh <<= 32;
  2036. psh |= (ulong)pY & 0xffffff00ul;
  2037. lock (m_notFoundLocations)
  2038. {
  2039. if(m_notFoundLocations.ContainsKey(psh))
  2040. {
  2041. if(m_notFoundLocations[psh] > DateTime.UtcNow)
  2042. return true;
  2043. m_notFoundLocations.Remove(psh);
  2044. }
  2045. return false;
  2046. }
  2047. }
  2048. private void DoExpiration()
  2049. {
  2050. List<ulong> m_toRemove = new List<ulong>();;
  2051. DateTime now = DateTime.UtcNow;
  2052. lock (m_notFoundLocations)
  2053. {
  2054. foreach (KeyValuePair<ulong, DateTime> kvp in m_notFoundLocations)
  2055. {
  2056. if (kvp.Value < now)
  2057. m_toRemove.Add(kvp.Key);
  2058. }
  2059. if (m_toRemove.Count > 0)
  2060. {
  2061. foreach (ulong u in m_toRemove)
  2062. m_notFoundLocations.Remove(u);
  2063. m_toRemove.Clear();
  2064. }
  2065. }
  2066. }
  2067. }
  2068. #endregion // NotFoundLocationCache class
  2069. #region getregions
  2070. private NotFoundLocationCache m_notFoundLocationCache = new NotFoundLocationCache();
  2071. protected GridRegion GetRegionContainingWorldLocation(IGridService pGridService, UUID pScopeID, double px, double py)
  2072. {
  2073. // Given a world position, get the GridRegion info for
  2074. // the region containing that point.
  2075. // check if we already found it does not exist
  2076. if (m_notFoundLocationCache.Contains(px, py))
  2077. return null;
  2078. // reduce to next grid corner
  2079. // this is all that is needed on 0.9 grids
  2080. uint possibleX = (uint)px & 0xffffff00u;
  2081. uint possibleY = (uint)py & 0xffffff00u;
  2082. GridRegion ret = pGridService.GetRegionByPosition(pScopeID, (int)possibleX, (int)possibleY);
  2083. if (ret != null)
  2084. return ret;
  2085. /* obsolete code
  2086. // for 0.8 regions just make a BIG area request. old code whould do it plus 4 more smaller on region open edges
  2087. // this is what 0.9 grids now do internally
  2088. List<GridRegion> possibleRegions = pGridService.GetRegionRange(pScopeID,
  2089. (int)(px - Constants.MaximumRegionSize), (int)(px + 1), // +1 bc left mb not part of range
  2090. (int)(py - Constants.MaximumRegionSize), (int)(py + 1));
  2091. if (possibleRegions != null && possibleRegions.Count > 0)
  2092. {
  2093. // If we found some regions, check to see if the point is within
  2094. foreach (GridRegion gr in possibleRegions)
  2095. {
  2096. if (px >= (double)gr.RegionLocX && px < (double)(gr.RegionLocX + gr.RegionSizeX)
  2097. && py >= (double)gr.RegionLocY && py < (double)(gr.RegionLocY + gr.RegionSizeY))
  2098. {
  2099. // Found a region that contains the point
  2100. return gr;
  2101. }
  2102. }
  2103. }
  2104. */
  2105. // remember this location was not found so we can quickly not find it next time
  2106. m_notFoundLocationCache.Add(px, py);
  2107. return null;
  2108. }
  2109. /// <summary>
  2110. /// Async component for informing client of which neighbours exist
  2111. /// </summary>
  2112. /// <remarks>
  2113. /// This needs to run asynchronously, as a network timeout may block the thread for a long while
  2114. /// </remarks>
  2115. /// <param name="remoteClient"></param>
  2116. /// <param name="a"></param>
  2117. /// <param name="regionHandle"></param>
  2118. /// <param name="endPoint"></param>
  2119. private void InformClientOfNeighbourAsync(ScenePresence sp, AgentCircuitData agentCircData, GridRegion reg,
  2120. IPEndPoint endPoint, bool newAgent)
  2121. {
  2122. if (newAgent)
  2123. {
  2124. // we may already had lost this sp
  2125. if(sp == null || sp.IsDeleted || sp.ControllingClient == null) // something bad already happened
  2126. return;
  2127. Scene scene = sp.Scene;
  2128. m_log.DebugFormat(
  2129. "[ENTITY TRANSFER MODULE]: Informing {0} {1} about neighbour {2} {3} at ({4},{5})",
  2130. sp.Name, sp.UUID, reg.RegionName, endPoint, reg.RegionCoordX, reg.RegionCoordY);
  2131. string capsPath = reg.ServerURI + CapsUtil.GetCapsSeedPath(agentCircData.CapsPath);
  2132. string reason = string.Empty;
  2133. EntityTransferContext ctx = new EntityTransferContext();
  2134. bool regionAccepted = scene.SimulationService.CreateAgent(reg, reg, agentCircData, (uint)TeleportFlags.Default, null, out reason);
  2135. if (regionAccepted)
  2136. {
  2137. // give time for createAgent to finish, since it is async and does grid services access
  2138. Thread.Sleep(500);
  2139. if (m_eqModule != null)
  2140. {
  2141. if(sp == null || sp.IsDeleted || sp.ControllingClient == null) // something bad already happened
  2142. return;
  2143. m_log.DebugFormat("{0} {1} is sending {2} EnableSimulator for neighbour region {3}(loc=<{4},{5}>,siz=<{6},{7}>) " +
  2144. "and EstablishAgentCommunication with seed cap {8}", LogHeader,
  2145. scene.RegionInfo.RegionName, sp.Name,
  2146. reg.RegionName, reg.RegionLocX, reg.RegionLocY, reg.RegionSizeX, reg.RegionSizeY, capsPath);
  2147. m_eqModule.EnableSimulator(reg.RegionHandle, endPoint, sp.UUID, reg.RegionSizeX, reg.RegionSizeY);
  2148. m_eqModule.EstablishAgentCommunication(sp.UUID, endPoint, capsPath, reg.RegionHandle, reg.RegionSizeX, reg.RegionSizeY);
  2149. }
  2150. else
  2151. {
  2152. sp.ControllingClient.InformClientOfNeighbour(reg.RegionHandle, endPoint);
  2153. // TODO: make Event Queue disablable!
  2154. }
  2155. m_log.DebugFormat("[ENTITY TRANSFER MODULE]: Completed inform {0} {1} about neighbour {2}", sp.Name, sp.UUID, endPoint);
  2156. }
  2157. else
  2158. {
  2159. sp.RemoveNeighbourRegion(reg.RegionHandle);
  2160. m_log.WarnFormat(
  2161. "[ENTITY TRANSFER MODULE]: Region {0} did not accept {1} {2}: {3}",
  2162. reg.RegionName, sp.Name, sp.UUID, reason);
  2163. }
  2164. }
  2165. }
  2166. // all this code should be moved to scene replacing the now bad one there
  2167. // cache Neighbors
  2168. List<GridRegion> Neighbors = null;
  2169. DateTime LastNeighborsTime = DateTime.MinValue;
  2170. /// <summary>
  2171. /// Return the list of online regions that are considered to be neighbours to the given scene.
  2172. /// </summary>
  2173. /// <param name="avatar"></param>
  2174. /// <param name="pRegionLocX"></param>
  2175. /// <param name="pRegionLocY"></param>
  2176. /// <returns></returns>
  2177. protected List<GridRegion> GetNeighbors(ScenePresence avatar)
  2178. {
  2179. if (Neighbors != null && (DateTime.UtcNow - LastNeighborsTime).TotalSeconds < 30)
  2180. {
  2181. return Neighbors;
  2182. }
  2183. Scene pScene = avatar.Scene;
  2184. uint dd = (uint)pScene.MaxRegionViewDistance;
  2185. if(dd <= 1)
  2186. return new List<GridRegion>();
  2187. RegionInfo regionInfo = pScene.RegionInfo;
  2188. uint startX = regionInfo.WorldLocX;
  2189. uint endX = startX + regionInfo.RegionSizeX;
  2190. uint startY = regionInfo.WorldLocY;
  2191. uint endY = startY + regionInfo.RegionSizeY;
  2192. --dd;
  2193. startX -= dd;
  2194. startY -= dd;
  2195. endX += dd;
  2196. endY += dd;
  2197. List<GridRegion> neighbours = avatar.Scene.GridService.GetRegionRange(
  2198. regionInfo.ScopeID, (int)startX, (int)endX, (int)startY, (int)endY);
  2199. // The r.RegionFlags == null check only needs to be made for simulators before 2015-01-14 (pre 0.8.1).
  2200. neighbours.RemoveAll( r => r.RegionID.Equals(regionInfo.RegionID));
  2201. Neighbors = neighbours;
  2202. LastNeighborsTime = DateTime.UtcNow;
  2203. return neighbours;
  2204. }
  2205. #endregion
  2206. #region Agent Arrived
  2207. public void AgentArrivedAtDestination(UUID id)
  2208. {
  2209. ScenePresence sp = m_scene.GetScenePresence(id);
  2210. if(sp == null || sp.IsDeleted || !sp.IsInTransit)
  2211. return;
  2212. //Scene.CloseAgent(sp.UUID, false);
  2213. sp.IsInTransit = false;
  2214. //m_entityTransferStateMachine.SetAgentArrivedAtDestination(id);
  2215. }
  2216. #endregion
  2217. #region Object Transfers
  2218. public GridRegion GetObjectDestination(SceneObjectGroup grp, Vector3 targetPosition, out Vector3 newpos)
  2219. {
  2220. newpos = targetPosition;
  2221. Scene scene = grp.Scene;
  2222. if (scene == null)
  2223. return null;
  2224. int x = (int)targetPosition.X + (int)scene.RegionInfo.WorldLocX;
  2225. if (targetPosition.X >= 0)
  2226. x++;
  2227. else
  2228. x--;
  2229. int y = (int)targetPosition.Y + (int)scene.RegionInfo.WorldLocY;
  2230. if (targetPosition.Y >= 0)
  2231. y++;
  2232. else
  2233. y--;
  2234. GridRegion neighbourRegion = scene.GridService.GetRegionByPosition(scene.RegionInfo.ScopeID,x,y);
  2235. if (neighbourRegion == null)
  2236. {
  2237. return null;
  2238. }
  2239. float newRegionSizeX = neighbourRegion.RegionSizeX;
  2240. float newRegionSizeY = neighbourRegion.RegionSizeY;
  2241. if (newRegionSizeX == 0)
  2242. newRegionSizeX = Constants.RegionSize;
  2243. if (newRegionSizeY == 0)
  2244. newRegionSizeY = Constants.RegionSize;
  2245. newpos.X = targetPosition.X - (neighbourRegion.RegionLocX - (int)scene.RegionInfo.WorldLocX);
  2246. newpos.Y = targetPosition.Y - (neighbourRegion.RegionLocY - (int)scene.RegionInfo.WorldLocY);
  2247. const float enterDistance = 0.2f;
  2248. newpos.X = Utils.Clamp(newpos.X, enterDistance, newRegionSizeX - enterDistance);
  2249. newpos.Y = Utils.Clamp(newpos.Y, enterDistance, newRegionSizeY - enterDistance);
  2250. return neighbourRegion;
  2251. }
  2252. /// <summary>
  2253. /// Move the given scene object into a new region
  2254. /// </summary>
  2255. /// <param name="newRegionHandle"></param>
  2256. /// <param name="grp">Scene Object Group that we're crossing</param>
  2257. /// <returns>
  2258. /// true if the crossing itself was successful, false on failure
  2259. /// FIMXE: we still return true if the crossing object was not successfully deleted from the originating region
  2260. /// </returns>
  2261. public bool CrossPrimGroupIntoNewRegion(GridRegion destination, Vector3 newPosition, SceneObjectGroup grp, bool silent, bool removeScripts)
  2262. {
  2263. //m_log.Debug(" >>> CrossPrimGroupIntoNewRegion <<<");
  2264. Culture.SetCurrentCulture();
  2265. bool successYN = false;
  2266. grp.RootPart.ClearUpdateSchedule();
  2267. //int primcrossingXMLmethod = 0;
  2268. if (destination != null)
  2269. {
  2270. if (m_scene.SimulationService != null)
  2271. successYN = m_scene.SimulationService.CreateObject(destination, newPosition, grp, true);
  2272. if (successYN)
  2273. {
  2274. // We remove the object here
  2275. try
  2276. {
  2277. grp.Scene.DeleteSceneObject(grp, silent, removeScripts);
  2278. }
  2279. catch (Exception e)
  2280. {
  2281. m_log.ErrorFormat(
  2282. "[ENTITY TRANSFER MODULE]: Exception deleting the old object left behind on a border crossing for {0}, {1}",
  2283. grp, e);
  2284. }
  2285. }
  2286. }
  2287. else
  2288. {
  2289. m_log.Error("[ENTITY TRANSFER MODULE]: destination was unexpectedly null in Scene.CrossPrimGroupIntoNewRegion()");
  2290. }
  2291. return successYN;
  2292. }
  2293. #endregion
  2294. #region Misc
  2295. public bool IsInTransit(UUID id)
  2296. {
  2297. return m_entityTransferStateMachine.GetAgentTransferState(id) != null;
  2298. }
  2299. protected void ReInstantiateScripts(ScenePresence sp)
  2300. {
  2301. int i = 0;
  2302. if (sp.InTransitScriptStates.Count > 0)
  2303. {
  2304. List<SceneObjectGroup> attachments = sp.GetAttachments();
  2305. foreach (SceneObjectGroup sog in attachments)
  2306. {
  2307. if (i < sp.InTransitScriptStates.Count)
  2308. {
  2309. sog.SetState(sp.InTransitScriptStates[i++], sp.Scene);
  2310. sog.CreateScriptInstances(0, false, sp.Scene.DefaultScriptEngine, -1);
  2311. sog.ResumeScripts();
  2312. }
  2313. else
  2314. m_log.ErrorFormat(
  2315. "[ENTITY TRANSFER MODULE]: InTransitScriptStates.Count={0} smaller than Attachments.Count={1}",
  2316. sp.InTransitScriptStates.Count, attachments.Count);
  2317. }
  2318. sp.InTransitScriptStates.Clear();
  2319. }
  2320. }
  2321. #endregion
  2322. public virtual bool HandleIncomingSceneObject(SceneObjectGroup so, Vector3 newPosition)
  2323. {
  2324. if (so.OwnerID.IsZero())
  2325. {
  2326. m_log.DebugFormat(
  2327. "[ENTITY TRANSFER MODULE]: Denied object {0}({1}) entry into {2} because ownerID is zero",
  2328. so.Name, so.UUID, m_sceneName);
  2329. return false;
  2330. }
  2331. // If the user is banned, we won't let any of their objects
  2332. // enter. Period.
  2333. if (m_sceneRegionInfo.EstateSettings.IsBanned(so.OwnerID))
  2334. {
  2335. m_log.DebugFormat(
  2336. "[ENTITY TRANSFER MODULE]: Denied {0} {1} into {2} of banned owner {3}",
  2337. so.Name, so.UUID, m_sceneName, so.OwnerID);
  2338. return false;
  2339. }
  2340. if(so.IsAttachmentCheckFull())
  2341. {
  2342. if(m_scene.GetScenePresence(so.OwnerID) == null)
  2343. {
  2344. m_log.DebugFormat(
  2345. "[ENTITY TRANSFER MODULE]: Denied attachment {0}({1}) owner {2} not in region {3}",
  2346. so.Name, so.UUID, so.OwnerID, m_sceneName);
  2347. return false;
  2348. }
  2349. }
  2350. if (!newPosition.IsZero())
  2351. so.RootPart.GroupPosition = newPosition;
  2352. if (!m_scene.AddSceneObject(so))
  2353. {
  2354. m_log.DebugFormat(
  2355. "[ENTITY TRANSFER MODULE]: Problem adding scene object {0} {1} into {2} ",
  2356. so.Name, so.UUID, m_sceneName);
  2357. return false;
  2358. }
  2359. if (!so.IsAttachment)
  2360. {
  2361. // FIXME: It would be better to never add the scene object at all rather than add it and then delete
  2362. // it
  2363. if (!m_scene.Permissions.CanObjectEntry(so, true, so.AbsolutePosition))
  2364. {
  2365. // Deny non attachments based on parcel settings
  2366. //
  2367. m_log.Info("[ENTITY TRANSFER MODULE]: Denied prim crossing because of parcel settings");
  2368. m_scene.DeleteSceneObject(so, false);
  2369. return false;
  2370. }
  2371. // For attachments, we need to wait until the agent is root
  2372. // before we restart the scripts, or else some functions won't work.
  2373. so.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource(so));
  2374. so.ResumeScripts();
  2375. // AddSceneObject already does this and doing it again messes
  2376. //if (so.RootPart.KeyframeMotion != null)
  2377. // so.RootPart.KeyframeMotion.UpdateSceneObject(so);
  2378. }
  2379. return true;
  2380. }
  2381. public virtual bool HandleIncomingAttachments(ScenePresence sp, List<SceneObjectGroup> attachments)
  2382. {
  2383. if (sp.IsDeleted)
  2384. return false;
  2385. if (m_sceneRegionInfo.EstateSettings.IsBanned(sp.UUID))
  2386. {
  2387. m_log.DebugFormat(
  2388. "[ENTITY TRANSFER MODULE]: Denied Attachments for banned avatar {0}", sp.Name);
  2389. return false;
  2390. }
  2391. foreach(SceneObjectGroup so in attachments)
  2392. {
  2393. if (!m_scene.AddSceneObject(so))
  2394. {
  2395. m_log.DebugFormat(
  2396. "[ENTITY TRANSFER MODULE]: Problem adding attachment {0} {1} into {2} ",
  2397. so.Name, so.UUID, m_sceneName);
  2398. continue;
  2399. }
  2400. }
  2401. sp.GotAttachmentsData = true;
  2402. return true;
  2403. }
  2404. private int GetStateSource(SceneObjectGroup sog)
  2405. {
  2406. ScenePresence sp = m_scene.GetScenePresence(sog.OwnerID);
  2407. if (sp != null)
  2408. return sp.GetStateSource();
  2409. return 2; // StateSource.PrimCrossing
  2410. }
  2411. }
  2412. }