ScenePresence.cs 276 KB

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