ScenePresence.cs 163 KB

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