ScenePresence.cs 266 KB

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