ScenePresence.cs 156 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922
  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.Xml;
  29. using System.Collections.Generic;
  30. using System.Reflection;
  31. using System.Timers;
  32. using OpenMetaverse;
  33. using log4net;
  34. using OpenSim.Framework;
  35. using OpenSim.Framework.Client;
  36. using OpenSim.Region.Framework.Interfaces;
  37. using OpenSim.Region.Framework.Scenes.Animation;
  38. using OpenSim.Region.Framework.Scenes.Types;
  39. using OpenSim.Region.Physics.Manager;
  40. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  41. using OpenSim.Services.Interfaces;
  42. using TeleportFlags = OpenSim.Framework.Constants.TeleportFlags;
  43. namespace OpenSim.Region.Framework.Scenes
  44. {
  45. enum ScriptControlled : uint
  46. {
  47. CONTROL_ZERO = 0,
  48. CONTROL_FWD = 1,
  49. CONTROL_BACK = 2,
  50. CONTROL_LEFT = 4,
  51. CONTROL_RIGHT = 8,
  52. CONTROL_UP = 16,
  53. CONTROL_DOWN = 32,
  54. CONTROL_ROT_LEFT = 256,
  55. CONTROL_ROT_RIGHT = 512,
  56. CONTROL_LBUTTON = 268435456,
  57. CONTROL_ML_LBUTTON = 1073741824
  58. }
  59. struct ScriptControllers
  60. {
  61. public UUID itemID;
  62. public ScriptControlled ignoreControls;
  63. public ScriptControlled eventControls;
  64. }
  65. public delegate void SendCourseLocationsMethod(UUID scene, ScenePresence presence, List<Vector3> coarseLocations, List<UUID> avatarUUIDs);
  66. public class ScenePresence : EntityBase, IScenePresence
  67. {
  68. // ~ScenePresence()
  69. // {
  70. // m_log.Debug("[SCENE PRESENCE] Destructor called");
  71. // }
  72. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  73. public PresenceType PresenceType { get; private set; }
  74. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  75. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  76. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  77. /// <summary>
  78. /// Experimentally determined "fudge factor" to make sit-target positions
  79. /// the same as in SecondLife. Fudge factor was tested for 36 different
  80. /// test cases including prims of type box, sphere, cylinder, and torus,
  81. /// with varying parameters for sit target location, prim size, prim
  82. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  83. /// issue #1716
  84. /// </summary>
  85. public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.418f);
  86. /// <summary>
  87. /// Movement updates for agents in neighboring regions are sent directly to clients.
  88. /// This value only affects how often agent positions are sent to neighbor regions
  89. /// for things such as distance-based update prioritization
  90. /// </summary>
  91. public static readonly float SIGNIFICANT_MOVEMENT = 2.0f;
  92. public UUID currentParcelUUID = UUID.Zero;
  93. /// <value>
  94. /// The animator for this avatar
  95. /// </value>
  96. public ScenePresenceAnimator Animator { get; private set; }
  97. /// <summary>
  98. /// Attachments recorded on this avatar.
  99. /// </summary>
  100. /// <remarks>
  101. /// TODO: For some reason, we effectively have a list both here and in Appearance. Need to work out if this is
  102. /// necessary.
  103. /// </remarks>
  104. private List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  105. public Object AttachmentsSyncLock { get; private set; }
  106. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  107. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  108. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  109. private bool MouseDown = false;
  110. // private SceneObjectGroup proxyObjectGroup;
  111. //private SceneObjectPart proxyObjectPart = null;
  112. public Vector3 lastKnownAllowedPosition;
  113. public bool sentMessageAboutRestrictedParcelFlyingDown;
  114. public Vector4 CollisionPlane = Vector4.UnitW;
  115. private Vector3 m_lastPosition;
  116. private Quaternion m_lastRotation;
  117. private Vector3 m_lastVelocity;
  118. private Vector3? m_forceToApply;
  119. private int m_userFlags;
  120. public int UserFlags
  121. {
  122. get { return m_userFlags; }
  123. }
  124. // Flying
  125. public bool Flying
  126. {
  127. get { return PhysicsActor != null && PhysicsActor.Flying; }
  128. set { PhysicsActor.Flying = value; }
  129. }
  130. // add for fly velocity control
  131. private bool FlyingOld {get; set;}
  132. public bool WasFlying
  133. {
  134. get; private set;
  135. }
  136. public bool IsColliding
  137. {
  138. get { return PhysicsActor != null && PhysicsActor.IsColliding; }
  139. // We would expect setting IsColliding to be private but it's used by a hack in Scene
  140. set { PhysicsActor.IsColliding = value; }
  141. }
  142. // private int m_lastColCount = -1; //KF: Look for Collision chnages
  143. // private int m_updateCount = 0; //KF: Update Anims for a while
  144. // private static readonly int UPDATE_COUNT = 10; // how many frames to update for
  145. private TeleportFlags m_teleportFlags;
  146. public TeleportFlags TeleportFlags
  147. {
  148. get { return m_teleportFlags; }
  149. set { m_teleportFlags = value; }
  150. }
  151. private uint m_requestedSitTargetID;
  152. private UUID m_requestedSitTargetUUID;
  153. /// <summary>
  154. /// Are we sitting on the ground?
  155. /// </summary>
  156. public bool SitGround { get; private set; }
  157. private SendCourseLocationsMethod m_sendCourseLocationsMethod;
  158. //private Vector3 m_requestedSitOffset = new Vector3();
  159. private Vector3 m_LastFinitePos;
  160. private float m_sitAvatarHeight = 2.0f;
  161. private Vector3 m_lastChildAgentUpdatePosition;
  162. private Vector3 m_lastChildAgentUpdateCamPosition;
  163. private const int LAND_VELOCITYMAG_MAX = 12;
  164. private float m_health = 100f;
  165. protected ulong crossingFromRegion;
  166. private readonly Vector3[] Dir_Vectors = new Vector3[11];
  167. protected Timer m_reprioritization_timer;
  168. protected bool m_reprioritizing;
  169. protected bool m_reprioritization_called;
  170. private Quaternion m_headrotation = Quaternion.Identity;
  171. private string m_nextSitAnimation = String.Empty;
  172. //PauPaw:Proper PID Controler for autopilot************
  173. public bool MovingToTarget { get; private set; }
  174. public Vector3 MoveToPositionTarget { get; private set; }
  175. /// <summary>
  176. /// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
  177. /// </summary>
  178. public bool LandAtTarget { get; private set; }
  179. private bool m_followCamAuto;
  180. private int m_movementUpdateCount;
  181. private const int NumMovementsBetweenRayCast = 5;
  182. private bool CameraConstraintActive;
  183. //private int m_moveToPositionStateStatus;
  184. //*****************************************************
  185. protected AvatarAppearance m_appearance;
  186. public AvatarAppearance Appearance
  187. {
  188. get { return m_appearance; }
  189. set
  190. {
  191. m_appearance = value;
  192. // m_log.DebugFormat("[SCENE PRESENCE]: Set appearance for {0} to {1}", Name, value);
  193. }
  194. }
  195. /// <summary>
  196. /// Copy of the script states while the agent is in transit. This state may
  197. /// need to be placed back in case of transfer fail.
  198. /// </summary>
  199. public List<string> InTransitScriptStates
  200. {
  201. get { return m_InTransitScriptStates; }
  202. private set { m_InTransitScriptStates = value; }
  203. }
  204. private List<string> m_InTransitScriptStates = new List<string>();
  205. /// <summary>
  206. /// Implemented Control Flags
  207. /// </summary>
  208. private enum Dir_ControlFlags
  209. {
  210. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  211. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  212. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  213. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  214. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  215. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  216. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  217. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  218. DIR_CONTROL_FLAG_LEFT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS,
  219. DIR_CONTROL_FLAG_RIGHT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG,
  220. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  221. }
  222. /// <summary>
  223. /// Position at which a significant movement was made
  224. /// </summary>
  225. private Vector3 posLastSignificantMove;
  226. // For teleports and crossings callbacks
  227. string m_callbackURI;
  228. UUID m_originRegionID;
  229. /// <value>
  230. /// Script engines present in the scene
  231. /// </value>
  232. private IScriptModule[] m_scriptEngines;
  233. #region Properties
  234. /// <summary>
  235. /// Physical scene representation of this Avatar.
  236. /// </summary>
  237. public PhysicsActor PhysicsActor { get; private set; }
  238. /// <summary>
  239. /// Record user movement inputs.
  240. /// </summary>
  241. public byte MovementFlag { get; private set; }
  242. private bool m_updateflag;
  243. public bool Updated
  244. {
  245. set { m_updateflag = value; }
  246. get { return m_updateflag; }
  247. }
  248. private bool m_invulnerable = true;
  249. public bool Invulnerable
  250. {
  251. set { m_invulnerable = value; }
  252. get { return m_invulnerable; }
  253. }
  254. private int m_userLevel;
  255. public int UserLevel
  256. {
  257. get { return m_userLevel; }
  258. private set { m_userLevel = value; }
  259. }
  260. private int m_godLevel;
  261. public int GodLevel
  262. {
  263. get { return m_godLevel; }
  264. private set { m_godLevel = value; }
  265. }
  266. private ulong m_rootRegionHandle;
  267. public ulong RegionHandle
  268. {
  269. get { return m_rootRegionHandle; }
  270. private set { m_rootRegionHandle = value; }
  271. }
  272. #region Client Camera
  273. /// <summary>
  274. /// Position of agent's camera in world (region cordinates)
  275. /// </summary>
  276. protected Vector3 m_lastCameraPosition;
  277. protected Vector3 m_CameraPosition;
  278. public Vector3 CameraPosition
  279. {
  280. get { return m_CameraPosition; }
  281. private set { m_CameraPosition = value; }
  282. }
  283. public Quaternion CameraRotation
  284. {
  285. get { return Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis); }
  286. }
  287. // Use these three vectors to figure out what the agent is looking at
  288. // Convert it to a Matrix and/or Quaternion
  289. //
  290. protected Vector3 m_CameraAtAxis;
  291. protected Vector3 m_CameraLeftAxis;
  292. protected Vector3 m_CameraUpAxis;
  293. public Vector3 CameraAtAxis
  294. {
  295. get { return m_CameraAtAxis; }
  296. private set { m_CameraAtAxis = value; }
  297. }
  298. public Vector3 CameraLeftAxis
  299. {
  300. get { return m_CameraLeftAxis; }
  301. private set { m_CameraLeftAxis = value; }
  302. }
  303. public Vector3 CameraUpAxis
  304. {
  305. get { return m_CameraUpAxis; }
  306. private set { m_CameraUpAxis = value; }
  307. }
  308. public Vector3 Lookat
  309. {
  310. get
  311. {
  312. Vector3 a = new Vector3(CameraAtAxis.X, CameraAtAxis.Y, 0);
  313. if (a == Vector3.Zero)
  314. return a;
  315. return Util.GetNormalizedVector(a);
  316. }
  317. }
  318. #endregion
  319. public readonly string Firstname;
  320. public readonly string Lastname;
  321. private string m_grouptitle;
  322. public string Grouptitle
  323. {
  324. get { return m_grouptitle; }
  325. set { m_grouptitle = value; }
  326. }
  327. // Agent's Draw distance.
  328. protected float m_DrawDistance;
  329. public float DrawDistance
  330. {
  331. get { return m_DrawDistance; }
  332. private set { m_DrawDistance = value; }
  333. }
  334. protected bool m_allowMovement = true;
  335. public bool AllowMovement
  336. {
  337. get { return m_allowMovement; }
  338. set { m_allowMovement = value; }
  339. }
  340. private bool m_setAlwaysRun;
  341. public bool SetAlwaysRun
  342. {
  343. get
  344. {
  345. if (PhysicsActor != null)
  346. {
  347. return PhysicsActor.SetAlwaysRun;
  348. }
  349. else
  350. {
  351. return m_setAlwaysRun;
  352. }
  353. }
  354. set
  355. {
  356. m_setAlwaysRun = value;
  357. if (PhysicsActor != null)
  358. {
  359. PhysicsActor.SetAlwaysRun = value;
  360. }
  361. }
  362. }
  363. private byte m_state;
  364. public byte State
  365. {
  366. get { return m_state; }
  367. set { m_state = value; }
  368. }
  369. private AgentManager.ControlFlags m_AgentControlFlags;
  370. public uint AgentControlFlags
  371. {
  372. get { return (uint)m_AgentControlFlags; }
  373. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  374. }
  375. /// <summary>
  376. /// This works out to be the ClientView object associated with this avatar, or it's client connection manager
  377. /// </summary>
  378. private IClientAPI m_controllingClient;
  379. public IClientAPI ControllingClient
  380. {
  381. get { return m_controllingClient; }
  382. private set { m_controllingClient = value; }
  383. }
  384. public IClientCore ClientView
  385. {
  386. get { return (IClientCore) m_controllingClient; }
  387. }
  388. protected Vector3 m_parentPosition;
  389. public Vector3 ParentPosition
  390. {
  391. get { return m_parentPosition; }
  392. set { m_parentPosition = value; }
  393. }
  394. /// <summary>
  395. /// Position of this avatar relative to the region the avatar is in
  396. /// </summary>
  397. public override Vector3 AbsolutePosition
  398. {
  399. get
  400. {
  401. if (PhysicsActor != null && ParentID == 0)
  402. {
  403. m_pos = PhysicsActor.Position;
  404. //m_log.DebugFormat(
  405. // "[SCENE PRESENCE]: Set position {0} for {1} in {2} via getting AbsolutePosition!",
  406. // m_pos, Name, Scene.RegionInfo.RegionName);
  407. }
  408. else
  409. {
  410. // Obtain the correct position of a seated avatar.
  411. // In addition to providing the correct position while
  412. // the avatar is seated, this value will also
  413. // be used as the location to unsit to.
  414. //
  415. // If ParentID is not 0, assume we are a seated avatar
  416. // and we should return the position based on the sittarget
  417. // offset and rotation of the prim we are seated on.
  418. //
  419. // Generally, m_pos will contain the position of the avatar
  420. // in the sim unless the avatar is on a sit target. While
  421. // on a sit target, m_pos will contain the desired offset
  422. // without the parent rotation applied.
  423. SceneObjectPart sitPart = ParentPart;
  424. if (sitPart != null)
  425. return sitPart.AbsolutePosition + (m_pos * sitPart.GetWorldRotation());
  426. }
  427. return m_pos;
  428. }
  429. set
  430. {
  431. if (PhysicsActor != null)
  432. {
  433. try
  434. {
  435. PhysicsActor.Position = value;
  436. }
  437. catch (Exception e)
  438. {
  439. m_log.Error("[SCENE PRESENCE]: ABSOLUTE POSITION " + e.Message);
  440. }
  441. }
  442. // Don't update while sitting
  443. if (ParentID == 0)
  444. {
  445. m_pos = value;
  446. ParentPosition = Vector3.Zero;
  447. }
  448. //m_log.DebugFormat(
  449. // "[ENTITY BASE]: In {0} set AbsolutePosition of {1} to {2}",
  450. // Scene.RegionInfo.RegionName, Name, m_pos);
  451. }
  452. }
  453. /// <summary>
  454. /// If sitting, returns the offset position from the prim the avatar is sitting on.
  455. /// Otherwise, returns absolute position in the scene.
  456. /// </summary>
  457. public Vector3 OffsetPosition
  458. {
  459. get { return m_pos; }
  460. // Don't remove setter. It's not currently used in core but
  461. // upcoming Avination code needs it.
  462. set
  463. {
  464. // There is no offset position when not seated
  465. if (ParentID == 0)
  466. return;
  467. m_pos = value;
  468. }
  469. }
  470. /// <summary>
  471. /// Current velocity of the avatar.
  472. /// </summary>
  473. public override Vector3 Velocity
  474. {
  475. get
  476. {
  477. if (PhysicsActor != null)
  478. {
  479. m_velocity = PhysicsActor.Velocity;
  480. // m_log.DebugFormat(
  481. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  482. // m_velocity, Name, Scene.RegionInfo.RegionName);
  483. }
  484. return m_velocity;
  485. }
  486. set
  487. {
  488. if (PhysicsActor != null)
  489. {
  490. try
  491. {
  492. PhysicsActor.Velocity = value;
  493. }
  494. catch (Exception e)
  495. {
  496. m_log.Error("[SCENE PRESENCE]: VELOCITY " + e.Message);
  497. }
  498. }
  499. m_velocity = value;
  500. // m_log.DebugFormat(
  501. // "[SCENE PRESENCE]: In {0} set velocity of {1} to {2}",
  502. // Scene.RegionInfo.RegionName, Name, m_velocity);
  503. }
  504. }
  505. private Quaternion m_bodyRot = Quaternion.Identity;
  506. public Quaternion Rotation
  507. {
  508. get { return m_bodyRot; }
  509. set
  510. {
  511. m_bodyRot = value;
  512. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
  513. }
  514. }
  515. public bool IsChildAgent { get; set; }
  516. /// <summary>
  517. /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
  518. /// </summary>
  519. public uint ParentID { get; set; }
  520. /// <summary>
  521. /// Are we sitting on an object?
  522. /// </summary>
  523. /// <remarks>A more readable way of testing presence sit status than ParentID == 0</remarks>
  524. public bool IsSatOnObject { get { return ParentID != 0; } }
  525. /// <summary>
  526. /// If the avatar is sitting, the prim that it's sitting on. If not sitting then null.
  527. /// </summary>
  528. /// <remarks>
  529. /// If you use this property then you must take a reference since another thread could set it to null.
  530. /// </remarks>
  531. public SceneObjectPart ParentPart { get; set; }
  532. public float Health
  533. {
  534. get { return m_health; }
  535. set { m_health = value; }
  536. }
  537. public void AdjustKnownSeeds()
  538. {
  539. Dictionary<ulong, string> seeds;
  540. if (Scene.CapsModule != null)
  541. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  542. else
  543. seeds = new Dictionary<ulong, string>();
  544. List<ulong> old = new List<ulong>();
  545. foreach (ulong handle in seeds.Keys)
  546. {
  547. uint x, y;
  548. Utils.LongToUInts(handle, out x, out y);
  549. x = x / Constants.RegionSize;
  550. y = y / Constants.RegionSize;
  551. if (Util.IsOutsideView(DrawDistance, x, Scene.RegionInfo.RegionLocX, y, Scene.RegionInfo.RegionLocY))
  552. {
  553. old.Add(handle);
  554. }
  555. }
  556. DropOldNeighbours(old);
  557. if (Scene.CapsModule != null)
  558. Scene.CapsModule.SetChildrenSeed(UUID, seeds);
  559. KnownRegions = seeds;
  560. //m_log.Debug(" ++++++++++AFTER+++++++++++++ ");
  561. //DumpKnownRegions();
  562. }
  563. public void DumpKnownRegions()
  564. {
  565. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  566. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  567. {
  568. uint x, y;
  569. Utils.LongToUInts(kvp.Key, out x, out y);
  570. x = x / Constants.RegionSize;
  571. y = y / Constants.RegionSize;
  572. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  573. }
  574. }
  575. private bool m_mouseLook;
  576. private bool m_leftButtonDown;
  577. private bool m_inTransit;
  578. public bool IsInTransit
  579. {
  580. get { return m_inTransit; }
  581. set {
  582. if(value)
  583. {
  584. if (Flying)
  585. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  586. else
  587. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  588. }
  589. m_inTransit = value;
  590. }
  591. }
  592. private float m_speedModifier = 1.0f;
  593. public float SpeedModifier
  594. {
  595. get { return m_speedModifier; }
  596. set { m_speedModifier = value; }
  597. }
  598. private bool m_forceFly;
  599. public bool ForceFly
  600. {
  601. get { return m_forceFly; }
  602. set { m_forceFly = value; }
  603. }
  604. private bool m_flyDisabled;
  605. public bool FlyDisabled
  606. {
  607. get { return m_flyDisabled; }
  608. set { m_flyDisabled = value; }
  609. }
  610. public string Viewer
  611. {
  612. get { return m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode).Viewer; }
  613. }
  614. #endregion
  615. #region Constructor(s)
  616. public ScenePresence(
  617. IClientAPI client, Scene world, AvatarAppearance appearance, PresenceType type)
  618. {
  619. AttachmentsSyncLock = new Object();
  620. IsChildAgent = true;
  621. m_sendCourseLocationsMethod = SendCoarseLocationsDefault;
  622. Animator = new ScenePresenceAnimator(this);
  623. PresenceType = type;
  624. DrawDistance = world.DefaultDrawDistance;
  625. RegionHandle = world.RegionInfo.RegionHandle;
  626. ControllingClient = client;
  627. Firstname = ControllingClient.FirstName;
  628. Lastname = ControllingClient.LastName;
  629. m_name = String.Format("{0} {1}", Firstname, Lastname);
  630. m_scene = world;
  631. m_uuid = client.AgentId;
  632. LocalId = m_scene.AllocateLocalId();
  633. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  634. if (account != null)
  635. m_userFlags = account.UserFlags;
  636. else
  637. m_userFlags = 0;
  638. if (account != null)
  639. UserLevel = account.UserLevel;
  640. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  641. if (gm != null)
  642. Grouptitle = gm.GetGroupTitle(m_uuid);
  643. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  644. AbsolutePosition = posLastSignificantMove = CameraPosition =
  645. m_lastCameraPosition = ControllingClient.StartPos;
  646. m_reprioritization_timer = new Timer(world.ReprioritizationInterval);
  647. m_reprioritization_timer.Elapsed += new ElapsedEventHandler(Reprioritize);
  648. m_reprioritization_timer.AutoReset = false;
  649. AdjustKnownSeeds();
  650. RegisterToEvents();
  651. SetDirectionVectors();
  652. Appearance = appearance;
  653. }
  654. public void RegisterToEvents()
  655. {
  656. ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
  657. ControllingClient.OnAgentUpdate += HandleAgentUpdate;
  658. ControllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  659. ControllingClient.OnAgentSit += HandleAgentSit;
  660. ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  661. ControllingClient.OnStartAnim += HandleStartAnim;
  662. ControllingClient.OnStopAnim += HandleStopAnim;
  663. ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  664. ControllingClient.OnAutoPilotGo += MoveToTarget;
  665. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  666. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  667. }
  668. private void SetDirectionVectors()
  669. {
  670. Dir_Vectors[0] = Vector3.UnitX; //FORWARD
  671. Dir_Vectors[1] = -Vector3.UnitX; //BACK
  672. Dir_Vectors[2] = Vector3.UnitY; //LEFT
  673. Dir_Vectors[3] = -Vector3.UnitY; //RIGHT
  674. Dir_Vectors[4] = Vector3.UnitZ; //UP
  675. Dir_Vectors[5] = -Vector3.UnitZ; //DOWN
  676. Dir_Vectors[6] = new Vector3(0.5f, 0f, 0f); //FORWARD_NUDGE
  677. Dir_Vectors[7] = new Vector3(-0.5f, 0f, 0f); //BACK_NUDGE
  678. Dir_Vectors[8] = new Vector3(0f, 0.5f, 0f); //LEFT_NUDGE
  679. Dir_Vectors[9] = new Vector3(0f, -0.5f, 0f); //RIGHT_NUDGE
  680. Dir_Vectors[10] = new Vector3(0f, 0f, -0.5f); //DOWN_Nudge
  681. }
  682. private Vector3[] GetWalkDirectionVectors()
  683. {
  684. Vector3[] vector = new Vector3[11];
  685. vector[0] = new Vector3(m_CameraUpAxis.Z, 0f, -m_CameraAtAxis.Z); //FORWARD
  686. vector[1] = new Vector3(-m_CameraUpAxis.Z, 0f, m_CameraAtAxis.Z); //BACK
  687. vector[2] = Vector3.UnitY; //LEFT
  688. vector[3] = -Vector3.UnitY; //RIGHT
  689. vector[4] = new Vector3(m_CameraAtAxis.Z, 0f, m_CameraUpAxis.Z); //UP
  690. vector[5] = new Vector3(-m_CameraAtAxis.Z, 0f, -m_CameraUpAxis.Z); //DOWN
  691. vector[6] = new Vector3(m_CameraUpAxis.Z, 0f, -m_CameraAtAxis.Z); //FORWARD_NUDGE
  692. vector[7] = new Vector3(-m_CameraUpAxis.Z, 0f, m_CameraAtAxis.Z); //BACK_NUDGE
  693. vector[8] = Vector3.UnitY; //LEFT_NUDGE
  694. vector[9] = -Vector3.UnitY; //RIGHT_NUDGE
  695. vector[10] = new Vector3(-m_CameraAtAxis.Z, 0f, -m_CameraUpAxis.Z); //DOWN_NUDGE
  696. return vector;
  697. }
  698. #endregion
  699. #region Status Methods
  700. /// <summary>
  701. /// Turns a child agent into a root agent.
  702. /// </summary>
  703. /// Child agents are logged into neighbouring sims largely to observe changes. Root agents exist when the
  704. /// avatar is actual in the sim. They can perform all actions.
  705. /// This change is made whenever an avatar enters a region, whether by crossing over from a neighbouring sim,
  706. /// teleporting in or on initial login.
  707. ///
  708. /// This method is on the critical path for transferring an avatar from one region to another. Delay here
  709. /// delays that crossing.
  710. /// </summary>
  711. public void MakeRootAgent(Vector3 pos, bool isFlying)
  712. {
  713. m_log.DebugFormat(
  714. "[SCENE]: Upgrading child to root agent for {0} in {1}",
  715. Name, m_scene.RegionInfo.RegionName);
  716. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  717. bool wasChild = IsChildAgent;
  718. IsChildAgent = false;
  719. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  720. if (gm != null)
  721. Grouptitle = gm.GetGroupTitle(m_uuid);
  722. RegionHandle = m_scene.RegionInfo.RegionHandle;
  723. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  724. // Moved this from SendInitialData to ensure that Appearance is initialized
  725. // before the inventory is processed in MakeRootAgent. This fixes a race condition
  726. // related to the handling of attachments
  727. //m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
  728. if (m_scene.TestBorderCross(pos, Cardinals.E))
  729. {
  730. Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.E);
  731. pos.X = crossedBorder.BorderLine.Z - 1;
  732. }
  733. if (m_scene.TestBorderCross(pos, Cardinals.N))
  734. {
  735. Border crossedBorder = m_scene.GetCrossedBorder(pos, Cardinals.N);
  736. pos.Y = crossedBorder.BorderLine.Z - 1;
  737. }
  738. CheckAndAdjustLandingPoint(ref pos);
  739. if (pos.X < 0f || pos.Y < 0f || pos.Z < 0f)
  740. {
  741. m_log.WarnFormat(
  742. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  743. pos, Name, UUID);
  744. if (pos.X < 0f) pos.X = 0f;
  745. if (pos.Y < 0f) pos.Y = 0f;
  746. if (pos.Z < 0f) pos.Z = 0f;
  747. }
  748. float localAVHeight = 1.56f;
  749. if (Appearance.AvatarHeight > 0)
  750. localAVHeight = Appearance.AvatarHeight;
  751. float posZLimit = 0;
  752. if (pos.X < Constants.RegionSize && pos.Y < Constants.RegionSize)
  753. posZLimit = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
  754. float newPosZ = posZLimit + localAVHeight / 2;
  755. if (posZLimit >= (pos.Z - (localAVHeight / 2)) && !(Single.IsInfinity(newPosZ) || Single.IsNaN(newPosZ)))
  756. {
  757. pos.Z = newPosZ;
  758. }
  759. AbsolutePosition = pos;
  760. AddToPhysicalScene(isFlying);
  761. if (ForceFly)
  762. {
  763. Flying = true;
  764. }
  765. else if (FlyDisabled)
  766. {
  767. Flying = false;
  768. }
  769. // Don't send an animation pack here, since on a region crossing this will sometimes cause a flying
  770. // avatar to return to the standing position in mid-air. On login it looks like this is being sent
  771. // elsewhere anyway
  772. // Animator.SendAnimPack();
  773. m_scene.SwapRootAgentCount(false);
  774. // The initial login scene presence is already root when it gets here
  775. // and it has already rezzed the attachments and started their scripts.
  776. // We do the following only for non-login agents, because their scripts
  777. // haven't started yet.
  778. lock (m_attachments)
  779. {
  780. if (wasChild && HasAttachments())
  781. {
  782. m_log.DebugFormat("[SCENE PRESENCE]: Restarting scripts in attachments...");
  783. // Resume scripts
  784. foreach (SceneObjectGroup sog in m_attachments)
  785. {
  786. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  787. sog.ResumeScripts();
  788. }
  789. }
  790. }
  791. // send the animations of the other presences to me
  792. m_scene.ForEachRootScenePresence(delegate(ScenePresence presence)
  793. {
  794. if (presence != this)
  795. presence.Animator.SendAnimPackToClient(ControllingClient);
  796. });
  797. // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
  798. // stall on the border crossing since the existing child agent will still have the last movement
  799. // recorded, which stops the input from being processed.
  800. MovementFlag = 0;
  801. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  802. }
  803. public int GetStateSource()
  804. {
  805. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  806. if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
  807. {
  808. // This will get your attention
  809. //m_log.Error("[XXX] Triggering CHANGED_TELEPORT");
  810. return 5; // StateSource.Teleporting
  811. }
  812. return 2; // StateSource.PrimCrossing
  813. }
  814. /// <summary>
  815. /// This turns a root agent into a child agent
  816. /// </summary>
  817. /// <remarks>
  818. /// when an agent departs this region for a neighbor, this gets called.
  819. ///
  820. /// It doesn't get called for a teleport. Reason being, an agent that
  821. /// teleports out may not end up anywhere near this region
  822. /// </remarks>
  823. public void MakeChildAgent()
  824. {
  825. m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1}", Name, Scene.RegionInfo.RegionName);
  826. // Reset these so that teleporting in and walking out isn't seen
  827. // as teleporting back
  828. TeleportFlags = TeleportFlags.Default;
  829. // It looks like Animator is set to null somewhere, and MakeChild
  830. // is called after that. Probably in aborted teleports.
  831. if (Animator == null)
  832. Animator = new ScenePresenceAnimator(this);
  833. else
  834. Animator.ResetAnimations();
  835. // m_log.DebugFormat(
  836. // "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  837. // Name, UUID, m_scene.RegionInfo.RegionName);
  838. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  839. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  840. //Velocity = new Vector3(0, 0, 0);
  841. IsChildAgent = true;
  842. m_scene.SwapRootAgentCount(true);
  843. RemoveFromPhysicalScene();
  844. // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
  845. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  846. }
  847. /// <summary>
  848. /// Removes physics plugin scene representation of this agent if it exists.
  849. /// </summary>
  850. public void RemoveFromPhysicalScene()
  851. {
  852. if (PhysicsActor != null)
  853. {
  854. // PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  855. PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
  856. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  857. PhysicsActor.UnSubscribeEvents();
  858. PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  859. PhysicsActor = null;
  860. }
  861. // else
  862. // {
  863. // m_log.ErrorFormat(
  864. // "[SCENE PRESENCE]: Attempt to remove physics actor for {0} on {1} but this scene presence has no physics actor",
  865. // Name, Scene.RegionInfo.RegionName);
  866. // }
  867. }
  868. /// <summary>
  869. /// Do not call this directly. Call Scene.RequestTeleportLocation() instead.
  870. /// </summary>
  871. /// <param name="pos"></param>
  872. public void Teleport(Vector3 pos)
  873. {
  874. TeleportWithMomentum(pos, null);
  875. }
  876. public void TeleportWithMomentum(Vector3 pos, Vector3? v)
  877. {
  878. if (ParentID != (uint)0)
  879. StandUp();
  880. bool isFlying = Flying;
  881. Vector3 vel = Velocity;
  882. RemoveFromPhysicalScene();
  883. CheckLandingPoint(ref pos);
  884. AbsolutePosition = pos;
  885. AddToPhysicalScene(isFlying);
  886. if (PhysicsActor != null)
  887. {
  888. if (v.HasValue)
  889. PhysicsActor.SetMomentum((Vector3)v);
  890. else
  891. PhysicsActor.SetMomentum(vel);
  892. }
  893. SendTerseUpdateToAllClients();
  894. }
  895. public void StopFlying()
  896. {
  897. ControllingClient.StopFlying(this);
  898. }
  899. // neighbouring regions we have enabled a child agent in
  900. // holds the seed cap for the child agent in that region
  901. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  902. public void AddNeighbourRegion(ulong regionHandle, string cap)
  903. {
  904. lock (m_knownChildRegions)
  905. {
  906. if (!m_knownChildRegions.ContainsKey(regionHandle))
  907. {
  908. uint x, y;
  909. Utils.LongToUInts(regionHandle, out x, out y);
  910. m_knownChildRegions.Add(regionHandle, cap);
  911. }
  912. }
  913. }
  914. public void RemoveNeighbourRegion(ulong regionHandle)
  915. {
  916. lock (m_knownChildRegions)
  917. {
  918. // Checking ContainsKey is redundant as Remove works either way and returns a bool
  919. // This is here to allow the Debug output to be conditional on removal
  920. //if (m_knownChildRegions.ContainsKey(regionHandle))
  921. // m_log.DebugFormat(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  922. m_knownChildRegions.Remove(regionHandle);
  923. }
  924. }
  925. public void DropOldNeighbours(List<ulong> oldRegions)
  926. {
  927. foreach (ulong handle in oldRegions)
  928. {
  929. RemoveNeighbourRegion(handle);
  930. Scene.CapsModule.DropChildSeed(UUID, handle);
  931. }
  932. }
  933. public Dictionary<ulong, string> KnownRegions
  934. {
  935. get
  936. {
  937. lock (m_knownChildRegions)
  938. return new Dictionary<ulong, string>(m_knownChildRegions);
  939. }
  940. set
  941. {
  942. // Replacing the reference is atomic but we still need to lock on
  943. // the original dictionary object which may be in use elsewhere
  944. lock (m_knownChildRegions)
  945. m_knownChildRegions = value;
  946. }
  947. }
  948. public List<ulong> KnownRegionHandles
  949. {
  950. get
  951. {
  952. return new List<ulong>(KnownRegions.Keys);
  953. }
  954. }
  955. public int KnownRegionCount
  956. {
  957. get
  958. {
  959. lock (m_knownChildRegions)
  960. return m_knownChildRegions.Count;
  961. }
  962. }
  963. #endregion
  964. #region Event Handlers
  965. /// <summary>
  966. /// Sets avatar height in the physics plugin
  967. /// </summary>
  968. /// <param name="height">New height of avatar</param>
  969. public void SetHeight(float height)
  970. {
  971. if (PhysicsActor != null && !IsChildAgent)
  972. PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
  973. }
  974. /// <summary>
  975. /// Complete Avatar's movement into the region.
  976. /// </summary>
  977. /// <param name="client"></param>
  978. /// <param name="openChildAgents">
  979. /// If true, send notification to neighbour regions to expect
  980. /// a child agent from the client. These neighbours can be some distance away, depending right now on the
  981. /// configuration of DefaultDrawDistance in the [Startup] section of config
  982. /// </param>
  983. public void CompleteMovement(IClientAPI client, bool openChildAgents)
  984. {
  985. // DateTime startTime = DateTime.Now;
  986. m_log.DebugFormat(
  987. "[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
  988. client.Name, Scene.RegionInfo.RegionName, AbsolutePosition);
  989. Vector3 look = Velocity;
  990. if ((look.X == 0) && (look.Y == 0) && (look.Z == 0))
  991. {
  992. look = new Vector3(0.99f, 0.042f, 0);
  993. }
  994. // Prevent teleporting to an underground location
  995. // (may crash client otherwise)
  996. //
  997. Vector3 pos = AbsolutePosition;
  998. float ground = m_scene.GetGroundHeight(pos.X, pos.Y);
  999. if (pos.Z < ground + 1.5f)
  1000. {
  1001. pos.Z = ground + 1.5f;
  1002. AbsolutePosition = pos;
  1003. }
  1004. bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1005. MakeRootAgent(AbsolutePosition, flying);
  1006. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1007. // m_log.DebugFormat("[SCENE PRESENCE] Completed movement");
  1008. if ((m_callbackURI != null) && !m_callbackURI.Equals(""))
  1009. {
  1010. // We cannot sleep here since this would hold up the inbound packet processing thread, as
  1011. // CompleteMovement() is executed synchronously. However, it might be better to delay the release
  1012. // here until we know for sure that the agent is active in this region. Sending AgentMovementComplete
  1013. // is not enough for Imprudence clients - there appears to be a small delay (<200ms, <500ms) until they regard this
  1014. // region as the current region, meaning that a close sent before then will fail the teleport.
  1015. // System.Threading.Thread.Sleep(2000);
  1016. m_log.DebugFormat(
  1017. "[SCENE PRESENCE]: Releasing {0} {1} with callback to {2}",
  1018. client.Name, client.AgentId, m_callbackURI);
  1019. Scene.SimulationService.ReleaseAgent(m_originRegionID, UUID, m_callbackURI);
  1020. m_callbackURI = null;
  1021. }
  1022. // else
  1023. // {
  1024. // m_log.DebugFormat(
  1025. // "[SCENE PRESENCE]: No callback provided on CompleteMovement of {0} {1} to {2}",
  1026. // client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
  1027. // }
  1028. ValidateAndSendAppearanceAndAgentData();
  1029. // Create child agents in neighbouring regions
  1030. if (openChildAgents && !IsChildAgent)
  1031. {
  1032. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  1033. if (m_agentTransfer != null)
  1034. Util.FireAndForget(delegate { m_agentTransfer.EnableChildAgents(this); });
  1035. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  1036. if (friendsModule != null)
  1037. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  1038. }
  1039. // m_log.DebugFormat(
  1040. // "[SCENE PRESENCE]: Completing movement of {0} into region {1} took {2}ms",
  1041. // client.Name, Scene.RegionInfo.RegionName, (DateTime.Now - startTime).Milliseconds);
  1042. }
  1043. /// <summary>
  1044. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  1045. /// hitYN is true when there's something in the way.
  1046. /// </summary>
  1047. /// <param name="hitYN"></param>
  1048. /// <param name="collisionPoint"></param>
  1049. /// <param name="localid"></param>
  1050. /// <param name="distance"></param>
  1051. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  1052. {
  1053. const float POSITION_TOLERANCE = 0.02f;
  1054. const float VELOCITY_TOLERANCE = 0.02f;
  1055. const float ROTATION_TOLERANCE = 0.02f;
  1056. if (m_followCamAuto)
  1057. {
  1058. if (hitYN)
  1059. {
  1060. CameraConstraintActive = true;
  1061. //m_log.DebugFormat("[RAYCASTRESULT]: {0}, {1}, {2}, {3}", hitYN, collisionPoint, localid, distance);
  1062. Vector3 normal = Vector3.Normalize(new Vector3(0f, 0f, collisionPoint.Z) - collisionPoint);
  1063. ControllingClient.SendCameraConstraint(new Vector4(normal.X, normal.Y, normal.Z, -1 * Vector3.Distance(new Vector3(0,0,collisionPoint.Z),collisionPoint)));
  1064. }
  1065. else
  1066. {
  1067. if (!m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE) ||
  1068. !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
  1069. !Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE))
  1070. {
  1071. if (CameraConstraintActive)
  1072. {
  1073. ControllingClient.SendCameraConstraint(new Vector4(0f, 0.5f, 0.9f, -3000f));
  1074. CameraConstraintActive = false;
  1075. }
  1076. }
  1077. }
  1078. }
  1079. }
  1080. /// <summary>
  1081. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  1082. /// </summary>
  1083. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  1084. {
  1085. // m_log.DebugFormat(
  1086. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  1087. // Scene.RegionInfo.RegionName, remoteClient.Name, agentData.ControlFlags);
  1088. if (IsChildAgent)
  1089. {
  1090. // // m_log.Debug("DEBUG: HandleAgentUpdate: child agent");
  1091. return;
  1092. }
  1093. ++m_movementUpdateCount;
  1094. if (m_movementUpdateCount < 1)
  1095. m_movementUpdateCount = 1;
  1096. #region Sanity Checking
  1097. // This is irritating. Really.
  1098. if (!AbsolutePosition.IsFinite())
  1099. {
  1100. RemoveFromPhysicalScene();
  1101. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  1102. m_pos = m_LastFinitePos;
  1103. if (!m_pos.IsFinite())
  1104. {
  1105. m_pos.X = 127f;
  1106. m_pos.Y = 127f;
  1107. m_pos.Z = 127f;
  1108. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999903");
  1109. }
  1110. AddToPhysicalScene(false);
  1111. }
  1112. else
  1113. {
  1114. m_LastFinitePos = m_pos;
  1115. }
  1116. #endregion Sanity Checking
  1117. #region Inputs
  1118. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  1119. // Camera location in world. We'll need to raytrace
  1120. // from this location from time to time.
  1121. CameraPosition = agentData.CameraCenter;
  1122. if (Vector3.Distance(m_lastCameraPosition, CameraPosition) >= Scene.RootReprioritizationDistance)
  1123. {
  1124. ReprioritizeUpdates();
  1125. m_lastCameraPosition = CameraPosition;
  1126. }
  1127. // Use these three vectors to figure out what the agent is looking at
  1128. // Convert it to a Matrix and/or Quaternion
  1129. CameraAtAxis = agentData.CameraAtAxis;
  1130. CameraLeftAxis = agentData.CameraLeftAxis;
  1131. m_CameraUpAxis = agentData.CameraUpAxis;
  1132. // The Agent's Draw distance setting
  1133. // When we get to the point of re-computing neighbors everytime this
  1134. // changes, then start using the agent's drawdistance rather than the
  1135. // region's draw distance.
  1136. // DrawDistance = agentData.Far;
  1137. DrawDistance = Scene.DefaultDrawDistance;
  1138. // Check if Client has camera in 'follow cam' or 'build' mode.
  1139. Vector3 camdif = (Vector3.One * Rotation - Vector3.One * CameraRotation);
  1140. m_followCamAuto = ((m_CameraUpAxis.Z > 0.959f && m_CameraUpAxis.Z < 0.98f)
  1141. && (Math.Abs(camdif.X) < 0.4f && Math.Abs(camdif.Y) < 0.4f)) ? true : false;
  1142. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  1143. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  1144. #endregion Inputs
  1145. // // Make anims work for client side autopilot
  1146. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  1147. // m_updateCount = UPDATE_COUNT;
  1148. //
  1149. // // Make turning in place work
  1150. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  1151. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  1152. // m_updateCount = UPDATE_COUNT;
  1153. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  1154. {
  1155. StandUp();
  1156. }
  1157. //m_log.DebugFormat("[FollowCam]: {0}", m_followCamAuto);
  1158. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  1159. if ((m_movementUpdateCount % NumMovementsBetweenRayCast) == 0 && m_scene.PhysicsScene.SupportsRayCast())
  1160. {
  1161. if (m_followCamAuto)
  1162. {
  1163. Vector3 posAdjusted = m_pos + HEAD_ADJUSTMENT;
  1164. m_scene.PhysicsScene.RaycastWorld(m_pos, Vector3.Normalize(CameraPosition - posAdjusted), Vector3.Distance(CameraPosition, posAdjusted) + 0.3f, RayCastCameraCallback);
  1165. }
  1166. }
  1167. lock (scriptedcontrols)
  1168. {
  1169. if (scriptedcontrols.Count > 0)
  1170. {
  1171. SendControlToScripts((uint)flags);
  1172. flags = RemoveIgnoredControls(flags, IgnoredControls);
  1173. }
  1174. }
  1175. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  1176. HandleAgentSitOnGround();
  1177. // In the future, these values might need to go global.
  1178. // Here's where you get them.
  1179. m_AgentControlFlags = flags;
  1180. m_headrotation = agentData.HeadRotation;
  1181. State = agentData.State;
  1182. PhysicsActor actor = PhysicsActor;
  1183. if (actor == null)
  1184. {
  1185. return;
  1186. }
  1187. if (AllowMovement && !SitGround)
  1188. {
  1189. Quaternion bodyRotation = agentData.BodyRotation;
  1190. bool update_rotation = false;
  1191. if (bodyRotation != Rotation)
  1192. {
  1193. Rotation = bodyRotation;
  1194. update_rotation = true;
  1195. }
  1196. bool update_movementflag = false;
  1197. if (agentData.UseClientAgentPosition)
  1198. {
  1199. MovingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).Length() > 0.2f;
  1200. MoveToPositionTarget = agentData.ClientAgentPosition;
  1201. }
  1202. int i = 0;
  1203. bool DCFlagKeyPressed = false;
  1204. Vector3 agent_control_v3 = Vector3.Zero;
  1205. bool oldflying = Flying;
  1206. if (ForceFly)
  1207. actor.Flying = true;
  1208. else if (FlyDisabled)
  1209. actor.Flying = false;
  1210. else
  1211. actor.Flying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1212. if (actor.Flying != oldflying)
  1213. update_movementflag = true;
  1214. if (ParentID == 0)
  1215. {
  1216. bool bAllowUpdateMoveToPosition = false;
  1217. Vector3[] dirVectors;
  1218. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  1219. // this prevents 'jumping' in inappropriate situations.
  1220. if (!Flying && (m_mouseLook || m_leftButtonDown))
  1221. dirVectors = GetWalkDirectionVectors();
  1222. else
  1223. dirVectors = Dir_Vectors;
  1224. // The fact that MovementFlag is a byte needs to be fixed
  1225. // it really should be a uint
  1226. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  1227. uint nudgehack = 250;
  1228. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  1229. {
  1230. if (((uint)flags & (uint)DCF) != 0)
  1231. {
  1232. DCFlagKeyPressed = true;
  1233. try
  1234. {
  1235. agent_control_v3 += dirVectors[i];
  1236. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  1237. }
  1238. catch (IndexOutOfRangeException)
  1239. {
  1240. // Why did I get this?
  1241. }
  1242. if ((MovementFlag & (byte)(uint)DCF) == 0)
  1243. {
  1244. if (DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE ||
  1245. DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT_NUDGE)
  1246. {
  1247. MovementFlag |= (byte)nudgehack;
  1248. }
  1249. // m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  1250. MovementFlag += (byte)(uint)DCF;
  1251. update_movementflag = true;
  1252. }
  1253. }
  1254. else
  1255. {
  1256. if ((MovementFlag & (byte)(uint)DCF) != 0 ||
  1257. ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE ||
  1258. DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT_NUDGE)
  1259. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  1260. ) // This or is for Nudge forward
  1261. {
  1262. // m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  1263. MovementFlag -= ((byte)(uint)DCF);
  1264. update_movementflag = true;
  1265. /*
  1266. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  1267. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  1268. {
  1269. m_log.Debug("Removed Hack flag");
  1270. }
  1271. */
  1272. }
  1273. else
  1274. {
  1275. bAllowUpdateMoveToPosition = true;
  1276. }
  1277. }
  1278. i++;
  1279. }
  1280. if (MovingToTarget)
  1281. {
  1282. // If the user has pressed a key then we want to cancel any move to target.
  1283. if (DCFlagKeyPressed)
  1284. {
  1285. ResetMoveToTarget();
  1286. update_movementflag = true;
  1287. }
  1288. else if (bAllowUpdateMoveToPosition)
  1289. {
  1290. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  1291. // certain position. It's only check for tolerance on returning to that position is 0.2
  1292. // rather than 1, at which point it removes its force target.
  1293. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2 : 1, ref agent_control_v3))
  1294. update_movementflag = true;
  1295. }
  1296. }
  1297. }
  1298. // Cause the avatar to stop flying if it's colliding
  1299. // with something with the down arrow pressed.
  1300. // Only do this if we're flying
  1301. if (Flying && !ForceFly)
  1302. {
  1303. // Landing detection code
  1304. // Are the landing controls requirements filled?
  1305. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  1306. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1307. if (Flying && IsColliding && controlland)
  1308. {
  1309. // nesting this check because LengthSquared() is expensive and we don't
  1310. // want to do it every step when flying.
  1311. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  1312. StopFlying();
  1313. }
  1314. }
  1315. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  1316. // which occurs later in the main scene loop
  1317. if (update_movementflag || (update_rotation && DCFlagKeyPressed))
  1318. {
  1319. // m_log.DebugFormat(
  1320. // "[SCENE PRESENCE]: In {0} adding velocity of {1} to {2}, umf = {3}, ur = {4}",
  1321. // m_scene.RegionInfo.RegionName, agent_control_v3, Name, update_movementflag, update_rotation);
  1322. AddNewMovement(agent_control_v3);
  1323. }
  1324. // else
  1325. // {
  1326. // if (!update_movementflag)
  1327. // {
  1328. // m_log.DebugFormat(
  1329. // "[SCENE PRESENCE]: In {0} ignoring requested update of {1} for {2} as update_movementflag = false",
  1330. // m_scene.RegionInfo.RegionName, agent_control_v3, Name);
  1331. // }
  1332. // }
  1333. // if (update_movementflag && ParentID == 0)
  1334. // Animator.UpdateMovementAnimations();
  1335. }
  1336. m_scene.EventManager.TriggerOnClientMovement(this);
  1337. }
  1338. /// <summary>
  1339. /// Calculate an update to move the presence to the set target.
  1340. /// </summary>
  1341. /// <remarks>
  1342. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  1343. /// </remarks>
  1344. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  1345. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  1346. public bool HandleMoveToTargetUpdate(double tolerance, ref Vector3 agent_control_v3)
  1347. {
  1348. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  1349. bool updated = false;
  1350. // m_log.DebugFormat(
  1351. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  1352. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  1353. double distanceToTarget = Util.GetDistanceTo(AbsolutePosition, MoveToPositionTarget);
  1354. // m_log.DebugFormat(
  1355. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  1356. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  1357. // Check the error term of the current position in relation to the target position
  1358. if (distanceToTarget <= tolerance)
  1359. {
  1360. // We are close enough to the target
  1361. AbsolutePosition = MoveToPositionTarget;
  1362. ResetMoveToTarget();
  1363. updated = true;
  1364. }
  1365. else
  1366. {
  1367. try
  1368. {
  1369. // move avatar in 3D at one meter/second towards target, in avatar coordinate frame.
  1370. // This movement vector gets added to the velocity through AddNewMovement().
  1371. // Theoretically we might need a more complex PID approach here if other
  1372. // unknown forces are acting on the avatar and we need to adaptively respond
  1373. // to such forces, but the following simple approach seems to works fine.
  1374. Vector3 LocalVectorToTarget3D =
  1375. (MoveToPositionTarget - AbsolutePosition) // vector from cur. pos to target in global coords
  1376. * Matrix4.CreateFromQuaternion(Quaternion.Inverse(Rotation)); // change to avatar coords
  1377. // Ignore z component of vector
  1378. // Vector3 LocalVectorToTarget2D = new Vector3((float)(LocalVectorToTarget3D.X), (float)(LocalVectorToTarget3D.Y), 0f);
  1379. LocalVectorToTarget3D.Normalize();
  1380. // update avatar movement flags. the avatar coordinate system is as follows:
  1381. //
  1382. // +X (forward)
  1383. //
  1384. // ^
  1385. // |
  1386. // |
  1387. // |
  1388. // |
  1389. // (left) +Y <--------o--------> -Y
  1390. // avatar
  1391. // |
  1392. // |
  1393. // |
  1394. // |
  1395. // v
  1396. // -X
  1397. //
  1398. // based on the above avatar coordinate system, classify the movement into
  1399. // one of left/right/back/forward.
  1400. if (LocalVectorToTarget3D.X < 0) //MoveBack
  1401. {
  1402. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1403. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  1404. updated = true;
  1405. }
  1406. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  1407. {
  1408. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1409. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  1410. updated = true;
  1411. }
  1412. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  1413. {
  1414. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1415. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  1416. updated = true;
  1417. }
  1418. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  1419. {
  1420. MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1421. AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  1422. updated = true;
  1423. }
  1424. if (LocalVectorToTarget3D.Z > 0) //Up
  1425. {
  1426. // Don't set these flags for up or down - doing so will make the avatar crouch or
  1427. // keep trying to jump even if walking along level ground
  1428. //MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
  1429. //AgentControlFlags
  1430. //AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_UP;
  1431. updated = true;
  1432. }
  1433. else if (LocalVectorToTarget3D.Z < 0) //Down
  1434. {
  1435. //MovementFlag += (byte)(uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
  1436. //AgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN;
  1437. updated = true;
  1438. }
  1439. // m_log.DebugFormat(
  1440. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  1441. // LocalVectorToTarget3D, agent_control_v3, Name);
  1442. agent_control_v3 += LocalVectorToTarget3D;
  1443. }
  1444. catch (Exception e)
  1445. {
  1446. //Avoid system crash, can be slower but...
  1447. m_log.DebugFormat("Crash! {0}", e.ToString());
  1448. }
  1449. }
  1450. return updated;
  1451. }
  1452. /// <summary>
  1453. /// Move to the given target over time.
  1454. /// </summary>
  1455. /// <param name="pos"></param>
  1456. /// <param name="noFly">
  1457. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  1458. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  1459. /// from start to finish.
  1460. /// </param>
  1461. /// <param name="landAtTarget">
  1462. /// If true and the avatar starts flying during the move then land at the target.
  1463. /// </param>
  1464. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget)
  1465. {
  1466. if (SitGround)
  1467. StandUp();
  1468. // m_log.DebugFormat(
  1469. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  1470. // Name, pos, m_scene.RegionInfo.RegionName);
  1471. if (pos.X < 0 || pos.X >= Constants.RegionSize
  1472. || pos.Y < 0 || pos.Y >= Constants.RegionSize
  1473. || pos.Z < 0)
  1474. return;
  1475. // Vector3 heightAdjust = new Vector3(0, 0, Appearance.AvatarHeight / 2);
  1476. // pos += heightAdjust;
  1477. //
  1478. // // Anti duck-walking measure
  1479. // if (Math.Abs(pos.Z - AbsolutePosition.Z) < 0.2f)
  1480. // {
  1481. //// m_log.DebugFormat("[SCENE PRESENCE]: Adjusting MoveToPosition from {0} to {1}", pos, AbsolutePosition);
  1482. // pos.Z = AbsolutePosition.Z;
  1483. // }
  1484. float terrainHeight = (float)m_scene.Heightmap[(int)pos.X, (int)pos.Y];
  1485. pos.Z = Math.Max(terrainHeight, pos.Z);
  1486. // Fudge factor. It appears that if one clicks "go here" on a piece of ground, the go here request is
  1487. // always slightly higher than the actual terrain height.
  1488. // FIXME: This constrains NPC movements as well, so should be somewhere else.
  1489. if (pos.Z - terrainHeight < 0.2)
  1490. pos.Z = terrainHeight;
  1491. // m_log.DebugFormat(
  1492. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  1493. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  1494. if (noFly)
  1495. Flying = false;
  1496. else if (pos.Z > terrainHeight)
  1497. Flying = true;
  1498. LandAtTarget = landAtTarget;
  1499. MovingToTarget = true;
  1500. MoveToPositionTarget = pos;
  1501. // Rotate presence around the z-axis to point in same direction as movement.
  1502. // Ignore z component of vector
  1503. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  1504. Vector3 localVectorToTarget2D = new Vector3((float)(localVectorToTarget3D.X), (float)(localVectorToTarget3D.Y), 0f);
  1505. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0}", localVectorToTarget2D);
  1506. // Calculate the yaw.
  1507. Vector3 angle = new Vector3(0, 0, (float)(Math.Atan2(localVectorToTarget2D.Y, localVectorToTarget2D.X)));
  1508. // m_log.DebugFormat("[SCENE PRESENCE]: Angle is {0}", angle);
  1509. Rotation = Quaternion.CreateFromEulers(angle);
  1510. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, Rotation);
  1511. Vector3 agent_control_v3 = new Vector3();
  1512. HandleMoveToTargetUpdate(1, ref agent_control_v3);
  1513. AddNewMovement(agent_control_v3);
  1514. }
  1515. /// <summary>
  1516. /// Reset the move to target.
  1517. /// </summary>
  1518. public void ResetMoveToTarget()
  1519. {
  1520. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  1521. MovingToTarget = false;
  1522. MoveToPositionTarget = Vector3.Zero;
  1523. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  1524. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  1525. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  1526. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  1527. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  1528. }
  1529. /// <summary>
  1530. /// Perform the logic necessary to stand the avatar up. This method also executes
  1531. /// the stand animation.
  1532. /// </summary>
  1533. public void StandUp()
  1534. {
  1535. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  1536. SitGround = false;
  1537. if (PhysicsActor == null)
  1538. AddToPhysicalScene(false);
  1539. if (ParentID != 0)
  1540. {
  1541. SceneObjectPart part = ParentPart;
  1542. TaskInventoryDictionary taskIDict = part.TaskInventory;
  1543. if (taskIDict != null)
  1544. {
  1545. lock (taskIDict)
  1546. {
  1547. foreach (UUID taskID in taskIDict.Keys)
  1548. {
  1549. UnRegisterControlEventsToScript(LocalId, taskID);
  1550. taskIDict[taskID].PermsMask &= ~(
  1551. 2048 | //PERMISSION_CONTROL_CAMERA
  1552. 4); // PERMISSION_TAKE_CONTROLS
  1553. }
  1554. }
  1555. }
  1556. ParentPosition = part.GetWorldPosition();
  1557. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  1558. m_pos += ParentPosition + new Vector3(0.0f, 0.0f, 2.0f * m_sitAvatarHeight);
  1559. ParentPosition = Vector3.Zero;
  1560. ParentID = 0;
  1561. ParentPart = null;
  1562. SendAvatarDataToAllAgents();
  1563. m_requestedSitTargetID = 0;
  1564. part.RemoveSittingAvatar(UUID);
  1565. if (part != null)
  1566. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  1567. }
  1568. Animator.TrySetMovementAnimation("STAND");
  1569. }
  1570. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  1571. {
  1572. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  1573. if (targetPart == null)
  1574. return null;
  1575. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  1576. // If the primitive the player clicked on has no sit target, and one or more other linked objects have sit targets that are not full, the sit target of the object with the lowest link number will be used.
  1577. // Get our own copy of the part array, and sort into the order we want to test
  1578. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  1579. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  1580. {
  1581. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  1582. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  1583. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  1584. return linkNum1 - linkNum2;
  1585. }
  1586. );
  1587. //look for prims with explicit sit targets that are available
  1588. foreach (SceneObjectPart part in partArray)
  1589. {
  1590. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  1591. {
  1592. //switch the target to this prim
  1593. return part;
  1594. }
  1595. }
  1596. // no explicit sit target found - use original target
  1597. return targetPart;
  1598. }
  1599. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  1600. {
  1601. Vector3 cameraEyeOffset = Vector3.Zero;
  1602. Vector3 cameraAtOffset = Vector3.Zero;
  1603. bool forceMouselook = false;
  1604. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1605. if (part == null)
  1606. return;
  1607. // TODO: determine position to sit at based on scene geometry; don't trust offset from client
  1608. // see http://wiki.secondlife.com/wiki/User:Andrew_Linden/Office_Hours/2007_11_06 for details on how LL does it
  1609. if (PhysicsActor != null)
  1610. m_sitAvatarHeight = PhysicsActor.Size.Z;
  1611. bool canSit = false;
  1612. Vector3 pos = part.AbsolutePosition + offset;
  1613. if (part.IsSitTargetSet)
  1614. {
  1615. if (part.SitTargetAvatar == UUID.Zero)
  1616. {
  1617. // m_log.DebugFormat(
  1618. // "[SCENE PRESENCE]: Sitting {0} on {1} {2} because sit target is set and unoccupied",
  1619. // Name, part.Name, part.LocalId);
  1620. offset = part.SitTargetPosition;
  1621. sitOrientation = part.SitTargetOrientation;
  1622. canSit = true;
  1623. }
  1624. }
  1625. else
  1626. {
  1627. if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
  1628. {
  1629. // m_log.DebugFormat(
  1630. // "[SCENE PRESENCE]: Sitting {0} on {1} {2} because sit target is unset and within 10m",
  1631. // Name, part.Name, part.LocalId);
  1632. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  1633. canSit = true;
  1634. }
  1635. // else
  1636. // {
  1637. // m_log.DebugFormat(
  1638. // "[SCENE PRESENCE]: Ignoring sit request of {0} on {1} {2} because sit target is unset and outside 10m",
  1639. // Name, part.Name, part.LocalId);
  1640. // }
  1641. }
  1642. if (canSit)
  1643. {
  1644. if (PhysicsActor != null)
  1645. {
  1646. // We can remove the physicsActor until they stand up.
  1647. RemoveFromPhysicalScene();
  1648. }
  1649. part.AddSittingAvatar(UUID);
  1650. cameraAtOffset = part.GetCameraAtOffset();
  1651. cameraEyeOffset = part.GetCameraEyeOffset();
  1652. forceMouselook = part.GetForceMouselook();
  1653. ControllingClient.SendSitResponse(
  1654. targetID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
  1655. m_requestedSitTargetUUID = targetID;
  1656. HandleAgentSit(ControllingClient, UUID);
  1657. // Moved here to avoid a race with default sit anim
  1658. // The script event needs to be raised after the default sit anim is set.
  1659. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  1660. }
  1661. }
  1662. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  1663. {
  1664. if (ParentID != 0)
  1665. {
  1666. StandUp();
  1667. }
  1668. // if (!String.IsNullOrEmpty(sitAnimation))
  1669. // {
  1670. // m_nextSitAnimation = sitAnimation;
  1671. // }
  1672. // else
  1673. // {
  1674. m_nextSitAnimation = "SIT";
  1675. // }
  1676. //SceneObjectPart part = m_scene.GetSceneObjectPart(targetID);
  1677. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  1678. if (part != null)
  1679. {
  1680. if (!String.IsNullOrEmpty(part.SitAnimation))
  1681. {
  1682. m_nextSitAnimation = part.SitAnimation;
  1683. }
  1684. m_requestedSitTargetID = part.LocalId;
  1685. m_requestedSitTargetUUID = targetID;
  1686. // m_log.DebugFormat("[SIT]: Client requested Sit Position: {0}", offset);
  1687. if (m_scene.PhysicsScene.SupportsRayCast())
  1688. {
  1689. //m_scene.PhysicsScene.RaycastWorld(Vector3.Zero,Vector3.Zero, 0.01f,new RaycastCallback());
  1690. //SitRayCastAvatarPosition(part);
  1691. //return;
  1692. }
  1693. }
  1694. else
  1695. {
  1696. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  1697. }
  1698. SendSitResponse(targetID, offset, Quaternion.Identity);
  1699. }
  1700. /*
  1701. public void SitRayCastAvatarPosition(SceneObjectPart part)
  1702. {
  1703. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1704. Vector3 StartRayCastPosition = AbsolutePosition;
  1705. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1706. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1707. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionResponse);
  1708. }
  1709. public void SitRayCastAvatarPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1710. {
  1711. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1712. if (part != null)
  1713. {
  1714. if (hitYN)
  1715. {
  1716. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1717. {
  1718. SitRaycastFindEdge(collisionPoint, normal);
  1719. m_log.DebugFormat("[SIT]: Raycast Avatar Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1720. }
  1721. else
  1722. {
  1723. SitRayCastAvatarPositionCameraZ(part);
  1724. }
  1725. }
  1726. else
  1727. {
  1728. SitRayCastAvatarPositionCameraZ(part);
  1729. }
  1730. }
  1731. else
  1732. {
  1733. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1734. m_requestedSitTargetUUID = UUID.Zero;
  1735. m_requestedSitTargetID = 0;
  1736. m_requestedSitOffset = Vector3.Zero;
  1737. }
  1738. }
  1739. public void SitRayCastAvatarPositionCameraZ(SceneObjectPart part)
  1740. {
  1741. // Next, try to raycast from the camera Z position
  1742. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1743. Vector3 StartRayCastPosition = AbsolutePosition; StartRayCastPosition.Z = CameraPosition.Z;
  1744. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1745. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1746. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastAvatarPositionCameraZResponse);
  1747. }
  1748. public void SitRayCastAvatarPositionCameraZResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1749. {
  1750. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1751. if (part != null)
  1752. {
  1753. if (hitYN)
  1754. {
  1755. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1756. {
  1757. SitRaycastFindEdge(collisionPoint, normal);
  1758. m_log.DebugFormat("[SIT]: Raycast Avatar Position + CameraZ succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1759. }
  1760. else
  1761. {
  1762. SitRayCastCameraPosition(part);
  1763. }
  1764. }
  1765. else
  1766. {
  1767. SitRayCastCameraPosition(part);
  1768. }
  1769. }
  1770. else
  1771. {
  1772. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1773. m_requestedSitTargetUUID = UUID.Zero;
  1774. m_requestedSitTargetID = 0;
  1775. m_requestedSitOffset = Vector3.Zero;
  1776. }
  1777. }
  1778. public void SitRayCastCameraPosition(SceneObjectPart part)
  1779. {
  1780. // Next, try to raycast from the camera position
  1781. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1782. Vector3 StartRayCastPosition = CameraPosition;
  1783. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1784. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1785. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastCameraPositionResponse);
  1786. }
  1787. public void SitRayCastCameraPositionResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1788. {
  1789. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1790. if (part != null)
  1791. {
  1792. if (hitYN)
  1793. {
  1794. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1795. {
  1796. SitRaycastFindEdge(collisionPoint, normal);
  1797. m_log.DebugFormat("[SIT]: Raycast Camera Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1798. }
  1799. else
  1800. {
  1801. SitRayHorizontal(part);
  1802. }
  1803. }
  1804. else
  1805. {
  1806. SitRayHorizontal(part);
  1807. }
  1808. }
  1809. else
  1810. {
  1811. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1812. m_requestedSitTargetUUID = UUID.Zero;
  1813. m_requestedSitTargetID = 0;
  1814. m_requestedSitOffset = Vector3.Zero;
  1815. }
  1816. }
  1817. public void SitRayHorizontal(SceneObjectPart part)
  1818. {
  1819. // Next, try to raycast from the avatar position to fwd
  1820. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1821. Vector3 StartRayCastPosition = CameraPosition;
  1822. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1823. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1824. m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastHorizontalResponse);
  1825. }
  1826. public void SitRayCastHorizontalResponse(bool hitYN, Vector3 collisionPoint, uint localid, float pdistance, Vector3 normal)
  1827. {
  1828. SceneObjectPart part = FindNextAvailableSitTarget(m_requestedSitTargetUUID);
  1829. if (part != null)
  1830. {
  1831. if (hitYN)
  1832. {
  1833. if (collisionPoint.ApproxEquals(m_requestedSitOffset + part.AbsolutePosition, 0.2f))
  1834. {
  1835. SitRaycastFindEdge(collisionPoint, normal);
  1836. m_log.DebugFormat("[SIT]: Raycast Horizontal Position succeeded at point: {0}, normal:{1}", collisionPoint, normal);
  1837. // Next, try to raycast from the camera position
  1838. Vector3 EndRayCastPosition = part.AbsolutePosition + m_requestedSitOffset;
  1839. Vector3 StartRayCastPosition = CameraPosition;
  1840. Vector3 direction = Vector3.Normalize(EndRayCastPosition - StartRayCastPosition);
  1841. float distance = Vector3.Distance(EndRayCastPosition, StartRayCastPosition);
  1842. //m_scene.PhysicsScene.RaycastWorld(StartRayCastPosition, direction, distance, SitRayCastResponseAvatarPosition);
  1843. }
  1844. else
  1845. {
  1846. ControllingClient.SendAlertMessage("Sit position not accessable.");
  1847. m_requestedSitTargetUUID = UUID.Zero;
  1848. m_requestedSitTargetID = 0;
  1849. m_requestedSitOffset = Vector3.Zero;
  1850. }
  1851. }
  1852. else
  1853. {
  1854. ControllingClient.SendAlertMessage("Sit position not accessable.");
  1855. m_requestedSitTargetUUID = UUID.Zero;
  1856. m_requestedSitTargetID = 0;
  1857. m_requestedSitOffset = Vector3.Zero;
  1858. }
  1859. }
  1860. else
  1861. {
  1862. ControllingClient.SendAlertMessage("Sit position no longer exists");
  1863. m_requestedSitTargetUUID = UUID.Zero;
  1864. m_requestedSitTargetID = 0;
  1865. m_requestedSitOffset = Vector3.Zero;
  1866. }
  1867. }
  1868. private void SitRaycastFindEdge(Vector3 collisionPoint, Vector3 collisionNormal)
  1869. {
  1870. int i = 0;
  1871. //throw new NotImplementedException();
  1872. //m_requestedSitTargetUUID = UUID.Zero;
  1873. //m_requestedSitTargetID = 0;
  1874. //m_requestedSitOffset = Vector3.Zero;
  1875. SendSitResponse(ControllingClient, m_requestedSitTargetUUID, collisionPoint - m_requestedSitOffset, Quaternion.Identity);
  1876. }
  1877. */
  1878. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  1879. {
  1880. if (!String.IsNullOrEmpty(m_nextSitAnimation))
  1881. {
  1882. HandleAgentSit(remoteClient, agentID, m_nextSitAnimation);
  1883. }
  1884. else
  1885. {
  1886. HandleAgentSit(remoteClient, agentID, "SIT");
  1887. }
  1888. }
  1889. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID, string sitAnimation)
  1890. {
  1891. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  1892. if (part != null)
  1893. {
  1894. if (part.ParentGroup.IsAttachment)
  1895. {
  1896. m_log.WarnFormat(
  1897. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  1898. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  1899. return;
  1900. }
  1901. if (part.SitTargetAvatar == UUID)
  1902. {
  1903. Vector3 sitTargetPos = part.SitTargetPosition;
  1904. Quaternion sitTargetOrient = part.SitTargetOrientation;
  1905. // m_log.DebugFormat(
  1906. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  1907. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  1908. //Quaternion vq = new Quaternion(sitTargetPos.X, sitTargetPos.Y+0.2f, sitTargetPos.Z+0.2f, 0);
  1909. //Quaternion nq = new Quaternion(-sitTargetOrient.X, -sitTargetOrient.Y, -sitTargetOrient.Z, sitTargetOrient.w);
  1910. //Quaternion result = (sitTargetOrient * vq) * nq;
  1911. m_pos = sitTargetPos + SIT_TARGET_ADJUSTMENT;
  1912. Rotation = sitTargetOrient;
  1913. ParentPosition = part.AbsolutePosition;
  1914. }
  1915. else
  1916. {
  1917. m_pos -= part.AbsolutePosition;
  1918. ParentPosition = part.AbsolutePosition;
  1919. // m_log.DebugFormat(
  1920. // "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
  1921. // Name, part.AbsolutePosition, m_pos, ParentPosition, part.Name, part.LocalId);
  1922. }
  1923. }
  1924. else
  1925. {
  1926. return;
  1927. }
  1928. ParentPart = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  1929. ParentID = m_requestedSitTargetID;
  1930. Velocity = Vector3.Zero;
  1931. RemoveFromPhysicalScene();
  1932. Animator.TrySetMovementAnimation(sitAnimation);
  1933. SendAvatarDataToAllAgents();
  1934. }
  1935. public void HandleAgentSitOnGround()
  1936. {
  1937. // m_updateCount = 0; // Kill animation update burst so that the SIT_G.. will stick.
  1938. Animator.TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
  1939. SitGround = true;
  1940. RemoveFromPhysicalScene();
  1941. }
  1942. /// <summary>
  1943. /// Event handler for the 'Always run' setting on the client
  1944. /// Tells the physics plugin to increase speed of movement.
  1945. /// </summary>
  1946. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  1947. {
  1948. SetAlwaysRun = pSetAlwaysRun;
  1949. }
  1950. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  1951. {
  1952. Animator.AddAnimation(animID, UUID.Zero);
  1953. }
  1954. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  1955. {
  1956. Animator.RemoveAnimation(animID);
  1957. }
  1958. /// <summary>
  1959. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  1960. /// </summary>
  1961. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  1962. public void AddNewMovement(Vector3 vec)
  1963. {
  1964. // m_log.DebugFormat("[SCENE PRESENCE]: Adding new movement {0} for {1}", vec, Name);
  1965. Vector3 direc = vec * Rotation;
  1966. direc.Normalize();
  1967. if (Flying != FlyingOld) // add for fly velocity control
  1968. {
  1969. FlyingOld = Flying; // add for fly velocity control
  1970. if (!Flying)
  1971. WasFlying = true; // add for fly velocity control
  1972. }
  1973. if (IsColliding)
  1974. WasFlying = false; // add for fly velocity control
  1975. if ((vec.Z == 0f) && !Flying)
  1976. direc.Z = 0f; // Prevent camera WASD up.
  1977. direc *= 0.03f * 128f * SpeedModifier;
  1978. if (PhysicsActor != null)
  1979. {
  1980. if (Flying)
  1981. {
  1982. direc *= 4.0f;
  1983. //bool controlland = (((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) || ((m_AgentControlFlags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  1984. //if (controlland)
  1985. // m_log.Info("[AGENT]: landCommand");
  1986. //if (IsColliding)
  1987. // m_log.Info("[AGENT]: colliding");
  1988. //if (Flying && IsColliding && controlland)
  1989. //{
  1990. // StopFlying();
  1991. // m_log.Info("[AGENT]: Stop Flying");
  1992. //}
  1993. }
  1994. if (Animator.Falling && WasFlying) // if falling from flying, disable motion add
  1995. {
  1996. direc *= 0.0f;
  1997. }
  1998. else if (!Flying && IsColliding)
  1999. {
  2000. if (direc.Z > 2.0f)
  2001. {
  2002. direc.Z *= 3.0f;
  2003. // TODO: PreJump and jump happen too quickly. Many times prejump gets ignored.
  2004. Animator.TrySetMovementAnimation("PREJUMP");
  2005. Animator.TrySetMovementAnimation("JUMP");
  2006. }
  2007. }
  2008. }
  2009. // TODO: Add the force instead of only setting it to support multiple forces per frame?
  2010. m_forceToApply = direc;
  2011. }
  2012. #endregion
  2013. #region Overridden Methods
  2014. public override void Update()
  2015. {
  2016. const float ROTATION_TOLERANCE = 0.01f;
  2017. const float VELOCITY_TOLERANCE = 0.001f;
  2018. const float POSITION_TOLERANCE = 0.05f;
  2019. if (IsChildAgent == false)
  2020. {
  2021. // NOTE: Velocity is not the same as m_velocity. Velocity will attempt to
  2022. // grab the latest PhysicsActor velocity, whereas m_velocity is often
  2023. // storing a requested force instead of an actual traveling velocity
  2024. // Throw away duplicate or insignificant updates
  2025. if (!Rotation.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE) ||
  2026. !Velocity.ApproxEquals(m_lastVelocity, VELOCITY_TOLERANCE) ||
  2027. !m_pos.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
  2028. {
  2029. SendTerseUpdateToAllClients();
  2030. // Update the "last" values
  2031. m_lastPosition = m_pos;
  2032. m_lastRotation = Rotation;
  2033. m_lastVelocity = Velocity;
  2034. }
  2035. CheckForBorderCrossing();
  2036. CheckForSignificantMovement(); // sends update to the modules.
  2037. }
  2038. }
  2039. #endregion
  2040. #region Update Client(s)
  2041. /// <summary>
  2042. /// Sends a location update to the client connected to this scenePresence
  2043. /// </summary>
  2044. /// <param name="remoteClient"></param>
  2045. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  2046. {
  2047. // If the client is inactive, it's getting its updates from another
  2048. // server.
  2049. if (remoteClient.IsActive)
  2050. {
  2051. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  2052. remoteClient.SendEntityUpdate(
  2053. this,
  2054. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  2055. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  2056. m_scene.StatsReporter.AddAgentUpdates(1);
  2057. }
  2058. }
  2059. // vars to support reduced update frequency when velocity is unchanged
  2060. private Vector3 lastVelocitySentToAllClients = Vector3.Zero;
  2061. private Vector3 lastPositionSentToAllClients = Vector3.Zero;
  2062. private int lastTerseUpdateToAllClientsTick = Util.EnvironmentTickCount();
  2063. /// <summary>
  2064. /// Send a location/velocity/accelleration update to all agents in scene
  2065. /// </summary>
  2066. public void SendTerseUpdateToAllClients()
  2067. {
  2068. int currentTick = Util.EnvironmentTickCount();
  2069. // Decrease update frequency when avatar is moving but velocity is
  2070. // not changing.
  2071. // If there is a mismatch between distance travelled and expected
  2072. // distance based on last velocity sent and velocity hasnt changed,
  2073. // then send a new terse update
  2074. float timeSinceLastUpdate = (currentTick - lastTerseUpdateToAllClientsTick) * 0.001f;
  2075. Vector3 expectedPosition = lastPositionSentToAllClients + lastVelocitySentToAllClients * timeSinceLastUpdate;
  2076. float distanceError = Vector3.Distance(OffsetPosition, expectedPosition);
  2077. float speed = Velocity.Length();
  2078. float velocidyDiff = Vector3.Distance(lastVelocitySentToAllClients, Velocity);
  2079. // assuming 5 ms. worst case precision for timer, use 2x that
  2080. // for distance error threshold
  2081. float distanceErrorThreshold = speed * 0.01f;
  2082. if (speed < 0.01f // allow rotation updates if avatar position is unchanged
  2083. || Math.Abs(distanceError) > distanceErrorThreshold
  2084. || velocidyDiff > 0.01f) // did velocity change from last update?
  2085. {
  2086. lastVelocitySentToAllClients = Velocity;
  2087. lastTerseUpdateToAllClientsTick = currentTick;
  2088. lastPositionSentToAllClients = OffsetPosition;
  2089. m_scene.ForEachClient(SendTerseUpdateToClient);
  2090. }
  2091. }
  2092. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2093. {
  2094. SendCourseLocationsMethod d = m_sendCourseLocationsMethod;
  2095. if (d != null)
  2096. {
  2097. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  2098. }
  2099. }
  2100. public void SetSendCourseLocationMethod(SendCourseLocationsMethod d)
  2101. {
  2102. if (d != null)
  2103. m_sendCourseLocationsMethod = d;
  2104. }
  2105. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  2106. {
  2107. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  2108. }
  2109. public void SendInitialDataToMe()
  2110. {
  2111. // Send all scene object to the new client
  2112. Util.FireAndForget(delegate
  2113. {
  2114. // we created a new ScenePresence (a new child agent) in a fresh region.
  2115. // Request info about all the (root) agents in this region
  2116. // Note: This won't send data *to* other clients in that region (children don't send)
  2117. SendOtherAgentsAvatarDataToMe();
  2118. SendOtherAgentsAppearanceToMe();
  2119. EntityBase[] entities = Scene.Entities.GetEntities();
  2120. foreach(EntityBase e in entities)
  2121. {
  2122. if (e != null && e is SceneObjectGroup)
  2123. ((SceneObjectGroup)e).SendFullUpdateToClient(ControllingClient);
  2124. }
  2125. });
  2126. }
  2127. /// <summary>
  2128. /// Do everything required once a client completes its movement into a region and becomes
  2129. /// a root agent.
  2130. /// </summary>
  2131. private void ValidateAndSendAppearanceAndAgentData()
  2132. {
  2133. //m_log.DebugFormat("[SCENE PRESENCE] SendInitialData: {0} ({1})", Name, UUID);
  2134. // Moved this into CompleteMovement to ensure that Appearance is initialized before
  2135. // the inventory arrives
  2136. // m_scene.GetAvatarAppearance(ControllingClient, out Appearance);
  2137. bool cachedappearance = false;
  2138. // We have an appearance but we may not have the baked textures. Check the asset cache
  2139. // to see if all the baked textures are already here.
  2140. if (m_scene.AvatarFactory != null)
  2141. cachedappearance = m_scene.AvatarFactory.ValidateBakedTextureCache(this);
  2142. // If we aren't using a cached appearance, then clear out the baked textures
  2143. if (!cachedappearance)
  2144. {
  2145. Appearance.ResetAppearance();
  2146. if (m_scene.AvatarFactory != null)
  2147. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  2148. }
  2149. // This agent just became root. We are going to tell everyone about it. The process of
  2150. // getting other avatars information was initiated elsewhere immediately after the child circuit connected... don't do it
  2151. // again here... this comes after the cached appearance check because the avatars
  2152. // appearance goes into the avatar update packet
  2153. SendAvatarDataToAllAgents();
  2154. SendAppearanceToAgent(this);
  2155. // If we are using the the cached appearance then send it out to everyone
  2156. if (cachedappearance)
  2157. {
  2158. m_log.DebugFormat("[SCENE PRESENCE]: baked textures are in the cache for {0}", Name);
  2159. // If the avatars baked textures are all in the cache, then we have a
  2160. // complete appearance... send it out, if not, then we'll send it when
  2161. // the avatar finishes updating its appearance
  2162. SendAppearanceToAllOtherAgents();
  2163. }
  2164. }
  2165. /// <summary>
  2166. /// Send this agent's avatar data to all other root and child agents in the scene
  2167. /// This agent must be root. This avatar will receive its own update.
  2168. /// </summary>
  2169. public void SendAvatarDataToAllAgents()
  2170. {
  2171. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  2172. // only send update from root agents to other clients; children are only "listening posts"
  2173. if (IsChildAgent)
  2174. {
  2175. m_log.WarnFormat(
  2176. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  2177. Name, Scene.RegionInfo.RegionName);
  2178. return;
  2179. }
  2180. int count = 0;
  2181. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  2182. {
  2183. SendAvatarDataToAgent(scenePresence);
  2184. count++;
  2185. });
  2186. m_scene.StatsReporter.AddAgentUpdates(count);
  2187. }
  2188. /// <summary>
  2189. /// Send avatar data for all other root agents to this agent, this agent
  2190. /// can be either a child or root
  2191. /// </summary>
  2192. public void SendOtherAgentsAvatarDataToMe()
  2193. {
  2194. int count = 0;
  2195. m_scene.ForEachRootScenePresence(delegate(ScenePresence scenePresence)
  2196. {
  2197. // only send information about other root agents
  2198. if (scenePresence.UUID == UUID)
  2199. return;
  2200. scenePresence.SendAvatarDataToAgent(this);
  2201. count++;
  2202. });
  2203. m_scene.StatsReporter.AddAgentUpdates(count);
  2204. }
  2205. /// <summary>
  2206. /// Send avatar data to an agent.
  2207. /// </summary>
  2208. /// <param name="avatar"></param>
  2209. public void SendAvatarDataToAgent(ScenePresence avatar)
  2210. {
  2211. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  2212. avatar.ControllingClient.SendAvatarDataImmediate(this);
  2213. Animator.SendAnimPackToClient(avatar.ControllingClient);
  2214. }
  2215. /// <summary>
  2216. /// Send this agent's appearance to all other root and child agents in the scene
  2217. /// This agent must be root.
  2218. /// </summary>
  2219. public void SendAppearanceToAllOtherAgents()
  2220. {
  2221. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  2222. // only send update from root agents to other clients; children are only "listening posts"
  2223. if (IsChildAgent)
  2224. {
  2225. m_log.WarnFormat(
  2226. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  2227. Name, Scene.RegionInfo.RegionName);
  2228. return;
  2229. }
  2230. int count = 0;
  2231. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  2232. {
  2233. // only send information to other root agents
  2234. if (scenePresence.UUID == UUID)
  2235. return;
  2236. SendAppearanceToAgent(scenePresence);
  2237. count++;
  2238. });
  2239. m_scene.StatsReporter.AddAgentUpdates(count);
  2240. }
  2241. /// <summary>
  2242. /// Send appearance from all other root agents to this agent. this agent
  2243. /// can be either root or child
  2244. /// </summary>
  2245. public void SendOtherAgentsAppearanceToMe()
  2246. {
  2247. // m_log.DebugFormat("[SCENE PRESENCE] SendOtherAgentsAppearanceToMe: {0} {1}", Name, UUID);
  2248. int count = 0;
  2249. m_scene.ForEachRootScenePresence(delegate(ScenePresence scenePresence)
  2250. {
  2251. // only send information about other root agents
  2252. if (scenePresence.UUID == UUID)
  2253. return;
  2254. scenePresence.SendAppearanceToAgent(this);
  2255. count++;
  2256. });
  2257. m_scene.StatsReporter.AddAgentUpdates(count);
  2258. }
  2259. /// <summary>
  2260. /// Send appearance data to an agent.
  2261. /// </summary>
  2262. /// <param name="avatar"></param>
  2263. public void SendAppearanceToAgent(ScenePresence avatar)
  2264. {
  2265. // m_log.DebugFormat(
  2266. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  2267. avatar.ControllingClient.SendAppearance(
  2268. UUID, Appearance.VisualParams, Appearance.Texture.GetBytes());
  2269. }
  2270. #endregion
  2271. #region Significant Movement Method
  2272. /// <summary>
  2273. /// This checks for a significant movement and sends a courselocationchange update
  2274. /// </summary>
  2275. protected void CheckForSignificantMovement()
  2276. {
  2277. if (Util.GetDistanceTo(AbsolutePosition, posLastSignificantMove) > SIGNIFICANT_MOVEMENT)
  2278. {
  2279. posLastSignificantMove = AbsolutePosition;
  2280. m_scene.EventManager.TriggerSignificantClientMovement(this);
  2281. }
  2282. // Minimum Draw distance is 64 meters, the Radius of the draw distance sphere is 32m
  2283. if (Util.GetDistanceTo(AbsolutePosition, m_lastChildAgentUpdatePosition) >= Scene.ChildReprioritizationDistance ||
  2284. Util.GetDistanceTo(CameraPosition, m_lastChildAgentUpdateCamPosition) >= Scene.ChildReprioritizationDistance)
  2285. {
  2286. m_lastChildAgentUpdatePosition = AbsolutePosition;
  2287. m_lastChildAgentUpdateCamPosition = CameraPosition;
  2288. ChildAgentDataUpdate cadu = new ChildAgentDataUpdate();
  2289. cadu.ActiveGroupID = UUID.Zero.Guid;
  2290. cadu.AgentID = UUID.Guid;
  2291. cadu.alwaysrun = SetAlwaysRun;
  2292. cadu.AVHeight = Appearance.AvatarHeight;
  2293. cadu.cameraPosition = CameraPosition;
  2294. cadu.drawdistance = DrawDistance;
  2295. cadu.GroupAccess = 0;
  2296. cadu.Position = AbsolutePosition;
  2297. cadu.regionHandle = RegionHandle;
  2298. // Throttles
  2299. float multiplier = 1;
  2300. int childRegions = KnownRegionCount;
  2301. if (childRegions != 0)
  2302. multiplier = 1f / childRegions;
  2303. // Minimum throttle for a child region is 1/4 of the root region throttle
  2304. if (multiplier <= 0.25f)
  2305. multiplier = 0.25f;
  2306. cadu.throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2307. cadu.Velocity = Velocity;
  2308. AgentPosition agentpos = new AgentPosition();
  2309. agentpos.CopyFrom(cadu);
  2310. // Let's get this out of the update loop
  2311. Util.FireAndForget(delegate { m_scene.SendOutChildAgentUpdates(agentpos, this); });
  2312. }
  2313. }
  2314. #endregion
  2315. #region Border Crossing Methods
  2316. /// <summary>
  2317. /// Starts the process of moving an avatar into another region if they are crossing the border.
  2318. /// </summary>
  2319. /// <remarks>
  2320. /// Also removes the avatar from the physical scene if transit has started.
  2321. /// </remarks>
  2322. protected void CheckForBorderCrossing()
  2323. {
  2324. // Check that we we are not a child
  2325. if (IsChildAgent)
  2326. return;
  2327. // If we don't have a PhysActor, we can't cross anyway
  2328. // Also don't do this while sat, sitting avatars cross with the
  2329. // object they sit on.
  2330. if (ParentID != 0 || PhysicsActor == null)
  2331. return;
  2332. if (!IsInTransit)
  2333. {
  2334. Vector3 pos2 = AbsolutePosition;
  2335. Vector3 vel = Velocity;
  2336. int neighbor = 0;
  2337. int[] fix = new int[2];
  2338. float timeStep = 0.1f;
  2339. pos2.X = pos2.X + (vel.X * timeStep);
  2340. pos2.Y = pos2.Y + (vel.Y * timeStep);
  2341. pos2.Z = pos2.Z + (vel.Z * timeStep);
  2342. if (!IsInTransit)
  2343. {
  2344. // Checks if where it's headed exists a region
  2345. bool needsTransit = false;
  2346. if (m_scene.TestBorderCross(pos2, Cardinals.W))
  2347. {
  2348. if (m_scene.TestBorderCross(pos2, Cardinals.S))
  2349. {
  2350. needsTransit = true;
  2351. neighbor = m_scene.HaveNeighbor(Cardinals.SW, ref fix);
  2352. }
  2353. else if (m_scene.TestBorderCross(pos2, Cardinals.N))
  2354. {
  2355. needsTransit = true;
  2356. neighbor = m_scene.HaveNeighbor(Cardinals.NW, ref fix);
  2357. }
  2358. else
  2359. {
  2360. needsTransit = true;
  2361. neighbor = m_scene.HaveNeighbor(Cardinals.W, ref fix);
  2362. }
  2363. }
  2364. else if (m_scene.TestBorderCross(pos2, Cardinals.E))
  2365. {
  2366. if (m_scene.TestBorderCross(pos2, Cardinals.S))
  2367. {
  2368. needsTransit = true;
  2369. neighbor = m_scene.HaveNeighbor(Cardinals.SE, ref fix);
  2370. }
  2371. else if (m_scene.TestBorderCross(pos2, Cardinals.N))
  2372. {
  2373. needsTransit = true;
  2374. neighbor = m_scene.HaveNeighbor(Cardinals.NE, ref fix);
  2375. }
  2376. else
  2377. {
  2378. needsTransit = true;
  2379. neighbor = m_scene.HaveNeighbor(Cardinals.E, ref fix);
  2380. }
  2381. }
  2382. else if (m_scene.TestBorderCross(pos2, Cardinals.S))
  2383. {
  2384. needsTransit = true;
  2385. neighbor = m_scene.HaveNeighbor(Cardinals.S, ref fix);
  2386. }
  2387. else if (m_scene.TestBorderCross(pos2, Cardinals.N))
  2388. {
  2389. needsTransit = true;
  2390. neighbor = m_scene.HaveNeighbor(Cardinals.N, ref fix);
  2391. }
  2392. // Makes sure avatar does not end up outside region
  2393. if (neighbor <= 0)
  2394. {
  2395. if (needsTransit)
  2396. {
  2397. if (m_requestedSitTargetUUID == UUID.Zero)
  2398. {
  2399. bool isFlying = Flying;
  2400. RemoveFromPhysicalScene();
  2401. Vector3 pos = AbsolutePosition;
  2402. if (AbsolutePosition.X < 0)
  2403. pos.X += Velocity.X * 2;
  2404. else if (AbsolutePosition.X > Constants.RegionSize)
  2405. pos.X -= Velocity.X * 2;
  2406. if (AbsolutePosition.Y < 0)
  2407. pos.Y += Velocity.Y * 2;
  2408. else if (AbsolutePosition.Y > Constants.RegionSize)
  2409. pos.Y -= Velocity.Y * 2;
  2410. Velocity = Vector3.Zero;
  2411. AbsolutePosition = pos;
  2412. // m_log.DebugFormat("[SCENE PRESENCE]: Prevented flyoff for {0} at {1}", Name, AbsolutePosition);
  2413. AddToPhysicalScene(isFlying);
  2414. }
  2415. }
  2416. }
  2417. else if (neighbor > 0)
  2418. {
  2419. if (!CrossToNewRegion())
  2420. {
  2421. if (m_requestedSitTargetUUID == UUID.Zero)
  2422. {
  2423. bool isFlying = Flying;
  2424. RemoveFromPhysicalScene();
  2425. Vector3 pos = AbsolutePosition;
  2426. if (AbsolutePosition.X < 0)
  2427. pos.X += Velocity.X * 2;
  2428. else if (AbsolutePosition.X > Constants.RegionSize)
  2429. pos.X -= Velocity.X * 2;
  2430. if (AbsolutePosition.Y < 0)
  2431. pos.Y += Velocity.Y * 2;
  2432. else if (AbsolutePosition.Y > Constants.RegionSize)
  2433. pos.Y -= Velocity.Y * 2;
  2434. Velocity = Vector3.Zero;
  2435. AbsolutePosition = pos;
  2436. AddToPhysicalScene(isFlying);
  2437. }
  2438. }
  2439. }
  2440. }
  2441. else
  2442. {
  2443. // This constant has been inferred from experimentation
  2444. // I'm not sure what this value should be, so I tried a few values.
  2445. timeStep = 0.04f;
  2446. pos2 = AbsolutePosition;
  2447. pos2.X = pos2.X + (vel.X * timeStep);
  2448. pos2.Y = pos2.Y + (vel.Y * timeStep);
  2449. // Don't touch the Z
  2450. m_pos = pos2;
  2451. m_log.DebugFormat("[SCENE PRESENCE]: In transit m_pos={0}", m_pos);
  2452. }
  2453. }
  2454. }
  2455. /// <summary>
  2456. /// Moves the agent outside the region bounds
  2457. /// Tells neighbor region that we're crossing to it
  2458. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  2459. /// set them to a child agent.
  2460. /// </summary>
  2461. protected bool CrossToNewRegion()
  2462. {
  2463. try
  2464. {
  2465. return m_scene.CrossAgentToNewRegion(this, Flying);
  2466. }
  2467. catch
  2468. {
  2469. return m_scene.CrossAgentToNewRegion(this, false);
  2470. }
  2471. }
  2472. public void RestoreInCurrentScene()
  2473. {
  2474. AddToPhysicalScene(false); // not exactly false
  2475. }
  2476. public void Reset()
  2477. {
  2478. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting {0} in {1}", Name, Scene.RegionInfo.RegionName);
  2479. // Put the child agent back at the center
  2480. AbsolutePosition
  2481. = new Vector3(((float)Constants.RegionSize * 0.5f), ((float)Constants.RegionSize * 0.5f), 70);
  2482. Animator.ResetAnimations();
  2483. }
  2484. /// <summary>
  2485. /// Computes which child agents to close when the scene presence moves to another region.
  2486. /// Removes those regions from m_knownRegions.
  2487. /// </summary>
  2488. /// <param name="newRegionX">The new region's x on the map</param>
  2489. /// <param name="newRegionY">The new region's y on the map</param>
  2490. /// <returns></returns>
  2491. public void CloseChildAgents(uint newRegionX, uint newRegionY)
  2492. {
  2493. List<ulong> byebyeRegions = new List<ulong>();
  2494. List<ulong> knownRegions = KnownRegionHandles;
  2495. m_log.DebugFormat(
  2496. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  2497. knownRegions.Count, Scene.RegionInfo.RegionName);
  2498. //DumpKnownRegions();
  2499. foreach (ulong handle in knownRegions)
  2500. {
  2501. // Don't close the agent on this region yet
  2502. if (handle != Scene.RegionInfo.RegionHandle)
  2503. {
  2504. uint x, y;
  2505. Utils.LongToUInts(handle, out x, out y);
  2506. x = x / Constants.RegionSize;
  2507. y = y / Constants.RegionSize;
  2508. // m_log.Debug("---> x: " + x + "; newx:" + newRegionX + "; Abs:" + (int)Math.Abs((int)(x - newRegionX)));
  2509. // m_log.Debug("---> y: " + y + "; newy:" + newRegionY + "; Abs:" + (int)Math.Abs((int)(y - newRegionY)));
  2510. if (Util.IsOutsideView(DrawDistance, x, newRegionX, y, newRegionY))
  2511. {
  2512. byebyeRegions.Add(handle);
  2513. }
  2514. }
  2515. }
  2516. if (byebyeRegions.Count > 0)
  2517. {
  2518. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  2519. Util.FireAndForget(delegate
  2520. {
  2521. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, byebyeRegions);
  2522. });
  2523. }
  2524. foreach (ulong handle in byebyeRegions)
  2525. {
  2526. RemoveNeighbourRegion(handle);
  2527. }
  2528. }
  2529. #endregion
  2530. /// <summary>
  2531. /// This allows the Sim owner the abiility to kick users from their sim currently.
  2532. /// It tells the client that the agent has permission to do so.
  2533. /// </summary>
  2534. public void GrantGodlikePowers(UUID agentID, UUID sessionID, UUID token, bool godStatus)
  2535. {
  2536. if (godStatus)
  2537. {
  2538. // For now, assign god level 200 to anyone
  2539. // who is granted god powers, but has no god level set.
  2540. //
  2541. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, agentID);
  2542. if (account != null)
  2543. {
  2544. if (account.UserLevel > 0)
  2545. GodLevel = account.UserLevel;
  2546. else
  2547. GodLevel = 200;
  2548. }
  2549. }
  2550. else
  2551. {
  2552. GodLevel = 0;
  2553. }
  2554. ControllingClient.SendAdminResponse(token, (uint)GodLevel);
  2555. }
  2556. #region Child Agent Updates
  2557. public void ChildAgentDataUpdate(AgentData cAgentData)
  2558. {
  2559. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  2560. if (!IsChildAgent)
  2561. return;
  2562. CopyFrom(cAgentData);
  2563. }
  2564. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  2565. /// <summary>
  2566. /// This updates important decision making data about a child agent
  2567. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  2568. /// </summary>
  2569. public void ChildAgentDataUpdate(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  2570. {
  2571. if (!IsChildAgent)
  2572. return;
  2573. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  2574. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  2575. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  2576. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  2577. // When we get to the point of re-computing neighbors everytime this
  2578. // changes, then start using the agent's drawdistance rather than the
  2579. // region's draw distance.
  2580. // DrawDistance = cAgentData.Far;
  2581. DrawDistance = Scene.DefaultDrawDistance;
  2582. if (cAgentData.Position != marker) // UGH!!
  2583. m_pos = cAgentData.Position + offset;
  2584. if (Vector3.Distance(AbsolutePosition, posLastSignificantMove) >= Scene.ChildReprioritizationDistance)
  2585. {
  2586. posLastSignificantMove = AbsolutePosition;
  2587. ReprioritizeUpdates();
  2588. }
  2589. CameraPosition = cAgentData.Center + offset;
  2590. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  2591. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles);
  2592. //cAgentData.AVHeight;
  2593. RegionHandle = cAgentData.RegionHandle;
  2594. //m_velocity = cAgentData.Velocity;
  2595. }
  2596. public void CopyTo(AgentData cAgent)
  2597. {
  2598. cAgent.CallbackURI = m_callbackURI;
  2599. cAgent.AgentID = UUID;
  2600. cAgent.RegionID = Scene.RegionInfo.RegionID;
  2601. cAgent.Position = AbsolutePosition;
  2602. cAgent.Velocity = m_velocity;
  2603. cAgent.Center = CameraPosition;
  2604. cAgent.AtAxis = CameraAtAxis;
  2605. cAgent.LeftAxis = CameraLeftAxis;
  2606. cAgent.UpAxis = m_CameraUpAxis;
  2607. cAgent.Far = DrawDistance;
  2608. // Throttles
  2609. float multiplier = 1;
  2610. int childRegions = KnownRegionCount;
  2611. if (childRegions != 0)
  2612. multiplier = 1f / childRegions;
  2613. // Minimum throttle for a child region is 1/4 of the root region throttle
  2614. if (multiplier <= 0.25f)
  2615. multiplier = 0.25f;
  2616. cAgent.Throttles = ControllingClient.GetThrottlesPacked(multiplier);
  2617. cAgent.HeadRotation = m_headrotation;
  2618. cAgent.BodyRotation = Rotation;
  2619. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  2620. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  2621. cAgent.GodLevel = (byte)GodLevel;
  2622. else
  2623. cAgent.GodLevel = (byte) 0;
  2624. cAgent.AlwaysRun = SetAlwaysRun;
  2625. cAgent.Appearance = new AvatarAppearance(Appearance);
  2626. lock (scriptedcontrols)
  2627. {
  2628. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  2629. int i = 0;
  2630. foreach (ScriptControllers c in scriptedcontrols.Values)
  2631. {
  2632. controls[i++] = new ControllerData(c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  2633. }
  2634. cAgent.Controllers = controls;
  2635. }
  2636. // Animations
  2637. try
  2638. {
  2639. cAgent.Anims = Animator.Animations.ToArray();
  2640. }
  2641. catch { }
  2642. if (Scene.AttachmentsModule != null)
  2643. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  2644. }
  2645. private void CopyFrom(AgentData cAgent)
  2646. {
  2647. m_originRegionID = cAgent.RegionID;
  2648. m_callbackURI = cAgent.CallbackURI;
  2649. // m_log.DebugFormat(
  2650. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  2651. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  2652. m_pos = cAgent.Position;
  2653. m_velocity = cAgent.Velocity;
  2654. CameraPosition = cAgent.Center;
  2655. CameraAtAxis = cAgent.AtAxis;
  2656. CameraLeftAxis = cAgent.LeftAxis;
  2657. m_CameraUpAxis = cAgent.UpAxis;
  2658. // When we get to the point of re-computing neighbors everytime this
  2659. // changes, then start using the agent's drawdistance rather than the
  2660. // region's draw distance.
  2661. // DrawDistance = cAgent.Far;
  2662. DrawDistance = Scene.DefaultDrawDistance;
  2663. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  2664. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  2665. m_headrotation = cAgent.HeadRotation;
  2666. Rotation = cAgent.BodyRotation;
  2667. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  2668. if (m_scene.Permissions.IsGod(new UUID(cAgent.AgentID)))
  2669. GodLevel = cAgent.GodLevel;
  2670. SetAlwaysRun = cAgent.AlwaysRun;
  2671. Appearance = new AvatarAppearance(cAgent.Appearance);
  2672. if (PhysicsActor != null)
  2673. {
  2674. bool isFlying = Flying;
  2675. RemoveFromPhysicalScene();
  2676. AddToPhysicalScene(isFlying);
  2677. }
  2678. try
  2679. {
  2680. lock (scriptedcontrols)
  2681. {
  2682. if (cAgent.Controllers != null)
  2683. {
  2684. scriptedcontrols.Clear();
  2685. foreach (ControllerData c in cAgent.Controllers)
  2686. {
  2687. ScriptControllers sc = new ScriptControllers();
  2688. sc.itemID = c.ItemID;
  2689. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  2690. sc.eventControls = (ScriptControlled)c.EventControls;
  2691. scriptedcontrols[sc.itemID] = sc;
  2692. }
  2693. }
  2694. }
  2695. }
  2696. catch { }
  2697. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  2698. if (cAgent.Anims != null)
  2699. Animator.Animations.FromArray(cAgent.Anims);
  2700. if (Scene.AttachmentsModule != null)
  2701. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  2702. }
  2703. public bool CopyAgent(out IAgentData agent)
  2704. {
  2705. agent = new CompleteAgentData();
  2706. CopyTo((AgentData)agent);
  2707. return true;
  2708. }
  2709. #endregion Child Agent Updates
  2710. /// <summary>
  2711. /// Handles part of the PID controller function for moving an avatar.
  2712. /// </summary>
  2713. public void UpdateMovement()
  2714. {
  2715. if (m_forceToApply.HasValue)
  2716. {
  2717. Vector3 force = m_forceToApply.Value;
  2718. Updated = true;
  2719. Velocity = force;
  2720. m_forceToApply = null;
  2721. }
  2722. }
  2723. /// <summary>
  2724. /// Adds a physical representation of the avatar to the Physics plugin
  2725. /// </summary>
  2726. public void AddToPhysicalScene(bool isFlying)
  2727. {
  2728. // m_log.DebugFormat(
  2729. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  2730. // Name, isFlying, Scene.RegionInfo.RegionName);
  2731. if (PhysicsActor != null)
  2732. {
  2733. m_log.ErrorFormat(
  2734. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  2735. Name, Scene.RegionInfo.RegionName);
  2736. }
  2737. if (Appearance.AvatarHeight == 0)
  2738. Appearance.SetHeight();
  2739. PhysicsScene scene = m_scene.PhysicsScene;
  2740. Vector3 pVec = AbsolutePosition;
  2741. PhysicsActor = scene.AddAvatar(
  2742. LocalId, Firstname + "." + Lastname, pVec,
  2743. new Vector3(0f, 0f, Appearance.AvatarHeight), isFlying);
  2744. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  2745. PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  2746. PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  2747. PhysicsActor.SubscribeEvents(500);
  2748. PhysicsActor.LocalID = LocalId;
  2749. }
  2750. private void OutOfBoundsCall(Vector3 pos)
  2751. {
  2752. //bool flying = Flying;
  2753. //RemoveFromPhysicalScene();
  2754. //AddToPhysicalScene(flying);
  2755. if (ControllingClient != null)
  2756. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  2757. }
  2758. /// <summary>
  2759. /// Event called by the physics plugin to tell the avatar about a collision.
  2760. /// </summary>
  2761. /// <remarks>
  2762. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  2763. /// ground or a prim then there will be collision information between the avatar and the surface.
  2764. ///
  2765. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  2766. /// any part of this method is relying on an every-frame call.
  2767. /// </remarks>
  2768. /// <param name="e"></param>
  2769. public void PhysicsCollisionUpdate(EventArgs e)
  2770. {
  2771. if (IsChildAgent)
  2772. return;
  2773. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  2774. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  2775. // as of this comment the interval is set in AddToPhysicalScene
  2776. // if (m_updateCount > 0)
  2777. // {
  2778. Animator.UpdateMovementAnimations();
  2779. // m_updateCount--;
  2780. // }
  2781. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  2782. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  2783. CollisionPlane = Vector4.UnitW;
  2784. // // No collisions at all means we may be flying. Update always
  2785. // // to make falling work
  2786. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  2787. // {
  2788. // m_updateCount = UPDATE_COUNT;
  2789. // m_lastColCount = coldata.Count;
  2790. // }
  2791. if (coldata.Count != 0)
  2792. {
  2793. switch (Animator.CurrentMovementAnimation)
  2794. {
  2795. case "STAND":
  2796. case "WALK":
  2797. case "RUN":
  2798. case "CROUCH":
  2799. case "CROUCHWALK":
  2800. {
  2801. ContactPoint lowest;
  2802. lowest.SurfaceNormal = Vector3.Zero;
  2803. lowest.Position = Vector3.Zero;
  2804. lowest.Position.Z = Single.NaN;
  2805. foreach (ContactPoint contact in coldata.Values)
  2806. {
  2807. if (Single.IsNaN(lowest.Position.Z) || contact.Position.Z < lowest.Position.Z)
  2808. {
  2809. lowest = contact;
  2810. }
  2811. }
  2812. CollisionPlane = new Vector4(-lowest.SurfaceNormal, -Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  2813. }
  2814. break;
  2815. }
  2816. }
  2817. if (Invulnerable)
  2818. return;
  2819. float starthealth = Health;
  2820. uint killerObj = 0;
  2821. foreach (uint localid in coldata.Keys)
  2822. {
  2823. SceneObjectPart part = Scene.GetSceneObjectPart(localid);
  2824. if (part != null && part.ParentGroup.Damage != -1.0f)
  2825. Health -= part.ParentGroup.Damage;
  2826. else
  2827. {
  2828. if (coldata[localid].PenetrationDepth >= 0.10f)
  2829. Health -= coldata[localid].PenetrationDepth * 5.0f;
  2830. }
  2831. if (Health <= 0.0f)
  2832. {
  2833. if (localid != 0)
  2834. killerObj = localid;
  2835. }
  2836. //m_log.Debug("[AVATAR]: Collision with localid: " + localid.ToString() + " at depth: " + coldata[localid].ToString());
  2837. }
  2838. //Health = 100;
  2839. if (!Invulnerable)
  2840. {
  2841. if (starthealth != Health)
  2842. {
  2843. ControllingClient.SendHealth(Health);
  2844. }
  2845. if (Health <= 0)
  2846. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  2847. }
  2848. }
  2849. public void setHealthWithUpdate(float health)
  2850. {
  2851. Health = health;
  2852. ControllingClient.SendHealth(Health);
  2853. }
  2854. protected internal void Close()
  2855. {
  2856. // Clear known regions
  2857. KnownRegions = new Dictionary<ulong, string>();
  2858. lock (m_reprioritization_timer)
  2859. {
  2860. m_reprioritization_timer.Enabled = false;
  2861. m_reprioritization_timer.Elapsed -= new ElapsedEventHandler(Reprioritize);
  2862. }
  2863. // I don't get it but mono crashes when you try to dispose of this timer,
  2864. // unsetting the elapsed callback should be enough to allow for cleanup however.
  2865. // m_reprioritizationTimer.Dispose();
  2866. RemoveFromPhysicalScene();
  2867. }
  2868. public void AddAttachment(SceneObjectGroup gobj)
  2869. {
  2870. lock (m_attachments)
  2871. {
  2872. // This may be true when the attachment comes back
  2873. // from serialization after login. Clear it.
  2874. gobj.IsDeleted = false;
  2875. m_attachments.Add(gobj);
  2876. }
  2877. }
  2878. /// <summary>
  2879. /// Get all the presence's attachments.
  2880. /// </summary>
  2881. /// <returns>A copy of the list which contains the attachments.</returns>
  2882. public List<SceneObjectGroup> GetAttachments()
  2883. {
  2884. lock (m_attachments)
  2885. return new List<SceneObjectGroup>(m_attachments);
  2886. }
  2887. /// <summary>
  2888. /// Get the scene objects attached to the given point.
  2889. /// </summary>
  2890. /// <param name="attachmentPoint"></param>
  2891. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  2892. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  2893. {
  2894. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  2895. lock (m_attachments)
  2896. {
  2897. foreach (SceneObjectGroup so in m_attachments)
  2898. {
  2899. if (attachmentPoint == so.AttachmentPoint)
  2900. attachments.Add(so);
  2901. }
  2902. }
  2903. return attachments;
  2904. }
  2905. public bool HasAttachments()
  2906. {
  2907. lock (m_attachments)
  2908. return m_attachments.Count > 0;
  2909. }
  2910. public bool HasScriptedAttachments()
  2911. {
  2912. lock (m_attachments)
  2913. {
  2914. foreach (SceneObjectGroup gobj in m_attachments)
  2915. {
  2916. if (gobj != null)
  2917. {
  2918. if (gobj.RootPart.Inventory.ContainsScripts())
  2919. return true;
  2920. }
  2921. }
  2922. }
  2923. return false;
  2924. }
  2925. public void RemoveAttachment(SceneObjectGroup gobj)
  2926. {
  2927. lock (m_attachments)
  2928. m_attachments.Remove(gobj);
  2929. }
  2930. /// <summary>
  2931. /// Clear all attachments
  2932. /// </summary>
  2933. public void ClearAttachments()
  2934. {
  2935. lock (m_attachments)
  2936. m_attachments.Clear();
  2937. }
  2938. /// <summary>
  2939. /// This is currently just being done for information.
  2940. /// </summary>
  2941. public bool ValidateAttachments()
  2942. {
  2943. bool validated = true;
  2944. lock (m_attachments)
  2945. {
  2946. // Validate
  2947. foreach (SceneObjectGroup gobj in m_attachments)
  2948. {
  2949. if (gobj == null)
  2950. {
  2951. m_log.WarnFormat(
  2952. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  2953. validated = false;
  2954. }
  2955. else if (gobj.IsDeleted)
  2956. {
  2957. m_log.WarnFormat(
  2958. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  2959. gobj.Name, gobj.UUID, Name);
  2960. validated = false;
  2961. }
  2962. }
  2963. }
  2964. return validated;
  2965. }
  2966. /// <summary>
  2967. /// Send a script event to this scene presence's attachments
  2968. /// </summary>
  2969. /// <param name="eventName">The name of the event</param>
  2970. /// <param name="args">The arguments for the event</param>
  2971. public void SendScriptEventToAttachments(string eventName, Object[] args)
  2972. {
  2973. Util.FireAndForget(delegate(object x)
  2974. {
  2975. if (m_scriptEngines.Length == 0)
  2976. return;
  2977. lock (m_attachments)
  2978. {
  2979. foreach (SceneObjectGroup grp in m_attachments)
  2980. {
  2981. // 16384 is CHANGED_ANIMATION
  2982. //
  2983. // Send this to all attachment root prims
  2984. //
  2985. foreach (IScriptModule m in m_scriptEngines)
  2986. {
  2987. if (m == null) // No script engine loaded
  2988. continue;
  2989. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  2990. }
  2991. }
  2992. }
  2993. });
  2994. }
  2995. internal void PushForce(Vector3 impulse)
  2996. {
  2997. if (PhysicsActor != null)
  2998. {
  2999. PhysicsActor.AddForce(impulse,true);
  3000. }
  3001. }
  3002. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  3003. {
  3004. ScriptControllers obj = new ScriptControllers();
  3005. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  3006. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  3007. obj.itemID = Script_item_UUID;
  3008. if (pass_on == 0 && accept == 0)
  3009. {
  3010. IgnoredControls |= (ScriptControlled)controls;
  3011. obj.ignoreControls = (ScriptControlled)controls;
  3012. }
  3013. if (pass_on == 0 && accept == 1)
  3014. {
  3015. IgnoredControls |= (ScriptControlled)controls;
  3016. obj.ignoreControls = (ScriptControlled)controls;
  3017. obj.eventControls = (ScriptControlled)controls;
  3018. }
  3019. if (pass_on == 1 && accept == 1)
  3020. {
  3021. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3022. obj.eventControls = (ScriptControlled)controls;
  3023. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  3024. }
  3025. lock (scriptedcontrols)
  3026. {
  3027. if (pass_on == 1 && accept == 0)
  3028. {
  3029. IgnoredControls &= ~(ScriptControlled)controls;
  3030. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  3031. scriptedcontrols.Remove(Script_item_UUID);
  3032. }
  3033. else
  3034. {
  3035. scriptedcontrols[Script_item_UUID] = obj;
  3036. }
  3037. }
  3038. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  3039. }
  3040. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  3041. {
  3042. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3043. lock (scriptedcontrols)
  3044. {
  3045. scriptedcontrols.Clear();
  3046. }
  3047. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  3048. }
  3049. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  3050. {
  3051. ScriptControllers takecontrols;
  3052. lock (scriptedcontrols)
  3053. {
  3054. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  3055. {
  3056. ScriptControlled sctc = takecontrols.eventControls;
  3057. ControllingClient.SendTakeControls((int)sctc, false, false);
  3058. ControllingClient.SendTakeControls((int)sctc, true, false);
  3059. scriptedcontrols.Remove(Script_item_UUID);
  3060. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  3061. foreach (ScriptControllers scData in scriptedcontrols.Values)
  3062. {
  3063. IgnoredControls |= scData.ignoreControls;
  3064. }
  3065. }
  3066. }
  3067. }
  3068. internal void SendControlToScripts(uint flags)
  3069. {
  3070. ScriptControlled allflags = ScriptControlled.CONTROL_ZERO;
  3071. if (MouseDown)
  3072. {
  3073. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  3074. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 || (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  3075. {
  3076. allflags = ScriptControlled.CONTROL_ZERO;
  3077. MouseDown = true;
  3078. }
  3079. }
  3080. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  3081. {
  3082. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  3083. MouseDown = true;
  3084. }
  3085. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  3086. {
  3087. allflags |= ScriptControlled.CONTROL_LBUTTON;
  3088. MouseDown = true;
  3089. }
  3090. // find all activated controls, whether the scripts are interested in them or not
  3091. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  3092. {
  3093. allflags |= ScriptControlled.CONTROL_FWD;
  3094. }
  3095. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  3096. {
  3097. allflags |= ScriptControlled.CONTROL_BACK;
  3098. }
  3099. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  3100. {
  3101. allflags |= ScriptControlled.CONTROL_UP;
  3102. }
  3103. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  3104. {
  3105. allflags |= ScriptControlled.CONTROL_DOWN;
  3106. }
  3107. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  3108. {
  3109. allflags |= ScriptControlled.CONTROL_LEFT;
  3110. }
  3111. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  3112. {
  3113. allflags |= ScriptControlled.CONTROL_RIGHT;
  3114. }
  3115. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  3116. {
  3117. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  3118. }
  3119. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  3120. {
  3121. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  3122. }
  3123. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  3124. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  3125. {
  3126. lock (scriptedcontrols)
  3127. {
  3128. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  3129. {
  3130. UUID scriptUUID = kvp.Key;
  3131. ScriptControllers scriptControlData = kvp.Value;
  3132. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  3133. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  3134. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  3135. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  3136. {
  3137. // only send if still pressed or just changed
  3138. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  3139. }
  3140. }
  3141. }
  3142. }
  3143. LastCommands = allflags;
  3144. }
  3145. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  3146. {
  3147. if (ignored == ScriptControlled.CONTROL_ZERO)
  3148. return flags;
  3149. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  3150. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  3151. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  3152. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  3153. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  3154. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  3155. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  3156. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  3157. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  3158. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  3159. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  3160. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  3161. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  3162. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  3163. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  3164. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  3165. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  3166. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  3167. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  3168. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  3169. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  3170. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  3171. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  3172. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  3173. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  3174. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  3175. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  3176. return flags;
  3177. }
  3178. private void ReprioritizeUpdates()
  3179. {
  3180. if (Scene.IsReprioritizationEnabled && Scene.UpdatePrioritizationScheme != UpdatePrioritizationSchemes.Time)
  3181. {
  3182. lock (m_reprioritization_timer)
  3183. {
  3184. if (!m_reprioritizing)
  3185. m_reprioritization_timer.Enabled = m_reprioritizing = true;
  3186. else
  3187. m_reprioritization_called = true;
  3188. }
  3189. }
  3190. }
  3191. private void Reprioritize(object sender, ElapsedEventArgs e)
  3192. {
  3193. ControllingClient.ReprioritizeUpdates();
  3194. lock (m_reprioritization_timer)
  3195. {
  3196. m_reprioritization_timer.Enabled = m_reprioritizing = m_reprioritization_called;
  3197. m_reprioritization_called = false;
  3198. }
  3199. }
  3200. private void CheckLandingPoint(ref Vector3 pos)
  3201. {
  3202. // Never constrain lures
  3203. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  3204. return;
  3205. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  3206. return;
  3207. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  3208. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  3209. land.LandData.UserLocation != Vector3.Zero &&
  3210. land.LandData.OwnerID != m_uuid &&
  3211. (!m_scene.Permissions.IsGod(m_uuid)) &&
  3212. (!m_scene.RegionInfo.EstateSettings.IsEstateManager(m_uuid)))
  3213. {
  3214. float curr = Vector3.Distance(AbsolutePosition, pos);
  3215. if (Vector3.Distance(land.LandData.UserLocation, pos) < curr)
  3216. pos = land.LandData.UserLocation;
  3217. else
  3218. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  3219. }
  3220. }
  3221. private void CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos)
  3222. {
  3223. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  3224. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  3225. (m_teleportFlags & TeleportFlags.ViaLandmark) != 0 ||
  3226. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3227. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0)
  3228. {
  3229. if (GodLevel < 200 &&
  3230. ((!m_scene.Permissions.IsGod(m_uuid) &&
  3231. !m_scene.RegionInfo.EstateSettings.IsEstateManager(m_uuid)) ||
  3232. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3233. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  3234. {
  3235. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  3236. if (spawnPoints.Length == 0)
  3237. return;
  3238. float distance = 9999;
  3239. int closest = -1;
  3240. for (int i = 0 ; i < spawnPoints.Length ; i++)
  3241. {
  3242. Vector3 spawnPosition = spawnPoints[i].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  3243. Vector3 offset = spawnPosition - pos;
  3244. float d = Vector3.Mag(offset);
  3245. if (d >= distance)
  3246. continue;
  3247. ILandObject land = m_scene.LandChannel.GetLandObject(spawnPosition.X, spawnPosition.Y);
  3248. if (land == null)
  3249. continue;
  3250. if (land.IsEitherBannedOrRestricted(UUID))
  3251. continue;
  3252. distance = d;
  3253. closest = i;
  3254. }
  3255. if (closest == -1)
  3256. return;
  3257. pos = spawnPoints[closest].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  3258. }
  3259. }
  3260. }
  3261. private void CheckAndAdjustLandingPoint(ref Vector3 pos)
  3262. {
  3263. SceneObjectGroup telehub = null;
  3264. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  3265. {
  3266. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  3267. {
  3268. CheckAndAdjustTelehub(telehub, ref pos);
  3269. return;
  3270. }
  3271. }
  3272. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  3273. if (land != null)
  3274. {
  3275. if (Scene.DebugTeleporting)
  3276. TeleportFlagsDebug();
  3277. // If we come in via login, landmark or map, we want to
  3278. // honor landing points. If we come in via Lure, we want
  3279. // to ignore them.
  3280. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  3281. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  3282. (m_teleportFlags & TeleportFlags.ViaLandmark) != 0 ||
  3283. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3284. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0)
  3285. {
  3286. // Don't restrict gods, estate managers, or land owners to
  3287. // the TP point. This behaviour mimics agni.
  3288. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  3289. land.LandData.UserLocation != Vector3.Zero &&
  3290. GodLevel < 200 &&
  3291. ((land.LandData.OwnerID != m_uuid &&
  3292. !m_scene.Permissions.IsGod(m_uuid) &&
  3293. !m_scene.RegionInfo.EstateSettings.IsEstateManager(m_uuid)) ||
  3294. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  3295. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  3296. {
  3297. pos = land.LandData.UserLocation;
  3298. }
  3299. }
  3300. land.SendLandUpdateToClient(ControllingClient);
  3301. }
  3302. }
  3303. private void TeleportFlagsDebug() {
  3304. // Some temporary debugging help to show all the TeleportFlags we have...
  3305. bool HG = false;
  3306. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  3307. HG = true;
  3308. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  3309. uint i = 0u;
  3310. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  3311. {
  3312. i = 1u << x;
  3313. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  3314. if (HG == false)
  3315. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  3316. else
  3317. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  3318. }
  3319. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  3320. }
  3321. }
  3322. }