ScenePresence.cs 196 KB

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