ScenePresence.cs 206 KB

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