ScenePresence.cs 267 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894
  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.PhysicsModules.SharedBase;
  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. // ~ScenePresence()
  76. // {
  77. // m_log.DebugFormat("[SCENE PRESENCE]: Destructor called on {0}", Name);
  78. // }
  79. public void TriggerScenePresenceUpdated()
  80. {
  81. if (m_scene != null)
  82. m_scene.EventManager.TriggerScenePresenceUpdated(this);
  83. }
  84. public bool IsNPC { get; private set; }
  85. // simple yes or no isGOD from god level >= 200
  86. // should only be set by GodController
  87. // we have two to suport legacy behaviour
  88. // IsViewerUIGod was controlled by viewer in older versions
  89. // IsGod may now be also controled by viewer acording to options
  90. public bool IsViewerUIGod { get; set; }
  91. public bool IsGod { get; set; }
  92. private PresenceType m_presenceType;
  93. public PresenceType PresenceType
  94. {
  95. get {return m_presenceType;}
  96. private set
  97. {
  98. m_presenceType = value;
  99. IsNPC = (m_presenceType == PresenceType.Npc);
  100. }
  101. }
  102. private ScenePresenceStateMachine m_stateMachine;
  103. /// <summary>
  104. /// The current state of this presence. Governs only the existence lifecycle. See ScenePresenceStateMachine
  105. /// for more details.
  106. /// </summary>
  107. public ScenePresenceState LifecycleState
  108. {
  109. get
  110. {
  111. return m_stateMachine.GetState();
  112. }
  113. set
  114. {
  115. m_stateMachine.SetState(value);
  116. }
  117. }
  118. /// <summary>
  119. /// This exists to prevent race conditions between two CompleteMovement threads if the simulator is slow and
  120. /// the viewer fires these in quick succession.
  121. /// </summary>
  122. /// <remarks>
  123. /// TODO: The child -> agent transition should be folded into LifecycleState and the CompleteMovement
  124. /// regulation done there.
  125. /// </remarks>
  126. private object m_completeMovementLock = new object();
  127. // private static readonly byte[] DEFAULT_TEXTURE = AvatarAppearance.GetDefaultTexture().GetBytes();
  128. private static readonly Array DIR_CONTROL_FLAGS = Enum.GetValues(typeof(Dir_ControlFlags));
  129. private static readonly Vector3 HEAD_ADJUSTMENT = new Vector3(0f, 0f, 0.3f);
  130. /// <summary>
  131. /// Experimentally determined "fudge factor" to make sit-target positions
  132. /// the same as in SecondLife. Fudge factor was tested for 36 different
  133. /// test cases including prims of type box, sphere, cylinder, and torus,
  134. /// with varying parameters for sit target location, prim size, prim
  135. /// rotation, prim cut, prim twist, prim taper, and prim shear. See mantis
  136. /// issue #1716
  137. /// </summary>
  138. public static readonly Vector3 SIT_TARGET_ADJUSTMENT = new Vector3(0.0f, 0.0f, 0.4f);
  139. public bool LegacySitOffsets = true;
  140. /// <summary>
  141. /// Movement updates for agents in neighboring regions are sent directly to clients.
  142. /// This value only affects how often agent positions are sent to neighbor regions
  143. /// for things such as distance-based update prioritization
  144. /// this are the square of real distances
  145. /// </summary>
  146. public static readonly float MOVEMENT = .25f;
  147. public static readonly float SIGNIFICANT_MOVEMENT = 16.0f;
  148. public static readonly float CHILDUPDATES_MOVEMENT = 100.0f;
  149. public static readonly float CHILDUPDATES_TIME = 2000f; // min time between child updates (ms)
  150. private UUID m_previusParcelUUID = UUID.Zero;
  151. private UUID m_currentParcelUUID = UUID.Zero;
  152. private bool m_previusParcelHide = false;
  153. private bool m_currentParcelHide = false;
  154. private object parcelLock = new Object();
  155. public double ParcelDwellTickMS;
  156. public UUID currentParcelUUID
  157. {
  158. get { return m_currentParcelUUID; }
  159. set
  160. {
  161. lock (parcelLock)
  162. {
  163. bool oldhide = m_currentParcelHide;
  164. bool checksame = true;
  165. if (value != m_currentParcelUUID)
  166. {
  167. ParcelDwellTickMS = Util.GetTimeStampMS();
  168. m_previusParcelHide = m_currentParcelHide;
  169. m_previusParcelUUID = m_currentParcelUUID;
  170. checksame = false;
  171. }
  172. m_currentParcelUUID = value;
  173. m_currentParcelHide = false;
  174. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  175. if (land != null && !land.LandData.SeeAVs)
  176. m_currentParcelHide = true;
  177. if (m_previusParcelUUID != UUID.Zero || checksame)
  178. ParcelCrossCheck(m_currentParcelUUID, m_previusParcelUUID, m_currentParcelHide, m_previusParcelHide, oldhide,checksame);
  179. }
  180. }
  181. }
  182. public void sitSOGmoved()
  183. {
  184. /*
  185. if (IsDeleted || !IsSatOnObject)
  186. //what me? nahh
  187. return;
  188. if (IsInTransit)
  189. return;
  190. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  191. if (land == null)
  192. return; //??
  193. UUID parcelID = land.LandData.GlobalID;
  194. if (m_currentParcelUUID != parcelID)
  195. currentParcelUUID = parcelID;
  196. */
  197. }
  198. public bool ParcelAllowThisAvatarSounds
  199. {
  200. get
  201. {
  202. try
  203. {
  204. lock (parcelLock)
  205. {
  206. ILandObject land = m_scene.LandChannel.GetLandObject(AbsolutePosition.X, AbsolutePosition.Y);
  207. if (land == null)
  208. return true;
  209. if (land.LandData.AnyAVSounds)
  210. return true;
  211. if (!land.LandData.GroupAVSounds)
  212. return false;
  213. return ControllingClient.IsGroupMember(land.LandData.GroupID);
  214. }
  215. }
  216. catch
  217. {
  218. return true;
  219. }
  220. }
  221. }
  222. public bool ParcelHideThisAvatar
  223. {
  224. get
  225. {
  226. return m_currentParcelHide;
  227. }
  228. }
  229. /// <value>
  230. /// The animator for this avatar
  231. /// </value>
  232. public ScenePresenceAnimator Animator { get; private set; }
  233. /// <value>
  234. /// Server Side Animation Override
  235. /// </value>
  236. public MovementAnimationOverrides Overrides { get; private set; }
  237. public String sitAnimation = "SIT";
  238. /// <summary>
  239. /// Attachments recorded on this avatar.
  240. /// </summary>
  241. /// <remarks>
  242. /// TODO: For some reason, we effectively have a list both here and in Appearance. Need to work out if this is
  243. /// necessary.
  244. /// </remarks>
  245. private List<SceneObjectGroup> m_attachments = new List<SceneObjectGroup>();
  246. public Object AttachmentsSyncLock { get; private set; }
  247. private Dictionary<UUID, ScriptControllers> scriptedcontrols = new Dictionary<UUID, ScriptControllers>();
  248. private ScriptControlled IgnoredControls = ScriptControlled.CONTROL_ZERO;
  249. private ScriptControlled LastCommands = ScriptControlled.CONTROL_ZERO;
  250. private bool MouseDown = false;
  251. public Vector3 lastKnownAllowedPosition;
  252. public bool sentMessageAboutRestrictedParcelFlyingDown;
  253. public Vector4 CollisionPlane = Vector4.UnitW;
  254. public Vector4 m_lastCollisionPlane = Vector4.UnitW;
  255. private byte m_lastState;
  256. private Vector3 m_lastPosition;
  257. private Quaternion m_lastRotation;
  258. private Vector3 m_lastVelocity;
  259. private Vector3 m_lastSize = new Vector3(0.45f,0.6f,1.9f);
  260. private bool SentInitialData = false;
  261. private int m_userFlags;
  262. public int UserFlags
  263. {
  264. get { return m_userFlags; }
  265. }
  266. // Flying
  267. public bool Flying
  268. {
  269. get { return PhysicsActor != null && PhysicsActor.Flying; }
  270. set { PhysicsActor.Flying = value; }
  271. }
  272. public bool IsColliding
  273. {
  274. get { return PhysicsActor != null && PhysicsActor.IsColliding; }
  275. // We would expect setting IsColliding to be private but it's used by a hack in Scene
  276. set { PhysicsActor.IsColliding = value; }
  277. }
  278. private List<uint> m_lastColliders = new List<uint>();
  279. private TeleportFlags m_teleportFlags;
  280. public TeleportFlags TeleportFlags
  281. {
  282. get { return m_teleportFlags; }
  283. set { m_teleportFlags = value; }
  284. }
  285. private uint m_requestedSitTargetID;
  286. private UUID m_requestedSitTargetUUID;
  287. /// <summary>
  288. /// Are we sitting on the ground?
  289. /// </summary>
  290. public bool SitGround { get; private set; }
  291. private SendCoarseLocationsMethod m_sendCoarseLocationsMethod;
  292. //private Vector3 m_requestedSitOffset = new Vector3();
  293. private Vector3 m_LastFinitePos;
  294. private float m_sitAvatarHeight = 2.0f;
  295. private bool m_childUpdatesBusy = false;
  296. private int m_lastChildUpdatesTime;
  297. private int m_lastChildAgentUpdateGodLevel;
  298. private float m_lastChildAgentUpdateDrawDistance;
  299. private Vector3 m_lastChildAgentUpdatePosition;
  300. // private Vector3 m_lastChildAgentUpdateCamPosition;
  301. private Vector3 m_lastCameraRayCastCam;
  302. private Vector3 m_lastCameraRayCastPos;
  303. private float m_FOV = 1.04f;
  304. private const int LAND_VELOCITYMAG_MAX = 12;
  305. private const float FLY_ROLL_MAX_RADIANS = 1.1f;
  306. private const float FLY_ROLL_RADIANS_PER_UPDATE = 0.06f;
  307. private const float FLY_ROLL_RESET_RADIANS_PER_UPDATE = 0.02f;
  308. private float m_health = 100f;
  309. private float m_healRate = 1f;
  310. private float m_healRatePerFrame = 0.05f;
  311. private readonly Vector3[] Dir_Vectors = new Vector3[12];
  312. protected int m_reprioritizationLastTime;
  313. protected bool m_reprioritizationBusy;
  314. protected Vector3 m_reprioritizationLastPosition;
  315. protected float m_reprioritizationLastDrawDistance;
  316. private Quaternion m_headrotation = Quaternion.Identity;
  317. //PauPaw:Proper PID Controler for autopilot************
  318. private bool m_movingToTarget;
  319. public bool MovingToTarget
  320. {
  321. get {return m_movingToTarget;}
  322. private set {m_movingToTarget = value; }
  323. }
  324. private Vector3 m_moveToPositionTarget;
  325. public Vector3 MoveToPositionTarget
  326. {
  327. get {return m_moveToPositionTarget;}
  328. private set {m_moveToPositionTarget = value; }
  329. }
  330. private float m_moveToSpeed;
  331. public float MoveToSpeed
  332. {
  333. get {return m_moveToSpeed;}
  334. private set {m_moveToSpeed = value; }
  335. }
  336. private double m_delayedStop = -1.0;
  337. /// <summary>
  338. /// Controls whether an avatar automatically moving to a target will land when it gets there (if flying).
  339. /// </summary>
  340. public bool LandAtTarget { get; private set; }
  341. private bool CameraConstraintActive;
  342. private object m_collisionEventLock = new Object();
  343. private int m_movementAnimationUpdateCounter = 0;
  344. public Vector3 PrevSitOffset { get; set; }
  345. protected AvatarAppearance m_appearance;
  346. public AvatarAppearance Appearance
  347. {
  348. get { return m_appearance; }
  349. set
  350. {
  351. m_appearance = value;
  352. // m_log.DebugFormat("[SCENE PRESENCE]: Set appearance for {0} to {1}", Name, value);
  353. }
  354. }
  355. /// <summary>
  356. /// Copy of the script states while the agent is in transit. This state may
  357. /// need to be placed back in case of transfer fail.
  358. /// </summary>
  359. public List<string> InTransitScriptStates
  360. {
  361. get { return m_InTransitScriptStates; }
  362. private set { m_InTransitScriptStates = value; }
  363. }
  364. private List<string> m_InTransitScriptStates = new List<string>();
  365. /// <summary>
  366. /// Implemented Control Flags
  367. /// </summary>
  368. private enum Dir_ControlFlags:uint
  369. {
  370. DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  371. DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  372. DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  373. DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  374. DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  375. DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  376. DIR_CONTROL_FLAG_FORWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS,
  377. DIR_CONTROL_FLAG_BACKWARD_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG,
  378. DIR_CONTROL_FLAG_LEFT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS,
  379. DIR_CONTROL_FLAG_RIGHT_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG,
  380. DIR_CONTROL_FLAG_UP_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS,
  381. DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  382. }
  383. /// <summary>
  384. /// Position at which a significant movement was made
  385. /// </summary>
  386. private Vector3 posLastSignificantMove;
  387. private Vector3 posLastMove;
  388. #region For teleports and crossings callbacks
  389. /// <summary>
  390. /// In the V1 teleport protocol, the destination simulator sends ReleaseAgent to this address.
  391. /// </summary>
  392. private string m_callbackURI;
  393. /// <summary>
  394. /// Records the region from which this presence originated, if not from login.
  395. /// </summary>
  396. /// <remarks>
  397. /// Also acts as a signal in the teleport V2 process to release UpdateAgent after a viewer has triggered
  398. /// CompleteMovement and made the previous child agent a root agent.
  399. /// </remarks>
  400. private UUID m_originRegionID;
  401. /// <summary>
  402. /// This object is used as a lock before accessing m_originRegionID to make sure that every thread is seeing
  403. /// the very latest value and not using some cached version. Cannot make m_originRegionID itself volatite as
  404. /// it is a value type.
  405. /// </summary>
  406. private object m_originRegionIDAccessLock = new object();
  407. private AutoResetEvent m_updateAgentReceivedAfterTransferEvent = new AutoResetEvent(false);
  408. /// <summary>
  409. /// Used by the entity transfer module to signal when the presence should not be closed because a subsequent
  410. /// teleport is reusing the connection.
  411. /// </summary>
  412. /// <remarks>May be refactored or move somewhere else soon.</remarks>
  413. public bool DoNotCloseAfterTeleport { get; set; }
  414. #endregion
  415. /// <value>
  416. /// Script engines present in the scene
  417. /// </value>
  418. private IScriptModule[] m_scriptEngines;
  419. private enum LandingPointBehavior
  420. {
  421. OS = 1,
  422. SL = 2
  423. }
  424. private LandingPointBehavior m_LandingPointBehavior = LandingPointBehavior.OS;
  425. #region Properties
  426. /// <summary>
  427. /// Physical scene representation of this Avatar.
  428. /// </summary>
  429. public PhysicsActor PhysicsActor { get; private set; }
  430. /// <summary>
  431. /// Record user movement inputs.
  432. /// </summary>
  433. public uint MovementFlag { get; private set; }
  434. /// <summary>
  435. /// Is the agent stop control flag currently active?
  436. /// </summary>
  437. public bool AgentControlStopActive { get; private set; }
  438. private bool m_invulnerable = true;
  439. public bool Invulnerable
  440. {
  441. set { m_invulnerable = value; }
  442. get { return m_invulnerable; }
  443. }
  444. public GodController GodController { get; private set; }
  445. private ulong m_rootRegionHandle;
  446. private Vector3 m_rootRegionPosition = new Vector3();
  447. public ulong RegionHandle
  448. {
  449. get { return m_rootRegionHandle; }
  450. private set
  451. {
  452. m_rootRegionHandle = value;
  453. // position rounded to lower multiple of 256m
  454. m_rootRegionPosition.X = (float)((m_rootRegionHandle >> 32) & 0xffffff00);
  455. m_rootRegionPosition.Y = (float)(m_rootRegionHandle & 0xffffff00);
  456. }
  457. }
  458. #region Client Camera
  459. /// <summary>
  460. /// Position of agent's camera in world (region cordinates)
  461. /// </summary>
  462. // protected Vector3 m_lastCameraPosition;
  463. private Vector4 m_lastCameraCollisionPlane = new Vector4(0f, 0f, 0f, 1);
  464. private bool m_doingCamRayCast = false;
  465. public Vector3 CameraPosition { get; set; }
  466. public Quaternion CameraRotation { get; private set; }
  467. // Use these three vectors to figure out what the agent is looking at
  468. // Convert it to a Matrix and/or Quaternion
  469. //
  470. public Vector3 CameraAtAxis { get; set; }
  471. public Vector3 CameraLeftAxis { get; set; }
  472. public Vector3 CameraUpAxis { get; set; }
  473. public Vector3 Lookat
  474. {
  475. get
  476. {
  477. Vector3 a = new Vector3(CameraAtAxis.X, CameraAtAxis.Y, 0);
  478. a.Normalize();
  479. return a;
  480. }
  481. }
  482. #endregion
  483. public string Firstname { get; private set; }
  484. public string Lastname { get; private set; }
  485. public bool haveGroupInformation;
  486. public bool gotCrossUpdate;
  487. public byte crossingFlags;
  488. public string Grouptitle
  489. {
  490. get { return m_groupTitle; }
  491. set { m_groupTitle = value; }
  492. }
  493. private string m_groupTitle;
  494. // Agent's Draw distance.
  495. private float m_drawDistance = 255f;
  496. public float DrawDistance
  497. {
  498. get
  499. {
  500. return m_drawDistance;
  501. }
  502. set
  503. {
  504. m_drawDistance = Util.Clamp(value, 32f, m_scene.MaxDrawDistance);
  505. }
  506. }
  507. public float RegionViewDistance
  508. {
  509. get
  510. {
  511. return Util.Clamp(m_drawDistance, 32f, m_scene.MaxRegionViewDistance);
  512. }
  513. }
  514. public bool AllowMovement { get; set; }
  515. private bool m_setAlwaysRun;
  516. public bool SetAlwaysRun
  517. {
  518. get
  519. {
  520. if (PhysicsActor != null)
  521. {
  522. return PhysicsActor.SetAlwaysRun;
  523. }
  524. else
  525. {
  526. return m_setAlwaysRun;
  527. }
  528. }
  529. set
  530. {
  531. m_setAlwaysRun = value;
  532. if (PhysicsActor != null)
  533. {
  534. PhysicsActor.SetAlwaysRun = value;
  535. }
  536. }
  537. }
  538. public byte State { get; set; }
  539. private AgentManager.ControlFlags m_AgentControlFlags;
  540. public uint AgentControlFlags
  541. {
  542. get { return (uint)m_AgentControlFlags; }
  543. set { m_AgentControlFlags = (AgentManager.ControlFlags)value; }
  544. }
  545. public IClientAPI ControllingClient { get; set; }
  546. public IClientCore ClientView
  547. {
  548. get { return (IClientCore)ControllingClient; }
  549. }
  550. public UUID COF { get; set; }
  551. // public Vector3 ParentPosition { get; set; }
  552. /// <summary>
  553. /// Position of this avatar relative to the region the avatar is in
  554. /// </summary>
  555. public override Vector3 AbsolutePosition
  556. {
  557. get
  558. {
  559. if (PhysicsActor != null)
  560. {
  561. m_pos = PhysicsActor.Position;
  562. // m_log.DebugFormat(
  563. // "[SCENE PRESENCE]: Set position of {0} in {1} to {2} via getting AbsolutePosition!",
  564. // Name, Scene.Name, m_pos);
  565. }
  566. else
  567. {
  568. // m_log.DebugFormat("[SCENE PRESENCE]: Fetching abs pos where PhysicsActor == null and parent part {0} for {1}", Name, Scene.Name);
  569. // Obtain the correct position of a seated avatar.
  570. // In addition to providing the correct position while
  571. // the avatar is seated, this value will also
  572. // be used as the location to unsit to.
  573. //
  574. // If ParentID is not 0, assume we are a seated avatar
  575. // and we should return the position based on the sittarget
  576. // offset and rotation of the prim we are seated on.
  577. //
  578. // Generally, m_pos will contain the position of the avatar
  579. // in the sim unless the avatar is on a sit target. While
  580. // on a sit target, m_pos will contain the desired offset
  581. // without the parent rotation applied.
  582. if (ParentPart != null)
  583. {
  584. SceneObjectPart rootPart = ParentPart.ParentGroup.RootPart;
  585. // if (sitPart != null)
  586. // return sitPart.AbsolutePosition + (m_pos * sitPart.GetWorldRotation());
  587. if (rootPart != null)
  588. return rootPart.AbsolutePosition + (m_pos * rootPart.GetWorldRotation());
  589. }
  590. }
  591. return m_pos;
  592. }
  593. set
  594. {
  595. // m_log.DebugFormat("[SCENE PRESENCE]: Setting position of {0} to {1} in {2}", Name, value, Scene.Name);
  596. // Util.PrintCallStack();
  597. if (PhysicsActor != null)
  598. {
  599. try
  600. {
  601. PhysicsActor.Position = value;
  602. }
  603. catch (Exception e)
  604. {
  605. m_log.Error("[SCENE PRESENCE]: ABSOLUTE POSITION " + e.Message);
  606. }
  607. }
  608. // Don't update while sitting. The PhysicsActor above is null whilst sitting.
  609. if (ParentID == 0)
  610. m_pos = value;
  611. //m_log.DebugFormat(
  612. // "[ENTITY BASE]: In {0} set AbsolutePosition of {1} to {2}",
  613. // Scene.RegionInfo.RegionName, Name, m_pos);
  614. TriggerScenePresenceUpdated();
  615. }
  616. }
  617. /// <summary>
  618. /// If sitting, returns the offset position from the prim the avatar is sitting on.
  619. /// Otherwise, returns absolute position in the scene.
  620. /// </summary>
  621. public Vector3 OffsetPosition
  622. {
  623. get { return m_pos; }
  624. // Don't remove setter. It's not currently used in core but
  625. // upcoming Avination code needs it.
  626. set
  627. {
  628. // There is no offset position when not seated
  629. if (ParentID == 0)
  630. return;
  631. m_pos = value;
  632. TriggerScenePresenceUpdated();
  633. }
  634. }
  635. /// <summary>
  636. /// Current velocity of the avatar.
  637. /// </summary>
  638. public override Vector3 Velocity
  639. {
  640. get
  641. {
  642. if (PhysicsActor != null)
  643. {
  644. m_velocity = PhysicsActor.Velocity;
  645. // m_log.DebugFormat(
  646. // "[SCENE PRESENCE]: Set velocity {0} for {1} in {2} via getting Velocity!",
  647. // m_velocity, Name, Scene.RegionInfo.RegionName);
  648. }
  649. return m_velocity;
  650. }
  651. set
  652. {
  653. if (PhysicsActor != null)
  654. {
  655. try
  656. {
  657. PhysicsActor.TargetVelocity = value;
  658. }
  659. catch (Exception e)
  660. {
  661. m_log.Error("[SCENE PRESENCE]: VELOCITY " + e.Message);
  662. }
  663. }
  664. m_velocity = value;
  665. // m_log.DebugFormat(
  666. // "[SCENE PRESENCE]: In {0} set velocity of {1} to {2}",
  667. // Scene.RegionInfo.RegionName, Name, m_velocity);
  668. }
  669. }
  670. // requested Velocity for physics engines avatar motors
  671. // only makes sense if there is a physical rep
  672. public Vector3 TargetVelocity
  673. {
  674. get
  675. {
  676. if (PhysicsActor != null)
  677. return PhysicsActor.TargetVelocity;
  678. else
  679. return Vector3.Zero;
  680. }
  681. set
  682. {
  683. if (PhysicsActor != null)
  684. {
  685. try
  686. {
  687. PhysicsActor.TargetVelocity = value;
  688. }
  689. catch (Exception e)
  690. {
  691. m_log.Error("[SCENE PRESENCE]: TARGETVELOCITY " + e.Message);
  692. }
  693. }
  694. }
  695. }
  696. private Quaternion m_bodyRot = Quaternion.Identity;
  697. /// <summary>
  698. /// The rotation of the avatar.
  699. /// </summary>
  700. /// <remarks>
  701. /// If the avatar is not sitting, this is with respect to the world
  702. /// If the avatar is sitting, this is a with respect to the part that it's sitting upon (a local rotation).
  703. /// If you always want the world rotation, use GetWorldRotation()
  704. /// </remarks>
  705. public Quaternion Rotation
  706. {
  707. get
  708. {
  709. return m_bodyRot;
  710. }
  711. set
  712. {
  713. m_bodyRot = value;
  714. if (PhysicsActor != null)
  715. {
  716. try
  717. {
  718. PhysicsActor.Orientation = m_bodyRot;
  719. }
  720. catch (Exception e)
  721. {
  722. m_log.Error("[SCENE PRESENCE]: Orientation " + e.Message);
  723. }
  724. }
  725. // m_log.DebugFormat("[SCENE PRESENCE]: Body rot for {0} set to {1}", Name, m_bodyRot);
  726. }
  727. }
  728. // Used for limited viewer 'fake' user rotations.
  729. private Vector3 m_AngularVelocity = Vector3.Zero;
  730. public Vector3 AngularVelocity
  731. {
  732. get { return m_AngularVelocity; }
  733. }
  734. public bool IsChildAgent { get; set; }
  735. public bool IsLoggingIn { get; set; }
  736. /// <summary>
  737. /// If the avatar is sitting, the local ID of the prim that it's sitting on. If not sitting then zero.
  738. /// </summary>
  739. public uint ParentID { get; set; }
  740. public UUID ParentUUID
  741. {
  742. get { return m_parentUUID; }
  743. set { m_parentUUID = value; }
  744. }
  745. private UUID m_parentUUID = UUID.Zero;
  746. /// <summary>
  747. /// Are we sitting on an object?
  748. /// </summary>
  749. /// <remarks>A more readable way of testing presence sit status than ParentID == 0</remarks>
  750. public bool IsSatOnObject { get { return ParentID != 0; } }
  751. /// <summary>
  752. /// If the avatar is sitting, the prim that it's sitting on. If not sitting then null.
  753. /// </summary>
  754. /// <remarks>
  755. /// If you use this property then you must take a reference since another thread could set it to null.
  756. /// </remarks>
  757. public SceneObjectPart ParentPart { get; set; }
  758. public float Health
  759. {
  760. get { return m_health; }
  761. set { m_health = value; }
  762. }
  763. public float HealRate
  764. {
  765. get { return m_healRate; }
  766. set
  767. {
  768. if(value > 100.0f)
  769. m_healRate = 100.0f;
  770. else if (value <= 0.0)
  771. m_healRate = 0.0f;
  772. else
  773. m_healRate = value;
  774. if(Scene != null)
  775. m_healRatePerFrame = m_healRate * Scene.FrameTime;
  776. else
  777. m_healRatePerFrame = 0.05f;
  778. }
  779. }
  780. /// <summary>
  781. /// Gets the world rotation of this presence.
  782. /// </summary>
  783. /// <remarks>
  784. /// Unlike Rotation, this returns the world rotation no matter whether the avatar is sitting on a prim or not.
  785. /// </remarks>
  786. /// <returns></returns>
  787. public Quaternion GetWorldRotation()
  788. {
  789. if (IsSatOnObject)
  790. {
  791. SceneObjectPart sitPart = ParentPart;
  792. if (sitPart != null)
  793. return sitPart.GetWorldRotation() * Rotation;
  794. }
  795. return Rotation;
  796. }
  797. /// <summary>
  798. /// Get velocity relative to the world.
  799. /// </summary>
  800. public Vector3 GetWorldVelocity()
  801. {
  802. SceneObjectPart sitPart = ParentPart;
  803. if (sitPart != null)
  804. return sitPart.ParentGroup.Velocity;
  805. return Velocity;
  806. }
  807. public void AdjustKnownSeeds()
  808. {
  809. Dictionary<ulong, string> seeds;
  810. if (Scene.CapsModule != null)
  811. seeds = Scene.CapsModule.GetChildrenSeeds(UUID);
  812. else
  813. seeds = new Dictionary<ulong, string>();
  814. KnownRegions = seeds;
  815. }
  816. public void DumpKnownRegions()
  817. {
  818. m_log.Info("================ KnownRegions "+Scene.RegionInfo.RegionName+" ================");
  819. foreach (KeyValuePair<ulong, string> kvp in KnownRegions)
  820. {
  821. uint x, y;
  822. Util.RegionHandleToRegionLoc(kvp.Key, out x, out y);
  823. m_log.Info(" >> "+x+", "+y+": "+kvp.Value);
  824. }
  825. }
  826. private bool m_mouseLook;
  827. private bool m_leftButtonDown;
  828. private bool m_inTransit;
  829. /// <summary>
  830. /// This signals whether the presence is in transit between neighbouring regions.
  831. /// </summary>
  832. /// <remarks>
  833. /// It is not set when the presence is teleporting or logging in/out directly to a region.
  834. /// </remarks>
  835. public bool IsInTransit
  836. {
  837. get { return m_inTransit; }
  838. set {
  839. if(value)
  840. {
  841. if (Flying)
  842. m_AgentControlFlags |= AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  843. else
  844. m_AgentControlFlags &= ~AgentManager.ControlFlags.AGENT_CONTROL_FLY;
  845. }
  846. m_inTransit = value;
  847. }
  848. }
  849. // this is is only valid if IsInTransit is true
  850. // only false on HG tps
  851. // used work arounf viewers asking source region about destination user
  852. public bool IsInLocalTransit {get; set; }
  853. /// <summary>
  854. /// Modifier for agent movement if we get an AGENT_CONTROL_STOP whilst walking or running
  855. /// </summary>
  856. /// <remarks>
  857. /// AGENT_CONTRL_STOP comes about if user holds down space key on viewers.
  858. /// </remarks>
  859. private const float AgentControlStopSlowVel = 0.2f;
  860. // velocities
  861. public const float AgentControlNudgeVel = 1.0f; // setting this diferent from normal as no effect currently
  862. public const float AgentControlNormalVel = 1.0f;
  863. // old normal speed was tuned to match sl normal plus Fast modifiers
  864. // so we need to rescale it
  865. private float m_speedModifier = 1.0f;
  866. public float SpeedModifier
  867. {
  868. get { return m_speedModifier; }
  869. set { m_speedModifier = value; }
  870. }
  871. private bool m_forceFly;
  872. public bool ForceFly
  873. {
  874. get { return m_forceFly; }
  875. set { m_forceFly = value; }
  876. }
  877. private bool m_flyDisabled;
  878. public bool FlyDisabled
  879. {
  880. get { return m_flyDisabled; }
  881. set { m_flyDisabled = value; }
  882. }
  883. public string Viewer
  884. {
  885. get { return Util.GetViewerName(m_scene.AuthenticateHandler.GetAgentCircuitData(ControllingClient.CircuitCode)); }
  886. }
  887. #endregion
  888. #region Constructor(s)
  889. public ScenePresence(
  890. IClientAPI client, Scene world, AvatarAppearance appearance, PresenceType type)
  891. {
  892. m_scene = world;
  893. AttachmentsSyncLock = new Object();
  894. AllowMovement = true;
  895. IsChildAgent = true;
  896. IsLoggingIn = false;
  897. m_sendCoarseLocationsMethod = SendCoarseLocationsDefault;
  898. Animator = new ScenePresenceAnimator(this);
  899. Overrides = new MovementAnimationOverrides();
  900. PresenceType = type;
  901. DrawDistance = world.DefaultDrawDistance;
  902. RegionHandle = world.RegionInfo.RegionHandle;
  903. ControllingClient = client;
  904. Firstname = ControllingClient.FirstName;
  905. Lastname = ControllingClient.LastName;
  906. m_name = String.Format("{0} {1}", Firstname, Lastname);
  907. m_uuid = client.AgentId;
  908. LocalId = m_scene.AllocateLocalId();
  909. LegacySitOffsets = m_scene.LegacySitOffsets;
  910. IsInLocalTransit = true;
  911. UserAccount account = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, m_uuid);
  912. if (account != null)
  913. m_userFlags = account.UserFlags;
  914. else
  915. m_userFlags = 0;
  916. int userlevel = 0;
  917. if (account != null)
  918. userlevel = account.UserLevel;
  919. GodController = new GodController(world, this, userlevel);
  920. // IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  921. // if (gm != null)
  922. // Grouptitle = gm.GetGroupTitle(m_uuid);
  923. m_scriptEngines = m_scene.RequestModuleInterfaces<IScriptModule>();
  924. AbsolutePosition = posLastMove = posLastSignificantMove = CameraPosition =
  925. m_reprioritizationLastPosition = ControllingClient.StartPos;
  926. m_reprioritizationLastDrawDistance = DrawDistance;
  927. // disable updates workjobs for now
  928. m_childUpdatesBusy = true;
  929. m_reprioritizationBusy = true;
  930. AdjustKnownSeeds();
  931. RegisterToClientEvents();
  932. SetDirectionVectors();
  933. Appearance = appearance;
  934. m_stateMachine = new ScenePresenceStateMachine(this);
  935. HealRate = 0.5f;
  936. IConfig sconfig = m_scene.Config.Configs["EntityTransfer"];
  937. if (sconfig != null)
  938. {
  939. string lpb = sconfig.GetString("LandingPointBehavior", "LandingPointBehavior_OS");
  940. if (lpb == "LandingPointBehavior_SL")
  941. m_LandingPointBehavior = LandingPointBehavior.SL;
  942. }
  943. m_bandwidth = 100000;
  944. m_lastBandwithTime = Util.GetTimeStamp() + 0.1;
  945. IConfig cconfig = m_scene.Config.Configs["ClientStack.LindenCaps"];
  946. if (cconfig != null)
  947. {
  948. m_capbandwidth = cconfig.GetInt("Cap_AssetThrottle", m_capbandwidth);
  949. if(m_capbandwidth > 0)
  950. {
  951. m_bandwidth = m_capbandwidth;
  952. if(m_bandwidth < 50000)
  953. m_bandwidth = 50000;
  954. }
  955. }
  956. m_bandwidthBurst = m_bandwidth / 5;
  957. ControllingClient.RefreshGroupMembership();
  958. }
  959. private float lastHealthSent = 0;
  960. private void RegionHeartbeatEnd(Scene scene)
  961. {
  962. if (IsChildAgent)
  963. return;
  964. m_movementAnimationUpdateCounter ++;
  965. if (m_movementAnimationUpdateCounter >= 2)
  966. {
  967. m_movementAnimationUpdateCounter = 0;
  968. if (Animator != null)
  969. {
  970. // If the parentID == 0 we are not sitting
  971. // if !SitGournd then we are not sitting on the ground
  972. // Fairly straightforward, now here comes the twist
  973. // if ParentUUID is NOT UUID.Zero, we are looking to
  974. // be sat on an object that isn't there yet. Should
  975. // be treated as if sat.
  976. if(ParentID == 0 && !SitGround && ParentUUID == UUID.Zero) // skip it if sitting
  977. Animator.UpdateMovementAnimations();
  978. }
  979. else
  980. {
  981. // m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  982. }
  983. }
  984. if(m_healRatePerFrame != 0f && Health != 100.0f)
  985. {
  986. float last = Health;
  987. Health += m_healRatePerFrame;
  988. if(Health > 100.0f)
  989. {
  990. Health = 100.0f;
  991. lastHealthSent = Health;
  992. ControllingClient.SendHealth(Health);
  993. }
  994. else if(Math.Abs(Health - lastHealthSent) > 1.0)
  995. {
  996. lastHealthSent = Health;
  997. ControllingClient.SendHealth(Health);
  998. }
  999. }
  1000. }
  1001. public void RegisterToClientEvents()
  1002. {
  1003. ControllingClient.OnCompleteMovementToRegion += CompleteMovement;
  1004. ControllingClient.OnAgentUpdate += HandleAgentUpdate;
  1005. ControllingClient.OnAgentCameraUpdate += HandleAgentCamerasUpdate;
  1006. ControllingClient.OnAgentRequestSit += HandleAgentRequestSit;
  1007. ControllingClient.OnAgentSit += HandleAgentSit;
  1008. ControllingClient.OnSetAlwaysRun += HandleSetAlwaysRun;
  1009. ControllingClient.OnStartAnim += HandleStartAnim;
  1010. ControllingClient.OnStopAnim += HandleStopAnim;
  1011. ControllingClient.OnChangeAnim += avnHandleChangeAnim;
  1012. ControllingClient.OnForceReleaseControls += HandleForceReleaseControls;
  1013. ControllingClient.OnAutoPilotGo += MoveToTargetHandle;
  1014. ControllingClient.OnUpdateThrottles += RaiseUpdateThrottles;
  1015. // ControllingClient.OnAgentFOV += HandleAgentFOV;
  1016. // ControllingClient.OnChildAgentStatus += new StatusChange(this.ChildStatusChange);
  1017. // ControllingClient.OnStopMovement += new GenericCall2(this.StopMovement);
  1018. }
  1019. public void RemoveClientEvents()
  1020. {
  1021. ControllingClient.OnCompleteMovementToRegion -= CompleteMovement;
  1022. ControllingClient.OnAgentUpdate -= HandleAgentUpdate;
  1023. ControllingClient.OnAgentCameraUpdate -= HandleAgentCamerasUpdate;
  1024. ControllingClient.OnAgentRequestSit -= HandleAgentRequestSit;
  1025. ControllingClient.OnAgentSit -= HandleAgentSit;
  1026. ControllingClient.OnSetAlwaysRun -= HandleSetAlwaysRun;
  1027. ControllingClient.OnStartAnim -= HandleStartAnim;
  1028. ControllingClient.OnStopAnim -= HandleStopAnim;
  1029. ControllingClient.OnChangeAnim -= avnHandleChangeAnim;
  1030. ControllingClient.OnForceReleaseControls -= HandleForceReleaseControls;
  1031. ControllingClient.OnAutoPilotGo -= MoveToTargetHandle;
  1032. ControllingClient.OnUpdateThrottles -= RaiseUpdateThrottles;
  1033. // ControllingClient.OnAgentFOV += HandleAgentFOV;
  1034. }
  1035. private void SetDirectionVectors()
  1036. {
  1037. Dir_Vectors[0] = new Vector3(AgentControlNormalVel,0,0); //FORWARD
  1038. Dir_Vectors[1] = new Vector3(-AgentControlNormalVel,0,0);; //BACK
  1039. Dir_Vectors[2] = new Vector3(0,AgentControlNormalVel,0); //LEFT
  1040. Dir_Vectors[3] = new Vector3(0,-AgentControlNormalVel,0); //RIGHT
  1041. Dir_Vectors[4] = new Vector3(0,0,AgentControlNormalVel); //UP
  1042. Dir_Vectors[5] = new Vector3(0,0,-AgentControlNormalVel); //DOWN
  1043. Dir_Vectors[6] = new Vector3(AgentControlNudgeVel, 0f, 0f); //FORWARD_NUDGE
  1044. Dir_Vectors[7] = new Vector3(-AgentControlNudgeVel, 0f, 0f); //BACK_NUDGE
  1045. Dir_Vectors[8] = new Vector3(0f, AgentControlNudgeVel, 0f); //LEFT_NUDGE
  1046. Dir_Vectors[9] = new Vector3(0f, -AgentControlNudgeVel, 0f); //RIGHT_NUDGE
  1047. Dir_Vectors[10] = new Vector3(0f, 0f, AgentControlNudgeVel); //UP_Nudge
  1048. Dir_Vectors[11] = new Vector3(0f, 0f, -AgentControlNudgeVel); //DOWN_Nudge
  1049. }
  1050. #endregion
  1051. #region Status Methods
  1052. /// <summary>
  1053. /// Turns a child agent into a root agent.
  1054. /// </summary>
  1055. /// <remarks>
  1056. /// Child agents are logged into neighbouring sims largely to observe changes. Root agents exist when the
  1057. /// avatar is actual in the sim. They can perform all actions.
  1058. /// This change is made whenever an avatar enters a region, whether by crossing over from a neighbouring sim,
  1059. /// teleporting in or on initial login.
  1060. ///
  1061. /// This method is on the critical path for transferring an avatar from one region to another. Delay here
  1062. /// delays that crossing.
  1063. /// </remarks>
  1064. // constants for physics position search
  1065. const float PhysSearchHeight = 600f;
  1066. const float PhysMinSkipGap = 50f;
  1067. const int PhysNumberCollisions = 30;
  1068. // only in use as part of completemovement
  1069. // other uses need fix
  1070. private bool MakeRootAgent(Vector3 pos, bool isFlying, ref Vector3 lookat)
  1071. {
  1072. //int ts = Util.EnvironmentTickCount();
  1073. lock (m_completeMovementLock)
  1074. {
  1075. if (!IsChildAgent)
  1076. return false;
  1077. //m_log.DebugFormat("[MakeRootAgent] enter lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1078. //m_log.DebugFormat("[SCENE]: known regions in {0}: {1}", Scene.RegionInfo.RegionName, KnownChildRegionHandles.Count);
  1079. // m_log.InfoFormat(
  1080. // "[SCENE]: Upgrading child to root agent for {0} in {1}",
  1081. // Name, m_scene.RegionInfo.RegionName);
  1082. if (ParentUUID != UUID.Zero)
  1083. {
  1084. m_log.DebugFormat("[SCENE PRESENCE]: Sitting avatar back on prim {0}", ParentUUID);
  1085. SceneObjectPart part = m_scene.GetSceneObjectPart(ParentUUID);
  1086. if (part == null)
  1087. {
  1088. m_log.ErrorFormat("[SCENE PRESENCE]: Can't find prim {0} to sit on", ParentUUID);
  1089. ParentID = 0;
  1090. ParentPart = null;
  1091. PrevSitOffset = Vector3.Zero;
  1092. HandleForceReleaseControls(ControllingClient, UUID); // needs testing
  1093. IsLoggingIn = false;
  1094. }
  1095. else
  1096. {
  1097. part.AddSittingAvatar(this);
  1098. // if not actually on the target invalidate it
  1099. if(gotCrossUpdate && (crossingFlags & 0x04) == 0)
  1100. part.SitTargetAvatar = UUID.Zero;
  1101. ParentID = part.LocalId;
  1102. ParentPart = part;
  1103. m_pos = PrevSitOffset;
  1104. pos = part.GetWorldPosition();
  1105. PhysicsActor partPhysActor = part.PhysActor;
  1106. if(partPhysActor != null)
  1107. {
  1108. partPhysActor.OnPhysicsRequestingCameraData -=
  1109. physActor_OnPhysicsRequestingCameraData;
  1110. partPhysActor.OnPhysicsRequestingCameraData +=
  1111. physActor_OnPhysicsRequestingCameraData;
  1112. }
  1113. }
  1114. ParentUUID = UUID.Zero;
  1115. }
  1116. else
  1117. {
  1118. IsLoggingIn = false;
  1119. }
  1120. IsChildAgent = false;
  1121. }
  1122. //m_log.DebugFormat("[MakeRootAgent] out lock: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1123. // Must reset this here so that a teleport to a region next to an existing region does not keep the flag
  1124. // set and prevent the close of the connection on a subsequent re-teleport.
  1125. // Should not be needed if we are not trying to tell this region to close
  1126. // DoNotCloseAfterTeleport = false;
  1127. RegionHandle = m_scene.RegionInfo.RegionHandle;
  1128. m_scene.EventManager.TriggerSetRootAgentScene(m_uuid, m_scene);
  1129. //m_log.DebugFormat("[MakeRootAgent] TriggerSetRootAgentScene: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1130. if (ParentID == 0)
  1131. {
  1132. bool positionChanged = false;
  1133. bool success = true;
  1134. if (m_LandingPointBehavior == LandingPointBehavior.OS)
  1135. success = CheckAndAdjustLandingPoint_OS(ref pos, ref lookat, ref positionChanged);
  1136. else
  1137. success = CheckAndAdjustLandingPoint_SL(ref pos, ref lookat, ref positionChanged);
  1138. if (!success)
  1139. m_log.DebugFormat("[SCENE PRESENCE MakeRootAgent]: houston we have a problem.. {0} ({1} got banned)", Name, UUID);
  1140. if (pos.X < 0f || pos.Y < 0f
  1141. || pos.X >= m_scene.RegionInfo.RegionSizeX
  1142. || pos.Y >= m_scene.RegionInfo.RegionSizeY)
  1143. {
  1144. m_log.WarnFormat(
  1145. "[SCENE PRESENCE]: MakeRootAgent() was given an illegal position of {0} for avatar {1}, {2}. Clamping",
  1146. pos, Name, UUID);
  1147. if (pos.X < 0f)
  1148. pos.X = 0.5f;
  1149. else if(pos.X >= m_scene.RegionInfo.RegionSizeX)
  1150. pos.X = m_scene.RegionInfo.RegionSizeX - 0.5f;
  1151. if (pos.Y < 0f)
  1152. pos.Y = 0.5f;
  1153. else if(pos.Y >= m_scene.RegionInfo.RegionSizeY)
  1154. pos.Y = m_scene.RegionInfo.RegionSizeY - 0.5f;
  1155. }
  1156. float groundHeight = m_scene.GetGroundHeight(pos.X, pos.Y) + .01f;
  1157. float physTestHeight;
  1158. if(PhysSearchHeight < groundHeight + 100f)
  1159. physTestHeight = groundHeight + 100f;
  1160. else
  1161. physTestHeight = PhysSearchHeight;
  1162. float localAVHalfHeight = 0.8f;
  1163. if (Appearance != null && Appearance.AvatarHeight > 0)
  1164. localAVHalfHeight = 0.5f * Appearance.AvatarHeight;
  1165. groundHeight += localAVHalfHeight;
  1166. if (groundHeight > pos.Z)
  1167. pos.Z = groundHeight;
  1168. bool checkPhysics = !positionChanged &&
  1169. m_scene.SupportsRayCastFiltered() &&
  1170. pos.Z < physTestHeight &&
  1171. ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  1172. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  1173. || (m_teleportFlags & TeleportFlags.ViaLocation) != 0
  1174. || (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0);
  1175. if(checkPhysics)
  1176. {
  1177. // land check was done above
  1178. RayFilterFlags rayfilter = RayFilterFlags.BackFaceCull;
  1179. rayfilter |= RayFilterFlags.PrimsNonPhantomAgents;
  1180. int physcount = PhysNumberCollisions;
  1181. float dist = physTestHeight - groundHeight + localAVHalfHeight;
  1182. Vector3 direction = new Vector3(0f, 0f, -1f);
  1183. Vector3 RayStart = pos;
  1184. RayStart.Z = physTestHeight;
  1185. List<ContactResult> physresults =
  1186. (List<ContactResult>)m_scene.RayCastFiltered(RayStart, direction, dist, physcount, rayfilter);
  1187. if (physresults != null && physresults.Count > 0)
  1188. {
  1189. float dest = physresults[0].Pos.Z;
  1190. if(physresults.Count > 1)
  1191. {
  1192. physresults.Sort(delegate(ContactResult a, ContactResult b)
  1193. {
  1194. return a.Depth.CompareTo(b.Depth);
  1195. });
  1196. int sel = 0;
  1197. int count = physresults.Count;
  1198. float curd = physresults[0].Depth;
  1199. float nextd = curd + PhysMinSkipGap;
  1200. float maxDepth = dist - pos.Z;
  1201. for(int i = 1; i < count; i++)
  1202. {
  1203. curd = physresults[i].Depth;
  1204. if(curd >= nextd)
  1205. {
  1206. sel = i;
  1207. if(curd >= maxDepth)
  1208. break;
  1209. }
  1210. nextd = curd + PhysMinSkipGap;
  1211. }
  1212. dest = physresults[sel].Pos.Z;
  1213. }
  1214. dest += localAVHalfHeight;
  1215. if(dest > pos.Z)
  1216. pos.Z = dest;
  1217. }
  1218. }
  1219. AbsolutePosition = pos;
  1220. // m_log.DebugFormat(
  1221. // "Set pos {0}, vel {1} in {1} to {2} from input position of {3} on MakeRootAgent",
  1222. // Name, Scene.Name, AbsolutePosition, pos);
  1223. //
  1224. if (m_teleportFlags == TeleportFlags.Default)
  1225. {
  1226. Vector3 vel = Velocity;
  1227. AddToPhysicalScene(isFlying);
  1228. if (PhysicsActor != null)
  1229. PhysicsActor.SetMomentum(vel);
  1230. }
  1231. else
  1232. {
  1233. AddToPhysicalScene(isFlying);
  1234. // reset camera to avatar pos
  1235. CameraPosition = pos;
  1236. }
  1237. if (ForceFly)
  1238. {
  1239. Flying = true;
  1240. }
  1241. else if (FlyDisabled)
  1242. {
  1243. Flying = false;
  1244. }
  1245. }
  1246. //m_log.DebugFormat("[MakeRootAgent] position and physical: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1247. m_scene.SwapRootAgentCount(false);
  1248. // If we don't reset the movement flag here, an avatar that crosses to a neighbouring sim and returns will
  1249. // stall on the border crossing since the existing child agent will still have the last movement
  1250. // recorded, which stops the input from being processed.
  1251. MovementFlag = 0;
  1252. m_scene.EventManager.TriggerOnMakeRootAgent(this);
  1253. //m_log.DebugFormat("[MakeRootAgent] TriggerOnMakeRootAgent and done: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1254. return true;
  1255. }
  1256. private void RestartAttachmentScripts()
  1257. {
  1258. // We need to restart scripts here so that they receive the correct changed events (CHANGED_TELEPORT
  1259. // and CHANGED_REGION) when the attachments have been rezzed in the new region. This cannot currently
  1260. // be done in AttachmentsModule.CopyAttachments(AgentData ad, IScenePresence sp) itself since we are
  1261. // not transporting the required data.
  1262. //
  1263. // We must take a copy of the attachments list here (rather than locking) to avoid a deadlock where a script in one of
  1264. // the attachments may start processing an event (which locks ScriptInstance.m_Script) that then calls a method here
  1265. // which needs to lock m_attachments. ResumeScripts() needs to take a ScriptInstance.m_Script lock to try to unset the Suspend status.
  1266. //
  1267. // FIXME: In theory, this deadlock should not arise since scripts should not be processing events until ResumeScripts().
  1268. // But XEngine starts all scripts unsuspended. Starting them suspended will not currently work because script rezzing
  1269. // is placed in an asynchronous queue in XEngine and so the ResumeScripts() call will almost certainly execute before the
  1270. // script is rezzed. This means the ResumeScripts() does absolutely nothing when using XEngine.
  1271. List<SceneObjectGroup> attachments = GetAttachments();
  1272. m_log.DebugFormat(
  1273. "[SCENE PRESENCE]: Restarting scripts in {0} attachments for {1} in {2}", attachments.Count, Name, Scene.Name);
  1274. // Resume scripts
  1275. foreach (SceneObjectGroup sog in attachments)
  1276. {
  1277. sog.ScheduleGroupForFullUpdate();
  1278. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1279. sog.ResumeScripts();
  1280. }
  1281. }
  1282. private static bool IsRealLogin(TeleportFlags teleportFlags)
  1283. {
  1284. return ((teleportFlags & TeleportFlags.ViaLogin) != 0) && ((teleportFlags & TeleportFlags.ViaHGLogin) == 0);
  1285. }
  1286. /// <summary>
  1287. /// Force viewers to show the avatar's current name.
  1288. /// </summary>
  1289. /// <remarks>
  1290. /// The avatar name that is shown above the avatar in the viewers is sent in ObjectUpdate packets,
  1291. /// and they get the name from the ScenePresence. Unfortunately, viewers have a bug (as of April 2014)
  1292. /// where they ignore changes to the avatar name. However, tey don't ignore changes to the avatar's
  1293. /// Group Title. So the following trick makes viewers update the avatar's name by briefly changing
  1294. /// the group title (to "(Loading)"), and then restoring it.
  1295. /// </remarks>
  1296. /*
  1297. public void ForceViewersUpdateName()
  1298. {
  1299. m_log.DebugFormat("[SCENE PRESENCE]: Forcing viewers to update the avatar name for " + Name);
  1300. UseFakeGroupTitle = true;
  1301. Util.FireAndForget(o =>
  1302. {
  1303. // Viewers only update the avatar name when idle. Therefore, we must wait long
  1304. // enough for the viewer to show the fake name that we had set above, and only
  1305. // then switch back to the true name. This delay was chosen because it has a high
  1306. // chance of succeeding (we don't want to choose a value that's too low).
  1307. Thread.Sleep(5000);
  1308. UseFakeGroupTitle = false;
  1309. SendAvatarDataToAllClients(false);
  1310. }, null, "Scenepresence.ForceViewersUpdateName");
  1311. }
  1312. */
  1313. public int GetStateSource()
  1314. {
  1315. /*
  1316. AgentCircuitData aCircuit = m_scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  1317. if (aCircuit != null && (aCircuit.teleportFlags != (uint)TeleportFlags.Default))
  1318. {
  1319. // This will get your attention
  1320. //m_log.Error("[XXX] Triggering CHANGED_TELEPORT");
  1321. return 5; // StateSource.Teleporting
  1322. }
  1323. return 2; // StateSource.PrimCrossing
  1324. */
  1325. return m_teleportFlags == TeleportFlags.Default ? 2 : 5;
  1326. }
  1327. /// <summary>
  1328. /// This turns a root agent into a child agent
  1329. /// </summary>
  1330. /// <remarks>
  1331. /// when an agent departs this region for a neighbor, this gets called.
  1332. ///
  1333. /// It doesn't get called for a teleport. Reason being, an agent that
  1334. /// teleports out may not end up anywhere near this region
  1335. /// </remarks>
  1336. public void MakeChildAgent(ulong newRegionHandle)
  1337. {
  1338. m_updateAgentReceivedAfterTransferEvent.Reset();
  1339. haveGroupInformation = false;
  1340. gotCrossUpdate = false;
  1341. crossingFlags = 0;
  1342. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  1343. RegionHandle = newRegionHandle;
  1344. m_log.DebugFormat("[SCENE PRESENCE]: Making {0} a child agent in {1} from root region {2}",
  1345. Name, Scene.RegionInfo.RegionName, newRegionHandle);
  1346. // Reset the m_originRegionID as it has dual use as a flag to signal that the UpdateAgent() call orignating
  1347. // from the source simulator has completed on a V2 teleport.
  1348. lock (m_originRegionIDAccessLock)
  1349. m_originRegionID = UUID.Zero;
  1350. // Reset these so that teleporting in and walking out isn't seen
  1351. // as teleporting back
  1352. TeleportFlags = TeleportFlags.Default;
  1353. MovementFlag = 0;
  1354. // It looks like Animator is set to null somewhere, and MakeChild
  1355. // is called after that. Probably in aborted teleports.
  1356. if (Animator == null)
  1357. Animator = new ScenePresenceAnimator(this);
  1358. else
  1359. Animator.ResetAnimations();
  1360. // m_log.DebugFormat(
  1361. // "[SCENE PRESENCE]: Downgrading root agent {0}, {1} to a child agent in {2}",
  1362. // Name, UUID, m_scene.RegionInfo.RegionName);
  1363. // Don't zero out the velocity since this can cause problems when an avatar is making a region crossing,
  1364. // depending on the exact timing. This shouldn't matter anyway since child agent positions are not updated.
  1365. //Velocity = new Vector3(0, 0, 0);
  1366. IsChildAgent = true;
  1367. m_scene.SwapRootAgentCount(true);
  1368. RemoveFromPhysicalScene();
  1369. ParentID = 0; // Child agents can't be sitting
  1370. // we dont have land information for child
  1371. m_previusParcelHide = false;
  1372. m_previusParcelUUID = UUID.Zero;
  1373. m_currentParcelHide = false;
  1374. m_currentParcelUUID = UUID.Zero;
  1375. // FIXME: Set RegionHandle to the region handle of the scene this agent is moving into
  1376. CollisionPlane = Vector4.UnitW;
  1377. m_scene.EventManager.TriggerOnMakeChildAgent(this);
  1378. }
  1379. /// <summary>
  1380. /// Removes physics plugin scene representation of this agent if it exists.
  1381. /// </summary>
  1382. public void RemoveFromPhysicalScene()
  1383. {
  1384. if (PhysicsActor != null)
  1385. {
  1386. // PhysicsActor.OnRequestTerseUpdate -= SendTerseUpdateToAllClients;
  1387. PhysicsActor.OnOutOfBounds -= OutOfBoundsCall;
  1388. PhysicsActor.OnCollisionUpdate -= PhysicsCollisionUpdate;
  1389. PhysicsActor.UnSubscribeEvents();
  1390. m_scene.PhysicsScene.RemoveAvatar(PhysicsActor);
  1391. PhysicsActor = null;
  1392. }
  1393. // else
  1394. // {
  1395. // m_log.ErrorFormat(
  1396. // "[SCENE PRESENCE]: Attempt to remove physics actor for {0} on {1} but this scene presence has no physics actor",
  1397. // Name, Scene.RegionInfo.RegionName);
  1398. // }
  1399. }
  1400. /// <summary>
  1401. /// Do not call this directly. Call Scene.RequestTeleportLocation() instead.
  1402. /// </summary>
  1403. /// <param name="pos"></param>
  1404. public void Teleport(Vector3 pos)
  1405. {
  1406. TeleportWithMomentum(pos, Vector3.Zero);
  1407. }
  1408. public void TeleportWithMomentum(Vector3 pos, Vector3? v)
  1409. {
  1410. if(!CheckLocalTPLandingPoint(ref pos))
  1411. return;
  1412. if (ParentID != (uint)0)
  1413. StandUp();
  1414. bool isFlying = Flying;
  1415. Vector3 vel = Velocity;
  1416. RemoveFromPhysicalScene();
  1417. AbsolutePosition = pos;
  1418. AddToPhysicalScene(isFlying);
  1419. if (PhysicsActor != null)
  1420. {
  1421. if (v.HasValue)
  1422. PhysicsActor.SetMomentum((Vector3)v);
  1423. else
  1424. PhysicsActor.SetMomentum(vel);
  1425. }
  1426. SendTerseUpdateToAllClients();
  1427. }
  1428. public void TeleportOnEject(Vector3 pos)
  1429. {
  1430. if (ParentID != (uint)0)
  1431. StandUp();
  1432. bool isFlying = Flying;
  1433. RemoveFromPhysicalScene();
  1434. AbsolutePosition = pos;
  1435. AddToPhysicalScene(isFlying);
  1436. SendTerseUpdateToAllClients();
  1437. }
  1438. public void avnLocalTeleport(Vector3 newpos, Vector3? newvel, bool rotateToVelXY)
  1439. {
  1440. if(!CheckLocalTPLandingPoint(ref newpos))
  1441. return;
  1442. AbsolutePosition = newpos;
  1443. if (newvel.HasValue)
  1444. {
  1445. if ((Vector3)newvel == Vector3.Zero)
  1446. {
  1447. if (PhysicsActor != null)
  1448. PhysicsActor.SetMomentum(Vector3.Zero);
  1449. m_velocity = Vector3.Zero;
  1450. }
  1451. else
  1452. {
  1453. if (PhysicsActor != null)
  1454. PhysicsActor.SetMomentum((Vector3)newvel);
  1455. m_velocity = (Vector3)newvel;
  1456. if (rotateToVelXY)
  1457. {
  1458. Vector3 lookAt = (Vector3)newvel;
  1459. lookAt.Z = 0;
  1460. lookAt.Normalize();
  1461. ControllingClient.SendLocalTeleport(newpos, lookAt, (uint)TeleportFlags.ViaLocation);
  1462. return;
  1463. }
  1464. }
  1465. }
  1466. SendTerseUpdateToAllClients();
  1467. }
  1468. public void StopFlying()
  1469. {
  1470. if (IsInTransit)
  1471. return;
  1472. Vector3 pos = AbsolutePosition;
  1473. if (Appearance.AvatarHeight != 127.0f)
  1474. pos += new Vector3(0f, 0f, (Appearance.AvatarHeight / 6f));
  1475. else
  1476. pos += new Vector3(0f, 0f, (1.56f / 6f));
  1477. AbsolutePosition = pos;
  1478. // attach a suitable collision plane regardless of the actual situation to force the LLClient to land.
  1479. // Collision plane below the avatar's position a 6th of the avatar's height is suitable.
  1480. // Mind you, that this method doesn't get called if the avatar's velocity magnitude is greater then a
  1481. // certain amount.. because the LLClient wouldn't land in that situation anyway.
  1482. // why are we still testing for this really old height value default???
  1483. if (Appearance.AvatarHeight != 127.0f)
  1484. CollisionPlane = new Vector4(0, 0, 0, pos.Z - Appearance.AvatarHeight / 6f);
  1485. else
  1486. CollisionPlane = new Vector4(0, 0, 0, pos.Z - (1.56f / 6f));
  1487. SendAgentTerseUpdate(this);
  1488. }
  1489. /// <summary>
  1490. /// Applies a roll accumulator to the avatar's angular velocity for the avatar fly roll effect.
  1491. /// </summary>
  1492. /// <param name="amount">Postive or negative roll amount in radians</param>
  1493. private void ApplyFlyingRoll(float amount, bool PressingUp, bool PressingDown)
  1494. {
  1495. float rollAmount = Util.Clamp(m_AngularVelocity.Z + amount, -FLY_ROLL_MAX_RADIANS, FLY_ROLL_MAX_RADIANS);
  1496. m_AngularVelocity.Z = rollAmount;
  1497. // APPLY EXTRA consideration for flying up and flying down during this time.
  1498. // if we're turning left
  1499. if (amount > 0)
  1500. {
  1501. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1502. // Automatically adds noise
  1503. if (PressingUp)
  1504. {
  1505. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS - 0.04f)
  1506. m_AngularVelocity.Z -= 0.9f;
  1507. }
  1508. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1509. if (PressingDown)
  1510. {
  1511. if (m_AngularVelocity.Z >= FLY_ROLL_MAX_RADIANS && m_AngularVelocity.Z < FLY_ROLL_MAX_RADIANS + 0.6f)
  1512. m_AngularVelocity.Z += 0.6f;
  1513. }
  1514. }
  1515. else // we're turning right.
  1516. {
  1517. // If we're at the max roll and pressing up, we want to swing BACK a bit
  1518. // Automatically adds noise
  1519. if (PressingUp)
  1520. {
  1521. if (m_AngularVelocity.Z <= (-FLY_ROLL_MAX_RADIANS))
  1522. m_AngularVelocity.Z += 0.6f;
  1523. }
  1524. // If we're at the max roll and pressing down, we want to swing MORE a bit
  1525. if (PressingDown)
  1526. {
  1527. if (m_AngularVelocity.Z >= -FLY_ROLL_MAX_RADIANS - 0.6f)
  1528. m_AngularVelocity.Z -= 0.6f;
  1529. }
  1530. }
  1531. }
  1532. /// <summary>
  1533. /// incrementally sets roll amount to zero
  1534. /// </summary>
  1535. /// <param name="amount">Positive roll amount in radians</param>
  1536. /// <returns></returns>
  1537. private float CalculateFlyingRollResetToZero(float amount)
  1538. {
  1539. const float rollMinRadians = 0f;
  1540. if (m_AngularVelocity.Z > 0)
  1541. {
  1542. float leftOverToMin = m_AngularVelocity.Z - rollMinRadians;
  1543. if (amount > leftOverToMin)
  1544. return -leftOverToMin;
  1545. else
  1546. return -amount;
  1547. }
  1548. else
  1549. {
  1550. float leftOverToMin = -m_AngularVelocity.Z - rollMinRadians;
  1551. if (amount > leftOverToMin)
  1552. return leftOverToMin;
  1553. else
  1554. return amount;
  1555. }
  1556. }
  1557. // neighbouring regions we have enabled a child agent in
  1558. // holds the seed cap for the child agent in that region
  1559. private Dictionary<ulong, string> m_knownChildRegions = new Dictionary<ulong, string>();
  1560. struct spRegionSizeInfo
  1561. {
  1562. public int sizeX;
  1563. public int sizeY;
  1564. }
  1565. private Dictionary<ulong, spRegionSizeInfo> m_knownChildRegionsSizeInfo = new Dictionary<ulong, spRegionSizeInfo>();
  1566. public void AddNeighbourRegion(GridRegion region, string capsPath)
  1567. {
  1568. lock (m_knownChildRegions)
  1569. {
  1570. ulong regionHandle = region.RegionHandle;
  1571. m_knownChildRegions.Add(regionHandle,capsPath);
  1572. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1573. sizeInfo.sizeX = region.RegionSizeX;
  1574. sizeInfo.sizeY = region.RegionSizeY;
  1575. m_knownChildRegionsSizeInfo[regionHandle] = sizeInfo;
  1576. }
  1577. }
  1578. public void AddNeighbourRegionSizeInfo(GridRegion region)
  1579. {
  1580. lock (m_knownChildRegions)
  1581. {
  1582. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1583. sizeInfo.sizeX = region.RegionSizeX;
  1584. sizeInfo.sizeY = region.RegionSizeY;
  1585. ulong regionHandle = region.RegionHandle;
  1586. if (!m_knownChildRegionsSizeInfo.ContainsKey(regionHandle))
  1587. {
  1588. m_knownChildRegionsSizeInfo.Add(regionHandle, sizeInfo);
  1589. }
  1590. else
  1591. m_knownChildRegionsSizeInfo[regionHandle] = sizeInfo;
  1592. }
  1593. }
  1594. public void SetNeighbourRegionSizeInfo(List<GridRegion> regionsList)
  1595. {
  1596. lock (m_knownChildRegions)
  1597. {
  1598. m_knownChildRegionsSizeInfo.Clear();
  1599. foreach (GridRegion region in regionsList)
  1600. {
  1601. spRegionSizeInfo sizeInfo = new spRegionSizeInfo();
  1602. sizeInfo.sizeX = region.RegionSizeX;
  1603. sizeInfo.sizeY = region.RegionSizeY;
  1604. ulong regionHandle = region.RegionHandle;
  1605. m_knownChildRegionsSizeInfo.Add(regionHandle, sizeInfo);
  1606. }
  1607. }
  1608. }
  1609. public void RemoveNeighbourRegion(ulong regionHandle)
  1610. {
  1611. lock (m_knownChildRegions)
  1612. {
  1613. // Checking ContainsKey is redundant as Remove works either way and returns a bool
  1614. // This is here to allow the Debug output to be conditional on removal
  1615. //if (m_knownChildRegions.ContainsKey(regionHandle))
  1616. // m_log.DebugFormat(" !!! removing known region {0} in {1}. Count = {2}", regionHandle, Scene.RegionInfo.RegionName, m_knownChildRegions.Count);
  1617. m_knownChildRegions.Remove(regionHandle);
  1618. m_knownChildRegionsSizeInfo.Remove(regionHandle);
  1619. }
  1620. }
  1621. public bool knowsNeighbourRegion(ulong regionHandle)
  1622. {
  1623. lock (m_knownChildRegions)
  1624. return m_knownChildRegions.ContainsKey(regionHandle);
  1625. }
  1626. public void DropOldNeighbours(List<ulong> oldRegions)
  1627. {
  1628. foreach (ulong handle in oldRegions)
  1629. {
  1630. RemoveNeighbourRegion(handle);
  1631. Scene.CapsModule.DropChildSeed(UUID, handle);
  1632. }
  1633. }
  1634. public void DropThisRootRegionFromNeighbours()
  1635. {
  1636. ulong handle = m_scene.RegionInfo.RegionHandle;
  1637. RemoveNeighbourRegion(handle);
  1638. Scene.CapsModule.DropChildSeed(UUID, handle);
  1639. }
  1640. public Dictionary<ulong, string> KnownRegions
  1641. {
  1642. get
  1643. {
  1644. lock (m_knownChildRegions)
  1645. return new Dictionary<ulong, string>(m_knownChildRegions);
  1646. }
  1647. set
  1648. {
  1649. // Replacing the reference is atomic but we still need to lock on
  1650. // the original dictionary object which may be in use elsewhere
  1651. lock (m_knownChildRegions)
  1652. m_knownChildRegions = value;
  1653. }
  1654. }
  1655. public List<ulong> KnownRegionHandles
  1656. {
  1657. get
  1658. {
  1659. lock (m_knownChildRegions)
  1660. return new List<ulong>(m_knownChildRegions.Keys);
  1661. }
  1662. }
  1663. public int KnownRegionCount
  1664. {
  1665. get
  1666. {
  1667. lock (m_knownChildRegions)
  1668. return m_knownChildRegions.Count;
  1669. }
  1670. }
  1671. #endregion
  1672. #region Event Handlers
  1673. /// <summary>
  1674. /// Sets avatar height in the physics plugin
  1675. /// </summary>
  1676. /// <param name="height">New height of avatar</param>
  1677. public void SetHeight(float height)
  1678. {
  1679. if (PhysicsActor != null && !IsChildAgent)
  1680. PhysicsActor.Size = new Vector3(0.45f, 0.6f, height);
  1681. }
  1682. public void SetSize(Vector3 size, float feetoffset)
  1683. {
  1684. if (PhysicsActor != null && !IsChildAgent)
  1685. PhysicsActor.setAvatarSize(size, feetoffset);
  1686. }
  1687. private bool WaitForUpdateAgent(IClientAPI client)
  1688. {
  1689. // Before the source region executes UpdateAgent
  1690. // (which triggers Scene.IncomingUpdateChildAgent(AgentData cAgentData) here in the destination,
  1691. // m_originRegionID is UUID.Zero; after, it's non-Zero. The CompleteMovement sequence initiated from the
  1692. // viewer (in turn triggered by the source region sending it a TeleportFinish event) waits until it's non-zero
  1693. try
  1694. {
  1695. if(m_updateAgentReceivedAfterTransferEvent.WaitOne(10000))
  1696. {
  1697. UUID originID = UUID.Zero;
  1698. lock (m_originRegionIDAccessLock)
  1699. originID = m_originRegionID;
  1700. if (originID.Equals(UUID.Zero))
  1701. {
  1702. // Movement into region will fail
  1703. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} at {1} got invalid origin region id ", client.Name, Scene.Name);
  1704. return false;
  1705. }
  1706. return true;
  1707. }
  1708. else
  1709. {
  1710. m_log.WarnFormat("[SCENE PRESENCE]: Update agent {0} at {1} did not receive agent update ", client.Name, Scene.Name);
  1711. return false;
  1712. }
  1713. }
  1714. catch { }
  1715. finally
  1716. {
  1717. m_updateAgentReceivedAfterTransferEvent.Reset();
  1718. }
  1719. return false;
  1720. }
  1721. public void RotateToLookAt(Vector3 lookAt)
  1722. {
  1723. if(ParentID == 0)
  1724. {
  1725. float n = lookAt.X * lookAt.X + lookAt.Y * lookAt.Y;
  1726. if(n < 0.0001f)
  1727. {
  1728. Rotation = Quaternion.Identity;
  1729. return;
  1730. }
  1731. n = lookAt.X/(float)Math.Sqrt(n);
  1732. float angle = (float)Math.Acos(n);
  1733. angle *= 0.5f;
  1734. float s = (float)Math.Sin(angle);
  1735. if(lookAt.Y < 0)
  1736. s = -s;
  1737. Rotation = new Quaternion(
  1738. 0f,
  1739. 0f,
  1740. s,
  1741. (float)Math.Cos(angle)
  1742. );
  1743. }
  1744. }
  1745. /// <summary>
  1746. /// Complete Avatar's movement into the region.
  1747. /// </summary>
  1748. /// <param name="client"></param>
  1749. /// <param name="openChildAgents">
  1750. /// If true, send notification to neighbour regions to expect
  1751. /// a child agent from the client. These neighbours can be some distance away, depending right now on the
  1752. /// configuration of DefaultDrawDistance in the [Startup] section of config
  1753. /// </param>
  1754. public void CompleteMovement(IClientAPI client, bool openChildAgents)
  1755. {
  1756. int ts = Util.EnvironmentTickCount();
  1757. m_log.InfoFormat(
  1758. "[SCENE PRESENCE]: Completing movement of {0} into region {1} in position {2}",
  1759. client.Name, Scene.Name, AbsolutePosition);
  1760. m_inTransit = true;
  1761. try
  1762. {
  1763. // Make sure it's not a login agent. We don't want to wait for updates during login
  1764. if (!IsNPC && !IsRealLogin(m_teleportFlags))
  1765. {
  1766. // Let's wait until UpdateAgent (called by departing region) is done
  1767. if (!WaitForUpdateAgent(client))
  1768. // The sending region never sent the UpdateAgent data, we have to refuse
  1769. return;
  1770. }
  1771. //m_log.DebugFormat("[CompleteMovement] WaitForUpdateAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1772. bool flying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  1773. Vector3 look = Lookat;
  1774. look.Z = 0f;
  1775. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01))
  1776. {
  1777. look = Velocity;
  1778. look.Normalize();
  1779. if ((Math.Abs(look.X) < 0.01) && (Math.Abs(look.Y) < 0.01) )
  1780. look = new Vector3(0.99f, 0.042f, 0);
  1781. }
  1782. // Check Default Location (Also See EntityTransferModule.TeleportAgentWithinRegion)
  1783. if (AbsolutePosition.X == 128f && AbsolutePosition.Y == 128f && AbsolutePosition.Z == 22.5f)
  1784. AbsolutePosition = Scene.RegionInfo.DefaultLandingPoint;
  1785. if (!MakeRootAgent(AbsolutePosition, flying, ref look))
  1786. {
  1787. m_log.DebugFormat(
  1788. "[SCENE PRESENCE]: Aborting CompleteMovement call for {0} in {1} as they are already root",
  1789. Name, Scene.Name);
  1790. return;
  1791. }
  1792. //m_log.DebugFormat("[CompleteMovement] MakeRootAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1793. if(!haveGroupInformation && !IsChildAgent && !IsNPC)
  1794. {
  1795. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  1796. if (gm != null)
  1797. Grouptitle = gm.GetGroupTitle(m_uuid);
  1798. //m_log.DebugFormat("[CompleteMovement] Missing Grouptitle: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1799. InventoryFolderBase cof = m_scene.InventoryService.GetFolderForType(client.AgentId, (FolderType)46);
  1800. if (cof == null)
  1801. COF = UUID.Zero;
  1802. else
  1803. COF = cof.ID;
  1804. m_log.DebugFormat("[CompleteMovement]: Missing COF for {0} is {1}", client.AgentId, COF);
  1805. }
  1806. if (!string.IsNullOrEmpty(m_callbackURI))
  1807. {
  1808. // We cannot sleep here since this would hold up the inbound packet processing thread, as
  1809. // CompleteMovement() is executed synchronously. However, it might be better to delay the release
  1810. // here until we know for sure that the agent is active in this region. Sending AgentMovementComplete
  1811. // is not enough for Imprudence clients - there appears to be a small delay (<200ms, <500ms) until they regard this
  1812. // region as the current region, meaning that a close sent before then will fail the teleport.
  1813. // System.Threading.Thread.Sleep(2000);
  1814. m_log.DebugFormat(
  1815. "[SCENE PRESENCE]: Releasing {0} {1} with callback to {2}",
  1816. client.Name, client.AgentId, m_callbackURI);
  1817. UUID originID;
  1818. lock (m_originRegionIDAccessLock)
  1819. originID = m_originRegionID;
  1820. Scene.SimulationService.ReleaseAgent(originID, UUID, m_callbackURI);
  1821. m_callbackURI = null;
  1822. //m_log.DebugFormat("[CompleteMovement] ReleaseAgent: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1823. }
  1824. // else
  1825. // {
  1826. // m_log.DebugFormat(
  1827. // "[SCENE PRESENCE]: No callback provided on CompleteMovement of {0} {1} to {2}",
  1828. // client.Name, client.AgentId, m_scene.RegionInfo.RegionName);
  1829. // }
  1830. // Tell the client that we're totally ready
  1831. ControllingClient.MoveAgentIntoRegion(m_scene.RegionInfo, AbsolutePosition, look);
  1832. //m_log.DebugFormat("[CompleteMovement] MoveAgentIntoRegion: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1833. bool isHGTP = (m_teleportFlags & TeleportFlags.ViaHGLogin) != 0;
  1834. int delayctnr = Util.EnvironmentTickCount();
  1835. if (!IsChildAgent)
  1836. {
  1837. if( ParentPart != null && !IsNPC && (crossingFlags & 0x08) != 0)
  1838. {
  1839. // SceneObjectPart root = ParentPart.ParentGroup.RootPart;
  1840. // if(root.LocalId != ParentPart.LocalId)
  1841. // ControllingClient.SendEntityTerseUpdateImmediate(root);
  1842. // ControllingClient.SendEntityTerseUpdateImmediate(ParentPart);
  1843. ParentPart.ParentGroup.SendFullUpdateToClient(ControllingClient);
  1844. }
  1845. // verify baked textures and cache
  1846. bool cachedbaked = false;
  1847. if (IsNPC)
  1848. cachedbaked = true;
  1849. else
  1850. {
  1851. if (m_scene.AvatarFactory != null && !isHGTP)
  1852. cachedbaked = m_scene.AvatarFactory.ValidateBakedTextureCache(this);
  1853. // not sure we need this
  1854. if (!cachedbaked)
  1855. {
  1856. if (m_scene.AvatarFactory != null)
  1857. m_scene.AvatarFactory.QueueAppearanceSave(UUID);
  1858. }
  1859. }
  1860. //m_log.DebugFormat("[CompleteMovement] Baked check: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1861. }
  1862. if(m_teleportFlags > 0)
  1863. {
  1864. gotCrossUpdate = false; // sanity check
  1865. if(Util.EnvironmentTickCountSubtract(delayctnr)< 500)
  1866. Thread.Sleep(500); // let viewers catch us
  1867. }
  1868. if(!gotCrossUpdate)
  1869. RotateToLookAt(look);
  1870. // HG
  1871. if(isHGTP)
  1872. {
  1873. // ControllingClient.SendNameReply(m_uuid, Firstname, Lastname);
  1874. m_log.DebugFormat("[CompleteMovement] HG");
  1875. }
  1876. m_previusParcelHide = false;
  1877. m_previusParcelUUID = UUID.Zero;
  1878. m_currentParcelHide = false;
  1879. m_currentParcelUUID = UUID.Zero;
  1880. ParcelDwellTickMS = Util.GetTimeStampMS();
  1881. if(!IsNPC)
  1882. {
  1883. GodController.SyncViewerState();
  1884. // start sending terrain patchs
  1885. if (!gotCrossUpdate)
  1886. Scene.SendLayerData(ControllingClient);
  1887. }
  1888. // send initial land overlay and parcel
  1889. ILandChannel landch = m_scene.LandChannel;
  1890. if (landch != null)
  1891. landch.sendClientInitialLandInfo(client);
  1892. if (!IsChildAgent)
  1893. {
  1894. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  1895. // send avatar object to all presences including us, so they cross it into region
  1896. // then hide if necessary
  1897. SendInitialAvatarDataToAllAgents(allpresences);
  1898. // send this look
  1899. SendAppearanceToAgent(this);
  1900. // send this animations
  1901. UUID[] animIDs = null;
  1902. int[] animseqs = null;
  1903. UUID[] animsobjs = null;
  1904. if (Animator != null)
  1905. Animator.GetArrays(out animIDs, out animseqs, out animsobjs);
  1906. bool haveAnims = (animIDs != null && animseqs != null && animsobjs != null);
  1907. if (haveAnims)
  1908. SendAnimPackToAgent(this, animIDs, animseqs, animsobjs);
  1909. // we should be able to receive updates, etc
  1910. // so release them
  1911. m_inTransit = false;
  1912. // send look and animations to others
  1913. // if not cached we send greys
  1914. // uncomented if will wait till avatar does baking
  1915. //if (cachedbaked)
  1916. {
  1917. foreach (ScenePresence p in allpresences)
  1918. {
  1919. if (p == this)
  1920. continue;
  1921. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  1922. continue;
  1923. SendAppearanceToAgentNF(p);
  1924. if (haveAnims)
  1925. SendAnimPackToAgentNF(p, animIDs, animseqs, animsobjs);
  1926. }
  1927. } // greys if
  1928. //m_log.DebugFormat("[CompleteMovement] ValidateAndSendAppearanceAndAgentData: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1929. // attachments
  1930. if (IsNPC || IsRealLogin(m_teleportFlags))
  1931. {
  1932. if (Scene.AttachmentsModule != null)
  1933. // Util.FireAndForget(
  1934. // o =>
  1935. // {
  1936. if (!IsNPC)
  1937. Scene.AttachmentsModule.RezAttachments(this);
  1938. else
  1939. Util.FireAndForget(x =>
  1940. {
  1941. Scene.AttachmentsModule.RezAttachments(this);
  1942. });
  1943. // });
  1944. }
  1945. else
  1946. {
  1947. if (m_attachments.Count > 0)
  1948. {
  1949. // m_log.DebugFormat(
  1950. // "[SCENE PRESENCE]: Restarting scripts in attachments for {0} in {1}", Name, Scene.Name);
  1951. foreach (SceneObjectGroup sog in m_attachments)
  1952. {
  1953. sog.RootPart.ParentGroup.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, GetStateSource());
  1954. sog.ResumeScripts();
  1955. }
  1956. foreach (ScenePresence p in allpresences)
  1957. {
  1958. if (p == this)
  1959. {
  1960. SendAttachmentsToAgentNF(this);
  1961. continue;
  1962. }
  1963. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  1964. continue;
  1965. SendAttachmentsToAgentNF(p);
  1966. }
  1967. }
  1968. }
  1969. //m_log.DebugFormat("[CompleteMovement] attachments: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1970. if (openChildAgents)
  1971. {
  1972. // Create child agents in neighbouring regions
  1973. IEntityTransferModule m_agentTransfer = m_scene.RequestModuleInterface<IEntityTransferModule>();
  1974. if (m_agentTransfer != null)
  1975. {
  1976. m_agentTransfer.EnableChildAgents(this);
  1977. }
  1978. }
  1979. // let updates be sent, with some delay
  1980. m_lastChildUpdatesTime = Util.EnvironmentTickCount() + 10000;
  1981. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  1982. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  1983. m_lastChildAgentUpdatePosition = AbsolutePosition;
  1984. m_childUpdatesBusy = false; // allow them
  1985. }
  1986. //m_log.DebugFormat("[CompleteMovement] openChildAgents: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1987. // send the rest of the world
  1988. if (m_teleportFlags > 0 && !IsNPC || m_currentParcelHide)
  1989. SendInitialDataToMe();
  1990. // priority uses avatar position only
  1991. // m_reprioritizationLastPosition = AbsolutePosition;
  1992. // m_reprioritizationLastDrawDistance = DrawDistance;
  1993. // m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  1994. // m_reprioritizationBusy = false;
  1995. //m_log.DebugFormat("[CompleteMovement] SendInitialDataToMe: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  1996. if (!IsChildAgent && openChildAgents)
  1997. {
  1998. IFriendsModule friendsModule = m_scene.RequestModuleInterface<IFriendsModule>();
  1999. if (friendsModule != null)
  2000. {
  2001. if(gotCrossUpdate)
  2002. friendsModule.IsNowRoot(this);
  2003. else
  2004. friendsModule.SendFriendsOnlineIfNeeded(ControllingClient);
  2005. }
  2006. //m_log.DebugFormat("[CompleteMovement] friendsModule: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2007. }
  2008. }
  2009. finally
  2010. {
  2011. haveGroupInformation = false;
  2012. gotCrossUpdate = false;
  2013. crossingFlags = 0;
  2014. m_inTransit = false;
  2015. }
  2016. m_scene.EventManager.OnRegionHeartbeatEnd += RegionHeartbeatEnd;
  2017. m_log.DebugFormat("[CompleteMovement] end: {0}ms", Util.EnvironmentTickCountSubtract(ts));
  2018. }
  2019. /// <summary>
  2020. /// Callback for the Camera view block check. Gets called with the results of the camera view block test
  2021. /// hitYN is true when there's something in the way.
  2022. /// </summary>
  2023. /// <param name="hitYN"></param>
  2024. /// <param name="collisionPoint"></param>
  2025. /// <param name="localid"></param>
  2026. /// <param name="distance"></param>
  2027. ///
  2028. private void checkCameraCollision()
  2029. {
  2030. if(m_doingCamRayCast || !m_scene.PhysicsScene.SupportsRayCast())
  2031. return;
  2032. if(m_mouseLook || ParentID != 0)
  2033. {
  2034. if (CameraConstraintActive)
  2035. {
  2036. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2037. UpdateCameraCollisionPlane(plane);
  2038. CameraConstraintActive = false;
  2039. }
  2040. return;
  2041. }
  2042. Vector3 posAdjusted = AbsolutePosition;
  2043. posAdjusted.Z += 1.0f; // viewer current camera focus point
  2044. if(posAdjusted.ApproxEquals(m_lastCameraRayCastPos, 0.2f) &&
  2045. CameraPosition.ApproxEquals(m_lastCameraRayCastCam, 0.2f))
  2046. return;
  2047. m_lastCameraRayCastCam = CameraPosition;
  2048. m_lastCameraRayCastPos = posAdjusted;
  2049. Vector3 tocam = CameraPosition - posAdjusted;
  2050. float distTocamlen = tocam.LengthSquared();
  2051. if (distTocamlen > 0.01f && distTocamlen < 400)
  2052. {
  2053. distTocamlen = (float)Math.Sqrt(distTocamlen);
  2054. tocam *= (1.0f / distTocamlen);
  2055. m_doingCamRayCast = true;
  2056. m_scene.PhysicsScene.RaycastWorld(posAdjusted, tocam, distTocamlen + 1.0f, RayCastCameraCallback);
  2057. return;
  2058. }
  2059. if (CameraConstraintActive)
  2060. {
  2061. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -10000f); // not right...
  2062. UpdateCameraCollisionPlane(plane);
  2063. CameraConstraintActive = false;
  2064. }
  2065. }
  2066. private void UpdateCameraCollisionPlane(Vector4 plane)
  2067. {
  2068. if (m_lastCameraCollisionPlane != plane)
  2069. {
  2070. m_lastCameraCollisionPlane = plane;
  2071. ControllingClient.SendCameraConstraint(plane);
  2072. }
  2073. }
  2074. public void RayCastCameraCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 pNormal)
  2075. {
  2076. if (hitYN && localid != LocalId)
  2077. {
  2078. if (localid != 0)
  2079. {
  2080. SceneObjectPart part = m_scene.GetSceneObjectPart(localid);
  2081. if (part != null && !part.VolumeDetectActive)
  2082. {
  2083. CameraConstraintActive = true;
  2084. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2085. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2086. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2087. pNormal.Normalize();
  2088. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2089. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2090. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2091. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2092. Vector3.Dot(collisionPoint, pNormal));
  2093. UpdateCameraCollisionPlane(plane);
  2094. }
  2095. }
  2096. else
  2097. {
  2098. CameraConstraintActive = true;
  2099. pNormal.X = (float) Math.Round(pNormal.X, 2);
  2100. pNormal.Y = (float) Math.Round(pNormal.Y, 2);
  2101. pNormal.Z = (float) Math.Round(pNormal.Z, 2);
  2102. pNormal.Normalize();
  2103. collisionPoint.X = (float) Math.Round(collisionPoint.X, 1);
  2104. collisionPoint.Y = (float) Math.Round(collisionPoint.Y, 1);
  2105. collisionPoint.Z = (float) Math.Round(collisionPoint.Z, 1);
  2106. Vector4 plane = new Vector4(pNormal.X, pNormal.Y, pNormal.Z,
  2107. Vector3.Dot(collisionPoint, pNormal));
  2108. UpdateCameraCollisionPlane(plane);
  2109. }
  2110. }
  2111. else if(CameraConstraintActive)
  2112. {
  2113. Vector4 plane = new Vector4(0.9f, 0.0f, 0.361f, -9000f); // not right...
  2114. UpdateCameraCollisionPlane(plane);
  2115. CameraConstraintActive = false;
  2116. }
  2117. m_doingCamRayCast = false;
  2118. }
  2119. /// <summary>
  2120. /// This is the event handler for client movement. If a client is moving, this event is triggering.
  2121. /// </summary>
  2122. public void HandleAgentUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2123. {
  2124. // m_log.DebugFormat(
  2125. // "[SCENE PRESENCE]: In {0} received agent update from {1}, flags {2}",
  2126. // Scene.Name, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2127. if (IsChildAgent)
  2128. {
  2129. // m_log.DebugFormat("DEBUG: HandleAgentUpdate: child agent in {0}", Scene.Name);
  2130. return;
  2131. }
  2132. if (IsInTransit)
  2133. return;
  2134. #region Sanity Checking
  2135. // This is irritating. Really.
  2136. if (!AbsolutePosition.IsFinite())
  2137. {
  2138. bool isphysical = PhysicsActor != null;
  2139. if(isphysical)
  2140. RemoveFromPhysicalScene();
  2141. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999902");
  2142. m_pos = m_LastFinitePos;
  2143. if (!m_pos.IsFinite())
  2144. {
  2145. m_pos.X = 127f;
  2146. m_pos.Y = 127f;
  2147. m_pos.Z = 127f;
  2148. m_log.Error("[AVATAR]: NonFinite Avatar position detected... Reset Position. Mantis this please. Error #9999903");
  2149. }
  2150. if(isphysical)
  2151. AddToPhysicalScene(false);
  2152. }
  2153. else
  2154. {
  2155. m_LastFinitePos = m_pos;
  2156. }
  2157. #endregion Sanity Checking
  2158. #region Inputs
  2159. AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2160. // The Agent's Draw distance setting
  2161. // When we get to the point of re-computing neighbors everytime this
  2162. // changes, then start using the agent's drawdistance rather than the
  2163. // region's draw distance.
  2164. DrawDistance = agentData.Far;
  2165. m_mouseLook = (flags & AgentManager.ControlFlags.AGENT_CONTROL_MOUSELOOK) != 0;
  2166. // FIXME: This does not work as intended because the viewer only sends the lbutton down when the button
  2167. // is first pressed, not whilst it is held down. If this is required in the future then need to look
  2168. // for an AGENT_CONTROL_LBUTTON_UP event and make sure to handle cases where an initial DOWN is not
  2169. // received (e.g. on holding LMB down on the avatar in a viewer).
  2170. m_leftButtonDown = (flags & AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0;
  2171. #endregion Inputs
  2172. // // Make anims work for client side autopilot
  2173. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0)
  2174. // m_updateCount = UPDATE_COUNT;
  2175. //
  2176. // // Make turning in place work
  2177. // if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0 ||
  2178. // (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2179. // m_updateCount = UPDATE_COUNT;
  2180. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STAND_UP) != 0)
  2181. {
  2182. StandUp();
  2183. }
  2184. // Raycast from the avatar's head to the camera to see if there's anything blocking the view
  2185. // this exclude checks may not be complete
  2186. if(agentData.NeedsCameraCollision) // condition parentID may be wrong
  2187. checkCameraCollision();
  2188. uint flagsForScripts = (uint)flags;
  2189. flags = RemoveIgnoredControls(flags, IgnoredControls);
  2190. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_SIT_ON_GROUND) != 0)
  2191. HandleAgentSitOnGround();
  2192. // In the future, these values might need to go global.
  2193. // Here's where you get them.
  2194. m_AgentControlFlags = flags;
  2195. m_headrotation = agentData.HeadRotation;
  2196. byte oldState = State;
  2197. State = agentData.State;
  2198. // We need to send this back to the client in order to stop the edit beams
  2199. if ((oldState & (uint)AgentState.Editing) != 0 && State == (uint)AgentState.None)
  2200. SendAgentTerseUpdate(this);
  2201. PhysicsActor actor = PhysicsActor;
  2202. // This will be the case if the agent is sitting on the groudn or on an object.
  2203. if (actor == null)
  2204. {
  2205. SendControlsToScripts(flagsForScripts);
  2206. return;
  2207. }
  2208. if (AllowMovement && !SitGround)
  2209. {
  2210. // m_log.DebugFormat("[SCENE PRESENCE]: Initial body rotation {0} for {1}", agentData.BodyRotation, Name);
  2211. bool update_rotation = false;
  2212. if (agentData.BodyRotation != Rotation)
  2213. {
  2214. Rotation = agentData.BodyRotation;
  2215. update_rotation = true;
  2216. }
  2217. bool update_movementflag = false;
  2218. bool mvToTarget = m_movingToTarget;
  2219. if (agentData.UseClientAgentPosition)
  2220. {
  2221. m_movingToTarget = (agentData.ClientAgentPosition - AbsolutePosition).LengthSquared() > 0.04f;
  2222. m_moveToPositionTarget = agentData.ClientAgentPosition;
  2223. m_moveToSpeed = -1f;
  2224. }
  2225. int i = 0;
  2226. bool DCFlagKeyPressed = false;
  2227. Vector3 agent_control_v3 = Vector3.Zero;
  2228. bool newFlying = false;
  2229. if (ForceFly)
  2230. newFlying = true;
  2231. else if (FlyDisabled)
  2232. newFlying = false;
  2233. else if(mvToTarget)
  2234. newFlying = actor.Flying;
  2235. else
  2236. newFlying = ((flags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  2237. if (actor.Flying != newFlying)
  2238. {
  2239. // Note: ScenePresence.Flying is actually fetched from the physical actor
  2240. // so setting PhysActor.Flying here also sets the ScenePresence's value.
  2241. actor.Flying = newFlying;
  2242. update_movementflag = true;
  2243. }
  2244. if (ParentID == 0)
  2245. {
  2246. bool bAllowUpdateMoveToPosition = false;
  2247. Vector3[] dirVectors;
  2248. // use camera up angle when in mouselook and not flying or when holding the left mouse button down and not flying
  2249. // this prevents 'jumping' in inappropriate situations.
  2250. // if (!Flying && (m_mouseLook || m_leftButtonDown))
  2251. // dirVectors = GetWalkDirectionVectors();
  2252. // else
  2253. dirVectors = Dir_Vectors;
  2254. // A DIR_CONTROL_FLAG occurs when the user is trying to move in a particular direction.
  2255. foreach (Dir_ControlFlags DCF in DIR_CONTROL_FLAGS)
  2256. {
  2257. if (((uint)flags & (uint)DCF) != 0)
  2258. {
  2259. DCFlagKeyPressed = true;
  2260. try
  2261. {
  2262. agent_control_v3 += Dir_Vectors[i];
  2263. //m_log.DebugFormat("[Motion]: {0}, {1}",i, dirVectors[i]);
  2264. }
  2265. catch (IndexOutOfRangeException)
  2266. {
  2267. // Why did I get this?
  2268. }
  2269. if (((MovementFlag & (uint)DCF) == 0))
  2270. {
  2271. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with {1}", Name, DCF);
  2272. MovementFlag |= (uint)DCF;
  2273. update_movementflag = true;
  2274. }
  2275. }
  2276. else
  2277. {
  2278. if ((MovementFlag & (uint)DCF) != 0)
  2279. {
  2280. //m_log.DebugFormat("[SCENE PRESENCE]: Updating MovementFlag for {0} with lack of {1}", Name, DCF);
  2281. MovementFlag &= (uint)~DCF;
  2282. update_movementflag = true;
  2283. /*
  2284. if ((DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD_NUDGE || DCF == Dir_ControlFlags.DIR_CONTROL_FLAG_BACKWARD_NUDGE)
  2285. && ((MovementFlag & (byte)nudgehack) == nudgehack))
  2286. {
  2287. m_log.Debug("Removed Hack flag");
  2288. }
  2289. */
  2290. }
  2291. else
  2292. {
  2293. bAllowUpdateMoveToPosition = true;
  2294. }
  2295. }
  2296. i++;
  2297. }
  2298. // Detect AGENT_CONTROL_STOP state changes
  2299. if (AgentControlStopActive != ((flags & AgentManager.ControlFlags.AGENT_CONTROL_STOP) != 0))
  2300. {
  2301. AgentControlStopActive = !AgentControlStopActive;
  2302. update_movementflag = true;
  2303. }
  2304. if (m_movingToTarget)
  2305. {
  2306. // If the user has pressed a key then we want to cancel any move to target.
  2307. if (DCFlagKeyPressed)
  2308. {
  2309. ResetMoveToTarget();
  2310. update_movementflag = true;
  2311. }
  2312. else if (bAllowUpdateMoveToPosition)
  2313. {
  2314. // The UseClientAgentPosition is set if parcel ban is forcing the avatar to move to a
  2315. // certain position. It's only check for tolerance on returning to that position is 0.2
  2316. // rather than 1, at which point it removes its force target.
  2317. if (HandleMoveToTargetUpdate(agentData.UseClientAgentPosition ? 0.2f : 1f, ref agent_control_v3))
  2318. update_movementflag = true;
  2319. }
  2320. }
  2321. }
  2322. // Cause the avatar to stop flying if it's colliding
  2323. // with something with the down arrow pressed.
  2324. // Only do this if we're flying
  2325. if (Flying && !ForceFly)
  2326. {
  2327. // Need to stop in mid air if user holds down AGENT_CONTROL_STOP
  2328. // if (AgentControlStopActive)
  2329. // {
  2330. // agent_control_v3 = Vector3.Zero;
  2331. // }
  2332. // else
  2333. {
  2334. // Landing detection code
  2335. // Are the landing controls requirements filled?
  2336. bool controlland = (((flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0) ||
  2337. ((flags & AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0));
  2338. //m_log.Debug("[CONTROL]: " +flags);
  2339. // Applies a satisfying roll effect to the avatar when flying.
  2340. if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_LEFT) != 0 && (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  2341. {
  2342. ApplyFlyingRoll(
  2343. FLY_ROLL_RADIANS_PER_UPDATE,
  2344. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2345. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2346. }
  2347. else if ((flags & AgentManager.ControlFlags.AGENT_CONTROL_TURN_RIGHT) != 0 &&
  2348. (flags & AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  2349. {
  2350. ApplyFlyingRoll(
  2351. -FLY_ROLL_RADIANS_PER_UPDATE,
  2352. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0,
  2353. (flags & AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0);
  2354. }
  2355. else
  2356. {
  2357. if (m_AngularVelocity.Z != 0)
  2358. m_AngularVelocity.Z += CalculateFlyingRollResetToZero(FLY_ROLL_RESET_RADIANS_PER_UPDATE);
  2359. }
  2360. /*
  2361. if (Flying && IsColliding && controlland)
  2362. {
  2363. // nesting this check because LengthSquared() is expensive and we don't
  2364. // want to do it every step when flying.
  2365. if ((Velocity.LengthSquared() <= LAND_VELOCITYMAG_MAX))
  2366. StopFlying();
  2367. }
  2368. */
  2369. }
  2370. }
  2371. else if (IsColliding && agent_control_v3.Z < 0f)
  2372. agent_control_v3.Z = 0;
  2373. // else if(AgentControlStopActive %% Velocity.Z <0.01f)
  2374. // m_log.DebugFormat("[SCENE PRESENCE]: MovementFlag {0} for {1}", MovementFlag, Name);
  2375. // If the agent update does move the avatar, then calculate the force ready for the velocity update,
  2376. // which occurs later in the main scene loop
  2377. // We also need to update if the user rotates their avatar whilst it is slow walking/running (if they
  2378. // held down AGENT_CONTROL_STOP whilst normal walking/running). However, we do not want to update
  2379. // if the user rotated whilst holding down AGENT_CONTROL_STOP when already still (which locks the
  2380. // avatar location in place).
  2381. if (update_movementflag
  2382. || (update_rotation && DCFlagKeyPressed && (!AgentControlStopActive || MovementFlag != 0)))
  2383. {
  2384. if (AgentControlStopActive)
  2385. {
  2386. // if (MovementFlag == 0 && Animator.Falling)
  2387. if (MovementFlag == 0 && Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling)
  2388. {
  2389. AddNewMovement(agent_control_v3, AgentControlStopSlowVel, true);
  2390. }
  2391. else
  2392. AddNewMovement(agent_control_v3, AgentControlStopSlowVel);
  2393. }
  2394. else
  2395. {
  2396. if(m_movingToTarget ||
  2397. (Animator.currentControlState != ScenePresenceAnimator.motionControlStates.flying &&
  2398. Animator.currentControlState != ScenePresenceAnimator.motionControlStates.onsurface)
  2399. )
  2400. AddNewMovement(agent_control_v3);
  2401. else
  2402. {
  2403. if (MovementFlag != 0)
  2404. AddNewMovement(agent_control_v3);
  2405. else
  2406. m_delayedStop = Util.GetTimeStampMS() + 200.0;
  2407. }
  2408. }
  2409. }
  2410. /*
  2411. if (update_movementflag && ParentID == 0 && m_delayedStop < 0)
  2412. {
  2413. // m_log.DebugFormat("[SCENE PRESENCE]: Updating movement animations for {0}", Name);
  2414. Animator.UpdateMovementAnimations();
  2415. }
  2416. */
  2417. SendControlsToScripts(flagsForScripts);
  2418. }
  2419. // We need to send this back to the client in order to see the edit beams
  2420. if ((State & (uint)AgentState.Editing) != 0)
  2421. SendAgentTerseUpdate(this);
  2422. // m_scene.EventManager.TriggerOnClientMovement(this);
  2423. }
  2424. private void HandleAgentFOV(IClientAPI remoteClient, float _fov)
  2425. {
  2426. m_FOV = _fov;
  2427. }
  2428. /// <summary>
  2429. /// This is the event handler for client cameras. If a client is moving, or moving the camera, this event is triggering.
  2430. /// </summary>
  2431. private void HandleAgentCamerasUpdate(IClientAPI remoteClient, AgentUpdateArgs agentData)
  2432. {
  2433. //m_log.DebugFormat(
  2434. // "[SCENE PRESENCE]: In {0} received agent camera update from {1}, flags {2}",
  2435. // Scene.RegionInfo.RegionName, remoteClient.Name, (AgentManager.ControlFlags)agentData.ControlFlags);
  2436. if (IsChildAgent)
  2437. return;
  2438. if(IsInTransit)
  2439. return;
  2440. // AgentManager.ControlFlags flags = (AgentManager.ControlFlags)agentData.ControlFlags;
  2441. // Camera location in world. We'll need to raytrace
  2442. // from this location from time to time.
  2443. CameraPosition = agentData.CameraCenter;
  2444. // Use these three vectors to figure out what the agent is looking at
  2445. // Convert it to a Matrix and/or Quaternion
  2446. // this may need lock
  2447. CameraAtAxis = agentData.CameraAtAxis;
  2448. CameraLeftAxis = agentData.CameraLeftAxis;
  2449. CameraUpAxis = agentData.CameraUpAxis;
  2450. DrawDistance = agentData.Far;
  2451. CameraAtAxis.Normalize();
  2452. CameraLeftAxis.Normalize();
  2453. CameraUpAxis.Normalize();
  2454. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  2455. CameraRotation = camRot;
  2456. if(agentData.NeedsCameraCollision)
  2457. checkCameraCollision();
  2458. TriggerScenePresenceUpdated();
  2459. }
  2460. /// <summary>
  2461. /// Calculate an update to move the presence to the set target.
  2462. /// </summary>
  2463. /// <remarks>
  2464. /// This doesn't actually perform the movement. Instead, it adds its vector to agent_control_v3.
  2465. /// </remarks>
  2466. /// <param value="agent_control_v3">Cumulative agent movement that this method will update.</param>
  2467. /// <returns>True if movement has been updated in some way. False otherwise.</returns>
  2468. public bool HandleMoveToTargetUpdate(float tolerance, ref Vector3 agent_control_v3)
  2469. {
  2470. // m_log.DebugFormat("[SCENE PRESENCE]: Called HandleMoveToTargetUpdate() for {0}", Name);
  2471. bool updated = false;
  2472. Vector3 LocalVectorToTarget3D = m_moveToPositionTarget - AbsolutePosition;
  2473. // m_log.DebugFormat(
  2474. // "[SCENE PRESENCE]: bAllowUpdateMoveToPosition {0}, m_moveToPositionInProgress {1}, m_autopilotMoving {2}",
  2475. // allowUpdate, m_moveToPositionInProgress, m_autopilotMoving);
  2476. float distanceToTarget;
  2477. if(Flying && !LandAtTarget)
  2478. {
  2479. distanceToTarget = LocalVectorToTarget3D.Length();
  2480. }
  2481. else
  2482. {
  2483. distanceToTarget = (float)Math.Sqrt(LocalVectorToTarget3D.X * LocalVectorToTarget3D.X +
  2484. LocalVectorToTarget3D.Y * LocalVectorToTarget3D.Y);
  2485. }
  2486. // m_log.DebugFormat(
  2487. // "[SCENE PRESENCE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  2488. // Name, AbsolutePosition, MoveToPositionTarget, distanceToTarget);
  2489. // Check the error term of the current position in relation to the target position
  2490. if (distanceToTarget <= tolerance)
  2491. {
  2492. // We are close enough to the target
  2493. Velocity = Vector3.Zero;
  2494. AbsolutePosition = m_moveToPositionTarget;
  2495. if (Flying)
  2496. {
  2497. if (LandAtTarget)
  2498. Flying = false;
  2499. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  2500. // the target if flying.
  2501. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  2502. // least be able to set collision status once, rather than 5 times to give it enough
  2503. // weighting so that that PhysicsActor thinks it really is colliding.
  2504. for (int i = 0; i < 5; i++)
  2505. IsColliding = true;
  2506. }
  2507. ResetMoveToTarget();
  2508. return false;
  2509. }
  2510. if(m_moveToSpeed > 0 && distanceToTarget <= m_moveToSpeed * Scene.FrameTime)
  2511. m_moveToSpeed = distanceToTarget / Scene.FrameTime;
  2512. try
  2513. {
  2514. // move avatar in 3D towards target, in avatar coordinate frame.
  2515. // This movement vector gets added to the velocity through AddNewMovement().
  2516. // Theoretically we might need a more complex PID approach here if other
  2517. // unknown forces are acting on the avatar and we need to adaptively respond
  2518. // to such forces, but the following simple approach seems to works fine.
  2519. float angle = 0.5f * (float)Math.Atan2(LocalVectorToTarget3D.Y, LocalVectorToTarget3D.X);
  2520. Quaternion rot = new Quaternion(0,0, (float)Math.Sin(angle),(float)Math.Cos(angle));
  2521. Rotation = rot;
  2522. LocalVectorToTarget3D = LocalVectorToTarget3D * Quaternion.Inverse(rot); // change to avatar coords
  2523. LocalVectorToTarget3D.Normalize();
  2524. // update avatar movement flags. the avatar coordinate system is as follows:
  2525. //
  2526. // +X (forward)
  2527. //
  2528. // ^
  2529. // |
  2530. // |
  2531. // |
  2532. // |
  2533. // (left) +Y <--------o--------> -Y
  2534. // avatar
  2535. // |
  2536. // |
  2537. // |
  2538. // |
  2539. // v
  2540. // -X
  2541. //
  2542. // based on the above avatar coordinate system, classify the movement into
  2543. // one of left/right/back/forward.
  2544. const uint noMovFlagsMask = (uint)(~(Dir_ControlFlags.DIR_CONTROL_FLAG_BACK |
  2545. Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD | Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT |
  2546. Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT | Dir_ControlFlags.DIR_CONTROL_FLAG_UP |
  2547. Dir_ControlFlags.DIR_CONTROL_FLAG_DOWN));
  2548. MovementFlag &= noMovFlagsMask;
  2549. uint tmpAgentControlFlags = (uint)m_AgentControlFlags;
  2550. tmpAgentControlFlags &= noMovFlagsMask;
  2551. if (LocalVectorToTarget3D.X < 0) //MoveBack
  2552. {
  2553. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2554. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_BACK;
  2555. updated = true;
  2556. }
  2557. else if (LocalVectorToTarget3D.X > 0) //Move Forward
  2558. {
  2559. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2560. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_FORWARD;
  2561. updated = true;
  2562. }
  2563. if (LocalVectorToTarget3D.Y > 0) //MoveLeft
  2564. {
  2565. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2566. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_LEFT;
  2567. updated = true;
  2568. }
  2569. else if (LocalVectorToTarget3D.Y < 0) //MoveRight
  2570. {
  2571. MovementFlag |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2572. tmpAgentControlFlags |= (uint)Dir_ControlFlags.DIR_CONTROL_FLAG_RIGHT;
  2573. updated = true;
  2574. }
  2575. if (LocalVectorToTarget3D.Z > 0) //Up
  2576. updated = true;
  2577. else if (LocalVectorToTarget3D.Z < 0) //Down
  2578. updated = true;
  2579. // m_log.DebugFormat(
  2580. // "[SCENE PRESENCE]: HandleMoveToTargetUpdate adding {0} to move vector {1} for {2}",
  2581. // LocalVectorToTarget3D, agent_control_v3, Name);
  2582. m_AgentControlFlags = (AgentManager.ControlFlags) tmpAgentControlFlags;
  2583. if(updated)
  2584. agent_control_v3 += LocalVectorToTarget3D;
  2585. }
  2586. catch (Exception e)
  2587. {
  2588. //Avoid system crash, can be slower but...
  2589. m_log.DebugFormat("Crash! {0}", e.ToString());
  2590. }
  2591. return updated;
  2592. // AddNewMovement(agent_control_v3);
  2593. }
  2594. public void MoveToTargetHandle(Vector3 pos, bool noFly, bool landAtTarget)
  2595. {
  2596. MoveToTarget(pos, noFly, landAtTarget);
  2597. }
  2598. /// <summary>
  2599. /// Move to the given target over time.
  2600. /// </summary>
  2601. /// <param name="pos"></param>
  2602. /// <param name="noFly">
  2603. /// If true, then don't allow the avatar to fly to the target, even if it's up in the air.
  2604. /// This is to allow movement to targets that are known to be on an elevated platform with a continuous path
  2605. /// from start to finish.
  2606. /// </param>
  2607. /// <param name="landAtTarget">
  2608. /// If true and the avatar starts flying during the move then land at the target.
  2609. /// </param>
  2610. public void MoveToTarget(Vector3 pos, bool noFly, bool landAtTarget, float tau = -1f)
  2611. {
  2612. m_delayedStop = -1;
  2613. if (SitGround)
  2614. StandUp();
  2615. // m_log.DebugFormat(
  2616. // "[SCENE PRESENCE]: Avatar {0} received request to move to position {1} in {2}",
  2617. // Name, pos, m_scene.RegionInfo.RegionName);
  2618. // Allow move to another sub-region within a megaregion
  2619. Vector2 regionSize;
  2620. regionSize = new Vector2(m_scene.RegionInfo.RegionSizeX, m_scene.RegionInfo.RegionSizeY);
  2621. if (pos.X < 0 || pos.X >= regionSize.X
  2622. || pos.Y < 0 || pos.Y >= regionSize.Y
  2623. || pos.Z < 0)
  2624. return;
  2625. float terrainHeight;
  2626. Scene targetScene = m_scene;
  2627. terrainHeight = m_scene.GetGroundHeight(pos.X, pos.Y);
  2628. // dont try to land underground
  2629. terrainHeight += Appearance.AvatarHeight * 0.5f + 0.2f;
  2630. if(terrainHeight > pos.Z)
  2631. pos.Z = terrainHeight;
  2632. // m_log.DebugFormat(
  2633. // "[SCENE PRESENCE]: Avatar {0} set move to target {1} (terrain height {2}) in {3}",
  2634. // Name, pos, terrainHeight, m_scene.RegionInfo.RegionName);
  2635. terrainHeight += Appearance.AvatarHeight; // so 1.5 * AvatarHeight above ground at target
  2636. bool shouldfly = Flying;
  2637. if (noFly)
  2638. shouldfly = false;
  2639. else if (pos.Z > terrainHeight || Flying)
  2640. shouldfly = true;
  2641. Vector3 localVectorToTarget3D = pos - AbsolutePosition;
  2642. // m_log.DebugFormat("[SCENE PRESENCE]: Local vector to target is {0},[1}", localVectorToTarget3D.X,localVectorToTarget3D.Y);
  2643. m_movingToTarget = true;
  2644. LandAtTarget = landAtTarget;
  2645. m_moveToPositionTarget = pos;
  2646. if(tau > 0)
  2647. {
  2648. if(tau < Scene.FrameTime)
  2649. tau = Scene.FrameTime;
  2650. m_moveToSpeed = localVectorToTarget3D.Length() / tau;
  2651. if(m_moveToSpeed < 0.5f) //to tune
  2652. m_moveToSpeed = 0.5f;
  2653. else if(m_moveToSpeed > 50f)
  2654. m_moveToSpeed = 50f;
  2655. SetAlwaysRun = false;
  2656. }
  2657. else
  2658. m_moveToSpeed = 4.096f * m_speedModifier;
  2659. Flying = shouldfly;
  2660. Vector3 control = Vector3.Zero;
  2661. if(HandleMoveToTargetUpdate(1f, ref control))
  2662. AddNewMovement(control);
  2663. }
  2664. /// <summary>
  2665. /// Reset the move to target.
  2666. /// </summary>
  2667. public void ResetMoveToTarget()
  2668. {
  2669. // m_log.DebugFormat("[SCENE PRESENCE]: Resetting move to target for {0}", Name);
  2670. m_movingToTarget = false;
  2671. m_moveToSpeed = -1f;
  2672. // MoveToPositionTarget = Vector3.Zero;
  2673. // lock(m_forceToApplyLock)
  2674. // m_forceToApplyValid = false; // cancel possible last action
  2675. // We need to reset the control flag as the ScenePresenceAnimator uses this to determine the correct
  2676. // resting animation (e.g. hover or stand). NPCs don't have a client that will quickly reset this flag.
  2677. // However, the line is here rather than in the NPC module since it also appears necessary to stop a
  2678. // viewer that uses "go here" from juddering on all subsequent avatar movements.
  2679. AgentControlFlags = (uint)AgentManager.ControlFlags.NONE;
  2680. }
  2681. /// <summary>
  2682. /// Perform the logic necessary to stand the avatar up. This method also executes
  2683. /// the stand animation.
  2684. /// </summary>
  2685. public void StandUp()
  2686. {
  2687. // m_log.DebugFormat("[SCENE PRESENCE]: StandUp() for {0}", Name);
  2688. bool satOnObject = IsSatOnObject;
  2689. SceneObjectPart part = ParentPart;
  2690. SitGround = false;
  2691. if (satOnObject)
  2692. {
  2693. PrevSitOffset = m_pos; // Save sit offset
  2694. UnRegisterSeatControls(part.ParentGroup.UUID);
  2695. TaskInventoryDictionary taskIDict = part.TaskInventory;
  2696. if (taskIDict != null)
  2697. {
  2698. lock (taskIDict)
  2699. {
  2700. foreach (UUID taskID in taskIDict.Keys)
  2701. {
  2702. UnRegisterControlEventsToScript(LocalId, taskID);
  2703. taskIDict[taskID].PermsMask &= ~(
  2704. 2048 | //PERMISSION_CONTROL_CAMERA
  2705. 4); // PERMISSION_TAKE_CONTROLS
  2706. }
  2707. }
  2708. }
  2709. // part.ParentGroup.DeleteAvatar(UUID);
  2710. Quaternion standRotation = part.ParentGroup.RootPart.RotationOffset;
  2711. Vector3 sitPartWorldPosition = part.ParentGroup.AbsolutePosition + m_pos * standRotation;
  2712. ControllingClient.SendClearFollowCamProperties(part.ParentUUID);
  2713. ParentID = 0;
  2714. ParentPart = null;
  2715. if (part.SitTargetAvatar == UUID)
  2716. standRotation = standRotation * part.SitTargetOrientation;
  2717. else
  2718. standRotation = standRotation * m_bodyRot;
  2719. m_bodyRot = standRotation;
  2720. Quaternion standRotationZ = new Quaternion(0,0,standRotation.Z,standRotation.W);
  2721. float t = standRotationZ.W * standRotationZ.W + standRotationZ.Z * standRotationZ.Z;
  2722. if (t > 0)
  2723. {
  2724. t = 1.0f / (float)Math.Sqrt(t);
  2725. standRotationZ.W *= t;
  2726. standRotationZ.Z *= t;
  2727. }
  2728. else
  2729. {
  2730. standRotationZ.W = 1.0f;
  2731. standRotationZ.Z = 0f;
  2732. }
  2733. Vector3 adjustmentForSitPose = new Vector3(0.75f, 0, m_sitAvatarHeight + .3f) * standRotationZ;
  2734. Vector3 standPos = sitPartWorldPosition + adjustmentForSitPose;
  2735. m_pos = standPos;
  2736. }
  2737. // We need to wait until we have calculated proper stand positions before sitting up the physical
  2738. // avatar to avoid race conditions.
  2739. if (PhysicsActor == null)
  2740. AddToPhysicalScene(false);
  2741. if (satOnObject)
  2742. {
  2743. m_requestedSitTargetID = 0;
  2744. part.RemoveSittingAvatar(this);
  2745. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2746. SendAvatarDataToAllAgents();
  2747. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2748. }
  2749. // reset to default sitAnimation
  2750. sitAnimation = "SIT";
  2751. // Animator.TrySetMovementAnimation("STAND");
  2752. Animator.SetMovementAnimations("STAND");
  2753. TriggerScenePresenceUpdated();
  2754. }
  2755. private SceneObjectPart FindNextAvailableSitTarget(UUID targetID)
  2756. {
  2757. SceneObjectPart targetPart = m_scene.GetSceneObjectPart(targetID);
  2758. if (targetPart == null)
  2759. return null;
  2760. // If the primitive the player clicked on has a sit target and that sit target is not full, that sit target is used.
  2761. // 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.
  2762. // Get our own copy of the part array, and sort into the order we want to test
  2763. SceneObjectPart[] partArray = targetPart.ParentGroup.Parts;
  2764. Array.Sort(partArray, delegate(SceneObjectPart p1, SceneObjectPart p2)
  2765. {
  2766. // we want the originally selected part first, then the rest in link order -- so make the selected part link num (-1)
  2767. int linkNum1 = p1==targetPart ? -1 : p1.LinkNum;
  2768. int linkNum2 = p2==targetPart ? -1 : p2.LinkNum;
  2769. return linkNum1 - linkNum2;
  2770. }
  2771. );
  2772. //look for prims with explicit sit targets that are available
  2773. foreach (SceneObjectPart part in partArray)
  2774. {
  2775. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2776. {
  2777. //switch the target to this prim
  2778. return part;
  2779. }
  2780. }
  2781. // no explicit sit target found - use original target
  2782. return targetPart;
  2783. }
  2784. private void SendSitResponse(UUID targetID, Vector3 offset, Quaternion sitOrientation)
  2785. {
  2786. Vector3 cameraEyeOffset = Vector3.Zero;
  2787. Vector3 cameraAtOffset = Vector3.Zero;
  2788. bool forceMouselook = false;
  2789. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2790. if (part == null)
  2791. return;
  2792. if (PhysicsActor != null)
  2793. m_sitAvatarHeight = PhysicsActor.Size.Z * 0.5f;
  2794. bool canSit = false;
  2795. if (part.IsSitTargetSet && part.SitTargetAvatar == UUID.Zero)
  2796. {
  2797. offset = part.SitTargetPosition;
  2798. sitOrientation = part.SitTargetOrientation;
  2799. canSit = true;
  2800. }
  2801. else
  2802. {
  2803. if (PhysicsSit(part,offset)) // physics engine
  2804. return;
  2805. Vector3 pos = part.AbsolutePosition + offset;
  2806. if (Util.GetDistanceTo(AbsolutePosition, pos) <= 10)
  2807. {
  2808. AbsolutePosition = pos + new Vector3(0.0f, 0.0f, m_sitAvatarHeight);
  2809. canSit = true;
  2810. }
  2811. }
  2812. if (canSit)
  2813. {
  2814. if (PhysicsActor != null)
  2815. {
  2816. // We can remove the physicsActor until they stand up.
  2817. RemoveFromPhysicalScene();
  2818. }
  2819. if (m_movingToTarget)
  2820. ResetMoveToTarget();
  2821. Velocity = Vector3.Zero;
  2822. m_AngularVelocity = Vector3.Zero;
  2823. part.AddSittingAvatar(this);
  2824. cameraAtOffset = part.GetCameraAtOffset();
  2825. cameraEyeOffset = part.GetCameraEyeOffset();
  2826. forceMouselook = part.GetForceMouselook();
  2827. if (!part.IsRoot)
  2828. {
  2829. sitOrientation = part.RotationOffset * sitOrientation;
  2830. offset = offset * part.RotationOffset;
  2831. offset += part.OffsetPosition;
  2832. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2833. {
  2834. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  2835. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2836. }
  2837. else
  2838. {
  2839. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2840. cameraAtOffset += part.OffsetPosition;
  2841. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2842. cameraEyeOffset += part.OffsetPosition;
  2843. }
  2844. }
  2845. ControllingClient.SendSitResponse(
  2846. part.ParentGroup.UUID, offset, sitOrientation, false, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2847. m_requestedSitTargetUUID = part.UUID;
  2848. HandleAgentSit(ControllingClient, UUID);
  2849. // Moved here to avoid a race with default sit anim
  2850. // The script event needs to be raised after the default sit anim is set.
  2851. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2852. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2853. }
  2854. }
  2855. public void HandleAgentRequestSit(IClientAPI remoteClient, UUID agentID, UUID targetID, Vector3 offset)
  2856. {
  2857. if (IsChildAgent)
  2858. return;
  2859. if (ParentID != 0)
  2860. {
  2861. if (ParentPart.UUID == targetID)
  2862. return; // already sitting here, ignore
  2863. StandUp();
  2864. }
  2865. SceneObjectPart part = FindNextAvailableSitTarget(targetID);
  2866. if (part != null)
  2867. {
  2868. m_requestedSitTargetID = part.LocalId;
  2869. m_requestedSitTargetUUID = part.UUID;
  2870. }
  2871. else
  2872. {
  2873. m_log.Warn("Sit requested on unknown object: " + targetID.ToString());
  2874. }
  2875. SendSitResponse(targetID, offset, Quaternion.Identity);
  2876. }
  2877. // returns false if does not suport so older sit can be tried
  2878. public bool PhysicsSit(SceneObjectPart part, Vector3 offset)
  2879. {
  2880. if (part == null || part.ParentGroup.IsAttachment)
  2881. return true;
  2882. if ( m_scene.PhysicsScene == null)
  2883. return false;
  2884. if (part.PhysActor == null)
  2885. {
  2886. // none physcis shape
  2887. if (part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  2888. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2889. else
  2890. { // non physical phantom TODO
  2891. // ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2892. return false;
  2893. }
  2894. return true;
  2895. }
  2896. if (m_scene.PhysicsScene.SitAvatar(part.PhysActor, AbsolutePosition, CameraPosition, offset, new Vector3(0.35f, 0, 0.65f), PhysicsSitResponse) != 0)
  2897. {
  2898. return true;
  2899. }
  2900. return false;
  2901. }
  2902. private bool CanEnterLandPosition(Vector3 testPos)
  2903. {
  2904. ILandObject land = m_scene.LandChannel.GetLandObject(testPos.X, testPos.Y);
  2905. if (land == null || land.LandData.Name == "NO_LAND")
  2906. return true;
  2907. return land.CanBeOnThisLand(UUID,testPos.Z);
  2908. }
  2909. // status
  2910. // < 0 ignore
  2911. // 0 bad sit spot
  2912. public void PhysicsSitResponse(int status, uint partID, Vector3 offset, Quaternion Orientation)
  2913. {
  2914. if (status < 0)
  2915. return;
  2916. if (status == 0)
  2917. {
  2918. ControllingClient.SendAlertMessage(" There is no suitable surface to sit on, try another spot.");
  2919. return;
  2920. }
  2921. SceneObjectPart part = m_scene.GetSceneObjectPart(partID);
  2922. if (part == null)
  2923. return;
  2924. Vector3 targetPos = part.GetWorldPosition() + offset * part.GetWorldRotation();
  2925. if(!CanEnterLandPosition(targetPos))
  2926. {
  2927. ControllingClient.SendAlertMessage(" Sit position on restricted land, try another spot");
  2928. return;
  2929. }
  2930. RemoveFromPhysicalScene();
  2931. if (m_movingToTarget)
  2932. ResetMoveToTarget();
  2933. Velocity = Vector3.Zero;
  2934. m_AngularVelocity = Vector3.Zero;
  2935. m_requestedSitTargetID = 0;
  2936. part.AddSittingAvatar(this);
  2937. ParentPart = part;
  2938. ParentID = part.LocalId;
  2939. Vector3 cameraAtOffset = part.GetCameraAtOffset();
  2940. Vector3 cameraEyeOffset = part.GetCameraEyeOffset();
  2941. bool forceMouselook = part.GetForceMouselook();
  2942. if (!part.IsRoot)
  2943. {
  2944. Orientation = part.RotationOffset * Orientation;
  2945. offset = offset * part.RotationOffset;
  2946. offset += part.OffsetPosition;
  2947. if (cameraAtOffset == Vector3.Zero && cameraEyeOffset == Vector3.Zero)
  2948. {
  2949. cameraAtOffset = part.ParentGroup.RootPart.GetCameraAtOffset();
  2950. cameraEyeOffset = part.ParentGroup.RootPart.GetCameraEyeOffset();
  2951. }
  2952. else
  2953. {
  2954. cameraAtOffset = cameraAtOffset * part.RotationOffset;
  2955. cameraAtOffset += part.OffsetPosition;
  2956. cameraEyeOffset = cameraEyeOffset * part.RotationOffset;
  2957. cameraEyeOffset += part.OffsetPosition;
  2958. }
  2959. }
  2960. m_bodyRot = Orientation;
  2961. m_pos = offset;
  2962. ControllingClient.SendSitResponse(
  2963. part.ParentGroup.UUID, offset, Orientation, true, cameraAtOffset, cameraEyeOffset, forceMouselook);
  2964. SendAvatarDataToAllAgents();
  2965. if (status == 3)
  2966. sitAnimation = "SIT_GROUND";
  2967. else
  2968. sitAnimation = "SIT";
  2969. Animator.SetMovementAnimations("SIT");
  2970. part.ParentGroup.TriggerScriptChangedEvent(Changed.LINK);
  2971. m_scene.EventManager.TriggerParcelPrimCountTainted(); // update select/ sat on
  2972. }
  2973. public void HandleAgentSit(IClientAPI remoteClient, UUID agentID)
  2974. {
  2975. if (IsChildAgent)
  2976. return;
  2977. SceneObjectPart part = m_scene.GetSceneObjectPart(m_requestedSitTargetID);
  2978. if (part != null)
  2979. {
  2980. if (part.ParentGroup.IsAttachment)
  2981. {
  2982. m_log.WarnFormat(
  2983. "[SCENE PRESENCE]: Avatar {0} tried to sit on part {1} from object {2} in {3} but this is an attachment for avatar id {4}",
  2984. Name, part.Name, part.ParentGroup.Name, Scene.Name, part.ParentGroup.AttachedAvatar);
  2985. return;
  2986. }
  2987. if (part.SitTargetAvatar == UUID)
  2988. {
  2989. Vector3 sitTargetPos = part.SitTargetPosition;
  2990. Quaternion sitTargetOrient = part.SitTargetOrientation;
  2991. // m_log.DebugFormat(
  2992. // "[SCENE PRESENCE]: Sitting {0} at sit target {1}, {2} on {3} {4}",
  2993. // Name, sitTargetPos, sitTargetOrient, part.Name, part.LocalId);
  2994. double x, y, z, m;
  2995. Vector3 sitOffset;
  2996. Quaternion r = sitTargetOrient;
  2997. Vector3 newPos;
  2998. if (LegacySitOffsets)
  2999. {
  3000. double m1,m2;
  3001. m1 = r.X * r.X + r.Y * r.Y;
  3002. m2 = r.Z * r.Z + r.W * r.W;
  3003. // Rotate the vector <0, 0, 1>
  3004. x = 2 * (r.X * r.Z + r.Y * r.W);
  3005. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3006. z = m2 - m1;
  3007. // Set m to be the square of the norm of r.
  3008. m = m1 + m2;
  3009. // This constant is emperically determined to be what is used in SL.
  3010. // See also http://opensimulator.org/mantis/view.php?id=7096
  3011. double offset = 0.05;
  3012. // Normally m will be ~ 1, but if someone passed a handcrafted quaternion
  3013. // to llSitTarget with values so small that squaring them is rounded off
  3014. // to zero, then m could be zero. The result of this floating point
  3015. // round off error (causing us to skip this impossible normalization)
  3016. // is only 5 cm.
  3017. if (m > 0.000001)
  3018. {
  3019. offset /= m;
  3020. }
  3021. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3022. sitOffset = up * (float)offset;
  3023. newPos = sitTargetPos - sitOffset + SIT_TARGET_ADJUSTMENT;
  3024. }
  3025. else
  3026. {
  3027. m = r.X * r.X + r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3028. if (Math.Abs(1.0 - m) > 0.000001)
  3029. {
  3030. if(m != 0)
  3031. {
  3032. m = 1.0 / Math.Sqrt(m);
  3033. r.X *= (float)m;
  3034. r.Y *= (float)m;
  3035. r.Z *= (float)m;
  3036. r.W *= (float)m;
  3037. }
  3038. else
  3039. {
  3040. r.X = 0.0f;
  3041. r.Y = 0.0f;
  3042. r.Z = 0.0f;
  3043. r.W = 1.0f;
  3044. m = 1.0f;
  3045. }
  3046. }
  3047. x = 2 * (r.X * r.Z + r.Y * r.W);
  3048. y = 2 * (-r.X * r.W + r.Y * r.Z);
  3049. z = -r.X * r.X - r.Y * r.Y + r.Z * r.Z + r.W * r.W;
  3050. Vector3 up = new Vector3((float)x, (float)y, (float)z);
  3051. sitOffset = up * Appearance.AvatarHeight * 0.02638f;
  3052. newPos = sitTargetPos + sitOffset + SIT_TARGET_ADJUSTMENT;
  3053. }
  3054. Quaternion newRot;
  3055. if (part.IsRoot)
  3056. {
  3057. newRot = sitTargetOrient;
  3058. }
  3059. else
  3060. {
  3061. newPos = newPos * part.RotationOffset;
  3062. newRot = part.RotationOffset * sitTargetOrient;
  3063. }
  3064. newPos += part.OffsetPosition;
  3065. m_pos = newPos;
  3066. Rotation = newRot;
  3067. // ParentPosition = part.AbsolutePosition;
  3068. }
  3069. else
  3070. {
  3071. // An viewer expects to specify sit positions as offsets to the root prim, even if a child prim is
  3072. // being sat upon.
  3073. m_pos -= part.GroupPosition;
  3074. // ParentPosition = part.AbsolutePosition;
  3075. // m_log.DebugFormat(
  3076. // "[SCENE PRESENCE]: Sitting {0} at position {1} ({2} + {3}) on part {4} {5} without sit target",
  3077. // Name, part.AbsolutePosition, m_pos, ParentPosition, part.Name, part.LocalId);
  3078. }
  3079. part.AddSittingAvatar(this);
  3080. ParentPart = part;
  3081. ParentID = m_requestedSitTargetID;
  3082. RemoveFromPhysicalScene();
  3083. m_AngularVelocity = Vector3.Zero;
  3084. Velocity = Vector3.Zero;
  3085. m_requestedSitTargetID = 0;
  3086. SendAvatarDataToAllAgents();
  3087. sitAnimation = "SIT";
  3088. if (!String.IsNullOrEmpty(part.SitAnimation))
  3089. {
  3090. sitAnimation = part.SitAnimation;
  3091. }
  3092. // Animator.TrySetMovementAnimation(sitAnimation);
  3093. Animator.SetMovementAnimations("SIT");
  3094. TriggerScenePresenceUpdated();
  3095. }
  3096. }
  3097. public void HandleAgentSitOnGround()
  3098. {
  3099. if (IsChildAgent)
  3100. return;
  3101. // m_updateCount = 0; // Kill animation update burst so that the SIT_G.. will stick..
  3102. sitAnimation = "SIT_GROUND_CONSTRAINED";
  3103. // Animator.TrySetMovementAnimation("SIT_GROUND_CONSTRAINED");
  3104. // TriggerScenePresenceUpdated();
  3105. SitGround = true;
  3106. RemoveFromPhysicalScene();
  3107. m_AngularVelocity = Vector3.Zero;
  3108. Velocity = Vector3.Zero;
  3109. Animator.SetMovementAnimations("SITGROUND");
  3110. TriggerScenePresenceUpdated();
  3111. }
  3112. /// <summary>
  3113. /// Event handler for the 'Always run' setting on the client
  3114. /// Tells the physics plugin to increase speed of movement.
  3115. /// </summary>
  3116. public void HandleSetAlwaysRun(IClientAPI remoteClient, bool pSetAlwaysRun)
  3117. {
  3118. SetAlwaysRun = pSetAlwaysRun;
  3119. }
  3120. public void HandleStartAnim(IClientAPI remoteClient, UUID animID)
  3121. {
  3122. Animator.AddAnimation(animID, UUID.Zero);
  3123. TriggerScenePresenceUpdated();
  3124. }
  3125. public void HandleStopAnim(IClientAPI remoteClient, UUID animID)
  3126. {
  3127. Animator.RemoveAnimation(animID, false);
  3128. TriggerScenePresenceUpdated();
  3129. }
  3130. public void avnHandleChangeAnim(UUID animID, bool addRemove,bool sendPack)
  3131. {
  3132. Animator.avnChangeAnim(animID, addRemove, sendPack);
  3133. }
  3134. /// <summary>
  3135. /// Rotate the avatar to the given rotation and apply a movement in the given relative vector
  3136. /// </summary>
  3137. /// <param name="vec">The vector in which to move. This is relative to the rotation argument</param>
  3138. /// <param name="thisAddSpeedModifier">
  3139. /// Optional additional speed modifier for this particular add. Default is 1</param>
  3140. public void AddNewMovement(Vector3 vec, float thisAddSpeedModifier = 1, bool breaking = false)
  3141. {
  3142. // m_log.DebugFormat(
  3143. // "[SCENE PRESENCE]: Adding new movement {0} with rotation {1}, thisAddSpeedModifier {2} for {3}",
  3144. // vec, Rotation, thisAddSpeedModifier, Name);
  3145. m_delayedStop = -1;
  3146. // rotate from avatar coord space to world
  3147. Quaternion rot = Rotation;
  3148. if (!Flying && PresenceType != PresenceType.Npc)
  3149. {
  3150. // force rotation to be around Z only, if not flying
  3151. // needed for mouselook
  3152. rot.X = 0;
  3153. rot.Y = 0;
  3154. }
  3155. Vector3 direc = vec * rot;
  3156. direc.Normalize();
  3157. if ((vec.Z == 0f) && !Flying)
  3158. direc.Z = 0f; // Prevent camera WASD up.
  3159. bool notmvtrgt = !m_movingToTarget || m_moveToSpeed <= 0;
  3160. // odd rescalings
  3161. if(notmvtrgt)
  3162. direc *= 4.096f * SpeedModifier * thisAddSpeedModifier;
  3163. else
  3164. direc *= m_moveToSpeed;
  3165. // m_log.DebugFormat("[SCENE PRESENCE]: Force to apply before modification was {0} for {1}", direc, Name);
  3166. if (Animator.currentControlState == ScenePresenceAnimator.motionControlStates.falling
  3167. && (PhysicsActor == null || !PhysicsActor.PIDHoverActive))
  3168. {
  3169. if (breaking)
  3170. direc.Z = -9999f; //hack to tell physics to stop on Z
  3171. else
  3172. direc = Vector3.Zero;
  3173. }
  3174. else if (Flying)
  3175. {
  3176. if (IsColliding && direc.Z < 0)
  3177. // landing situation, prevent avatar moving or it may fail to land
  3178. // animator will handle this condition and do the land
  3179. direc = Vector3.Zero;
  3180. else if(notmvtrgt)
  3181. direc *= 4.0f;
  3182. }
  3183. else if (IsColliding)
  3184. {
  3185. if (direc.Z > 2.0f && notmvtrgt) // reinforce jumps
  3186. {
  3187. direc.Z *= 2.6f;
  3188. }
  3189. else if (direc.Z < 0) // on a surface moving down (pg down) only changes animation
  3190. direc.Z = 0;
  3191. }
  3192. // m_log.DebugFormat("[SCENE PRESENCE]: Setting force to apply to {0} for {1}", direc, Name);
  3193. /*
  3194. lock(m_forceToApplyLock)
  3195. {
  3196. m_forceToApply = direc;
  3197. m_forceToApplyValid = true;
  3198. }
  3199. */
  3200. TargetVelocity = direc;
  3201. Animator.UpdateMovementAnimations();
  3202. }
  3203. #endregion
  3204. #region Overridden Methods
  3205. const float ROTATION_TOLERANCE = 0.01f;
  3206. const float VELOCITY_TOLERANCE = 0.1f;
  3207. const float LOWVELOCITYSQ = 0.1f;
  3208. const float POSITION_LARGETOLERANCE = 5f;
  3209. const float POSITION_SMALLTOLERANCE = 0.05f;
  3210. public override void Update()
  3211. {
  3212. if(IsChildAgent || IsDeleted)
  3213. return;
  3214. CheckForBorderCrossing();
  3215. if (IsInTransit || IsLoggingIn)
  3216. return;
  3217. if(m_movingToTarget)
  3218. {
  3219. m_delayedStop = -1;
  3220. Vector3 control = Vector3.Zero;
  3221. if(HandleMoveToTargetUpdate(1f, ref control))
  3222. AddNewMovement(control);
  3223. }
  3224. else if(m_delayedStop > 0)
  3225. {
  3226. if(IsSatOnObject)
  3227. m_delayedStop = -1;
  3228. else
  3229. if(Util.GetTimeStampMS() > m_delayedStop)
  3230. AddNewMovement(Vector3.Zero);
  3231. }
  3232. if (Appearance.AvatarSize != m_lastSize)
  3233. SendAvatarDataToAllAgents();
  3234. // Send terse position update if not sitting and position, velocity, or rotation
  3235. // has changed significantly from last sent update
  3236. if (!IsSatOnObject)
  3237. {
  3238. // this does need to be more complex later
  3239. Vector3 vel = Velocity;
  3240. Vector3 dpos = m_pos - m_lastPosition;
  3241. if( State != m_lastState ||
  3242. Math.Abs(vel.X - m_lastVelocity.X) > VELOCITY_TOLERANCE ||
  3243. Math.Abs(vel.Y - m_lastVelocity.Y) > VELOCITY_TOLERANCE ||
  3244. Math.Abs(vel.Z - m_lastVelocity.Z) > VELOCITY_TOLERANCE ||
  3245. Math.Abs(m_bodyRot.X - m_lastRotation.X) > ROTATION_TOLERANCE ||
  3246. Math.Abs(m_bodyRot.Y - m_lastRotation.Y) > ROTATION_TOLERANCE ||
  3247. Math.Abs(m_bodyRot.Z - m_lastRotation.Z) > ROTATION_TOLERANCE ||
  3248. (vel == Vector3.Zero && m_lastVelocity != Vector3.Zero) ||
  3249. Math.Abs(dpos.X) > POSITION_LARGETOLERANCE ||
  3250. Math.Abs(dpos.Y) > POSITION_LARGETOLERANCE ||
  3251. Math.Abs(dpos.Z) > POSITION_LARGETOLERANCE ||
  3252. ( (Math.Abs(dpos.X) > POSITION_SMALLTOLERANCE ||
  3253. Math.Abs(dpos.Y) > POSITION_SMALLTOLERANCE ||
  3254. Math.Abs(dpos.Z) > POSITION_SMALLTOLERANCE)
  3255. && vel.LengthSquared() < LOWVELOCITYSQ
  3256. ) ||
  3257. Math.Abs(CollisionPlane.X - m_lastCollisionPlane.X) > POSITION_SMALLTOLERANCE ||
  3258. Math.Abs(CollisionPlane.Y - m_lastCollisionPlane.Y) > POSITION_SMALLTOLERANCE ||
  3259. Math.Abs(CollisionPlane.W - m_lastCollisionPlane.W) > POSITION_SMALLTOLERANCE
  3260. )
  3261. {
  3262. SendTerseUpdateToAllClients();
  3263. }
  3264. }
  3265. CheckForSignificantMovement();
  3266. }
  3267. #endregion
  3268. #region Update Client(s)
  3269. public void SendUpdateToAgent(ScenePresence p)
  3270. {
  3271. IClientAPI remoteClient = p.ControllingClient;
  3272. if (remoteClient.IsActive)
  3273. {
  3274. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3275. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3276. m_scene.StatsReporter.AddAgentUpdates(1);
  3277. }
  3278. }
  3279. public void SendFullUpdateToClient(IClientAPI remoteClient)
  3280. {
  3281. if (remoteClient.IsActive)
  3282. {
  3283. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3284. remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
  3285. m_scene.StatsReporter.AddAgentUpdates(1);
  3286. }
  3287. }
  3288. // this is diferente from SendTerseUpdateToClient
  3289. // this sends bypassing entities updates
  3290. public void SendAgentTerseUpdate(ISceneEntity p)
  3291. {
  3292. ControllingClient.SendAgentTerseUpdate(p);
  3293. }
  3294. /// <summary>
  3295. /// Sends a location update to the client connected to this scenePresence
  3296. /// via entity updates
  3297. /// </summary>
  3298. /// <param name="remoteClient"></param>
  3299. public void SendTerseUpdateToClient(IClientAPI remoteClient)
  3300. {
  3301. // If the client is inactive, it's getting its updates from another
  3302. // server.
  3303. if (remoteClient.IsActive)
  3304. {
  3305. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3306. remoteClient.SendEntityUpdate(
  3307. this,
  3308. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3309. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3310. m_scene.StatsReporter.AddAgentUpdates(1);
  3311. }
  3312. }
  3313. public void SendTerseUpdateToAgent(ScenePresence p)
  3314. {
  3315. IClientAPI remoteClient = p.ControllingClient;
  3316. if (!remoteClient.IsActive)
  3317. return;
  3318. if (ParcelHideThisAvatar && p.currentParcelUUID != currentParcelUUID && !p.IsViewerUIGod)
  3319. return;
  3320. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3321. remoteClient.SendEntityUpdate(
  3322. this,
  3323. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3324. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3325. m_scene.StatsReporter.AddAgentUpdates(1);
  3326. }
  3327. public void SendTerseUpdateToAgentNF(ScenePresence p)
  3328. {
  3329. IClientAPI remoteClient = p.ControllingClient;
  3330. if (remoteClient.IsActive)
  3331. {
  3332. //m_log.DebugFormat("[SCENE PRESENCE]: " + Name + " sending TerseUpdate to " + remoteClient.Name + " : Pos={0} Rot={1} Vel={2}", m_pos, Rotation, m_velocity);
  3333. remoteClient.SendEntityUpdate(this,
  3334. PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  3335. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);
  3336. m_scene.StatsReporter.AddAgentUpdates(1);
  3337. }
  3338. }
  3339. /// <summary>
  3340. /// Send a location/velocity/accelleration update to all agents in scene
  3341. /// </summary>
  3342. public void SendTerseUpdateToAllClients()
  3343. {
  3344. m_lastState = State;
  3345. m_lastPosition = m_pos;
  3346. m_lastRotation = m_bodyRot;
  3347. m_lastVelocity = Velocity;
  3348. m_lastCollisionPlane = CollisionPlane;
  3349. m_scene.ForEachScenePresence(SendTerseUpdateToAgent);
  3350. // Update the "last" values
  3351. TriggerScenePresenceUpdated();
  3352. }
  3353. public void SendCoarseLocations(List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3354. {
  3355. SendCoarseLocationsMethod d = m_sendCoarseLocationsMethod;
  3356. if (d != null)
  3357. {
  3358. d.Invoke(m_scene.RegionInfo.originRegionID, this, coarseLocations, avatarUUIDs);
  3359. }
  3360. }
  3361. public void SetSendCoarseLocationMethod(SendCoarseLocationsMethod d)
  3362. {
  3363. if (d != null)
  3364. m_sendCoarseLocationsMethod = d;
  3365. }
  3366. public void SendCoarseLocationsDefault(UUID sceneId, ScenePresence p, List<Vector3> coarseLocations, List<UUID> avatarUUIDs)
  3367. {
  3368. ControllingClient.SendCoarseLocationUpdate(avatarUUIDs, coarseLocations);
  3369. }
  3370. public void SendInitialDataToMe()
  3371. {
  3372. // Send all scene object to the new client
  3373. SentInitialData = true;
  3374. Util.FireAndForget(delegate
  3375. {
  3376. // we created a new ScenePresence (a new child agent) in a fresh region.
  3377. // Request info about all the (root) agents in this region
  3378. // Note: This won't send data *to* other clients in that region (children don't send)
  3379. if (m_teleportFlags <= 0)
  3380. {
  3381. Scene.SendLayerData(ControllingClient);
  3382. ILandChannel landch = m_scene.LandChannel;
  3383. if (landch != null)
  3384. {
  3385. landch.sendClientInitialLandInfo(ControllingClient);
  3386. }
  3387. }
  3388. SendOtherAgentsAvatarFullToMe();
  3389. EntityBase[] entities = Scene.Entities.GetEntities();
  3390. foreach (EntityBase e in entities)
  3391. {
  3392. if (e != null && e is SceneObjectGroup && !((SceneObjectGroup)e).IsAttachment)
  3393. ((SceneObjectGroup)e).SendFullUpdateToClient(ControllingClient);
  3394. }
  3395. m_reprioritizationLastPosition = AbsolutePosition;
  3396. m_reprioritizationLastDrawDistance = DrawDistance;
  3397. m_reprioritizationLastTime = Util.EnvironmentTickCount() + 15000; // delay it
  3398. m_reprioritizationBusy = false;
  3399. });
  3400. }
  3401. /// <summary>
  3402. /// Send avatar full data appearance and animations for all other root agents to this agent, this agent
  3403. /// can be either a child or root
  3404. /// </summary>
  3405. public void SendOtherAgentsAvatarFullToMe()
  3406. {
  3407. int count = 0;
  3408. m_scene.ForEachRootScenePresence(delegate(ScenePresence p)
  3409. {
  3410. // only send information about other root agents
  3411. if (p.UUID == UUID)
  3412. return;
  3413. // get the avatar, then a kill if can't see it
  3414. p.SendInitialAvatarDataToAgent(this);
  3415. if (p.ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !IsViewerUIGod)
  3416. return;
  3417. p.SendAppearanceToAgentNF(this);
  3418. p.SendAnimPackToAgentNF(this);
  3419. p.SendAttachmentsToAgentNF(this);
  3420. count++;
  3421. });
  3422. m_scene.StatsReporter.AddAgentUpdates(count);
  3423. }
  3424. /// <summary>
  3425. /// Send this agent's avatar data to all other root and child agents in the scene
  3426. /// This agent must be root. This avatar will receive its own update.
  3427. /// </summary>
  3428. public void SendAvatarDataToAllAgents()
  3429. {
  3430. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAllAgents: {0} ({1})", Name, UUID);
  3431. // only send update from root agents to other clients; children are only "listening posts"
  3432. if (IsChildAgent)
  3433. {
  3434. m_log.WarnFormat(
  3435. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3436. Name, Scene.RegionInfo.RegionName);
  3437. return;
  3438. }
  3439. m_lastSize = Appearance.AvatarSize;
  3440. int count = 0;
  3441. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3442. {
  3443. SendAvatarDataToAgent(scenePresence);
  3444. count++;
  3445. });
  3446. m_scene.StatsReporter.AddAgentUpdates(count);
  3447. }
  3448. // sends avatar object to all clients so they cross it into region
  3449. // then sends kills to hide
  3450. public void SendInitialAvatarDataToAllAgents(List<ScenePresence> presences)
  3451. {
  3452. m_lastSize = Appearance.AvatarSize;
  3453. int count = 0;
  3454. foreach (ScenePresence p in presences)
  3455. {
  3456. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3457. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3458. // either just kill the object
  3459. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3460. // or also attachments viewer may still know about
  3461. SendKillTo(p);
  3462. count++;
  3463. }
  3464. m_scene.StatsReporter.AddAgentUpdates(count);
  3465. }
  3466. public void SendInitialAvatarDataToAgent(ScenePresence p)
  3467. {
  3468. p.ControllingClient.SendEntityFullUpdateImmediate(this);
  3469. if (p != this && ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3470. // either just kill the object
  3471. // p.ControllingClient.SendKillObject(new List<uint> {LocalId});
  3472. // or also attachments viewer may still know about
  3473. SendKillTo(p);
  3474. }
  3475. /// <summary>
  3476. /// Send avatar data to an agent.
  3477. /// </summary>
  3478. /// <param name="avatar"></param>
  3479. public void SendAvatarDataToAgent(ScenePresence avatar)
  3480. {
  3481. //m_log.DebugFormat("[SCENE PRESENCE] SendAvatarDataToAgent from {0} ({1}) to {2} ({3})", Name, UUID, avatar.Name, avatar.UUID);
  3482. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3483. return;
  3484. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3485. }
  3486. public void SendAvatarDataToAgentNF(ScenePresence avatar)
  3487. {
  3488. avatar.ControllingClient.SendEntityFullUpdateImmediate(this);
  3489. }
  3490. /// <summary>
  3491. /// Send this agent's appearance to all other root and child agents in the scene
  3492. /// This agent must be root.
  3493. /// </summary>
  3494. public void SendAppearanceToAllOtherAgents()
  3495. {
  3496. // m_log.DebugFormat("[SCENE PRESENCE] SendAppearanceToAllOtherAgents: {0} {1}", Name, UUID);
  3497. // only send update from root agents to other clients; children are only "listening posts"
  3498. if (IsChildAgent)
  3499. {
  3500. m_log.WarnFormat(
  3501. "[SCENE PRESENCE]: Attempt to send avatar data from a child agent for {0} in {1}",
  3502. Name, Scene.RegionInfo.RegionName);
  3503. return;
  3504. }
  3505. int count = 0;
  3506. m_scene.ForEachScenePresence(delegate(ScenePresence scenePresence)
  3507. {
  3508. // only send information to other root agents
  3509. if (scenePresence.UUID == UUID)
  3510. return;
  3511. SendAppearanceToAgent(scenePresence);
  3512. count++;
  3513. });
  3514. m_scene.StatsReporter.AddAgentUpdates(count);
  3515. }
  3516. public void SendAppearanceToAgent(ScenePresence avatar)
  3517. {
  3518. // m_log.DebugFormat(
  3519. // "[SCENE PRESENCE]: Sending appearance data from {0} {1} to {2} {3}", Name, m_uuid, avatar.Name, avatar.UUID);
  3520. if (ParcelHideThisAvatar && currentParcelUUID != avatar.currentParcelUUID && !avatar.IsViewerUIGod)
  3521. return;
  3522. SendAppearanceToAgentNF(avatar);
  3523. }
  3524. public void SendAppearanceToAgentNF(ScenePresence avatar)
  3525. {
  3526. avatar.ControllingClient.SendAppearance(
  3527. UUID, Appearance.VisualParams, Appearance.Texture.GetBytes());
  3528. }
  3529. public void SendAnimPackToAgent(ScenePresence p)
  3530. {
  3531. if (IsChildAgent || Animator == null)
  3532. return;
  3533. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3534. return;
  3535. Animator.SendAnimPackToClient(p.ControllingClient);
  3536. }
  3537. public void SendAnimPackToAgent(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3538. {
  3539. if (IsChildAgent)
  3540. return;
  3541. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3542. return;
  3543. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3544. }
  3545. public void SendAnimPackToAgentNF(ScenePresence p)
  3546. {
  3547. if (IsChildAgent || Animator == null)
  3548. return;
  3549. Animator.SendAnimPackToClient(p.ControllingClient);
  3550. }
  3551. public void SendAnimPackToAgentNF(ScenePresence p, UUID[] animations, int[] seqs, UUID[] objectIDs)
  3552. {
  3553. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3554. }
  3555. public void SendAnimPack(UUID[] animations, int[] seqs, UUID[] objectIDs)
  3556. {
  3557. if (IsChildAgent)
  3558. return;
  3559. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  3560. {
  3561. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  3562. return;
  3563. p.ControllingClient.SendAnimations(animations, seqs, ControllingClient.AgentId, objectIDs);
  3564. });
  3565. }
  3566. #endregion
  3567. #region Significant Movement Method
  3568. private void checkRePrioritization()
  3569. {
  3570. if(IsDeleted || !ControllingClient.IsActive)
  3571. return;
  3572. if(!SentInitialData)
  3573. {
  3574. SendInitialDataToMe();
  3575. return;
  3576. }
  3577. if(m_reprioritizationBusy)
  3578. return;
  3579. float limit = Scene.ReprioritizationDistance;
  3580. bool byDrawdistance = Scene.ObjectsCullingByDistance;
  3581. if(byDrawdistance)
  3582. {
  3583. float minregionSize = (float)Scene.RegionInfo.RegionSizeX;
  3584. if(minregionSize > (float)Scene.RegionInfo.RegionSizeY)
  3585. minregionSize = (float)Scene.RegionInfo.RegionSizeY;
  3586. minregionSize *= 0.5f;
  3587. if(DrawDistance > minregionSize && m_reprioritizationLastDrawDistance > minregionSize)
  3588. byDrawdistance = false;
  3589. else
  3590. byDrawdistance = (Math.Abs(DrawDistance - m_reprioritizationLastDrawDistance) > 0.5f * limit);
  3591. }
  3592. int tdiff = Util.EnvironmentTickCountSubtract(m_reprioritizationLastTime);
  3593. if(!byDrawdistance && tdiff < Scene.ReprioritizationInterval)
  3594. return;
  3595. // priority uses avatar position
  3596. Vector3 pos = AbsolutePosition;
  3597. Vector3 diff = pos - m_reprioritizationLastPosition;
  3598. limit *= limit;
  3599. if (!byDrawdistance && diff.LengthSquared() < limit)
  3600. return;
  3601. m_reprioritizationBusy = true;
  3602. m_reprioritizationLastPosition = pos;
  3603. m_reprioritizationLastDrawDistance = DrawDistance;
  3604. Util.FireAndForget(
  3605. o =>
  3606. {
  3607. ControllingClient.ReprioritizeUpdates();
  3608. m_reprioritizationLastTime = Util.EnvironmentTickCount();
  3609. m_reprioritizationBusy = false;
  3610. }, null, "ScenePresence.Reprioritization");
  3611. }
  3612. /// <summary>
  3613. /// This checks for a significant movement and sends a coarselocationchange update
  3614. /// </summary>
  3615. protected void CheckForSignificantMovement()
  3616. {
  3617. Vector3 pos = AbsolutePosition;
  3618. Vector3 diff = pos - posLastMove;
  3619. if (diff.LengthSquared() > MOVEMENT)
  3620. {
  3621. posLastMove = pos;
  3622. m_scene.EventManager.TriggerOnClientMovement(this);
  3623. }
  3624. diff = pos - posLastSignificantMove;
  3625. if (diff.LengthSquared() > SIGNIFICANT_MOVEMENT)
  3626. {
  3627. posLastSignificantMove = pos;
  3628. m_scene.EventManager.TriggerSignificantClientMovement(this);
  3629. }
  3630. // updates priority recalc
  3631. checkRePrioritization();
  3632. if(m_childUpdatesBusy)
  3633. return;
  3634. //possible KnownRegionHandles always contains current region and this check is not needed
  3635. int minhandles = 0;
  3636. if(KnownRegionHandles.Contains(RegionHandle))
  3637. minhandles++;
  3638. if(KnownRegionHandles.Count > minhandles)
  3639. {
  3640. int tdiff = Util.EnvironmentTickCountSubtract(m_lastChildUpdatesTime);
  3641. if(tdiff < CHILDUPDATES_TIME)
  3642. return;
  3643. bool doUpdate = false;
  3644. if(m_lastChildAgentUpdateGodLevel != GodController.ViwerUIGodLevel)
  3645. doUpdate = true;
  3646. if(!doUpdate && Math.Abs(DrawDistance - m_lastChildAgentUpdateDrawDistance) > 32.0f)
  3647. doUpdate = true;
  3648. if(!doUpdate)
  3649. {
  3650. diff = pos - m_lastChildAgentUpdatePosition;
  3651. if (diff.LengthSquared() > CHILDUPDATES_MOVEMENT)
  3652. doUpdate = true;
  3653. }
  3654. if(doUpdate)
  3655. {
  3656. m_childUpdatesBusy = true;
  3657. m_lastChildAgentUpdatePosition = pos;
  3658. m_lastChildAgentUpdateGodLevel = GodController.ViwerUIGodLevel;
  3659. m_lastChildAgentUpdateDrawDistance = DrawDistance;
  3660. // m_lastChildAgentUpdateCamPosition = CameraPosition;
  3661. AgentPosition agentpos = new AgentPosition();
  3662. agentpos.AgentID = new UUID(UUID.Guid);
  3663. agentpos.SessionID = ControllingClient.SessionId;
  3664. agentpos.Size = Appearance.AvatarSize;
  3665. agentpos.Center = CameraPosition;
  3666. agentpos.Far = DrawDistance;
  3667. agentpos.Position = AbsolutePosition;
  3668. agentpos.Velocity = Velocity;
  3669. agentpos.RegionHandle = RegionHandle;
  3670. agentpos.GodData = GodController.State();
  3671. agentpos.Throttles = ControllingClient.GetThrottlesPacked(1);
  3672. // Let's get this out of the update loop
  3673. Util.FireAndForget(
  3674. o =>
  3675. {
  3676. m_scene.SendOutChildAgentUpdates(agentpos, this);
  3677. m_lastChildUpdatesTime = Util.EnvironmentTickCount();
  3678. m_childUpdatesBusy = false;
  3679. }, null, "ScenePresence.SendOutChildAgentUpdates");
  3680. }
  3681. }
  3682. }
  3683. #endregion
  3684. #region Border Crossing Methods
  3685. /// <summary>
  3686. /// Starts the process of moving an avatar into another region if they are crossing the border.
  3687. /// </summary>
  3688. /// <remarks>
  3689. /// Also removes the avatar from the physical scene if transit has started.
  3690. /// </remarks>
  3691. protected void CheckForBorderCrossing()
  3692. {
  3693. // Check that we we are not a child
  3694. if (IsChildAgent || IsInTransit)
  3695. return;
  3696. // If we don't have a PhysActor, we can't cross anyway
  3697. // Also don't do this while sat, sitting avatars cross with the
  3698. // object they sit on. ParentUUID denoted a pending sit, don't
  3699. // interfere with it.
  3700. if (ParentID != 0 || PhysicsActor == null || ParentUUID != UUID.Zero)
  3701. return;
  3702. Vector3 pos2 = AbsolutePosition;
  3703. Vector3 vel = Velocity;
  3704. float timeStep = 0.1f;
  3705. pos2.X += vel.X * timeStep;
  3706. pos2.Y += vel.Y * timeStep;
  3707. pos2.Z += vel.Z * timeStep;
  3708. // m_log.DebugFormat(
  3709. // "[SCENE PRESENCE]: Testing border check for projected position {0} of {1} in {2}",
  3710. // pos2, Name, Scene.Name);
  3711. if (Scene.PositionIsInCurrentRegion(pos2))
  3712. return;
  3713. if (!CrossToNewRegion() && m_requestedSitTargetUUID == UUID.Zero)
  3714. {
  3715. // we don't have entity transfer module
  3716. Vector3 pos = AbsolutePosition;
  3717. vel = Velocity;
  3718. float px = pos.X;
  3719. if (px < 0)
  3720. pos.X += vel.X * 2;
  3721. else if (px > m_scene.RegionInfo.RegionSizeX)
  3722. pos.X -= vel.X * 2;
  3723. float py = pos.Y;
  3724. if (py < 0)
  3725. pos.Y += vel.Y * 2;
  3726. else if (py > m_scene.RegionInfo.RegionSizeY)
  3727. pos.Y -= vel.Y * 2;
  3728. Velocity = Vector3.Zero;
  3729. m_AngularVelocity = Vector3.Zero;
  3730. AbsolutePosition = pos;
  3731. }
  3732. }
  3733. public void CrossToNewRegionFail()
  3734. {
  3735. if (m_requestedSitTargetUUID == UUID.Zero)
  3736. {
  3737. bool isFlying = Flying;
  3738. RemoveFromPhysicalScene();
  3739. Vector3 pos = AbsolutePosition;
  3740. Vector3 vel = Velocity;
  3741. float px = pos.X;
  3742. if (px < 0)
  3743. pos.X += vel.X * 2;
  3744. else if (px > m_scene.RegionInfo.RegionSizeX)
  3745. pos.X -= vel.X * 2;
  3746. float py = pos.Y;
  3747. if (py < 0)
  3748. pos.Y += vel.Y * 2;
  3749. else if (py > m_scene.RegionInfo.RegionSizeY)
  3750. pos.Y -= vel.Y * 2;
  3751. Velocity = Vector3.Zero;
  3752. m_AngularVelocity = Vector3.Zero;
  3753. AbsolutePosition = pos;
  3754. AddToPhysicalScene(isFlying);
  3755. }
  3756. }
  3757. /// <summary>
  3758. /// Moves the agent outside the region bounds
  3759. /// Tells neighbor region that we're crossing to it
  3760. /// If the neighbor accepts, remove the agent's viewable avatar from this scene
  3761. /// set them to a child agent.
  3762. /// </summary>
  3763. protected bool CrossToNewRegion()
  3764. {
  3765. bool result = false;
  3766. // parcelRegionCross(false);
  3767. try
  3768. {
  3769. result = m_scene.CrossAgentToNewRegion(this, Flying);
  3770. }
  3771. catch
  3772. {
  3773. // result = m_scene.CrossAgentToNewRegion(this, false);
  3774. return false;
  3775. }
  3776. // if(!result)
  3777. // parcelRegionCross(true);
  3778. return result;
  3779. }
  3780. /// <summary>
  3781. /// Computes which child agents to close when the scene presence moves to another region.
  3782. /// Removes those regions from m_knownRegions.
  3783. /// </summary>
  3784. /// <param name="newRegionHandle">The new region's handle</param>
  3785. /// <param name="newRegionSizeX">The new region's size x</param>
  3786. /// <param name="newRegionSizeY">The new region's size y</param>
  3787. /// <returns></returns>
  3788. public List<ulong> GetChildAgentsToClose(ulong newRegionHandle, int newRegionSizeX, int newRegionSizeY)
  3789. {
  3790. ulong curRegionHandle = m_scene.RegionInfo.RegionHandle;
  3791. List<ulong> byebyeRegions = new List<ulong>();
  3792. if(newRegionHandle == curRegionHandle) //??
  3793. return byebyeRegions;
  3794. uint newRegionX, newRegionY;
  3795. List<ulong> knownRegions = KnownRegionHandles;
  3796. m_log.DebugFormat(
  3797. "[SCENE PRESENCE]: Closing child agents. Checking {0} regions in {1}",
  3798. knownRegions.Count, Scene.RegionInfo.RegionName);
  3799. Util.RegionHandleToRegionLoc(newRegionHandle, out newRegionX, out newRegionY);
  3800. uint x, y;
  3801. spRegionSizeInfo regInfo;
  3802. foreach (ulong handle in knownRegions)
  3803. {
  3804. if(newRegionY == 0) // HG
  3805. byebyeRegions.Add(handle);
  3806. else if(handle == curRegionHandle)
  3807. {
  3808. RegionInfo curreg = m_scene.RegionInfo;
  3809. if (Util.IsOutsideView(255, curreg.RegionLocX, newRegionX, curreg.RegionLocY, newRegionY,
  3810. (int)curreg.RegionSizeX, (int)curreg.RegionSizeX, newRegionSizeX, newRegionSizeY))
  3811. {
  3812. byebyeRegions.Add(handle);
  3813. }
  3814. }
  3815. else
  3816. {
  3817. Util.RegionHandleToRegionLoc(handle, out x, out y);
  3818. if (m_knownChildRegionsSizeInfo.TryGetValue(handle, out regInfo))
  3819. {
  3820. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  3821. // for now need to close all but first order bc RegionViewDistance it the target value not ours
  3822. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  3823. regInfo.sizeX, regInfo.sizeY, newRegionSizeX, newRegionSizeY))
  3824. {
  3825. byebyeRegions.Add(handle);
  3826. }
  3827. }
  3828. else
  3829. {
  3830. // if (Util.IsOutsideView(RegionViewDistance, x, newRegionX, y, newRegionY,
  3831. if (Util.IsOutsideView(255, x, newRegionX, y, newRegionY,
  3832. (int)Constants.RegionSize, (int)Constants.RegionSize, newRegionSizeX, newRegionSizeY))
  3833. {
  3834. byebyeRegions.Add(handle);
  3835. }
  3836. }
  3837. }
  3838. }
  3839. return byebyeRegions;
  3840. }
  3841. public void CloseChildAgents(List<ulong> byebyeRegions)
  3842. {
  3843. byebyeRegions.Remove(Scene.RegionInfo.RegionHandle);
  3844. if (byebyeRegions.Count > 0)
  3845. {
  3846. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  3847. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  3848. string auth = string.Empty;
  3849. if (acd != null)
  3850. auth = acd.SessionID.ToString();
  3851. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  3852. }
  3853. foreach (ulong handle in byebyeRegions)
  3854. {
  3855. RemoveNeighbourRegion(handle);
  3856. Scene.CapsModule.DropChildSeed(UUID, handle);
  3857. }
  3858. }
  3859. public void closeAllChildAgents()
  3860. {
  3861. List<ulong> byebyeRegions = new List<ulong>();
  3862. List<ulong> knownRegions = KnownRegionHandles;
  3863. foreach (ulong handle in knownRegions)
  3864. {
  3865. if (handle != Scene.RegionInfo.RegionHandle)
  3866. {
  3867. byebyeRegions.Add(handle);
  3868. RemoveNeighbourRegion(handle);
  3869. Scene.CapsModule.DropChildSeed(UUID, handle);
  3870. }
  3871. }
  3872. if (byebyeRegions.Count > 0)
  3873. {
  3874. m_log.Debug("[SCENE PRESENCE]: Closing " + byebyeRegions.Count + " child agents");
  3875. AgentCircuitData acd = Scene.AuthenticateHandler.GetAgentCircuitData(UUID);
  3876. string auth = string.Empty;
  3877. if (acd != null)
  3878. auth = acd.SessionID.ToString();
  3879. m_scene.SceneGridService.SendCloseChildAgentConnections(ControllingClient.AgentId, auth, byebyeRegions);
  3880. }
  3881. }
  3882. #endregion
  3883. /// <summary>
  3884. /// handle god level requests.
  3885. /// </summary>
  3886. public void GrantGodlikePowers(UUID token, bool godStatus)
  3887. {
  3888. if (IsNPC)
  3889. return;
  3890. bool wasgod = IsViewerUIGod;
  3891. GodController.RequestGodMode(godStatus);
  3892. if (wasgod != IsViewerUIGod)
  3893. parcelGodCheck(m_currentParcelUUID);
  3894. }
  3895. #region Child Agent Updates
  3896. public void UpdateChildAgent(AgentData cAgentData)
  3897. {
  3898. // m_log.Debug(" >>> ChildAgentDataUpdate <<< " + Scene.RegionInfo.RegionName);
  3899. if (!IsChildAgent)
  3900. return;
  3901. CopyFrom(cAgentData);
  3902. m_updateAgentReceivedAfterTransferEvent.Set();
  3903. }
  3904. private static Vector3 marker = new Vector3(-1f, -1f, -1f);
  3905. private void RaiseUpdateThrottles()
  3906. {
  3907. if(m_capbandwidth > 0)
  3908. return;
  3909. m_bandwidth = 4 * ControllingClient.GetAgentThrottleSilent((int)ThrottleOutPacketType.Texture);
  3910. if(m_bandwidth < 50000)
  3911. m_bandwidth = 50000;
  3912. m_bandwidthBurst = m_bandwidth / 5;
  3913. }
  3914. /// <summary>
  3915. /// This updates important decision making data about a child agent
  3916. /// The main purpose is to figure out what objects to send to a child agent that's in a neighboring region
  3917. /// </summary>
  3918. public void UpdateChildAgent(AgentPosition cAgentData, uint tRegionX, uint tRegionY, uint rRegionX, uint rRegionY)
  3919. {
  3920. if (!IsChildAgent)
  3921. return;
  3922. GodController.SetState(cAgentData.GodData);
  3923. RegionHandle = cAgentData.RegionHandle;
  3924. //m_log.Debug(" >>> ChildAgentPositionUpdate <<< " + rRegionX + "-" + rRegionY);
  3925. int shiftx = ((int)rRegionX - (int)tRegionX) * (int)Constants.RegionSize;
  3926. int shifty = ((int)rRegionY - (int)tRegionY) * (int)Constants.RegionSize;
  3927. Vector3 offset = new Vector3(shiftx, shifty, 0f);
  3928. DrawDistance = cAgentData.Far;
  3929. if (cAgentData.Position != marker) // UGH!!
  3930. m_pos = cAgentData.Position + offset;
  3931. CameraPosition = cAgentData.Center + offset;
  3932. if ((cAgentData.Throttles != null) && cAgentData.Throttles.Length > 0)
  3933. {
  3934. // some scaling factor
  3935. float x = m_pos.X;
  3936. if (x > m_scene.RegionInfo.RegionSizeX)
  3937. x -= m_scene.RegionInfo.RegionSizeX;
  3938. float y = m_pos.Y;
  3939. if (y > m_scene.RegionInfo.RegionSizeY)
  3940. y -= m_scene.RegionInfo.RegionSizeY;
  3941. x = x * x + y * y;
  3942. const float distScale = 0.4f / Constants.RegionSize / Constants.RegionSize;
  3943. float factor = 1.0f - distScale * x;
  3944. if (factor < 0.2f)
  3945. factor = 0.2f;
  3946. ControllingClient.SetChildAgentThrottle(cAgentData.Throttles,factor);
  3947. }
  3948. if(cAgentData.ChildrenCapSeeds != null && cAgentData.ChildrenCapSeeds.Count >0)
  3949. {
  3950. if (Scene.CapsModule != null)
  3951. {
  3952. Scene.CapsModule.SetChildrenSeed(UUID, cAgentData.ChildrenCapSeeds);
  3953. }
  3954. KnownRegions = cAgentData.ChildrenCapSeeds;
  3955. }
  3956. //cAgentData.AVHeight;
  3957. //m_velocity = cAgentData.Velocity;
  3958. checkRePrioritization();
  3959. }
  3960. public void CopyTo(AgentData cAgent, bool isCrossUpdate)
  3961. {
  3962. cAgent.CallbackURI = m_callbackURI;
  3963. cAgent.AgentID = UUID;
  3964. cAgent.RegionID = Scene.RegionInfo.RegionID;
  3965. cAgent.SessionID = ControllingClient.SessionId;
  3966. cAgent.Position = AbsolutePosition;
  3967. cAgent.Velocity = m_velocity;
  3968. cAgent.Center = CameraPosition;
  3969. cAgent.AtAxis = CameraAtAxis;
  3970. cAgent.LeftAxis = CameraLeftAxis;
  3971. cAgent.UpAxis = CameraUpAxis;
  3972. cAgent.Far = DrawDistance;
  3973. cAgent.GodData = GodController.State();
  3974. // Throttles
  3975. cAgent.Throttles = ControllingClient.GetThrottlesPacked(1);
  3976. cAgent.HeadRotation = m_headrotation;
  3977. cAgent.BodyRotation = Rotation;
  3978. cAgent.ControlFlags = (uint)m_AgentControlFlags;
  3979. cAgent.AlwaysRun = SetAlwaysRun;
  3980. // make clear we want the all thing
  3981. cAgent.Appearance = new AvatarAppearance(Appearance,true,true);
  3982. cAgent.ParentPart = ParentUUID;
  3983. cAgent.SitOffset = PrevSitOffset;
  3984. lock (scriptedcontrols)
  3985. {
  3986. ControllerData[] controls = new ControllerData[scriptedcontrols.Count];
  3987. int i = 0;
  3988. foreach (ScriptControllers c in scriptedcontrols.Values)
  3989. {
  3990. controls[i++] = new ControllerData(c.objectID, c.itemID, (uint)c.ignoreControls, (uint)c.eventControls);
  3991. }
  3992. cAgent.Controllers = controls;
  3993. }
  3994. // Animations
  3995. try
  3996. {
  3997. cAgent.Anims = Animator.Animations.ToArray();
  3998. }
  3999. catch { }
  4000. cAgent.DefaultAnim = Animator.Animations.DefaultAnimation;
  4001. cAgent.AnimState = Animator.Animations.ImplicitDefaultAnimation;
  4002. cAgent.MovementAnimationOverRides = Overrides.CloneAOPairs();
  4003. cAgent.MotionState = (byte)Animator.currentControlState;
  4004. if (Scene.AttachmentsModule != null)
  4005. Scene.AttachmentsModule.CopyAttachments(this, cAgent);
  4006. if(isCrossUpdate)
  4007. {
  4008. cAgent.CrossingFlags = crossingFlags;
  4009. cAgent.CrossingFlags |= 1;
  4010. cAgent.CrossExtraFlags = 0;
  4011. if((LastCommands & ScriptControlled.CONTROL_LBUTTON) != 0)
  4012. cAgent.CrossExtraFlags |= 1;
  4013. if((LastCommands & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  4014. cAgent.CrossExtraFlags |= 2;
  4015. }
  4016. else
  4017. cAgent.CrossingFlags = 0;
  4018. if(isCrossUpdate)
  4019. {
  4020. cAgent.agentCOF = COF;
  4021. cAgent.ActiveGroupID = ControllingClient.ActiveGroupId;
  4022. cAgent.ActiveGroupName = ControllingClient.ActiveGroupName;
  4023. if(Grouptitle == null)
  4024. cAgent.ActiveGroupTitle = String.Empty;
  4025. else
  4026. cAgent.ActiveGroupTitle = Grouptitle;
  4027. }
  4028. }
  4029. private void CopyFrom(AgentData cAgent)
  4030. {
  4031. m_callbackURI = cAgent.CallbackURI;
  4032. // m_log.DebugFormat(
  4033. // "[SCENE PRESENCE]: Set callback for {0} in {1} to {2} in CopyFrom()",
  4034. // Name, m_scene.RegionInfo.RegionName, m_callbackURI);
  4035. GodController.SetState(cAgent.GodData);
  4036. m_pos = cAgent.Position;
  4037. m_velocity = cAgent.Velocity;
  4038. CameraPosition = cAgent.Center;
  4039. CameraAtAxis = cAgent.AtAxis;
  4040. CameraLeftAxis = cAgent.LeftAxis;
  4041. CameraUpAxis = cAgent.UpAxis;
  4042. Quaternion camRot = Util.Axes2Rot(CameraAtAxis, CameraLeftAxis, CameraUpAxis);
  4043. CameraRotation = camRot;
  4044. ParentUUID = cAgent.ParentPart;
  4045. PrevSitOffset = cAgent.SitOffset;
  4046. // When we get to the point of re-computing neighbors everytime this
  4047. // changes, then start using the agent's drawdistance rather than the
  4048. // region's draw distance.
  4049. DrawDistance = cAgent.Far;
  4050. //DrawDistance = Scene.DefaultDrawDistance;
  4051. if (cAgent.ChildrenCapSeeds != null && cAgent.ChildrenCapSeeds.Count > 0)
  4052. {
  4053. if (Scene.CapsModule != null)
  4054. {
  4055. Scene.CapsModule.SetChildrenSeed(UUID, cAgent.ChildrenCapSeeds);
  4056. }
  4057. KnownRegions = cAgent.ChildrenCapSeeds;
  4058. }
  4059. if ((cAgent.Throttles != null) && cAgent.Throttles.Length > 0)
  4060. ControllingClient.SetChildAgentThrottle(cAgent.Throttles);
  4061. m_headrotation = cAgent.HeadRotation;
  4062. Rotation = cAgent.BodyRotation;
  4063. m_AgentControlFlags = (AgentManager.ControlFlags)cAgent.ControlFlags;
  4064. SetAlwaysRun = cAgent.AlwaysRun;
  4065. Appearance = new AvatarAppearance(cAgent.Appearance);
  4066. /*
  4067. bool isFlying = ((m_AgentControlFlags & AgentManager.ControlFlags.AGENT_CONTROL_FLY) != 0);
  4068. if (PhysicsActor != null)
  4069. {
  4070. RemoveFromPhysicalScene();
  4071. AddToPhysicalScene(isFlying);
  4072. }
  4073. */
  4074. if (Scene.AttachmentsModule != null)
  4075. Scene.AttachmentsModule.CopyAttachments(cAgent, this);
  4076. try
  4077. {
  4078. lock (scriptedcontrols)
  4079. {
  4080. if (cAgent.Controllers != null)
  4081. {
  4082. scriptedcontrols.Clear();
  4083. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4084. foreach (ControllerData c in cAgent.Controllers)
  4085. {
  4086. ScriptControllers sc = new ScriptControllers();
  4087. sc.objectID = c.ObjectID;
  4088. sc.itemID = c.ItemID;
  4089. sc.ignoreControls = (ScriptControlled)c.IgnoreControls;
  4090. sc.eventControls = (ScriptControlled)c.EventControls;
  4091. scriptedcontrols[sc.itemID] = sc;
  4092. IgnoredControls |= sc.ignoreControls; // this is not correct, aparently only last applied should count
  4093. }
  4094. }
  4095. }
  4096. }
  4097. catch { }
  4098. Animator.ResetAnimations();
  4099. Overrides.CopyAOPairsFrom(cAgent.MovementAnimationOverRides);
  4100. // FIXME: Why is this null check necessary? Where are the cases where we get a null Anims object?
  4101. if (cAgent.DefaultAnim != null)
  4102. Animator.Animations.SetDefaultAnimation(cAgent.DefaultAnim.AnimID, cAgent.DefaultAnim.SequenceNum, UUID.Zero);
  4103. if (cAgent.AnimState != null)
  4104. Animator.Animations.SetImplicitDefaultAnimation(cAgent.AnimState.AnimID, cAgent.AnimState.SequenceNum, UUID.Zero);
  4105. if (cAgent.Anims != null)
  4106. Animator.Animations.FromArray(cAgent.Anims);
  4107. if (cAgent.MotionState != 0)
  4108. Animator.currentControlState = (ScenePresenceAnimator.motionControlStates) cAgent.MotionState;
  4109. crossingFlags = cAgent.CrossingFlags;
  4110. gotCrossUpdate = (crossingFlags != 0);
  4111. if(gotCrossUpdate)
  4112. {
  4113. LastCommands &= ~(ScriptControlled.CONTROL_LBUTTON | ScriptControlled.CONTROL_ML_LBUTTON);
  4114. if((cAgent.CrossExtraFlags & 1) != 0)
  4115. LastCommands |= ScriptControlled.CONTROL_LBUTTON;
  4116. if((cAgent.CrossExtraFlags & 2) != 0)
  4117. LastCommands |= ScriptControlled.CONTROL_ML_LBUTTON;
  4118. MouseDown = (cAgent.CrossExtraFlags & 3) != 0;
  4119. }
  4120. haveGroupInformation = false;
  4121. // using this as protocol detection don't want to mess with the numbers for now
  4122. if(cAgent.ActiveGroupTitle != null)
  4123. {
  4124. haveGroupInformation = true;
  4125. COF = cAgent.agentCOF;
  4126. if(ControllingClient.IsGroupMember(cAgent.ActiveGroupID))
  4127. {
  4128. ControllingClient.ActiveGroupId = cAgent.ActiveGroupID;
  4129. ControllingClient.ActiveGroupName = cAgent.ActiveGroupName;
  4130. Grouptitle = cAgent.ActiveGroupTitle;
  4131. ControllingClient.ActiveGroupPowers =
  4132. ControllingClient.GetGroupPowers(cAgent.ActiveGroupID);
  4133. }
  4134. else
  4135. {
  4136. // we got a unknown active group so get what groups thinks about us
  4137. IGroupsModule gm = m_scene.RequestModuleInterface<IGroupsModule>();
  4138. if (gm != null)
  4139. gm.SendAgentGroupDataUpdate(ControllingClient);
  4140. }
  4141. }
  4142. lock (m_originRegionIDAccessLock)
  4143. m_originRegionID = cAgent.RegionID;
  4144. }
  4145. public bool CopyAgent(out IAgentData agent)
  4146. {
  4147. agent = new CompleteAgentData();
  4148. CopyTo((AgentData)agent, false);
  4149. return true;
  4150. }
  4151. #endregion Child Agent Updates
  4152. /// <summary>
  4153. /// Handles part of the PID controller function for moving an avatar.
  4154. /// </summary>
  4155. public void UpdateMovement()
  4156. {
  4157. /*
  4158. if (IsInTransit)
  4159. return;
  4160. lock(m_forceToApplyLock)
  4161. {
  4162. if (m_forceToApplyValid)
  4163. {
  4164. Velocity = m_forceToApply;
  4165. m_forceToApplyValid = false;
  4166. TriggerScenePresenceUpdated();
  4167. }
  4168. }
  4169. */
  4170. }
  4171. /// <summary>
  4172. /// Adds a physical representation of the avatar to the Physics plugin
  4173. /// </summary>
  4174. public void AddToPhysicalScene(bool isFlying)
  4175. {
  4176. // m_log.DebugFormat(
  4177. // "[SCENE PRESENCE]: Adding physics actor for {0}, ifFlying = {1} in {2}",
  4178. // Name, isFlying, Scene.RegionInfo.RegionName);
  4179. if (PhysicsActor != null)
  4180. {
  4181. m_log.ErrorFormat(
  4182. "[SCENE PRESENCE]: Adding physics actor for {0} to {1} but this scene presence already has a physics actor",
  4183. Name, Scene.RegionInfo.RegionName);
  4184. }
  4185. if (Appearance.AvatarHeight == 0)
  4186. // Appearance.SetHeight();
  4187. Appearance.SetSize(new Vector3(0.45f,0.6f,1.9f));
  4188. // lock(m_forceToApplyLock)
  4189. // m_forceToApplyValid = false;
  4190. PhysicsScene scene = m_scene.PhysicsScene;
  4191. Vector3 pVec = AbsolutePosition;
  4192. PhysicsActor = scene.AddAvatar(
  4193. LocalId, Firstname + "." + Lastname, pVec,
  4194. Appearance.AvatarBoxSize,Appearance.AvatarFeetOffset, isFlying);
  4195. PhysicsActor.Orientation = m_bodyRot;
  4196. //PhysicsActor.OnRequestTerseUpdate += SendTerseUpdateToAllClients;
  4197. PhysicsActor.OnCollisionUpdate += PhysicsCollisionUpdate;
  4198. PhysicsActor.OnOutOfBounds += OutOfBoundsCall; // Called for PhysicsActors when there's something wrong
  4199. PhysicsActor.SubscribeEvents(100);
  4200. PhysicsActor.LocalID = LocalId;
  4201. PhysicsActor.SetAlwaysRun = m_setAlwaysRun;
  4202. }
  4203. private void OutOfBoundsCall(Vector3 pos)
  4204. {
  4205. //bool flying = Flying;
  4206. //RemoveFromPhysicalScene();
  4207. //AddToPhysicalScene(flying);
  4208. if (ControllingClient != null)
  4209. ControllingClient.SendAgentAlertMessage("Physics is having a problem with your avatar. You may not be able to move until you relog.", true);
  4210. }
  4211. /// <summary>
  4212. /// Event called by the physics plugin to tell the avatar about a collision.
  4213. /// </summary>
  4214. /// <remarks>
  4215. /// This function is called continuously, even when there are no collisions. If the avatar is walking on the
  4216. /// ground or a prim then there will be collision information between the avatar and the surface.
  4217. ///
  4218. /// FIXME: However, we can't safely avoid calling this yet where there are no collisions without analyzing whether
  4219. /// any part of this method is relying on an every-frame call.
  4220. /// </remarks>
  4221. /// <param name="e"></param>
  4222. public void PhysicsCollisionUpdate(EventArgs e)
  4223. {
  4224. if (IsChildAgent)
  4225. return;
  4226. if(IsInTransit)
  4227. return;
  4228. //if ((Math.Abs(Velocity.X) > 0.1e-9f) || (Math.Abs(Velocity.Y) > 0.1e-9f))
  4229. // The Physics Scene will send updates every 500 ms grep: PhysicsActor.SubscribeEvents(
  4230. // as of this comment the interval is set in AddToPhysicalScene
  4231. // if (m_updateCount > 0)
  4232. // {
  4233. // if (Animator != null && Animator.UpdateMovementAnimations())
  4234. // TriggerScenePresenceUpdated();
  4235. // m_updateCount--;
  4236. // }
  4237. CollisionEventUpdate collisionData = (CollisionEventUpdate)e;
  4238. Dictionary<uint, ContactPoint> coldata = collisionData.m_objCollisionList;
  4239. // // No collisions at all means we may be flying. Update always
  4240. // // to make falling work
  4241. // if (m_lastColCount != coldata.Count || coldata.Count == 0)
  4242. // {
  4243. // m_updateCount = UPDATE_COUNT;
  4244. // m_lastColCount = coldata.Count;
  4245. // }
  4246. if (coldata.Count != 0)
  4247. {
  4248. ContactPoint lowest;
  4249. lowest.SurfaceNormal = Vector3.Zero;
  4250. lowest.Position = Vector3.Zero;
  4251. lowest.Position.Z = float.MaxValue;
  4252. foreach (ContactPoint contact in coldata.Values)
  4253. {
  4254. if (contact.CharacterFeet && contact.Position.Z < lowest.Position.Z)
  4255. lowest = contact;
  4256. }
  4257. if (lowest.Position.Z != float.MaxValue)
  4258. {
  4259. lowest.SurfaceNormal = -lowest.SurfaceNormal;
  4260. CollisionPlane = new Vector4(lowest.SurfaceNormal, Vector3.Dot(lowest.Position, lowest.SurfaceNormal));
  4261. }
  4262. else
  4263. CollisionPlane = Vector4.UnitW;
  4264. }
  4265. else
  4266. CollisionPlane = Vector4.UnitW;
  4267. RaiseCollisionScriptEvents(coldata);
  4268. // Gods do not take damage and Invulnerable is set depending on parcel/region flags
  4269. if (Invulnerable || IsViewerUIGod)
  4270. return;
  4271. // The following may be better in the ICombatModule
  4272. // probably tweaking of the values for ground and normal prim collisions will be needed
  4273. float startHealth = Health;
  4274. if(coldata.Count > 0)
  4275. {
  4276. uint killerObj = 0;
  4277. SceneObjectPart part = null;
  4278. float rvel; // relative velocity, negative on approch
  4279. foreach (uint localid in coldata.Keys)
  4280. {
  4281. if (localid == 0)
  4282. {
  4283. // 0 is the ground
  4284. rvel = coldata[0].RelativeSpeed;
  4285. if(rvel < -5.0f)
  4286. Health -= 0.01f * rvel * rvel;
  4287. }
  4288. else
  4289. {
  4290. part = Scene.GetSceneObjectPart(localid);
  4291. if(part != null && !part.ParentGroup.IsVolumeDetect)
  4292. {
  4293. if (part.ParentGroup.Damage > 0.0f)
  4294. {
  4295. // Something with damage...
  4296. Health -= part.ParentGroup.Damage;
  4297. part.ParentGroup.Scene.DeleteSceneObject(part.ParentGroup, false);
  4298. }
  4299. else
  4300. {
  4301. // An ordinary prim
  4302. rvel = coldata[localid].RelativeSpeed;
  4303. if(rvel < -5.0f)
  4304. {
  4305. Health -= 0.005f * rvel * rvel;
  4306. }
  4307. }
  4308. }
  4309. else
  4310. {
  4311. }
  4312. }
  4313. if (Health <= 0.0f)
  4314. {
  4315. if (localid != 0)
  4316. killerObj = localid;
  4317. }
  4318. }
  4319. if (Health <= 0)
  4320. {
  4321. ControllingClient.SendHealth(Health);
  4322. m_scene.EventManager.TriggerAvatarKill(killerObj, this);
  4323. return;
  4324. }
  4325. }
  4326. if(Math.Abs(Health - startHealth) > 1.0)
  4327. ControllingClient.SendHealth(Health);
  4328. }
  4329. public void setHealthWithUpdate(float health)
  4330. {
  4331. Health = health;
  4332. ControllingClient.SendHealth(Health);
  4333. }
  4334. protected internal void Close()
  4335. {
  4336. // Clear known regions
  4337. KnownRegions = new Dictionary<ulong, string>();
  4338. // I don't get it but mono crashes when you try to dispose of this timer,
  4339. // unsetting the elapsed callback should be enough to allow for cleanup however.
  4340. // m_reprioritizationTimer.Dispose();
  4341. RemoveFromPhysicalScene();
  4342. m_scene.EventManager.OnRegionHeartbeatEnd -= RegionHeartbeatEnd;
  4343. RemoveClientEvents();
  4344. // if (Animator != null)
  4345. // Animator.Close();
  4346. Animator = null;
  4347. scriptedcontrols.Clear();
  4348. ControllingClient = null;
  4349. LifecycleState = ScenePresenceState.Removed;
  4350. IsDeleted = true;
  4351. m_updateAgentReceivedAfterTransferEvent.Dispose();
  4352. m_updateAgentReceivedAfterTransferEvent = null;
  4353. }
  4354. public void AddAttachment(SceneObjectGroup gobj)
  4355. {
  4356. lock (m_attachments)
  4357. {
  4358. // This may be true when the attachment comes back
  4359. // from serialization after login. Clear it.
  4360. gobj.IsDeleted = false;
  4361. m_attachments.Add(gobj);
  4362. }
  4363. IBakedTextureModule bakedModule = m_scene.RequestModuleInterface<IBakedTextureModule>();
  4364. if (bakedModule != null)
  4365. bakedModule.UpdateMeshAvatar(m_uuid);
  4366. }
  4367. /// <summary>
  4368. /// Get all the presence's attachments.
  4369. /// </summary>
  4370. /// <returns>A copy of the list which contains the attachments.</returns>
  4371. public List<SceneObjectGroup> GetAttachments()
  4372. {
  4373. lock (m_attachments)
  4374. return new List<SceneObjectGroup>(m_attachments);
  4375. }
  4376. /// <summary>
  4377. /// Get the scene objects attached to the given point.
  4378. /// </summary>
  4379. /// <param name="attachmentPoint"></param>
  4380. /// <returns>Returns an empty list if there were no attachments at the point.</returns>
  4381. public List<SceneObjectGroup> GetAttachments(uint attachmentPoint)
  4382. {
  4383. List<SceneObjectGroup> attachments = new List<SceneObjectGroup>();
  4384. if (attachmentPoint >= 0)
  4385. {
  4386. lock (m_attachments)
  4387. {
  4388. foreach (SceneObjectGroup so in m_attachments)
  4389. {
  4390. if (attachmentPoint == so.AttachmentPoint)
  4391. attachments.Add(so);
  4392. }
  4393. }
  4394. }
  4395. return attachments;
  4396. }
  4397. public bool HasAttachments()
  4398. {
  4399. lock (m_attachments)
  4400. return m_attachments.Count > 0;
  4401. }
  4402. /// <summary>
  4403. /// Returns the total count of scripts in all parts inventories.
  4404. /// </summary>
  4405. public int ScriptCount()
  4406. {
  4407. int count = 0;
  4408. lock (m_attachments)
  4409. {
  4410. foreach (SceneObjectGroup gobj in m_attachments)
  4411. {
  4412. if (gobj != null)
  4413. {
  4414. count += gobj.ScriptCount();
  4415. }
  4416. }
  4417. }
  4418. return count;
  4419. }
  4420. /// <summary>
  4421. /// A float the value is a representative execution time in milliseconds of all scripts in all attachments.
  4422. /// </summary>
  4423. public float ScriptExecutionTime()
  4424. {
  4425. float time = 0.0f;
  4426. lock (m_attachments)
  4427. {
  4428. foreach (SceneObjectGroup gobj in m_attachments)
  4429. {
  4430. if (gobj != null)
  4431. {
  4432. time += gobj.ScriptExecutionTime();
  4433. }
  4434. }
  4435. }
  4436. return time;
  4437. }
  4438. /// <summary>
  4439. /// Returns the total count of running scripts in all parts.
  4440. /// </summary>
  4441. public int RunningScriptCount()
  4442. {
  4443. int count = 0;
  4444. lock (m_attachments)
  4445. {
  4446. foreach (SceneObjectGroup gobj in m_attachments)
  4447. {
  4448. if (gobj != null)
  4449. {
  4450. count += gobj.RunningScriptCount();
  4451. }
  4452. }
  4453. }
  4454. return count;
  4455. }
  4456. public bool HasScriptedAttachments()
  4457. {
  4458. lock (m_attachments)
  4459. {
  4460. foreach (SceneObjectGroup gobj in m_attachments)
  4461. {
  4462. if (gobj != null)
  4463. {
  4464. if (gobj.RootPart.Inventory.ContainsScripts())
  4465. return true;
  4466. }
  4467. }
  4468. }
  4469. return false;
  4470. }
  4471. public void RemoveAttachment(SceneObjectGroup gobj)
  4472. {
  4473. lock (m_attachments)
  4474. m_attachments.Remove(gobj);
  4475. }
  4476. /// <summary>
  4477. /// Clear all attachments
  4478. /// </summary>
  4479. public void ClearAttachments()
  4480. {
  4481. lock (m_attachments)
  4482. m_attachments.Clear();
  4483. }
  4484. /// <summary>
  4485. /// This is currently just being done for information.
  4486. /// </summary>
  4487. public bool ValidateAttachments()
  4488. {
  4489. bool validated = true;
  4490. lock (m_attachments)
  4491. {
  4492. // Validate
  4493. foreach (SceneObjectGroup gobj in m_attachments)
  4494. {
  4495. if (gobj == null)
  4496. {
  4497. m_log.WarnFormat(
  4498. "[SCENE PRESENCE]: Failed to validate an attachment for {0} since it was null. Continuing", Name);
  4499. validated = false;
  4500. }
  4501. else if (gobj.IsDeleted)
  4502. {
  4503. m_log.WarnFormat(
  4504. "[SCENE PRESENCE]: Failed to validate attachment {0} {1} for {2} since it had been deleted. Continuing",
  4505. gobj.Name, gobj.UUID, Name);
  4506. validated = false;
  4507. }
  4508. }
  4509. }
  4510. return validated;
  4511. }
  4512. public void SendAttachmentsToAllAgents()
  4513. {
  4514. lock (m_attachments)
  4515. {
  4516. foreach (SceneObjectGroup sog in m_attachments)
  4517. {
  4518. m_scene.ForEachScenePresence(delegate(ScenePresence p)
  4519. {
  4520. if (p != this && sog.HasPrivateAttachmentPoint)
  4521. return;
  4522. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4523. return;
  4524. SendTerseUpdateToAgentNF(p);
  4525. SendAttachmentFullUpdateToAgentNF(sog, p);
  4526. });
  4527. }
  4528. }
  4529. }
  4530. // send attachments to a client without filters except for huds
  4531. // for now they are checked in several places down the line...
  4532. public void SendAttachmentsToAgentNF(ScenePresence p)
  4533. {
  4534. SendTerseUpdateToAgentNF(p);
  4535. // SendAvatarDataToAgentNF(this);
  4536. lock (m_attachments)
  4537. {
  4538. foreach (SceneObjectGroup sog in m_attachments)
  4539. {
  4540. SendAttachmentFullUpdateToAgentNF(sog, p);
  4541. }
  4542. }
  4543. }
  4544. public void SendAttachmentFullUpdateToAgentNF(SceneObjectGroup sog, ScenePresence p)
  4545. {
  4546. if (p != this && sog.HasPrivateAttachmentPoint)
  4547. return;
  4548. SceneObjectPart[] parts = sog.Parts;
  4549. SceneObjectPart rootpart = sog.RootPart;
  4550. p.ControllingClient.SendEntityUpdate(rootpart, PrimUpdateFlags.FullUpdate);
  4551. for (int i = 0; i < parts.Length; i++)
  4552. {
  4553. SceneObjectPart part = parts[i];
  4554. if (part == rootpart)
  4555. continue;
  4556. p.ControllingClient.SendEntityUpdate(part, PrimUpdateFlags.FullUpdate);
  4557. }
  4558. }
  4559. public void SendAttachmentScheduleUpdate(SceneObjectGroup sog)
  4560. {
  4561. if (IsChildAgent || IsInTransit)
  4562. return;
  4563. SceneObjectPart[] origparts = sog.Parts;
  4564. SceneObjectPart[] parts = new SceneObjectPart[origparts.Length];
  4565. PrimUpdateFlags[] flags = new PrimUpdateFlags[origparts.Length];
  4566. SceneObjectPart rootpart = sog.RootPart;
  4567. UpdateRequired rootreq = sog.RootPart.UpdateFlag;
  4568. int j = 0;
  4569. bool allterse = true;
  4570. for (int i = 0; i < origparts.Length; i++)
  4571. {
  4572. if (origparts[i] != rootpart)
  4573. {
  4574. switch (origparts[i].UpdateFlag)
  4575. {
  4576. case UpdateRequired.NONE:
  4577. break;
  4578. case UpdateRequired.TERSE:
  4579. flags[j] = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4580. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4581. parts[j] = origparts[i];
  4582. j++;
  4583. break;
  4584. case UpdateRequired.FULL:
  4585. flags[j] = PrimUpdateFlags.FullUpdate;
  4586. allterse = false;
  4587. parts[j] = origparts[i];
  4588. j++;
  4589. break;
  4590. }
  4591. }
  4592. origparts[i].UpdateFlag = 0;
  4593. }
  4594. if (j == 0 && rootreq == UpdateRequired.NONE)
  4595. return;
  4596. PrimUpdateFlags rootflag = PrimUpdateFlags.FullUpdate;
  4597. if (rootreq != UpdateRequired.FULL && allterse)
  4598. {
  4599. rootflag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4600. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4601. }
  4602. int nparts = j;
  4603. ControllingClient.SendEntityUpdate(rootpart, rootflag);
  4604. for (int i = 0; i < nparts; i++)
  4605. {
  4606. ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4607. }
  4608. if (sog.HasPrivateAttachmentPoint)
  4609. return;
  4610. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4611. foreach (ScenePresence p in allPresences)
  4612. {
  4613. if (p == this)
  4614. continue;
  4615. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4616. continue;
  4617. p.ControllingClient.SendEntityUpdate(rootpart, rootflag);
  4618. for (int i = 0; i < nparts; i++)
  4619. {
  4620. p.ControllingClient.SendEntityUpdate(parts[i], flags[i]);
  4621. }
  4622. }
  4623. }
  4624. public void SendAttachmentUpdate(SceneObjectGroup sog, UpdateRequired UpdateFlag)
  4625. {
  4626. if (IsChildAgent || IsInTransit)
  4627. return;
  4628. PrimUpdateFlags flag;
  4629. switch (UpdateFlag)
  4630. {
  4631. case UpdateRequired.TERSE:
  4632. flag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4633. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4634. break;
  4635. case UpdateRequired.FULL:
  4636. flag = PrimUpdateFlags.FullUpdate;
  4637. break;
  4638. default:
  4639. return;
  4640. }
  4641. SceneObjectPart[] parts = sog.Parts;
  4642. SceneObjectPart rootpart = sog.RootPart;
  4643. // rootpart.UpdateFlag = 0;
  4644. ControllingClient.SendEntityUpdate(rootpart, flag);
  4645. for (int i = 0; i < parts.Length; i++)
  4646. {
  4647. SceneObjectPart part = parts[i];
  4648. if (part == rootpart)
  4649. continue;
  4650. ControllingClient.SendEntityUpdate(part, flag);
  4651. // part.UpdateFlag = 0;
  4652. }
  4653. if (sog.HasPrivateAttachmentPoint)
  4654. return;
  4655. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4656. foreach (ScenePresence p in allPresences)
  4657. {
  4658. if (p == this)
  4659. continue;
  4660. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4661. continue;
  4662. p.ControllingClient.SendEntityUpdate(rootpart, flag);
  4663. for (int i = 0; i < parts.Length; i++)
  4664. {
  4665. SceneObjectPart part = parts[i];
  4666. if (part == rootpart)
  4667. continue;
  4668. p.ControllingClient.SendEntityUpdate(part, flag);
  4669. }
  4670. }
  4671. }
  4672. public void SendAttachmentScheduleUpdate(SceneObjectPart part)
  4673. {
  4674. if (IsChildAgent || IsInTransit)
  4675. return;
  4676. PrimUpdateFlags flag;
  4677. switch (part.UpdateFlag)
  4678. {
  4679. case UpdateRequired.TERSE:
  4680. flag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4681. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4682. break;
  4683. case UpdateRequired.FULL:
  4684. flag = PrimUpdateFlags.FullUpdate;
  4685. break;
  4686. default:
  4687. return;
  4688. }
  4689. part.UpdateFlag = 0;
  4690. ControllingClient.SendEntityUpdate(part, flag);
  4691. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4692. return;
  4693. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4694. foreach (ScenePresence p in allPresences)
  4695. {
  4696. if (p == this)
  4697. continue;
  4698. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4699. continue;
  4700. p.ControllingClient.SendEntityUpdate(part, flag);
  4701. }
  4702. }
  4703. public void SendAttachmentUpdate(SceneObjectPart part, UpdateRequired UpdateFlag)
  4704. {
  4705. if (IsChildAgent || IsInTransit)
  4706. return;
  4707. PrimUpdateFlags flag;
  4708. switch (UpdateFlag)
  4709. {
  4710. case UpdateRequired.TERSE:
  4711. flag = PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
  4712. | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity;
  4713. break;
  4714. case UpdateRequired.FULL:
  4715. flag = PrimUpdateFlags.FullUpdate;
  4716. break;
  4717. default:
  4718. return;
  4719. }
  4720. // part.UpdateFlag = 0;
  4721. ControllingClient.SendEntityUpdate(part, flag);
  4722. if (part.ParentGroup.HasPrivateAttachmentPoint)
  4723. return;
  4724. List<ScenePresence> allPresences = m_scene.GetScenePresences();
  4725. foreach (ScenePresence p in allPresences)
  4726. {
  4727. if (p == this)
  4728. continue;
  4729. if (ParcelHideThisAvatar && currentParcelUUID != p.currentParcelUUID && !p.IsViewerUIGod)
  4730. continue;
  4731. p.ControllingClient.SendEntityUpdate(part, flag);
  4732. }
  4733. }
  4734. /// <summary>
  4735. /// Send a script event to this scene presence's attachments
  4736. /// </summary>
  4737. /// <param name="eventName">The name of the event</param>
  4738. /// <param name="args">The arguments for the event</param>
  4739. public void SendScriptEventToAttachments(string eventName, Object[] args)
  4740. {
  4741. Util.FireAndForget(delegate(object x)
  4742. {
  4743. if (m_scriptEngines.Length == 0)
  4744. return;
  4745. lock (m_attachments)
  4746. {
  4747. foreach (SceneObjectGroup grp in m_attachments)
  4748. {
  4749. // 16384 is CHANGED_ANIMATION
  4750. //
  4751. // Send this to all attachment root prims
  4752. //
  4753. foreach (IScriptModule m in m_scriptEngines)
  4754. {
  4755. if (m == null) // No script engine loaded
  4756. continue;
  4757. m.PostObjectEvent(grp.RootPart.UUID, "changed", new Object[] { (int)Changed.ANIMATION });
  4758. }
  4759. }
  4760. }
  4761. }, null, "ScenePresence.SendScriptEventToAttachments");
  4762. }
  4763. /// <summary>
  4764. /// Gets the mass.
  4765. /// </summary>
  4766. /// <returns>
  4767. /// The mass.
  4768. /// </returns>
  4769. public float GetMass()
  4770. {
  4771. PhysicsActor pa = PhysicsActor;
  4772. if (pa != null)
  4773. return pa.Mass;
  4774. else
  4775. return 0;
  4776. }
  4777. internal void PushForce(Vector3 impulse)
  4778. {
  4779. if (PhysicsActor != null)
  4780. {
  4781. PhysicsActor.AddForce(impulse,true);
  4782. }
  4783. }
  4784. CameraData physActor_OnPhysicsRequestingCameraData()
  4785. {
  4786. return new CameraData
  4787. {
  4788. Valid = true,
  4789. MouseLook = this.m_mouseLook,
  4790. CameraRotation = this.CameraRotation,
  4791. CameraAtAxis = this.CameraAtAxis
  4792. };
  4793. }
  4794. public void RegisterControlEventsToScript(int controls, int accept, int pass_on, uint Obj_localID, UUID Script_item_UUID)
  4795. {
  4796. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  4797. if (part == null)
  4798. return;
  4799. ControllingClient.SendTakeControls(controls, false, false);
  4800. ControllingClient.SendTakeControls(controls, true, false);
  4801. ScriptControllers obj = new ScriptControllers();
  4802. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4803. obj.eventControls = ScriptControlled.CONTROL_ZERO;
  4804. obj.objectID = part.ParentGroup.UUID;
  4805. obj.itemID = Script_item_UUID;
  4806. if (pass_on == 0 && accept == 0)
  4807. {
  4808. IgnoredControls |= (ScriptControlled)controls;
  4809. obj.ignoreControls = (ScriptControlled)controls;
  4810. }
  4811. if (pass_on == 0 && accept == 1)
  4812. {
  4813. IgnoredControls |= (ScriptControlled)controls;
  4814. obj.ignoreControls = (ScriptControlled)controls;
  4815. obj.eventControls = (ScriptControlled)controls;
  4816. }
  4817. if (pass_on == 1 && accept == 1)
  4818. {
  4819. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4820. obj.eventControls = (ScriptControlled)controls;
  4821. obj.ignoreControls = ScriptControlled.CONTROL_ZERO;
  4822. }
  4823. lock (scriptedcontrols)
  4824. {
  4825. if (pass_on == 1 && accept == 0)
  4826. {
  4827. IgnoredControls &= ~(ScriptControlled)controls;
  4828. if (scriptedcontrols.ContainsKey(Script_item_UUID))
  4829. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  4830. }
  4831. else
  4832. {
  4833. AddScriptToControlNotifications(Script_item_UUID, part, ref obj);
  4834. }
  4835. }
  4836. ControllingClient.SendTakeControls(controls, pass_on == 1 ? true : false, true);
  4837. }
  4838. private void AddScriptToControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part, ref ScriptControllers obj)
  4839. {
  4840. scriptedcontrols[Script_item_UUID] = obj;
  4841. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  4842. if (physActor != null)
  4843. {
  4844. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  4845. physActor.OnPhysicsRequestingCameraData += physActor_OnPhysicsRequestingCameraData;
  4846. }
  4847. }
  4848. private void RemoveScriptFromControlNotifications(OpenMetaverse.UUID Script_item_UUID, SceneObjectPart part)
  4849. {
  4850. scriptedcontrols.Remove(Script_item_UUID);
  4851. if (part != null)
  4852. {
  4853. PhysicsActor physActor = part.ParentGroup.RootPart.PhysActor;
  4854. if (physActor != null)
  4855. {
  4856. physActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  4857. }
  4858. }
  4859. }
  4860. public void HandleForceReleaseControls(IClientAPI remoteClient, UUID agentID)
  4861. {
  4862. foreach (ScriptControllers c in scriptedcontrols.Values)
  4863. {
  4864. SceneObjectGroup sog = m_scene.GetSceneObjectGroup(c.objectID);
  4865. if(sog != null && !sog.IsDeleted && sog.RootPart.PhysActor != null)
  4866. sog.RootPart.PhysActor.OnPhysicsRequestingCameraData -= physActor_OnPhysicsRequestingCameraData;
  4867. }
  4868. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4869. lock (scriptedcontrols)
  4870. {
  4871. scriptedcontrols.Clear();
  4872. }
  4873. ControllingClient.SendTakeControls(int.MaxValue, false, false);
  4874. }
  4875. public void HandleRevokePermissions(UUID objectID, uint permissions )
  4876. {
  4877. // still skeleton code
  4878. if((permissions & (16 | 0x8000 )) == 0) //PERMISSION_TRIGGER_ANIMATION | PERMISSION_OVERRIDE_ANIMATIONS
  4879. return;
  4880. if(objectID == m_scene.RegionInfo.RegionID) // for all objects
  4881. {
  4882. }
  4883. else
  4884. {
  4885. SceneObjectPart part = m_scene.GetSceneObjectPart(objectID);
  4886. if(part != null)
  4887. {
  4888. }
  4889. }
  4890. }
  4891. public void ClearControls()
  4892. {
  4893. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4894. lock (scriptedcontrols)
  4895. {
  4896. scriptedcontrols.Clear();
  4897. }
  4898. }
  4899. public void UnRegisterSeatControls(UUID obj)
  4900. {
  4901. List<UUID> takers = new List<UUID>();
  4902. foreach (ScriptControllers c in scriptedcontrols.Values)
  4903. {
  4904. if (c.objectID == obj)
  4905. takers.Add(c.itemID);
  4906. }
  4907. foreach (UUID t in takers)
  4908. {
  4909. UnRegisterControlEventsToScript(0, t);
  4910. }
  4911. }
  4912. public void UnRegisterControlEventsToScript(uint Obj_localID, UUID Script_item_UUID)
  4913. {
  4914. ScriptControllers takecontrols;
  4915. SceneObjectPart part = m_scene.GetSceneObjectPart(Obj_localID);
  4916. lock (scriptedcontrols)
  4917. {
  4918. if (scriptedcontrols.TryGetValue(Script_item_UUID, out takecontrols))
  4919. {
  4920. ScriptControlled sctc = takecontrols.eventControls;
  4921. ControllingClient.SendTakeControls((int)sctc, false, false);
  4922. ControllingClient.SendTakeControls((int)sctc, true, false);
  4923. RemoveScriptFromControlNotifications(Script_item_UUID, part);
  4924. IgnoredControls = ScriptControlled.CONTROL_ZERO;
  4925. foreach (ScriptControllers scData in scriptedcontrols.Values)
  4926. {
  4927. IgnoredControls |= scData.ignoreControls;
  4928. }
  4929. }
  4930. }
  4931. }
  4932. private void SendControlsToScripts(uint flags)
  4933. {
  4934. // Notify the scripts only after calling UpdateMovementAnimations(), so that if a script
  4935. // (e.g., a walking script) checks which animation is active it will be the correct animation.
  4936. lock (scriptedcontrols)
  4937. {
  4938. if (scriptedcontrols.Count <= 0)
  4939. return;
  4940. ScriptControlled allflags;
  4941. // convert mouse from edge to level
  4942. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP) != 0 ||
  4943. (flags & unchecked((uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_UP)) != 0)
  4944. {
  4945. allflags = ScriptControlled.CONTROL_ZERO;
  4946. }
  4947. else // recover last state of mouse
  4948. allflags = LastCommands & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON);
  4949. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN) != 0)
  4950. allflags |= ScriptControlled.CONTROL_ML_LBUTTON;
  4951. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN) != 0)
  4952. allflags |= ScriptControlled.CONTROL_LBUTTON;
  4953. // find all activated controls, whether the scripts are interested in them or not
  4954. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS) != 0)
  4955. {
  4956. allflags |= ScriptControlled.CONTROL_FWD;
  4957. }
  4958. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG) != 0)
  4959. {
  4960. allflags |= ScriptControlled.CONTROL_BACK;
  4961. }
  4962. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS) != 0)
  4963. {
  4964. allflags |= ScriptControlled.CONTROL_UP;
  4965. }
  4966. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG) != 0)
  4967. {
  4968. allflags |= ScriptControlled.CONTROL_DOWN;
  4969. }
  4970. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS) != 0)
  4971. {
  4972. allflags |= ScriptControlled.CONTROL_LEFT;
  4973. }
  4974. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG) != 0 || (flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG) != 0)
  4975. {
  4976. allflags |= ScriptControlled.CONTROL_RIGHT;
  4977. }
  4978. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG) != 0)
  4979. {
  4980. allflags |= ScriptControlled.CONTROL_ROT_RIGHT;
  4981. }
  4982. if ((flags & (uint)AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS) != 0)
  4983. {
  4984. allflags |= ScriptControlled.CONTROL_ROT_LEFT;
  4985. }
  4986. // optimization; we have to check per script, but if nothing is pressed and nothing changed, we can skip that
  4987. if (allflags != ScriptControlled.CONTROL_ZERO || allflags != LastCommands)
  4988. {
  4989. foreach (KeyValuePair<UUID, ScriptControllers> kvp in scriptedcontrols)
  4990. {
  4991. UUID scriptUUID = kvp.Key;
  4992. ScriptControllers scriptControlData = kvp.Value;
  4993. ScriptControlled localHeld = allflags & scriptControlData.eventControls; // the flags interesting for us
  4994. ScriptControlled localLast = LastCommands & scriptControlData.eventControls; // the activated controls in the last cycle
  4995. ScriptControlled localChange = localHeld ^ localLast; // the changed bits
  4996. if (localHeld != ScriptControlled.CONTROL_ZERO || localChange != ScriptControlled.CONTROL_ZERO)
  4997. {
  4998. // only send if still pressed or just changed
  4999. m_scene.EventManager.TriggerControlEvent(scriptUUID, UUID, (uint)localHeld, (uint)localChange);
  5000. }
  5001. }
  5002. }
  5003. LastCommands = allflags;
  5004. MouseDown = (allflags & (ScriptControlled.CONTROL_ML_LBUTTON | ScriptControlled.CONTROL_LBUTTON)) != 0;
  5005. }
  5006. }
  5007. internal static AgentManager.ControlFlags RemoveIgnoredControls(AgentManager.ControlFlags flags, ScriptControlled ignored)
  5008. {
  5009. if (ignored == ScriptControlled.CONTROL_ZERO)
  5010. return flags;
  5011. if ((ignored & ScriptControlled.CONTROL_BACK) != 0)
  5012. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_NEG);
  5013. if ((ignored & ScriptControlled.CONTROL_FWD) != 0)
  5014. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_AT_POS | AgentManager.ControlFlags.AGENT_CONTROL_AT_POS);
  5015. if ((ignored & ScriptControlled.CONTROL_DOWN) != 0)
  5016. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG);
  5017. if ((ignored & ScriptControlled.CONTROL_UP) != 0)
  5018. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_POS | AgentManager.ControlFlags.AGENT_CONTROL_UP_POS);
  5019. if ((ignored & ScriptControlled.CONTROL_LEFT) != 0)
  5020. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS | AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_POS);
  5021. if ((ignored & ScriptControlled.CONTROL_RIGHT) != 0)
  5022. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_LEFT_NEG | AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG);
  5023. if ((ignored & ScriptControlled.CONTROL_ROT_LEFT) != 0)
  5024. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_NEG);
  5025. if ((ignored & ScriptControlled.CONTROL_ROT_RIGHT) != 0)
  5026. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_YAW_POS);
  5027. if ((ignored & ScriptControlled.CONTROL_ML_LBUTTON) != 0)
  5028. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_ML_LBUTTON_DOWN);
  5029. if ((ignored & ScriptControlled.CONTROL_LBUTTON) != 0)
  5030. flags &= ~(AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_UP | AgentManager.ControlFlags.AGENT_CONTROL_LBUTTON_DOWN);
  5031. //DIR_CONTROL_FLAG_FORWARD = AgentManager.ControlFlags.AGENT_CONTROL_AT_POS,
  5032. //DIR_CONTROL_FLAG_BACK = AgentManager.ControlFlags.AGENT_CONTROL_AT_NEG,
  5033. //DIR_CONTROL_FLAG_LEFT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_POS,
  5034. //DIR_CONTROL_FLAG_RIGHT = AgentManager.ControlFlags.AGENT_CONTROL_LEFT_NEG,
  5035. //DIR_CONTROL_FLAG_UP = AgentManager.ControlFlags.AGENT_CONTROL_UP_POS,
  5036. //DIR_CONTROL_FLAG_DOWN = AgentManager.ControlFlags.AGENT_CONTROL_UP_NEG,
  5037. //DIR_CONTROL_FLAG_DOWN_NUDGE = AgentManager.ControlFlags.AGENT_CONTROL_NUDGE_UP_NEG
  5038. return flags;
  5039. }
  5040. // returns true it local teleport allowed and sets the destiny position into pos
  5041. private bool CheckLocalTPLandingPoint(ref Vector3 pos)
  5042. {
  5043. // Never constrain lures
  5044. if ((TeleportFlags & TeleportFlags.ViaLure) != 0)
  5045. return true;
  5046. if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5047. return true;
  5048. // do not constrain gods and estate managers
  5049. if(m_scene.Permissions.IsGod(m_uuid) ||
  5050. m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5051. return true;
  5052. // will teleport to a telehub spawn point or landpoint if that results in getting closer to target
  5053. // if not the local teleport fails.
  5054. float currDistanceSQ = Vector3.DistanceSquared(AbsolutePosition, pos);
  5055. // first check telehub
  5056. UUID TelehubObjectID = m_scene.RegionInfo.RegionSettings.TelehubObject;
  5057. if ( TelehubObjectID != UUID.Zero)
  5058. {
  5059. SceneObjectGroup telehubSOG = m_scene.GetSceneObjectGroup(TelehubObjectID);
  5060. if(telehubSOG != null)
  5061. {
  5062. Vector3 spawnPos;
  5063. float spawnDistSQ;
  5064. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5065. if(spawnPoints.Length == 0)
  5066. {
  5067. spawnPos = new Vector3(128.0f, 128.0f, pos.Z);
  5068. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5069. }
  5070. else
  5071. {
  5072. Vector3 hubPos = telehubSOG.AbsolutePosition;
  5073. Quaternion hubRot = telehubSOG.GroupRotation;
  5074. spawnPos = spawnPoints[0].GetLocation(hubPos, hubRot);
  5075. spawnDistSQ = Vector3.DistanceSquared(spawnPos, pos);
  5076. float testDistSQ;
  5077. Vector3 testSpawnPos;
  5078. for(int i = 1; i< spawnPoints.Length; i++)
  5079. {
  5080. testSpawnPos = spawnPoints[i].GetLocation(hubPos, hubRot);
  5081. testDistSQ = Vector3.DistanceSquared(testSpawnPos, pos);
  5082. if(testDistSQ < spawnDistSQ)
  5083. {
  5084. spawnPos = testSpawnPos;
  5085. spawnDistSQ = testDistSQ;
  5086. }
  5087. }
  5088. }
  5089. if (currDistanceSQ < spawnDistSQ)
  5090. {
  5091. // we are already close
  5092. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5093. return false;
  5094. }
  5095. else
  5096. {
  5097. pos = spawnPos;
  5098. return true;
  5099. }
  5100. }
  5101. }
  5102. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5103. if (land.LandData.LandingType != (byte)LandingType.LandingPoint
  5104. || land.LandData.OwnerID == m_uuid)
  5105. return true;
  5106. Vector3 landLocation = land.LandData.UserLocation;
  5107. if(landLocation == Vector3.Zero)
  5108. return true;
  5109. if (currDistanceSQ < Vector3.DistanceSquared(landLocation, pos))
  5110. {
  5111. ControllingClient.SendAlertMessage("Can't teleport closer to destination");
  5112. return false;
  5113. }
  5114. pos = land.LandData.UserLocation;
  5115. return true;
  5116. }
  5117. const TeleportFlags TeleHubTPFlags = TeleportFlags.ViaLogin
  5118. | TeleportFlags.ViaHGLogin | TeleportFlags.ViaLocation;
  5119. private bool CheckAndAdjustTelehub(SceneObjectGroup telehub, ref Vector3 pos, ref bool positionChanged)
  5120. {
  5121. // forcing telehubs on any tp that reachs this
  5122. if ((m_teleportFlags & TeleHubTPFlags) != 0 ||
  5123. (m_scene.TelehubAllowLandmarks == true ? false : ((m_teleportFlags & TeleportFlags.ViaLandmark) != 0 )))
  5124. {
  5125. ILandObject land;
  5126. Vector3 teleHubPosition = telehub.AbsolutePosition;
  5127. SpawnPoint[] spawnPoints = m_scene.RegionInfo.RegionSettings.SpawnPoints().ToArray();
  5128. if(spawnPoints.Length == 0)
  5129. {
  5130. land = m_scene.LandChannel.GetLandObject(teleHubPosition.X,teleHubPosition.Y);
  5131. if(land != null)
  5132. {
  5133. pos = teleHubPosition;
  5134. if(land.IsEitherBannedOrRestricted(UUID))
  5135. return false;
  5136. positionChanged = true;
  5137. return true;
  5138. }
  5139. else
  5140. return false;
  5141. }
  5142. int index;
  5143. int tries;
  5144. bool selected = false;
  5145. bool validhub = false;
  5146. Vector3 spawnPosition;
  5147. Quaternion teleHubRotation = telehub.GroupRotation;
  5148. switch(m_scene.SpawnPointRouting)
  5149. {
  5150. case "random":
  5151. tries = spawnPoints.Length;
  5152. if(tries < 3) // no much sense in random with a few points when there same can have bans
  5153. goto case "sequence";
  5154. do
  5155. {
  5156. index = Util.RandomClass.Next(spawnPoints.Length - 1);
  5157. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5158. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5159. if(land != null && !land.IsEitherBannedOrRestricted(UUID))
  5160. selected = true;
  5161. } while(selected == false && --tries > 0 );
  5162. if(tries <= 0)
  5163. goto case "sequence";
  5164. pos = spawnPosition;
  5165. return true;
  5166. case "sequence":
  5167. tries = spawnPoints.Length;
  5168. selected = false;
  5169. validhub = false;
  5170. do
  5171. {
  5172. index = m_scene.SpawnPoint();
  5173. spawnPosition = spawnPoints[index].GetLocation(teleHubPosition, teleHubRotation);
  5174. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5175. if(land != null)
  5176. {
  5177. validhub = true;
  5178. if(land.IsEitherBannedOrRestricted(UUID))
  5179. selected = false;
  5180. else
  5181. selected = true;
  5182. }
  5183. } while(selected == false && --tries > 0);
  5184. if(!validhub)
  5185. return false;
  5186. pos = spawnPosition;
  5187. if(!selected)
  5188. return false;
  5189. positionChanged = true;
  5190. return true;
  5191. default:
  5192. case "closest":
  5193. float distancesq = float.MaxValue;
  5194. int closest = -1;
  5195. validhub = false;
  5196. for(int i = 0; i < spawnPoints.Length; i++)
  5197. {
  5198. spawnPosition = spawnPoints[i].GetLocation(teleHubPosition, teleHubRotation);
  5199. Vector3 offset = spawnPosition - pos;
  5200. float dsq = offset.LengthSquared();
  5201. land = m_scene.LandChannel.GetLandObject(spawnPosition.X,spawnPosition.Y);
  5202. if(land == null)
  5203. continue;
  5204. validhub = true;
  5205. if(land.IsEitherBannedOrRestricted(UUID))
  5206. continue;
  5207. if(dsq >= distancesq)
  5208. continue;
  5209. distancesq = dsq;
  5210. closest = i;
  5211. }
  5212. if(!validhub)
  5213. return false;
  5214. if(closest < 0)
  5215. {
  5216. pos = spawnPoints[0].GetLocation(teleHubPosition, teleHubRotation);
  5217. positionChanged = true;
  5218. return false;
  5219. }
  5220. pos = spawnPoints[closest].GetLocation(teleHubPosition, teleHubRotation);
  5221. positionChanged = true;
  5222. return true;
  5223. }
  5224. }
  5225. return false;
  5226. }
  5227. const TeleportFlags adicionalLandPointFlags = TeleportFlags.ViaLandmark |
  5228. TeleportFlags.ViaLocation | TeleportFlags.ViaHGLogin;
  5229. // Modify landing point based on possible banning, telehubs or parcel restrictions.
  5230. // This is the behavior in OpenSim for a very long time, different from SL
  5231. private bool CheckAndAdjustLandingPoint_OS(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5232. {
  5233. string reason;
  5234. // Honor bans
  5235. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  5236. return false;
  5237. SceneObjectGroup telehub = null;
  5238. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5239. {
  5240. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5241. {
  5242. CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged);
  5243. return true;
  5244. }
  5245. }
  5246. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5247. if (land != null)
  5248. {
  5249. if (Scene.DebugTeleporting)
  5250. TeleportFlagsDebug();
  5251. // If we come in via login, landmark or map, we want to
  5252. // honor landing points. If we come in via Lure, we want
  5253. // to ignore them.
  5254. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5255. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID) ||
  5256. (m_teleportFlags & adicionalLandPointFlags) != 0)
  5257. {
  5258. // Don't restrict gods, estate managers, or land owners to
  5259. // the TP point. This behaviour mimics agni.
  5260. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5261. land.LandData.UserLocation != Vector3.Zero &&
  5262. !IsViewerUIGod &&
  5263. ((land.LandData.OwnerID != m_uuid &&
  5264. !m_scene.Permissions.IsGod(m_uuid) &&
  5265. !m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid)) ||
  5266. (m_teleportFlags & TeleportFlags.ViaLocation) != 0 ||
  5267. (m_teleportFlags & Constants.TeleportFlags.ViaHGLogin) != 0))
  5268. {
  5269. pos = land.LandData.UserLocation;
  5270. positionChanged = true;
  5271. }
  5272. }
  5273. land.SendLandUpdateToClient(ControllingClient);
  5274. }
  5275. return true;
  5276. }
  5277. // Modify landing point based on telehubs or parcel restrictions.
  5278. // This is a behavior coming from AVN, somewhat mimicking SL
  5279. private bool CheckAndAdjustLandingPoint_SL(ref Vector3 pos, ref Vector3 lookat, ref bool positionChanged)
  5280. {
  5281. string reason;
  5282. // dont mess with gods
  5283. if(IsGod)
  5284. return true;
  5285. // respect region owner and managers
  5286. // if(m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_uuid))
  5287. // return true;
  5288. if (!m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
  5289. {
  5290. SceneObjectGroup telehub = null;
  5291. if (m_scene.RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = m_scene.GetSceneObjectGroup(m_scene.RegionInfo.RegionSettings.TelehubObject)) != null)
  5292. {
  5293. if(CheckAndAdjustTelehub(telehub, ref pos, ref positionChanged))
  5294. return true;
  5295. }
  5296. }
  5297. // Honor bans, actually we don't honour them
  5298. if (!m_scene.TestLandRestrictions(UUID, out reason, ref pos.X, ref pos.Y))
  5299. return false;
  5300. ILandObject land = m_scene.LandChannel.GetLandObject(pos.X, pos.Y);
  5301. if (land != null)
  5302. {
  5303. if (Scene.DebugTeleporting)
  5304. TeleportFlagsDebug();
  5305. // If we come in via login, landmark or map, we want to
  5306. // honor landing points. If we come in via Lure, we want
  5307. // to ignore them.
  5308. if ((m_teleportFlags & (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)) ==
  5309. (TeleportFlags.ViaLogin | TeleportFlags.ViaRegionID)
  5310. || (m_teleportFlags & adicionalLandPointFlags) != 0)
  5311. {
  5312. if (land.LandData.LandingType == (byte)LandingType.LandingPoint &&
  5313. land.LandData.UserLocation != Vector3.Zero )
  5314. // &&
  5315. // land.LandData.OwnerID != m_uuid )
  5316. {
  5317. pos = land.LandData.UserLocation;
  5318. if(land.LandData.UserLookAt != Vector3.Zero)
  5319. lookat = land.LandData.UserLookAt;
  5320. positionChanged = true;
  5321. }
  5322. }
  5323. }
  5324. return true;
  5325. }
  5326. private DetectedObject CreateDetObject(SceneObjectPart obj)
  5327. {
  5328. DetectedObject detobj = new DetectedObject();
  5329. detobj.keyUUID = obj.UUID;
  5330. detobj.nameStr = obj.Name;
  5331. detobj.ownerUUID = obj.OwnerID;
  5332. detobj.posVector = obj.AbsolutePosition;
  5333. detobj.rotQuat = obj.GetWorldRotation();
  5334. detobj.velVector = obj.Velocity;
  5335. detobj.colliderType = 0;
  5336. detobj.groupUUID = obj.GroupID;
  5337. detobj.linkNumber = 0;
  5338. return detobj;
  5339. }
  5340. private DetectedObject CreateDetObject(ScenePresence av)
  5341. {
  5342. DetectedObject detobj = new DetectedObject();
  5343. detobj.keyUUID = av.UUID;
  5344. detobj.nameStr = av.ControllingClient.Name;
  5345. detobj.ownerUUID = av.UUID;
  5346. detobj.posVector = av.AbsolutePosition;
  5347. detobj.rotQuat = av.Rotation;
  5348. detobj.velVector = av.Velocity;
  5349. detobj.colliderType = av.IsNPC ? 0x20 : 0x1; // OpenSim\Region\ScriptEngine\Shared\Helpers.cs
  5350. if(av.IsSatOnObject)
  5351. detobj.colliderType |= 0x4; //passive
  5352. else if(detobj.velVector != Vector3.Zero)
  5353. detobj.colliderType |= 0x2; //active
  5354. detobj.groupUUID = av.ControllingClient.ActiveGroupId;
  5355. detobj.linkNumber = 0;
  5356. return detobj;
  5357. }
  5358. private DetectedObject CreateDetObjectForGround()
  5359. {
  5360. DetectedObject detobj = new DetectedObject();
  5361. detobj.keyUUID = UUID.Zero;
  5362. detobj.nameStr = "";
  5363. detobj.ownerUUID = UUID.Zero;
  5364. detobj.posVector = AbsolutePosition;
  5365. detobj.rotQuat = Quaternion.Identity;
  5366. detobj.velVector = Vector3.Zero;
  5367. detobj.colliderType = 0;
  5368. detobj.groupUUID = UUID.Zero;
  5369. detobj.linkNumber = 0;
  5370. return detobj;
  5371. }
  5372. private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
  5373. {
  5374. ColliderArgs colliderArgs = new ColliderArgs();
  5375. List<DetectedObject> colliding = new List<DetectedObject>();
  5376. foreach (uint localId in colliders)
  5377. {
  5378. if (localId == 0)
  5379. continue;
  5380. SceneObjectPart obj = m_scene.GetSceneObjectPart(localId);
  5381. if (obj != null)
  5382. {
  5383. if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
  5384. colliding.Add(CreateDetObject(obj));
  5385. }
  5386. else
  5387. {
  5388. ScenePresence av = m_scene.GetScenePresence(localId);
  5389. if (av != null && (!av.IsChildAgent))
  5390. {
  5391. if (!dest.CollisionFilteredOut(av.UUID, av.Name))
  5392. colliding.Add(CreateDetObject(av));
  5393. }
  5394. }
  5395. }
  5396. colliderArgs.Colliders = colliding;
  5397. return colliderArgs;
  5398. }
  5399. private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);
  5400. private void SendCollisionEvent(SceneObjectGroup dest, scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
  5401. {
  5402. ColliderArgs CollidingMessage;
  5403. if (colliders.Count > 0)
  5404. {
  5405. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5406. {
  5407. CollidingMessage = CreateColliderArgs(dest.RootPart, colliders);
  5408. if (CollidingMessage.Colliders.Count > 0)
  5409. notify(dest.RootPart.LocalId, CollidingMessage);
  5410. }
  5411. }
  5412. }
  5413. private void SendLandCollisionEvent(SceneObjectGroup dest, scriptEvents ev, ScriptCollidingNotification notify)
  5414. {
  5415. if ((dest.RootPart.ScriptEvents & ev) != 0)
  5416. {
  5417. ColliderArgs LandCollidingMessage = new ColliderArgs();
  5418. List<DetectedObject> colliding = new List<DetectedObject>();
  5419. colliding.Add(CreateDetObjectForGround());
  5420. LandCollidingMessage.Colliders = colliding;
  5421. notify(dest.RootPart.LocalId, LandCollidingMessage);
  5422. }
  5423. }
  5424. private void RaiseCollisionScriptEvents(Dictionary<uint, ContactPoint> coldata)
  5425. {
  5426. try
  5427. {
  5428. List<uint> thisHitColliders = new List<uint>();
  5429. List<uint> endedColliders = new List<uint>();
  5430. List<uint> startedColliders = new List<uint>();
  5431. if (coldata.Count == 0)
  5432. {
  5433. if (m_lastColliders.Count == 0)
  5434. return; // nothing to do
  5435. foreach (uint localID in m_lastColliders)
  5436. {
  5437. endedColliders.Add(localID);
  5438. }
  5439. m_lastColliders.Clear();
  5440. }
  5441. else
  5442. {
  5443. List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();
  5444. if(ParcelAllowThisAvatarSounds)
  5445. {
  5446. CollisionForSoundInfo soundinfo;
  5447. ContactPoint curcontact;
  5448. foreach (uint id in coldata.Keys)
  5449. {
  5450. thisHitColliders.Add(id);
  5451. if (!m_lastColliders.Contains(id))
  5452. {
  5453. startedColliders.Add(id);
  5454. curcontact = coldata[id];
  5455. if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
  5456. {
  5457. soundinfo = new CollisionForSoundInfo();
  5458. soundinfo.colliderID = id;
  5459. soundinfo.position = curcontact.Position;
  5460. soundinfo.relativeVel = curcontact.RelativeSpeed;
  5461. soundinfolist.Add(soundinfo);
  5462. }
  5463. }
  5464. }
  5465. }
  5466. else
  5467. {
  5468. foreach (uint id in coldata.Keys)
  5469. {
  5470. thisHitColliders.Add(id);
  5471. if (!m_lastColliders.Contains(id))
  5472. startedColliders.Add(id);
  5473. }
  5474. }
  5475. // calculate things that ended colliding
  5476. foreach (uint localID in m_lastColliders)
  5477. {
  5478. if (!thisHitColliders.Contains(localID))
  5479. {
  5480. endedColliders.Add(localID);
  5481. }
  5482. }
  5483. //add the items that started colliding this time to the last colliders list.
  5484. foreach (uint localID in startedColliders)
  5485. {
  5486. m_lastColliders.Add(localID);
  5487. }
  5488. // remove things that ended colliding from the last colliders list
  5489. foreach (uint localID in endedColliders)
  5490. {
  5491. m_lastColliders.Remove(localID);
  5492. }
  5493. if (soundinfolist.Count > 0)
  5494. CollisionSounds.AvatarCollisionSound(this, soundinfolist);
  5495. }
  5496. foreach (SceneObjectGroup att in GetAttachments())
  5497. {
  5498. SendCollisionEvent(att, scriptEvents.collision_start, startedColliders, m_scene.EventManager.TriggerScriptCollidingStart);
  5499. SendCollisionEvent(att, scriptEvents.collision , m_lastColliders , m_scene.EventManager.TriggerScriptColliding);
  5500. SendCollisionEvent(att, scriptEvents.collision_end , endedColliders , m_scene.EventManager.TriggerScriptCollidingEnd);
  5501. if (startedColliders.Contains(0))
  5502. SendLandCollisionEvent(att, scriptEvents.land_collision_start, m_scene.EventManager.TriggerScriptLandCollidingStart);
  5503. if (m_lastColliders.Contains(0))
  5504. SendLandCollisionEvent(att, scriptEvents.land_collision, m_scene.EventManager.TriggerScriptLandColliding);
  5505. if (endedColliders.Contains(0))
  5506. SendLandCollisionEvent(att, scriptEvents.land_collision_end, m_scene.EventManager.TriggerScriptLandCollidingEnd);
  5507. }
  5508. }
  5509. catch { }
  5510. // finally
  5511. // {
  5512. // m_collisionEventFlag = false;
  5513. // }
  5514. }
  5515. private void TeleportFlagsDebug() {
  5516. // Some temporary debugging help to show all the TeleportFlags we have...
  5517. bool HG = false;
  5518. if((m_teleportFlags & TeleportFlags.ViaHGLogin) == TeleportFlags.ViaHGLogin)
  5519. HG = true;
  5520. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5521. uint i = 0u;
  5522. for (int x = 0; x <= 30 ; x++, i = 1u << x)
  5523. {
  5524. i = 1u << x;
  5525. if((m_teleportFlags & (TeleportFlags)i) == (TeleportFlags)i)
  5526. if (HG == false)
  5527. m_log.InfoFormat("[SCENE PRESENCE]: Teleport Flags include {0}", ((TeleportFlags) i).ToString());
  5528. else
  5529. m_log.InfoFormat("[SCENE PRESENCE]: HG Teleport Flags include {0}", ((TeleportFlags)i).ToString());
  5530. }
  5531. m_log.InfoFormat("[SCENE PRESENCE]: TELEPORT ******************");
  5532. }
  5533. private void parcelGodCheck(UUID currentParcelID)
  5534. {
  5535. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5536. foreach (ScenePresence p in allpresences)
  5537. {
  5538. if (p.IsDeleted || p.IsChildAgent || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5539. continue;
  5540. if (p.ParcelHideThisAvatar && p.currentParcelUUID != currentParcelID)
  5541. {
  5542. if (IsViewerUIGod)
  5543. p.SendViewTo(this);
  5544. else
  5545. p.SendKillTo(this);
  5546. }
  5547. }
  5548. }
  5549. private void ParcelCrossCheck(UUID currentParcelID,UUID previusParcelID,
  5550. bool currentParcelHide, bool previusParcelHide, bool oldhide, bool check)
  5551. {
  5552. List<ScenePresence> killsToSendto = new List<ScenePresence>();
  5553. List<ScenePresence> killsToSendme = new List<ScenePresence>();
  5554. List<ScenePresence> viewsToSendto = new List<ScenePresence>();
  5555. List<ScenePresence> viewsToSendme = new List<ScenePresence>();
  5556. List<ScenePresence> allpresences = null;
  5557. if (IsInTransit || IsChildAgent)
  5558. return;
  5559. if (check)
  5560. {
  5561. // check is relative to current parcel only
  5562. if (oldhide == currentParcelHide)
  5563. return;
  5564. allpresences = m_scene.GetScenePresences();
  5565. if (oldhide)
  5566. { // where private
  5567. foreach (ScenePresence p in allpresences)
  5568. {
  5569. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5570. continue;
  5571. // those on not on parcel see me
  5572. if (currentParcelID != p.currentParcelUUID)
  5573. {
  5574. viewsToSendto.Add(p); // they see me
  5575. }
  5576. }
  5577. } // where private end
  5578. else
  5579. { // where public
  5580. foreach (ScenePresence p in allpresences)
  5581. {
  5582. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5583. continue;
  5584. // those not on parcel dont see me
  5585. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5586. {
  5587. killsToSendto.Add(p); // they dont see me
  5588. }
  5589. }
  5590. } // where public end
  5591. allpresences.Clear();
  5592. }
  5593. else
  5594. {
  5595. if (currentParcelHide)
  5596. {
  5597. // now on a private parcel
  5598. allpresences = m_scene.GetScenePresences();
  5599. if (previusParcelHide && previusParcelID != UUID.Zero)
  5600. {
  5601. foreach (ScenePresence p in allpresences)
  5602. {
  5603. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5604. continue;
  5605. // only those on previus parcel need receive kills
  5606. if (previusParcelID == p.currentParcelUUID)
  5607. {
  5608. if(!p.IsViewerUIGod)
  5609. killsToSendto.Add(p); // they dont see me
  5610. if(!IsViewerUIGod)
  5611. killsToSendme.Add(p); // i dont see them
  5612. }
  5613. // only those on new parcel need see
  5614. if (currentParcelID == p.currentParcelUUID)
  5615. {
  5616. viewsToSendto.Add(p); // they see me
  5617. viewsToSendme.Add(p); // i see them
  5618. }
  5619. }
  5620. }
  5621. else
  5622. {
  5623. //was on a public area
  5624. allpresences = m_scene.GetScenePresences();
  5625. foreach (ScenePresence p in allpresences)
  5626. {
  5627. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5628. continue;
  5629. // those not on new parcel dont see me
  5630. if (currentParcelID != p.currentParcelUUID && !p.IsViewerUIGod)
  5631. {
  5632. killsToSendto.Add(p); // they dont see me
  5633. }
  5634. else
  5635. {
  5636. viewsToSendme.Add(p); // i see those on it
  5637. }
  5638. }
  5639. }
  5640. allpresences.Clear();
  5641. } // now on a private parcel end
  5642. else
  5643. {
  5644. // now on public parcel
  5645. if (previusParcelHide && previusParcelID != UUID.Zero)
  5646. {
  5647. // was on private area
  5648. allpresences = m_scene.GetScenePresences();
  5649. foreach (ScenePresence p in allpresences)
  5650. {
  5651. if (p.IsDeleted || p == this || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5652. continue;
  5653. // only those old parcel need kills
  5654. if (previusParcelID == p.currentParcelUUID && !IsViewerUIGod)
  5655. {
  5656. killsToSendme.Add(p); // i dont see them
  5657. }
  5658. else
  5659. {
  5660. viewsToSendto.Add(p); // they see me
  5661. }
  5662. }
  5663. }
  5664. else
  5665. return; // was on a public area also
  5666. } // now on public parcel end
  5667. }
  5668. // send the things
  5669. if (killsToSendto.Count > 0)
  5670. {
  5671. foreach (ScenePresence p in killsToSendto)
  5672. {
  5673. // m_log.Debug("[AVATAR]: killTo: " + Lastname + " " + p.Lastname);
  5674. SendKillTo(p);
  5675. }
  5676. }
  5677. if (killsToSendme.Count > 0)
  5678. {
  5679. foreach (ScenePresence p in killsToSendme)
  5680. {
  5681. // m_log.Debug("[AVATAR]: killToMe: " + Lastname + " " + p.Lastname);
  5682. p.SendKillTo(this);
  5683. }
  5684. }
  5685. if (viewsToSendto.Count > 0)
  5686. {
  5687. foreach (ScenePresence p in viewsToSendto)
  5688. {
  5689. SendViewTo(p);
  5690. }
  5691. }
  5692. if (viewsToSendme.Count > 0 )
  5693. {
  5694. foreach (ScenePresence p in viewsToSendme)
  5695. {
  5696. if (p.IsChildAgent)
  5697. continue;
  5698. // m_log.Debug("[AVATAR]: viewMe: " + Lastname + "<-" + p.Lastname);
  5699. p.SendViewTo(this);
  5700. }
  5701. }
  5702. }
  5703. public void HasMovedAway(bool nearRegion)
  5704. {
  5705. if (nearRegion)
  5706. {
  5707. if (Scene.AttachmentsModule != null)
  5708. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5709. if (!ParcelHideThisAvatar || IsViewerUIGod)
  5710. return;
  5711. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5712. foreach (ScenePresence p in allpresences)
  5713. {
  5714. if (p.IsDeleted || p == this || p.IsChildAgent || p.ControllingClient == null || !p.ControllingClient.IsActive)
  5715. continue;
  5716. if (p.currentParcelUUID == m_currentParcelUUID)
  5717. {
  5718. p.SendKillTo(this);
  5719. }
  5720. }
  5721. }
  5722. else
  5723. {
  5724. GodController.HasMovedAway();
  5725. List<ScenePresence> allpresences = m_scene.GetScenePresences();
  5726. foreach (ScenePresence p in allpresences)
  5727. {
  5728. if (p == this)
  5729. continue;
  5730. SendKillTo(p);
  5731. if (!p.IsChildAgent)
  5732. p.SendKillTo(this);
  5733. }
  5734. if (Scene.AttachmentsModule != null)
  5735. Scene.AttachmentsModule.DeleteAttachmentsFromScene(this, true);
  5736. }
  5737. }
  5738. // kill with attachs root kills
  5739. public void SendKillTo(ScenePresence p)
  5740. {
  5741. List<uint> ids = new List<uint>(m_attachments.Count + 1);
  5742. foreach (SceneObjectGroup sog in m_attachments)
  5743. {
  5744. ids.Add(sog.RootPart.LocalId);
  5745. }
  5746. ids.Add(LocalId);
  5747. p.ControllingClient.SendKillObject(ids);
  5748. }
  5749. /*
  5750. // kill with hack
  5751. public void SendKillTo(ScenePresence p)
  5752. {
  5753. foreach (SceneObjectGroup sog in m_attachments)
  5754. p.ControllingClient.SendPartFullUpdate(sog.RootPart, LocalId + 1);
  5755. p.ControllingClient.SendKillObject(new List<uint> { LocalId });
  5756. }
  5757. */
  5758. public void SendViewTo(ScenePresence p)
  5759. {
  5760. SendAvatarDataToAgentNF(p);
  5761. SendAppearanceToAgent(p);
  5762. if (Animator != null)
  5763. Animator.SendAnimPackToClient(p.ControllingClient);
  5764. SendAttachmentsToAgentNF(p);
  5765. }
  5766. public void SetAnimationOverride(string animState, UUID animID)
  5767. {
  5768. Overrides.SetOverride(animState, animID);
  5769. // Animator.SendAnimPack();
  5770. Animator.ForceUpdateMovementAnimations();
  5771. }
  5772. public UUID GetAnimationOverride(string animState)
  5773. {
  5774. return Overrides.GetOverriddenAnimation(animState);
  5775. }
  5776. // http caps assets bandwidth control
  5777. private int m_capbandwidth = -1;
  5778. private int m_bandwidth = 100000;
  5779. private int m_bandwidthBurst = 20000;
  5780. private int m_bytesControl;
  5781. private double m_lastBandwithTime;
  5782. private object m_throttleLock = new object();
  5783. public bool CapCanSendAsset(int type, int size)
  5784. {
  5785. if(size == 0)
  5786. return true;
  5787. lock (m_throttleLock)
  5788. {
  5789. if (type > 1)
  5790. {
  5791. // not texture or mesh
  5792. m_bytesControl -= size;
  5793. return true;
  5794. }
  5795. double currenttime = Util.GetTimeStamp();
  5796. double timeElapsed = currenttime - m_lastBandwithTime;
  5797. if (timeElapsed > .02)
  5798. {
  5799. m_lastBandwithTime = currenttime;
  5800. int add = (int)(m_bandwidth * timeElapsed);
  5801. m_bytesControl += add;
  5802. if (m_bytesControl > m_bandwidthBurst)
  5803. m_bytesControl = m_bandwidthBurst;
  5804. }
  5805. if (m_bytesControl > 0 )
  5806. {
  5807. m_bytesControl -= size;
  5808. return true;
  5809. }
  5810. }
  5811. return false;
  5812. }
  5813. }
  5814. }