EntityTransferModule.cs 126 KB

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