ScenePresence.cs 187 KB

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