ScenePresence.cs 180 KB

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