1
0

ScenePresence.cs 206 KB

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