EntityTransferModule.cs 126 KB

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