ScenePresence.cs 182 KB

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