Scene.cs 241 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925
  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 copyrightD
  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.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.Drawing;
  31. using System.Drawing.Imaging;
  32. using System.IO;
  33. using System.Text;
  34. using System.Threading;
  35. using System.Timers;
  36. using System.Xml;
  37. using Nini.Config;
  38. using OpenMetaverse;
  39. using OpenMetaverse.Packets;
  40. using OpenMetaverse.Imaging;
  41. using OpenSim.Framework;
  42. using OpenSim.Framework.Monitoring;
  43. using OpenSim.Services.Interfaces;
  44. using OpenSim.Framework.Communications;
  45. using OpenSim.Framework.Console;
  46. using OpenSim.Region.Framework.Interfaces;
  47. using OpenSim.Region.Framework.Scenes.Scripting;
  48. using OpenSim.Region.Framework.Scenes.Serialization;
  49. using OpenSim.Region.Physics.Manager;
  50. using Timer=System.Timers.Timer;
  51. using TPFlags = OpenSim.Framework.Constants.TeleportFlags;
  52. using GridRegion = OpenSim.Services.Interfaces.GridRegion;
  53. using PermissionMask = OpenSim.Framework.PermissionMask;
  54. namespace OpenSim.Region.Framework.Scenes
  55. {
  56. public delegate bool FilterAvatarList(ScenePresence avatar);
  57. public partial class Scene : SceneBase
  58. {
  59. private const long DEFAULT_MIN_TIME_FOR_PERSISTENCE = 60L;
  60. private const long DEFAULT_MAX_TIME_FOR_PERSISTENCE = 600L;
  61. public delegate void SynchronizeSceneHandler(Scene scene);
  62. #region Fields
  63. public bool EmergencyMonitoring = false;
  64. /// <summary>
  65. /// Show debug information about animations.
  66. /// </summary>
  67. public bool DebugAnimations { get; set; }
  68. /// <summary>
  69. /// Show debug information about teleports.
  70. /// </summary>
  71. public bool DebugTeleporting { get; set; }
  72. /// <summary>
  73. /// Show debug information about the scene loop.
  74. /// </summary>
  75. public bool DebugUpdates { get; set; }
  76. /// <summary>
  77. /// If true then the scene is saved to persistent storage periodically, every m_update_backup frames and
  78. /// if objects meet required conditions (m_dontPersistBefore and m_dontPersistAfter).
  79. /// </summary>
  80. /// <remarks>
  81. /// Even if false, the scene will still be saved on clean shutdown.
  82. /// FIXME: Currently, setting this to false will mean that objects are not periodically returned from parcels.
  83. /// This needs to be fixed.
  84. /// </remarks>
  85. public bool PeriodicBackup { get; set; }
  86. /// <summary>
  87. /// If false then the scene is never saved to persistence storage even if PeriodicBackup == true and even
  88. /// if the scene is being shut down for the final time.
  89. /// </summary>
  90. public bool UseBackup { get; set; }
  91. /// <summary>
  92. /// If false then physical objects are disabled, though collisions will continue as normal.
  93. /// </summary>
  94. public bool PhysicsEnabled { get; set; }
  95. /// <summary>
  96. /// If false then scripts are not enabled on the smiulator
  97. /// </summary>
  98. public bool ScriptsEnabled
  99. {
  100. get { return m_scripts_enabled; }
  101. set
  102. {
  103. if (m_scripts_enabled != value)
  104. {
  105. if (!value)
  106. {
  107. m_log.Info("Stopping all Scripts in Scene");
  108. EntityBase[] entities = Entities.GetEntities();
  109. foreach (EntityBase ent in entities)
  110. {
  111. if (ent is SceneObjectGroup)
  112. ((SceneObjectGroup)ent).RemoveScriptInstances(false);
  113. }
  114. }
  115. else
  116. {
  117. m_log.Info("Starting all Scripts in Scene");
  118. EntityBase[] entities = Entities.GetEntities();
  119. foreach (EntityBase ent in entities)
  120. {
  121. if (ent is SceneObjectGroup)
  122. {
  123. SceneObjectGroup sog = (SceneObjectGroup)ent;
  124. sog.CreateScriptInstances(0, false, DefaultScriptEngine, 0);
  125. sog.ResumeScripts();
  126. }
  127. }
  128. }
  129. m_scripts_enabled = value;
  130. }
  131. }
  132. }
  133. private bool m_scripts_enabled;
  134. public SynchronizeSceneHandler SynchronizeScene;
  135. /// <summary>
  136. /// Used to prevent simultaneous calls to code that adds and removes agents.
  137. /// </summary>
  138. private object m_removeClientLock = new object();
  139. /// <summary>
  140. /// Statistical information for this scene.
  141. /// </summary>
  142. public SimStatsReporter StatsReporter { get; private set; }
  143. public List<Border> NorthBorders = new List<Border>();
  144. public List<Border> EastBorders = new List<Border>();
  145. public List<Border> SouthBorders = new List<Border>();
  146. public List<Border> WestBorders = new List<Border>();
  147. /// <summary>
  148. /// Controls whether physics can be applied to prims. Even if false, prims still have entries in a
  149. /// PhysicsScene in order to perform collision detection
  150. /// </summary>
  151. public bool PhysicalPrims { get; private set; }
  152. /// <summary>
  153. /// Controls whether prims can be collided with.
  154. /// </summary>
  155. /// <remarks>
  156. /// If this is set to false then prims cannot be subject to physics either.
  157. /// </summary>
  158. public bool CollidablePrims { get; private set; }
  159. /// <summary>
  160. /// Minimum value of the size of a non-physical prim in each axis
  161. /// </summary>
  162. public float m_minNonphys = 0.001f;
  163. /// <summary>
  164. /// Maximum value of the size of a non-physical prim in each axis
  165. /// </summary>
  166. public float m_maxNonphys = 256;
  167. /// <summary>
  168. /// Minimum value of the size of a physical prim in each axis
  169. /// </summary>
  170. public float m_minPhys = 0.01f;
  171. /// <summary>
  172. /// Maximum value of the size of a physical prim in each axis
  173. /// </summary>
  174. public float m_maxPhys = 10;
  175. /// <summary>
  176. /// Max prims an object will hold
  177. /// </summary>
  178. public int m_linksetCapacity = 0;
  179. public bool m_clampPrimSize;
  180. public bool m_trustBinaries;
  181. public bool m_allowScriptCrossings;
  182. public bool m_useFlySlow;
  183. public bool m_useTrashOnDelete = true;
  184. /// <summary>
  185. /// Temporarily setting to trigger appearance resends at 60 second intervals.
  186. /// </summary>
  187. public bool SendPeriodicAppearanceUpdates { get; set; }
  188. protected float m_defaultDrawDistance = 255.0f;
  189. public float DefaultDrawDistance
  190. {
  191. get { return m_defaultDrawDistance; }
  192. }
  193. private List<string> m_AllowedViewers = new List<string>();
  194. private List<string> m_BannedViewers = new List<string>();
  195. // TODO: need to figure out how allow client agents but deny
  196. // root agents when ACL denies access to root agent
  197. public bool m_strictAccessControl = true;
  198. public int MaxUndoCount { get; set; }
  199. public bool SeeIntoRegion { get; set; }
  200. // Using this for RegionReady module to prevent LoginsDisabled from changing under our feet;
  201. public bool LoginLock = false;
  202. public bool StartDisabled = false;
  203. public bool LoadingPrims;
  204. public IXfer XferManager;
  205. // the minimum time that must elapse before a changed object will be considered for persisted
  206. public long m_dontPersistBefore = DEFAULT_MIN_TIME_FOR_PERSISTENCE * 10000000L;
  207. // the maximum time that must elapse before a changed object will be considered for persisted
  208. public long m_persistAfter = DEFAULT_MAX_TIME_FOR_PERSISTENCE * 10000000L;
  209. protected int m_splitRegionID;
  210. protected Timer m_restartWaitTimer = new Timer();
  211. protected List<RegionInfo> m_regionRestartNotifyList = new List<RegionInfo>();
  212. protected List<RegionInfo> m_neighbours = new List<RegionInfo>();
  213. protected string m_simulatorVersion = "OpenSimulator Server";
  214. protected AgentCircuitManager m_authenticateHandler;
  215. protected SceneCommunicationService m_sceneGridService;
  216. protected ISimulationDataService m_SimulationDataService;
  217. protected IEstateDataService m_EstateDataService;
  218. protected IAssetService m_AssetService;
  219. protected IAuthorizationService m_AuthorizationService;
  220. protected IInventoryService m_InventoryService;
  221. protected IGridService m_GridService;
  222. protected ILibraryService m_LibraryService;
  223. protected ISimulationService m_simulationService;
  224. protected IAuthenticationService m_AuthenticationService;
  225. protected IPresenceService m_PresenceService;
  226. protected IUserAccountService m_UserAccountService;
  227. protected IAvatarService m_AvatarService;
  228. protected IGridUserService m_GridUserService;
  229. protected IXMLRPC m_xmlrpcModule;
  230. protected IWorldComm m_worldCommModule;
  231. protected IAvatarFactoryModule m_AvatarFactory;
  232. protected IConfigSource m_config;
  233. protected IRegionSerialiserModule m_serialiser;
  234. protected IDialogModule m_dialogModule;
  235. protected ICapabilitiesModule m_capsModule;
  236. protected IGroupsModule m_groupsModule;
  237. private Dictionary<string, string> m_extraSettings;
  238. /// <summary>
  239. /// Current scene frame number
  240. /// </summary>
  241. public uint Frame
  242. {
  243. get;
  244. protected set;
  245. }
  246. /// <summary>
  247. /// Current maintenance run number
  248. /// </summary>
  249. public uint MaintenanceRun { get; private set; }
  250. /// <summary>
  251. /// The minimum length of time in seconds that will be taken for a scene frame. If the frame takes less time then we
  252. /// will sleep for the remaining period.
  253. /// </summary>
  254. /// <remarks>
  255. /// One can tweak this number to experiment. One current effect of reducing it is to make avatar animations
  256. /// occur too quickly (viewer 1) or with even more slide (viewer 2).
  257. /// </remarks>
  258. public float MinFrameTime { get; private set; }
  259. /// <summary>
  260. /// The minimum length of time in seconds that will be taken for a maintenance run.
  261. /// </summary>
  262. public float MinMaintenanceTime { get; private set; }
  263. private int m_update_physics = 1;
  264. private int m_update_entitymovement = 1;
  265. private int m_update_objects = 1;
  266. private int m_update_temp_cleaning = 1000;
  267. private int m_update_presences = 1; // Update scene presence movements
  268. private int m_update_events = 1;
  269. private int m_update_backup = 200;
  270. private int m_update_terrain = 50;
  271. // private int m_update_land = 1;
  272. private int m_update_coarse_locations = 50;
  273. private int agentMS;
  274. private int frameMS;
  275. private int physicsMS2;
  276. private int physicsMS;
  277. private int otherMS;
  278. private int tempOnRezMS;
  279. private int eventMS;
  280. private int backupMS;
  281. private int terrainMS;
  282. private int landMS;
  283. private int spareMS;
  284. /// <summary>
  285. /// Tick at which the last frame was processed.
  286. /// </summary>
  287. private int m_lastFrameTick;
  288. /// <summary>
  289. /// Tick at which the last maintenance run occurred.
  290. /// </summary>
  291. private int m_lastMaintenanceTick;
  292. /// <summary>
  293. /// Signals whether temporary objects are currently being cleaned up. Needed because this is launched
  294. /// asynchronously from the update loop.
  295. /// </summary>
  296. private bool m_cleaningTemps = false;
  297. // private Object m_heartbeatLock = new Object();
  298. // TODO: Possibly stop other classes being able to manipulate this directly.
  299. private SceneGraph m_sceneGraph;
  300. private volatile int m_bordersLocked;
  301. private readonly Timer m_restartTimer = new Timer(15000); // Wait before firing
  302. private volatile bool m_backingup;
  303. private Dictionary<UUID, ReturnInfo> m_returns = new Dictionary<UUID, ReturnInfo>();
  304. private Dictionary<UUID, SceneObjectGroup> m_groupsWithTargets = new Dictionary<UUID, SceneObjectGroup>();
  305. private string m_defaultScriptEngine;
  306. /// <summary>
  307. /// Tick at which the last login occurred.
  308. /// </summary>
  309. private int m_LastLogin;
  310. /// <summary>
  311. /// Thread that runs the scene loop.
  312. /// </summary>
  313. private Thread m_heartbeatThread;
  314. /// <summary>
  315. /// True if these scene is in the process of shutting down or is shutdown.
  316. /// </summary>
  317. public bool ShuttingDown
  318. {
  319. get { return m_shuttingDown; }
  320. }
  321. private volatile bool m_shuttingDown;
  322. /// <summary>
  323. /// Is the scene active?
  324. /// </summary>
  325. /// <remarks>
  326. /// If false, maintenance and update loops are not being run. Updates can still be triggered manually if
  327. /// the scene is not active.
  328. /// </remarks>
  329. public bool Active
  330. {
  331. get { return m_active; }
  332. set
  333. {
  334. if (value)
  335. {
  336. if (!m_active)
  337. Start(false);
  338. }
  339. else
  340. {
  341. // This appears assymetric with Start() above but is not - setting m_active = false stops the loops
  342. // XXX: Possibly this should be in an explicit Stop() method for symmetry.
  343. m_active = false;
  344. }
  345. }
  346. }
  347. private volatile bool m_active;
  348. // private int m_lastUpdate;
  349. // private bool m_firstHeartbeat = true;
  350. private UpdatePrioritizationSchemes m_priorityScheme = UpdatePrioritizationSchemes.Time;
  351. private bool m_reprioritizationEnabled = true;
  352. private double m_reprioritizationInterval = 5000.0;
  353. private double m_rootReprioritizationDistance = 10.0;
  354. private double m_childReprioritizationDistance = 20.0;
  355. private Timer m_mapGenerationTimer = new Timer();
  356. private bool m_generateMaptiles;
  357. #endregion Fields
  358. #region Properties
  359. /* Used by the loadbalancer plugin on GForge */
  360. public int SplitRegionID
  361. {
  362. get { return m_splitRegionID; }
  363. set { m_splitRegionID = value; }
  364. }
  365. public bool BordersLocked
  366. {
  367. get { return m_bordersLocked == 1; }
  368. set
  369. {
  370. if (value == true)
  371. m_bordersLocked = 1;
  372. else
  373. m_bordersLocked = 0;
  374. }
  375. }
  376. public new float TimeDilation
  377. {
  378. get { return m_sceneGraph.PhysicsScene.TimeDilation; }
  379. }
  380. public SceneCommunicationService SceneGridService
  381. {
  382. get { return m_sceneGridService; }
  383. }
  384. public ISimulationDataService SimulationDataService
  385. {
  386. get
  387. {
  388. if (m_SimulationDataService == null)
  389. {
  390. m_SimulationDataService = RequestModuleInterface<ISimulationDataService>();
  391. if (m_SimulationDataService == null)
  392. {
  393. throw new Exception("No ISimulationDataService available.");
  394. }
  395. }
  396. return m_SimulationDataService;
  397. }
  398. }
  399. public IEstateDataService EstateDataService
  400. {
  401. get
  402. {
  403. if (m_EstateDataService == null)
  404. {
  405. m_EstateDataService = RequestModuleInterface<IEstateDataService>();
  406. if (m_EstateDataService == null)
  407. {
  408. throw new Exception("No IEstateDataService available.");
  409. }
  410. }
  411. return m_EstateDataService;
  412. }
  413. }
  414. public IAssetService AssetService
  415. {
  416. get
  417. {
  418. if (m_AssetService == null)
  419. {
  420. m_AssetService = RequestModuleInterface<IAssetService>();
  421. if (m_AssetService == null)
  422. {
  423. throw new Exception("No IAssetService available.");
  424. }
  425. }
  426. return m_AssetService;
  427. }
  428. }
  429. public IAuthorizationService AuthorizationService
  430. {
  431. get
  432. {
  433. if (m_AuthorizationService == null)
  434. {
  435. m_AuthorizationService = RequestModuleInterface<IAuthorizationService>();
  436. //if (m_AuthorizationService == null)
  437. //{
  438. // // don't throw an exception if no authorization service is set for the time being
  439. // m_log.InfoFormat("[SCENE]: No Authorization service is configured");
  440. //}
  441. }
  442. return m_AuthorizationService;
  443. }
  444. }
  445. public IInventoryService InventoryService
  446. {
  447. get
  448. {
  449. if (m_InventoryService == null)
  450. {
  451. m_InventoryService = RequestModuleInterface<IInventoryService>();
  452. if (m_InventoryService == null)
  453. {
  454. throw new Exception("No IInventoryService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  455. }
  456. }
  457. return m_InventoryService;
  458. }
  459. }
  460. public IGridService GridService
  461. {
  462. get
  463. {
  464. if (m_GridService == null)
  465. {
  466. m_GridService = RequestModuleInterface<IGridService>();
  467. if (m_GridService == null)
  468. {
  469. throw new Exception("No IGridService available. This could happen if the config_include folder doesn't exist or if the OpenSim.ini [Architecture] section isn't set. Please also check that you have the correct version of your inventory service dll. Sometimes old versions of this dll will still exist. Do a clean checkout and re-create the opensim.ini from the opensim.ini.example.");
  470. }
  471. }
  472. return m_GridService;
  473. }
  474. }
  475. public ILibraryService LibraryService
  476. {
  477. get
  478. {
  479. if (m_LibraryService == null)
  480. m_LibraryService = RequestModuleInterface<ILibraryService>();
  481. return m_LibraryService;
  482. }
  483. }
  484. public ISimulationService SimulationService
  485. {
  486. get
  487. {
  488. if (m_simulationService == null)
  489. m_simulationService = RequestModuleInterface<ISimulationService>();
  490. return m_simulationService;
  491. }
  492. }
  493. public IAuthenticationService AuthenticationService
  494. {
  495. get
  496. {
  497. if (m_AuthenticationService == null)
  498. m_AuthenticationService = RequestModuleInterface<IAuthenticationService>();
  499. return m_AuthenticationService;
  500. }
  501. }
  502. public IPresenceService PresenceService
  503. {
  504. get
  505. {
  506. if (m_PresenceService == null)
  507. m_PresenceService = RequestModuleInterface<IPresenceService>();
  508. return m_PresenceService;
  509. }
  510. }
  511. public IUserAccountService UserAccountService
  512. {
  513. get
  514. {
  515. if (m_UserAccountService == null)
  516. m_UserAccountService = RequestModuleInterface<IUserAccountService>();
  517. return m_UserAccountService;
  518. }
  519. }
  520. public IAvatarService AvatarService
  521. {
  522. get
  523. {
  524. if (m_AvatarService == null)
  525. m_AvatarService = RequestModuleInterface<IAvatarService>();
  526. return m_AvatarService;
  527. }
  528. }
  529. public IGridUserService GridUserService
  530. {
  531. get
  532. {
  533. if (m_GridUserService == null)
  534. m_GridUserService = RequestModuleInterface<IGridUserService>();
  535. return m_GridUserService;
  536. }
  537. }
  538. public IAttachmentsModule AttachmentsModule { get; set; }
  539. public IEntityTransferModule EntityTransferModule { get; private set; }
  540. public IAgentAssetTransactions AgentTransactionsModule { get; private set; }
  541. public IUserManagement UserManagementModule { get; private set; }
  542. public IAvatarFactoryModule AvatarFactory
  543. {
  544. get { return m_AvatarFactory; }
  545. }
  546. public ICapabilitiesModule CapsModule
  547. {
  548. get { return m_capsModule; }
  549. }
  550. public int MonitorFrameTime { get { return frameMS; } }
  551. public int MonitorPhysicsUpdateTime { get { return physicsMS; } }
  552. public int MonitorPhysicsSyncTime { get { return physicsMS2; } }
  553. public int MonitorOtherTime { get { return otherMS; } }
  554. public int MonitorTempOnRezTime { get { return tempOnRezMS; } }
  555. public int MonitorEventTime { get { return eventMS; } } // This may need to be divided into each event?
  556. public int MonitorBackupTime { get { return backupMS; } }
  557. public int MonitorTerrainTime { get { return terrainMS; } }
  558. public int MonitorLandTime { get { return landMS; } }
  559. public int MonitorLastFrameTick { get { return m_lastFrameTick; } }
  560. public UpdatePrioritizationSchemes UpdatePrioritizationScheme { get { return m_priorityScheme; } }
  561. public bool IsReprioritizationEnabled { get { return m_reprioritizationEnabled; } }
  562. public double ReprioritizationInterval { get { return m_reprioritizationInterval; } }
  563. public double RootReprioritizationDistance { get { return m_rootReprioritizationDistance; } }
  564. public double ChildReprioritizationDistance { get { return m_childReprioritizationDistance; } }
  565. public AgentCircuitManager AuthenticateHandler
  566. {
  567. get { return m_authenticateHandler; }
  568. }
  569. // an instance to the physics plugin's Scene object.
  570. public PhysicsScene PhysicsScene
  571. {
  572. get { return m_sceneGraph.PhysicsScene; }
  573. set
  574. {
  575. // If we're not doing the initial set
  576. // Then we've got to remove the previous
  577. // event handler
  578. if (PhysicsScene != null && PhysicsScene.SupportsNINJAJoints)
  579. {
  580. PhysicsScene.OnJointMoved -= jointMoved;
  581. PhysicsScene.OnJointDeactivated -= jointDeactivated;
  582. PhysicsScene.OnJointErrorMessage -= jointErrorMessage;
  583. }
  584. m_sceneGraph.PhysicsScene = value;
  585. if (PhysicsScene != null && m_sceneGraph.PhysicsScene.SupportsNINJAJoints)
  586. {
  587. // register event handlers to respond to joint movement/deactivation
  588. PhysicsScene.OnJointMoved += jointMoved;
  589. PhysicsScene.OnJointDeactivated += jointDeactivated;
  590. PhysicsScene.OnJointErrorMessage += jointErrorMessage;
  591. }
  592. }
  593. }
  594. public string DefaultScriptEngine
  595. {
  596. get { return m_defaultScriptEngine; }
  597. }
  598. public EntityManager Entities
  599. {
  600. get { return m_sceneGraph.Entities; }
  601. }
  602. // used in sequence see: SpawnPoint()
  603. private int m_SpawnPoint;
  604. // can be closest/random/sequence
  605. public string SpawnPointRouting
  606. {
  607. get; private set;
  608. }
  609. // allow landmarks to pass
  610. public bool TelehubAllowLandmarks
  611. {
  612. get; private set;
  613. }
  614. #endregion Properties
  615. #region Constructors
  616. public Scene(RegionInfo regInfo, AgentCircuitManager authen,
  617. SceneCommunicationService sceneGridService,
  618. ISimulationDataService simDataService, IEstateDataService estateDataService,
  619. IConfigSource config, string simulatorVersion)
  620. : this(regInfo)
  621. {
  622. m_config = config;
  623. MinFrameTime = 0.089f;
  624. MinMaintenanceTime = 1;
  625. Random random = new Random();
  626. m_lastAllocatedLocalId = (uint)(random.NextDouble() * (double)(uint.MaxValue / 2)) + (uint)(uint.MaxValue / 4);
  627. m_authenticateHandler = authen;
  628. m_sceneGridService = sceneGridService;
  629. m_SimulationDataService = simDataService;
  630. m_EstateDataService = estateDataService;
  631. m_regionHandle = RegionInfo.RegionHandle;
  632. m_asyncSceneObjectDeleter = new AsyncSceneObjectGroupDeleter(this);
  633. m_asyncSceneObjectDeleter.Enabled = true;
  634. m_asyncInventorySender = new AsyncInventorySender(this);
  635. #region Region Settings
  636. // Load region settings
  637. // LoadRegionSettings creates new region settings in persistence if they don't already exist for this region.
  638. // However, in this case, the default textures are not set in memory properly, so we need to do it here and
  639. // resave.
  640. // FIXME: It shouldn't be up to the database plugins to create this data - we should do it when a new
  641. // region is set up and avoid these gyrations.
  642. RegionSettings rs = simDataService.LoadRegionSettings(RegionInfo.RegionID);
  643. m_extraSettings = simDataService.GetExtra(RegionInfo.RegionID);
  644. bool updatedTerrainTextures = false;
  645. if (rs.TerrainTexture1 == UUID.Zero)
  646. {
  647. rs.TerrainTexture1 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_1;
  648. updatedTerrainTextures = true;
  649. }
  650. if (rs.TerrainTexture2 == UUID.Zero)
  651. {
  652. rs.TerrainTexture2 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_2;
  653. updatedTerrainTextures = true;
  654. }
  655. if (rs.TerrainTexture3 == UUID.Zero)
  656. {
  657. rs.TerrainTexture3 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_3;
  658. updatedTerrainTextures = true;
  659. }
  660. if (rs.TerrainTexture4 == UUID.Zero)
  661. {
  662. rs.TerrainTexture4 = RegionSettings.DEFAULT_TERRAIN_TEXTURE_4;
  663. updatedTerrainTextures = true;
  664. }
  665. if (updatedTerrainTextures)
  666. rs.Save();
  667. RegionInfo.RegionSettings = rs;
  668. if (estateDataService != null)
  669. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  670. #endregion Region Settings
  671. //Bind Storage Manager functions to some land manager functions for this scene
  672. EventManager.OnLandObjectAdded +=
  673. new EventManager.LandObjectAdded(simDataService.StoreLandObject);
  674. EventManager.OnLandObjectRemoved +=
  675. new EventManager.LandObjectRemoved(simDataService.RemoveLandObject);
  676. m_sceneGraph = new SceneGraph(this);
  677. // If the scene graph has an Unrecoverable error, restart this sim.
  678. // Currently the only thing that causes it to happen is two kinds of specific
  679. // Physics based crashes.
  680. //
  681. // Out of memory
  682. // Operating system has killed the plugin
  683. m_sceneGraph.UnRecoverableError
  684. += () =>
  685. {
  686. m_log.ErrorFormat("[SCENE]: Restarting region {0} due to unrecoverable physics crash", Name);
  687. RestartNow();
  688. };
  689. RegisterDefaultSceneEvents();
  690. // XXX: Don't set the public property since we don't want to activate here. This needs to be handled
  691. // better in the future.
  692. m_scripts_enabled = !RegionInfo.RegionSettings.DisableScripts;
  693. PhysicsEnabled = !RegionInfo.RegionSettings.DisablePhysics;
  694. m_simulatorVersion = simulatorVersion + " (" + Util.GetRuntimeInformation() + ")";
  695. #region Region Config
  696. // Region config overrides global config
  697. //
  698. if (m_config.Configs["Startup"] != null)
  699. {
  700. IConfig startupConfig = m_config.Configs["Startup"];
  701. StartDisabled = startupConfig.GetBoolean("StartDisabled", false);
  702. m_defaultDrawDistance = startupConfig.GetFloat("DefaultDrawDistance", m_defaultDrawDistance);
  703. UseBackup = startupConfig.GetBoolean("UseSceneBackup", UseBackup);
  704. if (!UseBackup)
  705. m_log.InfoFormat("[SCENE]: Backup has been disabled for {0}", RegionInfo.RegionName);
  706. //Animation states
  707. m_useFlySlow = startupConfig.GetBoolean("enableflyslow", false);
  708. SeeIntoRegion = startupConfig.GetBoolean("see_into_region", true);
  709. MaxUndoCount = startupConfig.GetInt("MaxPrimUndos", 20);
  710. PhysicalPrims = startupConfig.GetBoolean("physical_prim", PhysicalPrims);
  711. CollidablePrims = startupConfig.GetBoolean("collidable_prim", CollidablePrims);
  712. m_minNonphys = startupConfig.GetFloat("NonPhysicalPrimMin", m_minNonphys);
  713. if (RegionInfo.NonphysPrimMin > 0)
  714. {
  715. m_minNonphys = RegionInfo.NonphysPrimMin;
  716. }
  717. m_maxNonphys = startupConfig.GetFloat("NonPhysicalPrimMax", m_maxNonphys);
  718. if (RegionInfo.NonphysPrimMax > 0)
  719. {
  720. m_maxNonphys = RegionInfo.NonphysPrimMax;
  721. }
  722. m_minPhys = startupConfig.GetFloat("PhysicalPrimMin", m_minPhys);
  723. if (RegionInfo.PhysPrimMin > 0)
  724. {
  725. m_minPhys = RegionInfo.PhysPrimMin;
  726. }
  727. m_maxPhys = startupConfig.GetFloat("PhysicalPrimMax", m_maxPhys);
  728. if (RegionInfo.PhysPrimMax > 0)
  729. {
  730. m_maxPhys = RegionInfo.PhysPrimMax;
  731. }
  732. // Here, if clamping is requested in either global or
  733. // local config, it will be used
  734. //
  735. m_clampPrimSize = startupConfig.GetBoolean("ClampPrimSize", m_clampPrimSize);
  736. if (RegionInfo.ClampPrimSize)
  737. {
  738. m_clampPrimSize = true;
  739. }
  740. m_linksetCapacity = startupConfig.GetInt("LinksetPrims", m_linksetCapacity);
  741. if (RegionInfo.LinksetCapacity > 0)
  742. {
  743. m_linksetCapacity = RegionInfo.LinksetCapacity;
  744. }
  745. m_useTrashOnDelete = startupConfig.GetBoolean("UseTrashOnDelete", m_useTrashOnDelete);
  746. m_trustBinaries = startupConfig.GetBoolean("TrustBinaries", m_trustBinaries);
  747. m_allowScriptCrossings = startupConfig.GetBoolean("AllowScriptCrossing", m_allowScriptCrossings);
  748. m_dontPersistBefore =
  749. startupConfig.GetLong("MinimumTimeBeforePersistenceConsidered", DEFAULT_MIN_TIME_FOR_PERSISTENCE);
  750. m_dontPersistBefore *= 10000000;
  751. m_persistAfter =
  752. startupConfig.GetLong("MaximumTimeBeforePersistenceConsidered", DEFAULT_MAX_TIME_FOR_PERSISTENCE);
  753. m_persistAfter *= 10000000;
  754. m_defaultScriptEngine = startupConfig.GetString("DefaultScriptEngine", "XEngine");
  755. SpawnPointRouting = startupConfig.GetString("SpawnPointRouting", "closest");
  756. TelehubAllowLandmarks = startupConfig.GetBoolean("TelehubAllowLandmark", false);
  757. m_strictAccessControl = startupConfig.GetBoolean("StrictAccessControl", m_strictAccessControl);
  758. string[] possibleMapConfigSections = new string[] { "Map", "Startup" };
  759. m_generateMaptiles
  760. = Util.GetConfigVarFromSections<bool>(config, "GenerateMaptiles", possibleMapConfigSections, true);
  761. if (m_generateMaptiles)
  762. {
  763. int maptileRefresh = startupConfig.GetInt("MaptileRefresh", 0);
  764. if (maptileRefresh != 0)
  765. {
  766. m_mapGenerationTimer.Interval = maptileRefresh * 1000;
  767. m_mapGenerationTimer.Elapsed += RegenerateMaptileAndReregister;
  768. m_mapGenerationTimer.AutoReset = true;
  769. m_mapGenerationTimer.Start();
  770. }
  771. }
  772. else
  773. {
  774. string tile
  775. = Util.GetConfigVarFromSections<string>(
  776. config, "MaptileStaticUUID", possibleMapConfigSections, UUID.Zero.ToString());
  777. UUID tileID;
  778. if (tile != UUID.Zero.ToString() && UUID.TryParse(tile, out tileID))
  779. {
  780. RegionInfo.RegionSettings.TerrainImageID = tileID;
  781. }
  782. else
  783. {
  784. RegionInfo.RegionSettings.TerrainImageID = RegionInfo.MaptileStaticUUID;
  785. m_log.InfoFormat("[SCENE]: Region {0}, maptile set to {1}", RegionInfo.RegionName, RegionInfo.MaptileStaticUUID.ToString());
  786. }
  787. }
  788. string[] possibleAccessControlConfigSections = new string[] { "AccessControl", "Startup" };
  789. string grant
  790. = Util.GetConfigVarFromSections<string>(
  791. config, "AllowedClients", possibleAccessControlConfigSections, "");
  792. if (grant.Length > 0)
  793. {
  794. foreach (string viewer in grant.Split('|'))
  795. {
  796. m_AllowedViewers.Add(viewer.Trim().ToLower());
  797. }
  798. }
  799. grant
  800. = Util.GetConfigVarFromSections<string>(
  801. config, "BannedClients", possibleAccessControlConfigSections, "");
  802. if (grant.Length > 0)
  803. {
  804. foreach (string viewer in grant.Split('|'))
  805. {
  806. m_BannedViewers.Add(viewer.Trim().ToLower());
  807. }
  808. }
  809. MinFrameTime = startupConfig.GetFloat( "MinFrameTime", MinFrameTime);
  810. m_update_backup = startupConfig.GetInt( "UpdateStorageEveryNFrames", m_update_backup);
  811. m_update_coarse_locations = startupConfig.GetInt( "UpdateCoarseLocationsEveryNFrames", m_update_coarse_locations);
  812. m_update_entitymovement = startupConfig.GetInt( "UpdateEntityMovementEveryNFrames", m_update_entitymovement);
  813. m_update_events = startupConfig.GetInt( "UpdateEventsEveryNFrames", m_update_events);
  814. m_update_objects = startupConfig.GetInt( "UpdateObjectsEveryNFrames", m_update_objects);
  815. m_update_physics = startupConfig.GetInt( "UpdatePhysicsEveryNFrames", m_update_physics);
  816. m_update_presences = startupConfig.GetInt( "UpdateAgentsEveryNFrames", m_update_presences);
  817. m_update_terrain = startupConfig.GetInt( "UpdateTerrainEveryNFrames", m_update_terrain);
  818. m_update_temp_cleaning = startupConfig.GetInt( "UpdateTempCleaningEveryNFrames", m_update_temp_cleaning);
  819. }
  820. // FIXME: Ultimately this should be in a module.
  821. SendPeriodicAppearanceUpdates = true;
  822. IConfig appearanceConfig = m_config.Configs["Appearance"];
  823. if (appearanceConfig != null)
  824. {
  825. SendPeriodicAppearanceUpdates
  826. = appearanceConfig.GetBoolean("ResendAppearanceUpdates", SendPeriodicAppearanceUpdates);
  827. }
  828. #endregion Region Config
  829. #region Interest Management
  830. IConfig interestConfig = m_config.Configs["InterestManagement"];
  831. if (interestConfig != null)
  832. {
  833. string update_prioritization_scheme = interestConfig.GetString("UpdatePrioritizationScheme", "Time").Trim().ToLower();
  834. try
  835. {
  836. m_priorityScheme = (UpdatePrioritizationSchemes)Enum.Parse(typeof(UpdatePrioritizationSchemes), update_prioritization_scheme, true);
  837. }
  838. catch (Exception)
  839. {
  840. m_log.Warn("[PRIORITIZER]: UpdatePrioritizationScheme was not recognized, setting to default prioritizer Time");
  841. m_priorityScheme = UpdatePrioritizationSchemes.Time;
  842. }
  843. m_reprioritizationEnabled = interestConfig.GetBoolean("ReprioritizationEnabled", true);
  844. m_reprioritizationInterval = interestConfig.GetDouble("ReprioritizationInterval", 5000.0);
  845. m_rootReprioritizationDistance = interestConfig.GetDouble("RootReprioritizationDistance", 10.0);
  846. m_childReprioritizationDistance = interestConfig.GetDouble("ChildReprioritizationDistance", 20.0);
  847. }
  848. m_log.DebugFormat("[SCENE]: Using the {0} prioritization scheme", m_priorityScheme);
  849. #endregion Interest Management
  850. StatsReporter = new SimStatsReporter(this);
  851. StatsReporter.OnSendStatsResult += SendSimStatsPackets;
  852. StatsReporter.OnStatsIncorrect += m_sceneGraph.RecalculateStats;
  853. }
  854. public Scene(RegionInfo regInfo) : base(regInfo)
  855. {
  856. PhysicalPrims = true;
  857. CollidablePrims = true;
  858. PhysicsEnabled = true;
  859. PeriodicBackup = true;
  860. UseBackup = true;
  861. BordersLocked = true;
  862. Border northBorder = new Border();
  863. northBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  864. northBorder.CrossDirection = Cardinals.N;
  865. NorthBorders.Add(northBorder);
  866. Border southBorder = new Border();
  867. southBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue,0); //--->
  868. southBorder.CrossDirection = Cardinals.S;
  869. SouthBorders.Add(southBorder);
  870. Border eastBorder = new Border();
  871. eastBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue, (int)Constants.RegionSize); //<---
  872. eastBorder.CrossDirection = Cardinals.E;
  873. EastBorders.Add(eastBorder);
  874. Border westBorder = new Border();
  875. westBorder.BorderLine = new Vector3(float.MinValue, float.MaxValue,0); //--->
  876. westBorder.CrossDirection = Cardinals.W;
  877. WestBorders.Add(westBorder);
  878. BordersLocked = false;
  879. m_eventManager = new EventManager();
  880. m_permissions = new ScenePermissions(this);
  881. }
  882. #endregion
  883. #region Startup / Close Methods
  884. /// <value>
  885. /// The scene graph for this scene
  886. /// </value>
  887. /// TODO: Possibly stop other classes being able to manipulate this directly.
  888. public SceneGraph SceneGraph
  889. {
  890. get { return m_sceneGraph; }
  891. }
  892. protected virtual void RegisterDefaultSceneEvents()
  893. {
  894. IDialogModule dm = RequestModuleInterface<IDialogModule>();
  895. if (dm != null)
  896. m_eventManager.OnPermissionError += dm.SendAlertToUser;
  897. m_eventManager.OnSignificantClientMovement += HandleOnSignificantClientMovement;
  898. }
  899. public override string GetSimulatorVersion()
  900. {
  901. return m_simulatorVersion;
  902. }
  903. /// <summary>
  904. /// Process the fact that a neighbouring region has come up.
  905. /// </summary>
  906. /// <remarks>
  907. /// We only add it to the neighbor list if it's within 1 region from here.
  908. /// Agents may have draw distance values that cross two regions though, so
  909. /// we add it to the notify list regardless of distance. We'll check
  910. /// the agent's draw distance before notifying them though.
  911. /// </remarks>
  912. /// <param name="otherRegion">RegionInfo handle for the new region.</param>
  913. /// <returns>True after all operations complete, throws exceptions otherwise.</returns>
  914. public override void OtherRegionUp(GridRegion otherRegion)
  915. {
  916. uint xcell = (uint)((int)otherRegion.RegionLocX / (int)Constants.RegionSize);
  917. uint ycell = (uint)((int)otherRegion.RegionLocY / (int)Constants.RegionSize);
  918. //m_log.InfoFormat("[SCENE]: (on region {0}): Region {1} up in coords {2}-{3}",
  919. // RegionInfo.RegionName, otherRegion.RegionName, xcell, ycell);
  920. if (RegionInfo.RegionHandle != otherRegion.RegionHandle)
  921. {
  922. // If these are cast to INT because long + negative values + abs returns invalid data
  923. int resultX = Math.Abs((int)xcell - (int)RegionInfo.RegionLocX);
  924. int resultY = Math.Abs((int)ycell - (int)RegionInfo.RegionLocY);
  925. if (resultX <= 1 && resultY <= 1)
  926. {
  927. // Let the grid service module know, so this can be cached
  928. m_eventManager.TriggerOnRegionUp(otherRegion);
  929. try
  930. {
  931. ForEachRootScenePresence(delegate(ScenePresence agent)
  932. {
  933. //agent.ControllingClient.new
  934. //this.CommsManager.InterRegion.InformRegionOfChildAgent(otherRegion.RegionHandle, agent.ControllingClient.RequestClientInfo());
  935. List<ulong> old = new List<ulong>();
  936. old.Add(otherRegion.RegionHandle);
  937. agent.DropOldNeighbours(old);
  938. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  939. EntityTransferModule.EnableChildAgent(agent, otherRegion);
  940. });
  941. }
  942. catch (NullReferenceException)
  943. {
  944. // This means that we're not booted up completely yet.
  945. // This shouldn't happen too often anymore.
  946. m_log.Error("[SCENE]: Couldn't inform client of regionup because we got a null reference exception");
  947. }
  948. }
  949. else
  950. {
  951. m_log.InfoFormat(
  952. "[SCENE]: Got notice about far away Region: {0} at ({1}, {2})",
  953. otherRegion.RegionName, otherRegion.RegionLocX, otherRegion.RegionLocY);
  954. }
  955. }
  956. }
  957. public void AddNeighborRegion(RegionInfo region)
  958. {
  959. lock (m_neighbours)
  960. {
  961. if (!CheckNeighborRegion(region))
  962. {
  963. m_neighbours.Add(region);
  964. }
  965. }
  966. }
  967. public bool CheckNeighborRegion(RegionInfo region)
  968. {
  969. bool found = false;
  970. lock (m_neighbours)
  971. {
  972. foreach (RegionInfo reg in m_neighbours)
  973. {
  974. if (reg.RegionHandle == region.RegionHandle)
  975. {
  976. found = true;
  977. break;
  978. }
  979. }
  980. }
  981. return found;
  982. }
  983. /// <summary>
  984. /// Checks whether this region has a neighbour in the given direction.
  985. /// </summary>
  986. /// <param name="car"></param>
  987. /// <param name="fix"></param>
  988. /// <returns>
  989. /// An integer which represents a compass point. N == 1, going clockwise until we reach NW == 8.
  990. /// Returns a positive integer if there is a region in that direction, a negative integer if not.
  991. /// </returns>
  992. public int HaveNeighbor(Cardinals car, ref int[] fix)
  993. {
  994. uint neighbourx = RegionInfo.RegionLocX;
  995. uint neighboury = RegionInfo.RegionLocY;
  996. int dir = (int)car;
  997. if (dir > 1 && dir < 5) //Heading East
  998. neighbourx++;
  999. else if (dir > 5) // Heading West
  1000. neighbourx--;
  1001. if (dir < 3 || dir == 8) // Heading North
  1002. neighboury++;
  1003. else if (dir > 3 && dir < 7) // Heading Sout
  1004. neighboury--;
  1005. int x = (int)(neighbourx * Constants.RegionSize);
  1006. int y = (int)(neighboury * Constants.RegionSize);
  1007. GridRegion neighbourRegion = GridService.GetRegionByPosition(RegionInfo.ScopeID, x, y);
  1008. if (neighbourRegion == null)
  1009. {
  1010. fix[0] = (int)(RegionInfo.RegionLocX - neighbourx);
  1011. fix[1] = (int)(RegionInfo.RegionLocY - neighboury);
  1012. return dir * (-1);
  1013. }
  1014. else
  1015. return dir;
  1016. }
  1017. // Alias IncomingHelloNeighbour OtherRegionUp, for now
  1018. public GridRegion IncomingHelloNeighbour(RegionInfo neighbour)
  1019. {
  1020. OtherRegionUp(new GridRegion(neighbour));
  1021. return new GridRegion(RegionInfo);
  1022. }
  1023. // This causes the region to restart immediatley.
  1024. public void RestartNow()
  1025. {
  1026. IConfig startupConfig = m_config.Configs["Startup"];
  1027. if (startupConfig != null)
  1028. {
  1029. if (startupConfig.GetBoolean("InworldRestartShutsDown", false))
  1030. {
  1031. MainConsole.Instance.RunCommand("shutdown");
  1032. return;
  1033. }
  1034. }
  1035. m_log.InfoFormat("[REGION]: Restarting region {0}", Name);
  1036. Close();
  1037. base.Restart();
  1038. }
  1039. // This is a helper function that notifies root agents in this region that a new sim near them has come up
  1040. // This is in the form of a timer because when an instance of OpenSim.exe is started,
  1041. // Even though the sims initialize, they don't listen until 'all of the sims are initialized'
  1042. // If we tell an agent about a sim that's not listening yet, the agent will not be able to connect to it.
  1043. // subsequently the agent will never see the region come back online.
  1044. public void RestartNotifyWaitElapsed(object sender, ElapsedEventArgs e)
  1045. {
  1046. m_restartWaitTimer.Stop();
  1047. lock (m_regionRestartNotifyList)
  1048. {
  1049. foreach (RegionInfo region in m_regionRestartNotifyList)
  1050. {
  1051. GridRegion r = new GridRegion(region);
  1052. try
  1053. {
  1054. ForEachRootScenePresence(delegate(ScenePresence agent)
  1055. {
  1056. if (EntityTransferModule != null && agent.PresenceType != PresenceType.Npc)
  1057. EntityTransferModule.EnableChildAgent(agent, r);
  1058. });
  1059. }
  1060. catch (NullReferenceException)
  1061. {
  1062. // This means that we're not booted up completely yet.
  1063. // This shouldn't happen too often anymore.
  1064. }
  1065. }
  1066. // Reset list to nothing.
  1067. m_regionRestartNotifyList.Clear();
  1068. }
  1069. }
  1070. public int GetInaccurateNeighborCount()
  1071. {
  1072. return m_neighbours.Count;
  1073. }
  1074. // This is the method that shuts down the scene.
  1075. public override void Close()
  1076. {
  1077. if (m_shuttingDown)
  1078. {
  1079. m_log.WarnFormat("[SCENE]: Ignoring close request because already closing {0}", Name);
  1080. return;
  1081. }
  1082. m_log.InfoFormat("[SCENE]: Closing down the single simulator: {0}", RegionInfo.RegionName);
  1083. StatsReporter.Close();
  1084. m_restartTimer.Stop();
  1085. m_restartTimer.Close();
  1086. // Kick all ROOT agents with the message, 'The simulator is going down'
  1087. ForEachScenePresence(delegate(ScenePresence avatar)
  1088. {
  1089. avatar.RemoveNeighbourRegion(RegionInfo.RegionHandle);
  1090. if (!avatar.IsChildAgent)
  1091. avatar.ControllingClient.Kick("The simulator is going down.");
  1092. avatar.ControllingClient.SendShutdownConnectionNotice();
  1093. });
  1094. // Stop updating the scene objects and agents.
  1095. m_shuttingDown = true;
  1096. // Wait here, or the kick messages won't actually get to the agents before the scene terminates.
  1097. // We also need to wait to avoid a race condition with the scene update loop which might not yet
  1098. // have checked ShuttingDown.
  1099. Thread.Sleep(500);
  1100. // Stop all client threads.
  1101. ForEachScenePresence(delegate(ScenePresence avatar) { IncomingCloseAgent(avatar.UUID, false); });
  1102. m_log.Debug("[SCENE]: Persisting changed objects");
  1103. EventManager.TriggerSceneShuttingDown(this);
  1104. Backup(false);
  1105. m_sceneGraph.Close();
  1106. if (!GridService.DeregisterRegion(RegionInfo.RegionID))
  1107. m_log.WarnFormat("[SCENE]: Deregister from grid failed for region {0}", Name);
  1108. base.Close();
  1109. // XEngine currently listens to the EventManager.OnShutdown event to trigger script stop and persistence.
  1110. // Therefore. we must dispose of the PhysicsScene after this to prevent a window where script code can
  1111. // attempt to reference a null or disposed physics scene.
  1112. if (PhysicsScene != null)
  1113. {
  1114. PhysicsScene phys = PhysicsScene;
  1115. // remove the physics engine from both Scene and SceneGraph
  1116. PhysicsScene = null;
  1117. phys.Dispose();
  1118. phys = null;
  1119. }
  1120. }
  1121. public override void Start()
  1122. {
  1123. Start(true);
  1124. }
  1125. /// <summary>
  1126. /// Start the scene
  1127. /// </summary>
  1128. /// <param name='startScripts'>
  1129. /// Start the scripts within the scene.
  1130. /// </param>
  1131. public void Start(bool startScripts)
  1132. {
  1133. m_active = true;
  1134. // m_log.DebugFormat("[SCENE]: Starting Heartbeat timer for {0}", RegionInfo.RegionName);
  1135. //m_heartbeatTimer.Enabled = true;
  1136. //m_heartbeatTimer.Interval = (int)(m_timespan * 1000);
  1137. //m_heartbeatTimer.Elapsed += new ElapsedEventHandler(Heartbeat);
  1138. if (m_heartbeatThread != null)
  1139. {
  1140. m_heartbeatThread.Abort();
  1141. m_heartbeatThread = null;
  1142. }
  1143. // m_lastUpdate = Util.EnvironmentTickCount();
  1144. m_heartbeatThread
  1145. = Watchdog.StartThread(
  1146. Heartbeat, string.Format("Heartbeat ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, false);
  1147. StartScripts();
  1148. }
  1149. /// <summary>
  1150. /// Sets up references to modules required by the scene
  1151. /// </summary>
  1152. public void SetModuleInterfaces()
  1153. {
  1154. m_xmlrpcModule = RequestModuleInterface<IXMLRPC>();
  1155. m_worldCommModule = RequestModuleInterface<IWorldComm>();
  1156. XferManager = RequestModuleInterface<IXfer>();
  1157. m_AvatarFactory = RequestModuleInterface<IAvatarFactoryModule>();
  1158. AttachmentsModule = RequestModuleInterface<IAttachmentsModule>();
  1159. m_serialiser = RequestModuleInterface<IRegionSerialiserModule>();
  1160. m_dialogModule = RequestModuleInterface<IDialogModule>();
  1161. m_capsModule = RequestModuleInterface<ICapabilitiesModule>();
  1162. EntityTransferModule = RequestModuleInterface<IEntityTransferModule>();
  1163. m_groupsModule = RequestModuleInterface<IGroupsModule>();
  1164. AgentTransactionsModule = RequestModuleInterface<IAgentAssetTransactions>();
  1165. UserManagementModule = RequestModuleInterface<IUserManagement>();
  1166. }
  1167. #endregion
  1168. #region Update Methods
  1169. /// <summary>
  1170. /// Activate the various loops necessary to continually update the scene.
  1171. /// </summary>
  1172. private void Heartbeat()
  1173. {
  1174. // if (!Monitor.TryEnter(m_heartbeatLock))
  1175. // {
  1176. // Watchdog.RemoveThread();
  1177. // return;
  1178. // }
  1179. // try
  1180. // {
  1181. m_eventManager.TriggerOnRegionStarted(this);
  1182. // The first frame can take a very long time due to physics actors being added on startup. Therefore,
  1183. // don't turn on the watchdog alarm for this thread until the second frame, in order to prevent false
  1184. // alarms for scenes with many objects.
  1185. Update(1);
  1186. Watchdog.StartThread(
  1187. Maintenance, string.Format("Maintenance ({0})", RegionInfo.RegionName), ThreadPriority.Normal, false, true);
  1188. Watchdog.GetCurrentThreadInfo().AlarmIfTimeout = true;
  1189. Update(-1);
  1190. // m_lastUpdate = Util.EnvironmentTickCount();
  1191. // m_firstHeartbeat = false;
  1192. // }
  1193. // finally
  1194. // {
  1195. // Monitor.Pulse(m_heartbeatLock);
  1196. // Monitor.Exit(m_heartbeatLock);
  1197. // }
  1198. Watchdog.RemoveThread();
  1199. }
  1200. private void Maintenance()
  1201. {
  1202. DoMaintenance(-1);
  1203. Watchdog.RemoveThread();
  1204. }
  1205. public void DoMaintenance(int runs)
  1206. {
  1207. long? endRun = null;
  1208. int runtc;
  1209. int previousMaintenanceTick;
  1210. if (runs >= 0)
  1211. endRun = MaintenanceRun + runs;
  1212. List<Vector3> coarseLocations;
  1213. List<UUID> avatarUUIDs;
  1214. while (!m_shuttingDown && ((endRun == null && Active) || MaintenanceRun < endRun))
  1215. {
  1216. runtc = Util.EnvironmentTickCount();
  1217. ++MaintenanceRun;
  1218. // Coarse locations relate to positions of green dots on the mini-map (on a SecondLife client)
  1219. if (MaintenanceRun % (m_update_coarse_locations / 10) == 0)
  1220. {
  1221. SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
  1222. // Send coarse locations to clients
  1223. ForEachScenePresence(delegate(ScenePresence presence)
  1224. {
  1225. presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
  1226. });
  1227. }
  1228. if (SendPeriodicAppearanceUpdates && MaintenanceRun % 60 == 0)
  1229. {
  1230. // m_log.DebugFormat("[SCENE]: Sending periodic appearance updates");
  1231. if (AvatarFactory != null)
  1232. {
  1233. ForEachRootScenePresence(sp => AvatarFactory.SendAppearance(sp.UUID));
  1234. }
  1235. }
  1236. Watchdog.UpdateThread();
  1237. previousMaintenanceTick = m_lastMaintenanceTick;
  1238. m_lastMaintenanceTick = Util.EnvironmentTickCount();
  1239. runtc = Util.EnvironmentTickCountSubtract(m_lastMaintenanceTick, runtc);
  1240. runtc = (int)(MinMaintenanceTime * 1000) - runtc;
  1241. if (runtc > 0)
  1242. Thread.Sleep(runtc);
  1243. // Optionally warn if a frame takes double the amount of time that it should.
  1244. if (DebugUpdates
  1245. && Util.EnvironmentTickCountSubtract(
  1246. m_lastMaintenanceTick, previousMaintenanceTick) > (int)(MinMaintenanceTime * 1000 * 2))
  1247. m_log.WarnFormat(
  1248. "[SCENE]: Maintenance took {0} ms (desired max {1} ms) in {2}",
  1249. Util.EnvironmentTickCountSubtract(m_lastMaintenanceTick, previousMaintenanceTick),
  1250. MinMaintenanceTime * 1000,
  1251. RegionInfo.RegionName);
  1252. }
  1253. }
  1254. public override void Update(int frames)
  1255. {
  1256. long? endFrame = null;
  1257. if (frames >= 0)
  1258. endFrame = Frame + frames;
  1259. float physicsFPS = 0f;
  1260. int previousFrameTick, tmpMS;
  1261. int maintc = Util.EnvironmentTickCount();
  1262. while (!m_shuttingDown && ((endFrame == null && Active) || Frame < endFrame))
  1263. {
  1264. ++Frame;
  1265. // m_log.DebugFormat("[SCENE]: Processing frame {0} in {1}", Frame, RegionInfo.RegionName);
  1266. agentMS = tempOnRezMS = eventMS = backupMS = terrainMS = landMS = spareMS = 0;
  1267. try
  1268. {
  1269. EventManager.TriggerRegionHeartbeatStart(this);
  1270. // Apply taints in terrain module to terrain in physics scene
  1271. if (Frame % m_update_terrain == 0)
  1272. {
  1273. tmpMS = Util.EnvironmentTickCount();
  1274. UpdateTerrain();
  1275. terrainMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1276. }
  1277. tmpMS = Util.EnvironmentTickCount();
  1278. if (PhysicsEnabled && Frame % m_update_physics == 0)
  1279. m_sceneGraph.UpdatePreparePhysics();
  1280. physicsMS2 = Util.EnvironmentTickCountSubtract(tmpMS);
  1281. // Apply any pending avatar force input to the avatar's velocity
  1282. tmpMS = Util.EnvironmentTickCount();
  1283. if (Frame % m_update_entitymovement == 0)
  1284. m_sceneGraph.UpdateScenePresenceMovement();
  1285. agentMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1286. // Perform the main physics update. This will do the actual work of moving objects and avatars according to their
  1287. // velocity
  1288. tmpMS = Util.EnvironmentTickCount();
  1289. if (Frame % m_update_physics == 0)
  1290. {
  1291. if (PhysicsEnabled)
  1292. physicsFPS = m_sceneGraph.UpdatePhysics(MinFrameTime);
  1293. if (SynchronizeScene != null)
  1294. SynchronizeScene(this);
  1295. }
  1296. physicsMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1297. tmpMS = Util.EnvironmentTickCount();
  1298. // Check if any objects have reached their targets
  1299. CheckAtTargets();
  1300. // Update SceneObjectGroups that have scheduled themselves for updates
  1301. // Objects queue their updates onto all scene presences
  1302. if (Frame % m_update_objects == 0)
  1303. m_sceneGraph.UpdateObjectGroups();
  1304. // Run through all ScenePresences looking for updates
  1305. // Presence updates and queued object updates for each presence are sent to clients
  1306. if (Frame % m_update_presences == 0)
  1307. m_sceneGraph.UpdatePresences();
  1308. agentMS += Util.EnvironmentTickCountSubtract(tmpMS);
  1309. // Delete temp-on-rez stuff
  1310. if (Frame % m_update_temp_cleaning == 0 && !m_cleaningTemps)
  1311. {
  1312. tmpMS = Util.EnvironmentTickCount();
  1313. m_cleaningTemps = true;
  1314. Util.FireAndForget(delegate { CleanTempObjects(); m_cleaningTemps = false; });
  1315. tempOnRezMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1316. }
  1317. if (Frame % m_update_events == 0)
  1318. {
  1319. tmpMS = Util.EnvironmentTickCount();
  1320. UpdateEvents();
  1321. eventMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1322. }
  1323. if (PeriodicBackup && Frame % m_update_backup == 0)
  1324. {
  1325. tmpMS = Util.EnvironmentTickCount();
  1326. UpdateStorageBackup();
  1327. backupMS = Util.EnvironmentTickCountSubtract(tmpMS);
  1328. }
  1329. //if (Frame % m_update_land == 0)
  1330. //{
  1331. // int ldMS = Util.EnvironmentTickCount();
  1332. // UpdateLand();
  1333. // landMS = Util.EnvironmentTickCountSubtract(ldMS);
  1334. //}
  1335. if (!LoginsEnabled && Frame == 20)
  1336. {
  1337. // m_log.DebugFormat("{0} {1} {2}", LoginsDisabled, m_sceneGraph.GetActiveScriptsCount(), LoginLock);
  1338. // In 99.9% of cases it is a bad idea to manually force garbage collection. However,
  1339. // this is a rare case where we know we have just went through a long cycle of heap
  1340. // allocations, and there is no more work to be done until someone logs in
  1341. GC.Collect();
  1342. if (!LoginLock)
  1343. {
  1344. if (!StartDisabled)
  1345. {
  1346. m_log.InfoFormat("[REGION]: Enabling logins for {0}", RegionInfo.RegionName);
  1347. LoginsEnabled = true;
  1348. }
  1349. m_sceneGridService.InformNeighborsThatRegionisUp(
  1350. RequestModuleInterface<INeighbourService>(), RegionInfo);
  1351. // Region ready should always be set
  1352. Ready = true;
  1353. }
  1354. else
  1355. {
  1356. // This handles a case of a region having no scripts for the RegionReady module
  1357. if (m_sceneGraph.GetActiveScriptsCount() == 0)
  1358. {
  1359. // In this case, we leave it to the IRegionReadyModule to enable logins
  1360. // LoginLock can currently only be set by a region module implementation.
  1361. // If somehow this hasn't been done then the quickest way to bugfix is to see the
  1362. // NullReferenceException
  1363. IRegionReadyModule rrm = RequestModuleInterface<IRegionReadyModule>();
  1364. rrm.TriggerRegionReady(this);
  1365. }
  1366. }
  1367. }
  1368. }
  1369. catch (Exception e)
  1370. {
  1371. m_log.ErrorFormat(
  1372. "[SCENE]: Failed on region {0} with exception {1}{2}",
  1373. RegionInfo.RegionName, e.Message, e.StackTrace);
  1374. }
  1375. EventManager.TriggerRegionHeartbeatEnd(this);
  1376. Watchdog.UpdateThread();
  1377. previousFrameTick = m_lastFrameTick;
  1378. m_lastFrameTick = Util.EnvironmentTickCount();
  1379. tmpMS = Util.EnvironmentTickCountSubtract(m_lastFrameTick, maintc);
  1380. tmpMS = (int)(MinFrameTime * 1000) - tmpMS;
  1381. if (tmpMS > 0)
  1382. {
  1383. Thread.Sleep(tmpMS);
  1384. spareMS += tmpMS;
  1385. }
  1386. frameMS = Util.EnvironmentTickCountSubtract(maintc);
  1387. maintc = Util.EnvironmentTickCount();
  1388. otherMS = tempOnRezMS + eventMS + backupMS + terrainMS + landMS;
  1389. // if (Frame%m_update_avatars == 0)
  1390. // UpdateInWorldTime();
  1391. StatsReporter.AddPhysicsFPS(physicsFPS);
  1392. StatsReporter.AddTimeDilation(TimeDilation);
  1393. StatsReporter.AddFPS(1);
  1394. StatsReporter.addFrameMS(frameMS);
  1395. StatsReporter.addAgentMS(agentMS);
  1396. StatsReporter.addPhysicsMS(physicsMS + physicsMS2);
  1397. StatsReporter.addOtherMS(otherMS);
  1398. StatsReporter.AddSpareMS(spareMS);
  1399. StatsReporter.addScriptLines(m_sceneGraph.GetScriptLPS());
  1400. // Optionally warn if a frame takes double the amount of time that it should.
  1401. if (DebugUpdates
  1402. && Util.EnvironmentTickCountSubtract(
  1403. m_lastFrameTick, previousFrameTick) > (int)(MinFrameTime * 1000 * 2))
  1404. m_log.WarnFormat(
  1405. "[SCENE]: Frame took {0} ms (desired max {1} ms) in {2}",
  1406. Util.EnvironmentTickCountSubtract(m_lastFrameTick, previousFrameTick),
  1407. MinFrameTime * 1000,
  1408. RegionInfo.RegionName);
  1409. }
  1410. }
  1411. public void AddGroupTarget(SceneObjectGroup grp)
  1412. {
  1413. lock (m_groupsWithTargets)
  1414. m_groupsWithTargets[grp.UUID] = grp;
  1415. }
  1416. public void RemoveGroupTarget(SceneObjectGroup grp)
  1417. {
  1418. lock (m_groupsWithTargets)
  1419. m_groupsWithTargets.Remove(grp.UUID);
  1420. }
  1421. private void CheckAtTargets()
  1422. {
  1423. List<SceneObjectGroup> objs = null;
  1424. lock (m_groupsWithTargets)
  1425. {
  1426. if (m_groupsWithTargets.Count != 0)
  1427. objs = new List<SceneObjectGroup>(m_groupsWithTargets.Values);
  1428. }
  1429. if (objs != null)
  1430. {
  1431. foreach (SceneObjectGroup entry in objs)
  1432. entry.checkAtTargets();
  1433. }
  1434. }
  1435. /// <summary>
  1436. /// Send out simstats data to all clients
  1437. /// </summary>
  1438. /// <param name="stats">Stats on the Simulator's performance</param>
  1439. private void SendSimStatsPackets(SimStats stats)
  1440. {
  1441. ForEachRootClient(delegate(IClientAPI client)
  1442. {
  1443. client.SendSimStats(stats);
  1444. });
  1445. }
  1446. /// <summary>
  1447. /// Update the terrain if it needs to be updated.
  1448. /// </summary>
  1449. private void UpdateTerrain()
  1450. {
  1451. EventManager.TriggerTerrainTick();
  1452. }
  1453. /// <summary>
  1454. /// Back up queued up changes
  1455. /// </summary>
  1456. private void UpdateStorageBackup()
  1457. {
  1458. if (!m_backingup)
  1459. {
  1460. m_backingup = true;
  1461. Util.FireAndForget(BackupWaitCallback);
  1462. }
  1463. }
  1464. /// <summary>
  1465. /// Sends out the OnFrame event to the modules
  1466. /// </summary>
  1467. private void UpdateEvents()
  1468. {
  1469. m_eventManager.TriggerOnFrame();
  1470. }
  1471. /// <summary>
  1472. /// Wrapper for Backup() that can be called with Util.FireAndForget()
  1473. /// </summary>
  1474. private void BackupWaitCallback(object o)
  1475. {
  1476. Backup(false);
  1477. }
  1478. /// <summary>
  1479. /// Backup the scene. This acts as the main method of the backup thread.
  1480. /// </summary>
  1481. /// <param name="forced">
  1482. /// If true, then any changes that have not yet been persisted are persisted. If false,
  1483. /// then the persistence decision is left to the backup code (in some situations, such as object persistence,
  1484. /// it's much more efficient to backup multiple changes at once rather than every single one).
  1485. /// <returns></returns>
  1486. public void Backup(bool forced)
  1487. {
  1488. lock (m_returns)
  1489. {
  1490. EventManager.TriggerOnBackup(SimulationDataService, forced);
  1491. m_backingup = false;
  1492. foreach (KeyValuePair<UUID, ReturnInfo> ret in m_returns)
  1493. {
  1494. UUID transaction = UUID.Random();
  1495. GridInstantMessage msg = new GridInstantMessage();
  1496. msg.fromAgentID = new Guid(UUID.Zero.ToString()); // From server
  1497. msg.toAgentID = new Guid(ret.Key.ToString());
  1498. msg.imSessionID = new Guid(transaction.ToString());
  1499. msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
  1500. msg.fromAgentName = "Server";
  1501. msg.dialog = (byte)19; // Object msg
  1502. msg.fromGroup = false;
  1503. msg.offline = (byte)0;
  1504. msg.ParentEstateID = RegionInfo.EstateSettings.ParentEstateID;
  1505. msg.Position = Vector3.Zero;
  1506. msg.RegionID = RegionInfo.RegionID.Guid;
  1507. // We must fill in a null-terminated 'empty' string here since bytes[0] will crash viewer 3.
  1508. msg.binaryBucket = Util.StringToBytes256("\0");
  1509. if (ret.Value.count > 1)
  1510. msg.message = string.Format("Your {0} objects were returned from {1} in region {2} due to {3}", ret.Value.count, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1511. else
  1512. msg.message = string.Format("Your object {0} was returned from {1} in region {2} due to {3}", ret.Value.objectName, ret.Value.location.ToString(), RegionInfo.RegionName, ret.Value.reason);
  1513. IMessageTransferModule tr = RequestModuleInterface<IMessageTransferModule>();
  1514. if (tr != null)
  1515. tr.SendInstantMessage(msg, delegate(bool success) {});
  1516. }
  1517. m_returns.Clear();
  1518. }
  1519. }
  1520. /// <summary>
  1521. /// Synchronous force backup. For deletes and links/unlinks
  1522. /// </summary>
  1523. /// <param name="group">Object to be backed up</param>
  1524. public void ForceSceneObjectBackup(SceneObjectGroup group)
  1525. {
  1526. if (group != null)
  1527. {
  1528. group.ProcessBackup(SimulationDataService, true);
  1529. }
  1530. }
  1531. /// <summary>
  1532. /// Tell an agent that their object has been returned.
  1533. /// </summary>
  1534. /// <remarks>
  1535. /// The actual return is handled by the caller.
  1536. /// </remarks>
  1537. /// <param name="agentID">Avatar Unique Id</param>
  1538. /// <param name="objectName">Name of object returned</param>
  1539. /// <param name="location">Location of object returned</param>
  1540. /// <param name="reason">Reasion for object return</param>
  1541. public void AddReturn(UUID agentID, string objectName, Vector3 location, string reason)
  1542. {
  1543. lock (m_returns)
  1544. {
  1545. if (m_returns.ContainsKey(agentID))
  1546. {
  1547. ReturnInfo info = m_returns[agentID];
  1548. info.count++;
  1549. m_returns[agentID] = info;
  1550. }
  1551. else
  1552. {
  1553. ReturnInfo info = new ReturnInfo();
  1554. info.count = 1;
  1555. info.objectName = objectName;
  1556. info.location = location;
  1557. info.reason = reason;
  1558. m_returns[agentID] = info;
  1559. }
  1560. }
  1561. }
  1562. #endregion
  1563. #region Load Terrain
  1564. /// <summary>
  1565. /// Store the terrain in the persistant data store
  1566. /// </summary>
  1567. public void SaveTerrain()
  1568. {
  1569. SimulationDataService.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1570. }
  1571. public void StoreWindlightProfile(RegionLightShareData wl)
  1572. {
  1573. RegionInfo.WindlightSettings = wl;
  1574. SimulationDataService.StoreRegionWindlightSettings(wl);
  1575. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1576. }
  1577. public void LoadWindlightProfile()
  1578. {
  1579. RegionInfo.WindlightSettings = SimulationDataService.LoadRegionWindlightSettings(RegionInfo.RegionID);
  1580. m_eventManager.TriggerOnSaveNewWindlightProfile();
  1581. }
  1582. /// <summary>
  1583. /// Loads the World heightmap
  1584. /// </summary>
  1585. public override void LoadWorldMap()
  1586. {
  1587. try
  1588. {
  1589. double[,] map = SimulationDataService.LoadTerrain(RegionInfo.RegionID);
  1590. if (map == null)
  1591. {
  1592. // This should be in the Terrain module, but it isn't because
  1593. // the heightmap is needed _way_ before the modules are initialized...
  1594. IConfig terrainConfig = m_config.Configs["Terrain"];
  1595. String m_InitialTerrain = "pinhead-island";
  1596. if (terrainConfig != null)
  1597. m_InitialTerrain = terrainConfig.GetString("InitialTerrain", m_InitialTerrain);
  1598. m_log.InfoFormat("[TERRAIN]: No default terrain. Generating a new terrain {0}.", m_InitialTerrain);
  1599. Heightmap = new TerrainChannel(m_InitialTerrain);
  1600. SimulationDataService.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1601. }
  1602. else
  1603. {
  1604. Heightmap = new TerrainChannel(map);
  1605. }
  1606. }
  1607. catch (IOException e)
  1608. {
  1609. m_log.WarnFormat(
  1610. "[TERRAIN]: Scene.cs: LoadWorldMap() - Regenerating as failed with exception {0}{1}",
  1611. e.Message, e.StackTrace);
  1612. // Non standard region size. If there's an old terrain in the database, it might read past the buffer
  1613. #pragma warning disable 0162
  1614. if ((int)Constants.RegionSize != 256)
  1615. {
  1616. Heightmap = new TerrainChannel();
  1617. SimulationDataService.StoreTerrain(Heightmap.GetDoubles(), RegionInfo.RegionID);
  1618. }
  1619. }
  1620. catch (Exception e)
  1621. {
  1622. m_log.WarnFormat(
  1623. "[TERRAIN]: Scene.cs: LoadWorldMap() - Failed with exception {0}{1}", e.Message, e.StackTrace);
  1624. }
  1625. }
  1626. /// <summary>
  1627. /// Register this region with a grid service
  1628. /// </summary>
  1629. /// <exception cref="System.Exception">Thrown if registration of the region itself fails.</exception>
  1630. public void RegisterRegionWithGrid()
  1631. {
  1632. m_sceneGridService.SetScene(this);
  1633. //// Unfortunately this needs to be here and it can't be async.
  1634. //// The map tile image is stored in RegionSettings, but it also needs to be
  1635. //// stored in the GridService, because that's what the world map module uses
  1636. //// to send the map image UUIDs (of other regions) to the viewer...
  1637. if (m_generateMaptiles)
  1638. RegenerateMaptile();
  1639. GridRegion region = new GridRegion(RegionInfo);
  1640. string error = GridService.RegisterRegion(RegionInfo.ScopeID, region);
  1641. if (error != String.Empty)
  1642. throw new Exception(error);
  1643. }
  1644. #endregion
  1645. #region Load Land
  1646. /// <summary>
  1647. /// Loads all Parcel data from the datastore for region identified by regionID
  1648. /// </summary>
  1649. /// <param name="regionID">Unique Identifier of the Region to load parcel data for</param>
  1650. public void loadAllLandObjectsFromStorage(UUID regionID)
  1651. {
  1652. m_log.Info("[SCENE]: Loading land objects from storage");
  1653. List<LandData> landData = SimulationDataService.LoadLandObjects(regionID);
  1654. if (LandChannel != null)
  1655. {
  1656. if (landData.Count == 0)
  1657. {
  1658. EventManager.TriggerNoticeNoLandDataFromStorage();
  1659. }
  1660. else
  1661. {
  1662. EventManager.TriggerIncomingLandDataFromStorage(landData);
  1663. }
  1664. }
  1665. else
  1666. {
  1667. m_log.Error("[SCENE]: Land Channel is not defined. Cannot load from storage!");
  1668. }
  1669. }
  1670. #endregion
  1671. #region Primitives Methods
  1672. /// <summary>
  1673. /// Loads the World's objects
  1674. /// </summary>
  1675. /// <param name="regionID"></param>
  1676. public virtual void LoadPrimsFromStorage(UUID regionID)
  1677. {
  1678. LoadingPrims = true;
  1679. m_log.Info("[SCENE]: Loading objects from datastore");
  1680. List<SceneObjectGroup> PrimsFromDB = SimulationDataService.LoadObjects(regionID);
  1681. m_log.InfoFormat("[SCENE]: Loaded {0} objects from the datastore", PrimsFromDB.Count);
  1682. foreach (SceneObjectGroup group in PrimsFromDB)
  1683. {
  1684. AddRestoredSceneObject(group, true, true);
  1685. EventManager.TriggerOnSceneObjectLoaded(group);
  1686. SceneObjectPart rootPart = group.GetPart(group.UUID);
  1687. rootPart.Flags &= ~PrimFlags.Scripted;
  1688. rootPart.TrimPermissions();
  1689. // Don't do this here - it will get done later on when sculpt data is loaded.
  1690. // group.CheckSculptAndLoad();
  1691. }
  1692. LoadingPrims = false;
  1693. EventManager.TriggerPrimsLoaded(this);
  1694. }
  1695. public bool SupportsRayCastFiltered()
  1696. {
  1697. if (PhysicsScene == null)
  1698. return false;
  1699. return PhysicsScene.SupportsRaycastWorldFiltered();
  1700. }
  1701. public object RayCastFiltered(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter)
  1702. {
  1703. if (PhysicsScene == null)
  1704. return null;
  1705. return PhysicsScene.RaycastWorld(position, direction, length, Count,filter);
  1706. }
  1707. /// <summary>
  1708. /// Gets a new rez location based on the raycast and the size of the object that is being rezzed.
  1709. /// </summary>
  1710. /// <param name="RayStart"></param>
  1711. /// <param name="RayEnd"></param>
  1712. /// <param name="RayTargetID"></param>
  1713. /// <param name="rot"></param>
  1714. /// <param name="bypassRayCast"></param>
  1715. /// <param name="RayEndIsIntersection"></param>
  1716. /// <param name="frontFacesOnly"></param>
  1717. /// <param name="scale"></param>
  1718. /// <param name="FaceCenter"></param>
  1719. /// <returns></returns>
  1720. public Vector3 GetNewRezLocation(Vector3 RayStart, Vector3 RayEnd, UUID RayTargetID, Quaternion rot, byte bypassRayCast, byte RayEndIsIntersection, bool frontFacesOnly, Vector3 scale, bool FaceCenter)
  1721. {
  1722. Vector3 pos = Vector3.Zero;
  1723. if (RayEndIsIntersection == (byte)1)
  1724. {
  1725. pos = RayEnd;
  1726. return pos;
  1727. }
  1728. if (RayTargetID != UUID.Zero)
  1729. {
  1730. SceneObjectPart target = GetSceneObjectPart(RayTargetID);
  1731. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  1732. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  1733. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  1734. if (target != null)
  1735. {
  1736. pos = target.AbsolutePosition;
  1737. //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString());
  1738. // TODO: Raytrace better here
  1739. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  1740. Ray NewRay = new Ray(AXOrigin, AXdirection);
  1741. // Ray Trace against target here
  1742. EntityIntersection ei = target.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, FaceCenter);
  1743. // Un-comment out the following line to Get Raytrace results printed to the console.
  1744. // m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1745. float ScaleOffset = 0.5f;
  1746. // If we hit something
  1747. if (ei.HitTF)
  1748. {
  1749. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  1750. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  1751. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  1752. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  1753. ScaleOffset = Math.Abs(ScaleOffset);
  1754. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1755. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  1756. // Set the position to the intersection point
  1757. Vector3 offset = (normal * (ScaleOffset / 2f));
  1758. pos = (intersectionpoint + offset);
  1759. //Seems to make no sense to do this as this call is used for rezzing from inventory as well, and with inventory items their size is not always 0.5f
  1760. //And in cases when we weren't rezzing from inventory we were re-adding the 0.25 straight after calling this method
  1761. // Un-offset the prim (it gets offset later by the consumer method)
  1762. //pos.Z -= 0.25F;
  1763. }
  1764. return pos;
  1765. }
  1766. else
  1767. {
  1768. // We don't have a target here, so we're going to raytrace all the objects in the scene.
  1769. EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection), true, false);
  1770. // Un-comment the following line to print the raytrace results to the console.
  1771. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  1772. if (ei.HitTF)
  1773. {
  1774. pos = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  1775. } else
  1776. {
  1777. // fall back to our stupid functionality
  1778. pos = RayEnd;
  1779. }
  1780. return pos;
  1781. }
  1782. }
  1783. else
  1784. {
  1785. // fall back to our stupid functionality
  1786. pos = RayEnd;
  1787. //increase height so its above the ground.
  1788. //should be getting the normal of the ground at the rez point and using that?
  1789. pos.Z += scale.Z / 2f;
  1790. return pos;
  1791. }
  1792. }
  1793. /// <summary>
  1794. /// Create a New SceneObjectGroup/Part by raycasting
  1795. /// </summary>
  1796. /// <param name="ownerID"></param>
  1797. /// <param name="groupID"></param>
  1798. /// <param name="RayEnd"></param>
  1799. /// <param name="rot"></param>
  1800. /// <param name="shape"></param>
  1801. /// <param name="bypassRaycast"></param>
  1802. /// <param name="RayStart"></param>
  1803. /// <param name="RayTargetID"></param>
  1804. /// <param name="RayEndIsIntersection"></param>
  1805. public virtual void AddNewPrim(UUID ownerID, UUID groupID, Vector3 RayEnd, Quaternion rot, PrimitiveBaseShape shape,
  1806. byte bypassRaycast, Vector3 RayStart, UUID RayTargetID,
  1807. byte RayEndIsIntersection)
  1808. {
  1809. Vector3 pos = GetNewRezLocation(RayStart, RayEnd, RayTargetID, rot, bypassRaycast, RayEndIsIntersection, true, new Vector3(0.5f, 0.5f, 0.5f), false);
  1810. if (Permissions.CanRezObject(1, ownerID, pos))
  1811. {
  1812. // rez ON the ground, not IN the ground
  1813. // pos.Z += 0.25F; The rez point should now be correct so that its not in the ground
  1814. AddNewPrim(ownerID, groupID, pos, rot, shape);
  1815. }
  1816. else
  1817. {
  1818. IClientAPI client = null;
  1819. if (TryGetClient(ownerID, out client))
  1820. client.SendAlertMessage("You cannot create objects here.");
  1821. }
  1822. }
  1823. public virtual SceneObjectGroup AddNewPrim(
  1824. UUID ownerID, UUID groupID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1825. {
  1826. //m_log.DebugFormat(
  1827. // "[SCENE]: Scene.AddNewPrim() pcode {0} called for {1} in {2}", shape.PCode, ownerID, RegionInfo.RegionName);
  1828. SceneObjectGroup sceneObject = null;
  1829. // If an entity creator has been registered for this prim type then use that
  1830. if (m_entityCreators.ContainsKey((PCode)shape.PCode))
  1831. {
  1832. sceneObject = m_entityCreators[(PCode)shape.PCode].CreateEntity(ownerID, groupID, pos, rot, shape);
  1833. }
  1834. else
  1835. {
  1836. // Otherwise, use this default creation code;
  1837. sceneObject = new SceneObjectGroup(ownerID, pos, rot, shape);
  1838. AddNewSceneObject(sceneObject, true);
  1839. sceneObject.SetGroup(groupID, null);
  1840. }
  1841. if (UserManagementModule != null)
  1842. sceneObject.RootPart.CreatorIdentification = UserManagementModule.GetUserUUI(ownerID);
  1843. sceneObject.ScheduleGroupForFullUpdate();
  1844. return sceneObject;
  1845. }
  1846. /// <summary>
  1847. /// Add an object into the scene that has come from storage
  1848. /// </summary>
  1849. ///
  1850. /// <param name="sceneObject"></param>
  1851. /// <param name="attachToBackup">
  1852. /// If true, changes to the object will be reflected in its persisted data
  1853. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1854. /// </param>
  1855. /// <param name="alreadyPersisted">
  1856. /// If true, we won't persist this object until it changes
  1857. /// If false, we'll persist this object immediately
  1858. /// </param>
  1859. /// <param name="sendClientUpdates">
  1860. /// If true, we send updates to the client to tell it about this object
  1861. /// If false, we leave it up to the caller to do this
  1862. /// </param>
  1863. /// <returns>
  1864. /// true if the object was added, false if an object with the same uuid was already in the scene
  1865. /// </returns>
  1866. public bool AddRestoredSceneObject(
  1867. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates)
  1868. {
  1869. if (m_sceneGraph.AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, sendClientUpdates))
  1870. {
  1871. EventManager.TriggerObjectAddedToScene(sceneObject);
  1872. return true;
  1873. }
  1874. return false;
  1875. }
  1876. /// <summary>
  1877. /// Add an object into the scene that has come from storage
  1878. /// </summary>
  1879. ///
  1880. /// <param name="sceneObject"></param>
  1881. /// <param name="attachToBackup">
  1882. /// If true, changes to the object will be reflected in its persisted data
  1883. /// If false, the persisted data will not be changed even if the object in the scene is changed
  1884. /// </param>
  1885. /// <param name="alreadyPersisted">
  1886. /// If true, we won't persist this object until it changes
  1887. /// If false, we'll persist this object immediately
  1888. /// </param>
  1889. /// <returns>
  1890. /// true if the object was added, false if an object with the same uuid was already in the scene
  1891. /// </returns>
  1892. public bool AddRestoredSceneObject(
  1893. SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted)
  1894. {
  1895. return AddRestoredSceneObject(sceneObject, attachToBackup, alreadyPersisted, true);
  1896. }
  1897. /// <summary>
  1898. /// Add a newly created object to the scene. Updates are also sent to viewers.
  1899. /// </summary>
  1900. /// <param name="sceneObject"></param>
  1901. /// <param name="attachToBackup">
  1902. /// If true, the object is made persistent into the scene.
  1903. /// If false, the object will not persist over server restarts
  1904. /// </param>
  1905. /// <returns>true if the object was added. false if not</returns>
  1906. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup)
  1907. {
  1908. return AddNewSceneObject(sceneObject, attachToBackup, true);
  1909. }
  1910. /// <summary>
  1911. /// Add a newly created object to the scene
  1912. /// </summary>
  1913. /// <param name="sceneObject"></param>
  1914. /// <param name="attachToBackup">
  1915. /// If true, the object is made persistent into the scene.
  1916. /// If false, the object will not persist over server restarts
  1917. /// </param>
  1918. /// <param name="sendClientUpdates">
  1919. /// If true, updates for the new scene object are sent to all viewers in range.
  1920. /// If false, it is left to the caller to schedule the update
  1921. /// </param>
  1922. /// <returns>true if the object was added. false if not</returns>
  1923. public bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates)
  1924. {
  1925. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, sendClientUpdates))
  1926. {
  1927. EventManager.TriggerObjectAddedToScene(sceneObject);
  1928. return true;
  1929. }
  1930. return false;
  1931. }
  1932. /// <summary>
  1933. /// Add a newly created object to the scene.
  1934. /// </summary>
  1935. /// <remarks>
  1936. /// This method does not send updates to the client - callers need to handle this themselves.
  1937. /// </remarks>
  1938. /// <param name="sceneObject"></param>
  1939. /// <param name="attachToBackup"></param>
  1940. /// <param name="pos">Position of the object. If null then the position stored in the object is used.</param>
  1941. /// <param name="rot">Rotation of the object. If null then the rotation stored in the object is used.</param>
  1942. /// <param name="vel">Velocity of the object. This parameter only has an effect if the object is physical</param>
  1943. /// <returns></returns>
  1944. public bool AddNewSceneObject(
  1945. SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel)
  1946. {
  1947. if (m_sceneGraph.AddNewSceneObject(sceneObject, attachToBackup, pos, rot, vel))
  1948. {
  1949. EventManager.TriggerObjectAddedToScene(sceneObject);
  1950. return true;
  1951. }
  1952. return false;
  1953. }
  1954. /// <summary>
  1955. /// Delete every object from the scene. This does not include attachments worn by avatars.
  1956. /// </summary>
  1957. public void DeleteAllSceneObjects()
  1958. {
  1959. lock (Entities)
  1960. {
  1961. EntityBase[] entities = Entities.GetEntities();
  1962. foreach (EntityBase e in entities)
  1963. {
  1964. if (e is SceneObjectGroup)
  1965. {
  1966. SceneObjectGroup sog = (SceneObjectGroup)e;
  1967. if (!sog.IsAttachment)
  1968. DeleteSceneObject((SceneObjectGroup)e, false);
  1969. }
  1970. }
  1971. }
  1972. }
  1973. /// <summary>
  1974. /// Synchronously delete the given object from the scene.
  1975. /// </summary>
  1976. /// <remarks>
  1977. /// Scripts are also removed.
  1978. /// </remarks>
  1979. /// <param name="group">Object Id</param>
  1980. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  1981. public void DeleteSceneObject(SceneObjectGroup group, bool silent)
  1982. {
  1983. DeleteSceneObject(group, silent, true);
  1984. }
  1985. /// <summary>
  1986. /// Synchronously delete the given object from the scene.
  1987. /// </summary>
  1988. /// <param name="group">Object Id</param>
  1989. /// <param name="silent">Suppress broadcasting changes to other clients.</param>
  1990. /// <param name="removeScripts">If true, then scripts are removed. If false, then they are only stopped.</para>
  1991. public void DeleteSceneObject(SceneObjectGroup group, bool silent, bool removeScripts)
  1992. {
  1993. // m_log.DebugFormat("[SCENE]: Deleting scene object {0} {1}", group.Name, group.UUID);
  1994. if (removeScripts)
  1995. group.RemoveScriptInstances(true);
  1996. else
  1997. group.StopScriptInstances();
  1998. SceneObjectPart[] partList = group.Parts;
  1999. foreach (SceneObjectPart part in partList)
  2000. {
  2001. if (part.KeyframeMotion != null)
  2002. {
  2003. part.KeyframeMotion.Delete();
  2004. part.KeyframeMotion = null;
  2005. }
  2006. if (part.IsJoint() && ((part.Flags & PrimFlags.Physics) != 0))
  2007. {
  2008. PhysicsScene.RequestJointDeletion(part.Name); // FIXME: what if the name changed?
  2009. }
  2010. else if (part.PhysActor != null)
  2011. {
  2012. part.RemoveFromPhysics();
  2013. }
  2014. }
  2015. if (UnlinkSceneObject(group, false))
  2016. {
  2017. EventManager.TriggerObjectBeingRemovedFromScene(group);
  2018. EventManager.TriggerParcelPrimCountTainted();
  2019. }
  2020. group.DeleteGroupFromScene(silent);
  2021. // m_log.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID);
  2022. }
  2023. /// <summary>
  2024. /// Unlink the given object from the scene. Unlike delete, this just removes the record of the object - the
  2025. /// object itself is not destroyed.
  2026. /// </summary>
  2027. /// <param name="so">The scene object.</param>
  2028. /// <param name="softDelete">If true, only deletes from scene, but keeps the object in the database.</param>
  2029. /// <returns>true if the object was in the scene, false if it was not</returns>
  2030. public bool UnlinkSceneObject(SceneObjectGroup so, bool softDelete)
  2031. {
  2032. if (m_sceneGraph.DeleteSceneObject(so.UUID, softDelete))
  2033. {
  2034. if (!softDelete)
  2035. {
  2036. // Force a database update so that the scene object group ID is accurate. It's possible that the
  2037. // group has recently been delinked from another group but that this change has not been persisted
  2038. // to the DB.
  2039. // This is an expensive thing to do so only do it if absolutely necessary.
  2040. if (so.HasGroupChangedDueToDelink)
  2041. ForceSceneObjectBackup(so);
  2042. so.DetachFromBackup();
  2043. SimulationDataService.RemoveObject(so.UUID, RegionInfo.RegionID);
  2044. }
  2045. // We need to keep track of this state in case this group is still queued for further backup.
  2046. so.IsDeleted = true;
  2047. return true;
  2048. }
  2049. return false;
  2050. }
  2051. /// <summary>
  2052. /// Move the given scene object into a new region depending on which region its absolute position has moved
  2053. /// into.
  2054. ///
  2055. /// </summary>
  2056. /// <param name="attemptedPosition">the attempted out of region position of the scene object</param>
  2057. /// <param name="grp">the scene object that we're crossing</param>
  2058. public void CrossPrimGroupIntoNewRegion(Vector3 attemptedPosition, SceneObjectGroup grp, bool silent)
  2059. {
  2060. if (grp == null)
  2061. return;
  2062. if (grp.IsDeleted)
  2063. return;
  2064. if (grp.RootPart.DIE_AT_EDGE)
  2065. {
  2066. // We remove the object here
  2067. try
  2068. {
  2069. DeleteSceneObject(grp, false);
  2070. }
  2071. catch (Exception)
  2072. {
  2073. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  2074. }
  2075. return;
  2076. }
  2077. if (grp.RootPart.RETURN_AT_EDGE)
  2078. {
  2079. // We remove the object here
  2080. try
  2081. {
  2082. List<SceneObjectGroup> objects = new List<SceneObjectGroup>();
  2083. objects.Add(grp);
  2084. SceneObjectGroup[] objectsArray = objects.ToArray();
  2085. returnObjects(objectsArray, UUID.Zero);
  2086. }
  2087. catch (Exception)
  2088. {
  2089. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  2090. }
  2091. return;
  2092. }
  2093. if (EntityTransferModule != null)
  2094. EntityTransferModule.Cross(grp, attemptedPosition, silent);
  2095. }
  2096. public Border GetCrossedBorder(Vector3 position, Cardinals gridline)
  2097. {
  2098. if (BordersLocked)
  2099. {
  2100. switch (gridline)
  2101. {
  2102. case Cardinals.N:
  2103. lock (NorthBorders)
  2104. {
  2105. foreach (Border b in NorthBorders)
  2106. {
  2107. if (b.TestCross(position))
  2108. return b;
  2109. }
  2110. }
  2111. break;
  2112. case Cardinals.S:
  2113. lock (SouthBorders)
  2114. {
  2115. foreach (Border b in SouthBorders)
  2116. {
  2117. if (b.TestCross(position))
  2118. return b;
  2119. }
  2120. }
  2121. break;
  2122. case Cardinals.E:
  2123. lock (EastBorders)
  2124. {
  2125. foreach (Border b in EastBorders)
  2126. {
  2127. if (b.TestCross(position))
  2128. return b;
  2129. }
  2130. }
  2131. break;
  2132. case Cardinals.W:
  2133. lock (WestBorders)
  2134. {
  2135. foreach (Border b in WestBorders)
  2136. {
  2137. if (b.TestCross(position))
  2138. return b;
  2139. }
  2140. }
  2141. break;
  2142. }
  2143. }
  2144. else
  2145. {
  2146. switch (gridline)
  2147. {
  2148. case Cardinals.N:
  2149. foreach (Border b in NorthBorders)
  2150. {
  2151. if (b.TestCross(position))
  2152. return b;
  2153. }
  2154. break;
  2155. case Cardinals.S:
  2156. foreach (Border b in SouthBorders)
  2157. {
  2158. if (b.TestCross(position))
  2159. return b;
  2160. }
  2161. break;
  2162. case Cardinals.E:
  2163. foreach (Border b in EastBorders)
  2164. {
  2165. if (b.TestCross(position))
  2166. return b;
  2167. }
  2168. break;
  2169. case Cardinals.W:
  2170. foreach (Border b in WestBorders)
  2171. {
  2172. if (b.TestCross(position))
  2173. return b;
  2174. }
  2175. break;
  2176. }
  2177. }
  2178. return null;
  2179. }
  2180. public bool TestBorderCross(Vector3 position, Cardinals border)
  2181. {
  2182. if (BordersLocked)
  2183. {
  2184. switch (border)
  2185. {
  2186. case Cardinals.N:
  2187. lock (NorthBorders)
  2188. {
  2189. foreach (Border b in NorthBorders)
  2190. {
  2191. if (b.TestCross(position))
  2192. return true;
  2193. }
  2194. }
  2195. break;
  2196. case Cardinals.E:
  2197. lock (EastBorders)
  2198. {
  2199. foreach (Border b in EastBorders)
  2200. {
  2201. if (b.TestCross(position))
  2202. return true;
  2203. }
  2204. }
  2205. break;
  2206. case Cardinals.S:
  2207. lock (SouthBorders)
  2208. {
  2209. foreach (Border b in SouthBorders)
  2210. {
  2211. if (b.TestCross(position))
  2212. return true;
  2213. }
  2214. }
  2215. break;
  2216. case Cardinals.W:
  2217. lock (WestBorders)
  2218. {
  2219. foreach (Border b in WestBorders)
  2220. {
  2221. if (b.TestCross(position))
  2222. return true;
  2223. }
  2224. }
  2225. break;
  2226. }
  2227. }
  2228. else
  2229. {
  2230. switch (border)
  2231. {
  2232. case Cardinals.N:
  2233. foreach (Border b in NorthBorders)
  2234. {
  2235. if (b.TestCross(position))
  2236. return true;
  2237. }
  2238. break;
  2239. case Cardinals.E:
  2240. foreach (Border b in EastBorders)
  2241. {
  2242. if (b.TestCross(position))
  2243. return true;
  2244. }
  2245. break;
  2246. case Cardinals.S:
  2247. foreach (Border b in SouthBorders)
  2248. {
  2249. if (b.TestCross(position))
  2250. return true;
  2251. }
  2252. break;
  2253. case Cardinals.W:
  2254. foreach (Border b in WestBorders)
  2255. {
  2256. if (b.TestCross(position))
  2257. return true;
  2258. }
  2259. break;
  2260. }
  2261. }
  2262. return false;
  2263. }
  2264. /// <summary>
  2265. /// Called when objects or attachments cross the border, or teleport, between regions.
  2266. /// </summary>
  2267. /// <param name="sog"></param>
  2268. /// <returns></returns>
  2269. public bool IncomingCreateObject(Vector3 newPosition, ISceneObject sog)
  2270. {
  2271. //m_log.DebugFormat(" >>> IncomingCreateObject(sog) <<< {0} deleted? {1} isAttach? {2}", ((SceneObjectGroup)sog).AbsolutePosition,
  2272. // ((SceneObjectGroup)sog).IsDeleted, ((SceneObjectGroup)sog).RootPart.IsAttachment);
  2273. SceneObjectGroup newObject;
  2274. try
  2275. {
  2276. newObject = (SceneObjectGroup)sog;
  2277. }
  2278. catch (Exception e)
  2279. {
  2280. m_log.WarnFormat("[INTERREGION]: Problem casting object, exception {0}{1}", e.Message, e.StackTrace);
  2281. return false;
  2282. }
  2283. // If the user is banned, we won't let any of their objects
  2284. // enter. Period.
  2285. //
  2286. if (RegionInfo.EstateSettings.IsBanned(newObject.OwnerID))
  2287. {
  2288. m_log.InfoFormat("[INTERREGION]: Denied prim crossing for banned avatar {0}", newObject.OwnerID);
  2289. return false;
  2290. }
  2291. if (newPosition != Vector3.Zero)
  2292. newObject.RootPart.GroupPosition = newPosition;
  2293. if (!AddSceneObject(newObject))
  2294. {
  2295. m_log.DebugFormat(
  2296. "[INTERREGION]: Problem adding scene object {0} in {1} ", newObject.UUID, RegionInfo.RegionName);
  2297. return false;
  2298. }
  2299. if (!newObject.IsAttachment)
  2300. {
  2301. // FIXME: It would be better to never add the scene object at all rather than add it and then delete
  2302. // it
  2303. if (!Permissions.CanObjectEntry(newObject.UUID, true, newObject.AbsolutePosition))
  2304. {
  2305. // Deny non attachments based on parcel settings
  2306. //
  2307. m_log.Info("[INTERREGION]: Denied prim crossing because of parcel settings");
  2308. DeleteSceneObject(newObject, false);
  2309. return false;
  2310. }
  2311. // For attachments, we need to wait until the agent is root
  2312. // before we restart the scripts, or else some functions won't work.
  2313. newObject.RootPart.ParentGroup.CreateScriptInstances(0, false, DefaultScriptEngine, GetStateSource(newObject));
  2314. newObject.ResumeScripts();
  2315. if (newObject.RootPart.KeyframeMotion != null)
  2316. newObject.RootPart.KeyframeMotion.UpdateSceneObject(newObject);
  2317. }
  2318. // Do this as late as possible so that listeners have full access to the incoming object
  2319. EventManager.TriggerOnIncomingSceneObject(newObject);
  2320. return true;
  2321. }
  2322. /// <summary>
  2323. /// Adds a Scene Object group to the Scene.
  2324. /// Verifies that the creator of the object is not banned from the simulator.
  2325. /// Checks if the item is an Attachment
  2326. /// </summary>
  2327. /// <param name="sceneObject"></param>
  2328. /// <returns>True if the SceneObjectGroup was added, False if it was not</returns>
  2329. public bool AddSceneObject(SceneObjectGroup sceneObject)
  2330. {
  2331. // Force allocation of new LocalId
  2332. //
  2333. SceneObjectPart[] parts = sceneObject.Parts;
  2334. for (int i = 0; i < parts.Length; i++)
  2335. parts[i].LocalId = 0;
  2336. if (sceneObject.IsAttachmentCheckFull()) // Attachment
  2337. {
  2338. sceneObject.RootPart.AddFlag(PrimFlags.TemporaryOnRez);
  2339. sceneObject.RootPart.AddFlag(PrimFlags.Phantom);
  2340. // Don't sent a full update here because this will cause full updates to be sent twice for
  2341. // attachments on region crossings, resulting in viewer glitches.
  2342. AddRestoredSceneObject(sceneObject, false, false, false);
  2343. // Handle attachment special case
  2344. SceneObjectPart RootPrim = sceneObject.RootPart;
  2345. // Fix up attachment Parent Local ID
  2346. ScenePresence sp = GetScenePresence(sceneObject.OwnerID);
  2347. if (sp != null)
  2348. {
  2349. SceneObjectGroup grp = sceneObject;
  2350. // m_log.DebugFormat(
  2351. // "[ATTACHMENT]: Received attachment {0}, inworld asset id {1}", grp.FromItemID, grp.UUID);
  2352. // m_log.DebugFormat(
  2353. // "[ATTACHMENT]: Attach to avatar {0} at position {1}", sp.UUID, grp.AbsolutePosition);
  2354. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2355. // We must currently not resume scripts at this stage since AttachmentsModule does not have the
  2356. // information that this is due to a teleport/border cross rather than an ordinary attachment.
  2357. // We currently do this in Scene.MakeRootAgent() instead.
  2358. if (AttachmentsModule != null)
  2359. AttachmentsModule.AttachObject(sp, grp, 0, false, false, true);
  2360. }
  2361. else
  2362. {
  2363. RootPrim.RemFlag(PrimFlags.TemporaryOnRez);
  2364. RootPrim.AddFlag(PrimFlags.TemporaryOnRez);
  2365. }
  2366. }
  2367. else
  2368. {
  2369. AddRestoredSceneObject(sceneObject, true, false);
  2370. }
  2371. return true;
  2372. }
  2373. private int GetStateSource(SceneObjectGroup sog)
  2374. {
  2375. ScenePresence sp = GetScenePresence(sog.OwnerID);
  2376. if (sp != null)
  2377. return sp.GetStateSource();
  2378. return 2; // StateSource.PrimCrossing
  2379. }
  2380. #endregion
  2381. #region Add/Remove Avatar Methods
  2382. public override ISceneAgent AddNewClient(IClientAPI client, PresenceType type)
  2383. {
  2384. ScenePresence sp;
  2385. bool vialogin;
  2386. bool reallyNew = true;
  2387. // Validation occurs in LLUDPServer
  2388. //
  2389. // XXX: A race condition exists here where two simultaneous calls to AddNewClient can interfere with
  2390. // each other. In practice, this does not currently occur in the code.
  2391. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2392. // We lock here on AgentCircuitData to prevent a race condition between the thread adding a new connection
  2393. // and a simultaneous one that removes it (as can happen if the client is closed at a particular point
  2394. // whilst connecting).
  2395. //
  2396. // It would be easier to lock across all NewUserConnection(), AddNewClient() and
  2397. // RemoveClient() calls for all agents, but this would allow a slow call (e.g. because of slow service
  2398. // response in some module listening to AddNewClient()) from holding up unrelated agent calls.
  2399. //
  2400. // In practice, the lock (this) in LLUDPServer.AddNewClient() currently lock across all
  2401. // AddNewClient() operations (though not other ops).
  2402. // In the future this can be relieved once locking per agent (not necessarily on AgentCircuitData) is improved.
  2403. lock (aCircuit)
  2404. {
  2405. vialogin
  2406. = (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0
  2407. || (aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0;
  2408. // CheckHeartbeat();
  2409. sp = GetScenePresence(client.AgentId);
  2410. // XXX: Not sure how good it is to add a new client if a scene presence already exists. Possibly this
  2411. // could occur if a viewer crashes and relogs before the old client is kicked out. But this could cause
  2412. // other problems, and possible the code calling AddNewClient() should ensure that no client is already
  2413. // connected.
  2414. if (sp == null)
  2415. {
  2416. m_log.DebugFormat(
  2417. "[SCENE]: Adding new child scene presence {0} {1} to scene {2} at pos {3}",
  2418. client.Name, client.AgentId, RegionInfo.RegionName, client.StartPos);
  2419. m_clientManager.Add(client);
  2420. SubscribeToClientEvents(client);
  2421. sp = m_sceneGraph.CreateAndAddChildScenePresence(client, aCircuit.Appearance, type);
  2422. m_eventManager.TriggerOnNewPresence(sp);
  2423. sp.TeleportFlags = (TPFlags)aCircuit.teleportFlags;
  2424. }
  2425. else
  2426. {
  2427. m_log.WarnFormat(
  2428. "[SCENE]: Already found {0} scene presence for {1} in {2} when asked to add new scene presence",
  2429. sp.IsChildAgent ? "child" : "root", sp.Name, RegionInfo.RegionName);
  2430. reallyNew = false;
  2431. }
  2432. // We must set this here so that TriggerOnNewClient and TriggerOnClientLogin can determine whether the
  2433. // client is for a root or child agent.
  2434. client.SceneAgent = sp;
  2435. // This is currently also being done earlier in NewUserConnection for real users to see if this
  2436. // resolves problems where HG agents are occasionally seen by others as "Unknown user" in chat and other
  2437. // places. However, we still need to do it here for NPCs.
  2438. CacheUserName(sp, aCircuit);
  2439. if (reallyNew)
  2440. EventManager.TriggerOnNewClient(client);
  2441. if (vialogin)
  2442. EventManager.TriggerOnClientLogin(client);
  2443. }
  2444. m_LastLogin = Util.EnvironmentTickCount();
  2445. return sp;
  2446. }
  2447. /// <summary>
  2448. /// Cache the user name for later use.
  2449. /// </summary>
  2450. /// <param name="sp"></param>
  2451. /// <param name="aCircuit"></param>
  2452. private void CacheUserName(ScenePresence sp, AgentCircuitData aCircuit)
  2453. {
  2454. if (UserManagementModule != null)
  2455. {
  2456. string first = aCircuit.firstname, last = aCircuit.lastname;
  2457. if (sp != null && sp.PresenceType == PresenceType.Npc)
  2458. {
  2459. UserManagementModule.AddUser(aCircuit.AgentID, first, last);
  2460. }
  2461. else
  2462. {
  2463. string homeURL = string.Empty;
  2464. if (aCircuit.ServiceURLs.ContainsKey("HomeURI"))
  2465. homeURL = aCircuit.ServiceURLs["HomeURI"].ToString();
  2466. if (aCircuit.lastname.StartsWith("@"))
  2467. {
  2468. string[] parts = aCircuit.firstname.Split('.');
  2469. if (parts.Length >= 2)
  2470. {
  2471. first = parts[0];
  2472. last = parts[1];
  2473. }
  2474. }
  2475. UserManagementModule.AddUser(aCircuit.AgentID, first, last, homeURL);
  2476. }
  2477. }
  2478. }
  2479. private bool VerifyClient(AgentCircuitData aCircuit, System.Net.IPEndPoint ep, out bool vialogin)
  2480. {
  2481. vialogin = false;
  2482. // Do the verification here
  2483. if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaHGLogin) != 0)
  2484. {
  2485. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via HG login", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2486. vialogin = true;
  2487. IUserAgentVerificationModule userVerification = RequestModuleInterface<IUserAgentVerificationModule>();
  2488. if (userVerification != null && ep != null)
  2489. {
  2490. if (!userVerification.VerifyClient(aCircuit, ep.Address.ToString()))
  2491. {
  2492. // uh-oh, this is fishy
  2493. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned false", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2494. return false;
  2495. }
  2496. else
  2497. m_log.DebugFormat("[SCENE]: User Client Verification for {0} {1} in {2} returned true", aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2498. }
  2499. }
  2500. else if ((aCircuit.teleportFlags & (uint)Constants.TeleportFlags.ViaLogin) != 0)
  2501. {
  2502. m_log.DebugFormat("[SCENE]: Incoming client {0} {1} in region {2} via regular login. Client IP verification not performed.",
  2503. aCircuit.firstname, aCircuit.lastname, RegionInfo.RegionName);
  2504. vialogin = true;
  2505. }
  2506. return true;
  2507. }
  2508. // Called by Caps, on the first HTTP contact from the client
  2509. public override bool CheckClient(UUID agentID, System.Net.IPEndPoint ep)
  2510. {
  2511. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(agentID);
  2512. if (aCircuit != null)
  2513. {
  2514. bool vialogin = false;
  2515. if (!VerifyClient(aCircuit, ep, out vialogin))
  2516. {
  2517. // if it doesn't pass, we remove the agentcircuitdata altogether
  2518. // and the scene presence and the client, if they exist
  2519. try
  2520. {
  2521. // We need to wait for the client to make UDP contact first.
  2522. // It's the UDP contact that creates the scene presence
  2523. ScenePresence sp = WaitGetScenePresence(agentID);
  2524. if (sp != null)
  2525. {
  2526. PresenceService.LogoutAgent(sp.ControllingClient.SessionId);
  2527. IncomingCloseAgent(sp.UUID, false);
  2528. }
  2529. else
  2530. {
  2531. m_log.WarnFormat("[SCENE]: Could not find scene presence for {0}", agentID);
  2532. }
  2533. // BANG! SLASH!
  2534. m_authenticateHandler.RemoveCircuit(agentID);
  2535. return false;
  2536. }
  2537. catch (Exception e)
  2538. {
  2539. m_log.DebugFormat("[SCENE]: Exception while closing aborted client: {0}", e.StackTrace);
  2540. }
  2541. }
  2542. else
  2543. return true;
  2544. }
  2545. return false;
  2546. }
  2547. /// <summary>
  2548. /// Register for events from the client
  2549. /// </summary>
  2550. /// <param name="client">The IClientAPI of the connected client</param>
  2551. public virtual void SubscribeToClientEvents(IClientAPI client)
  2552. {
  2553. SubscribeToClientTerrainEvents(client);
  2554. SubscribeToClientPrimEvents(client);
  2555. SubscribeToClientPrimRezEvents(client);
  2556. SubscribeToClientInventoryEvents(client);
  2557. SubscribeToClientTeleportEvents(client);
  2558. SubscribeToClientScriptEvents(client);
  2559. SubscribeToClientParcelEvents(client);
  2560. SubscribeToClientGridEvents(client);
  2561. SubscribeToClientNetworkEvents(client);
  2562. }
  2563. public virtual void SubscribeToClientTerrainEvents(IClientAPI client)
  2564. {
  2565. client.OnRegionHandShakeReply += SendLayerData;
  2566. }
  2567. public virtual void SubscribeToClientPrimEvents(IClientAPI client)
  2568. {
  2569. client.OnUpdatePrimGroupPosition += m_sceneGraph.UpdatePrimGroupPosition;
  2570. client.OnUpdatePrimSinglePosition += m_sceneGraph.UpdatePrimSinglePosition;
  2571. client.OnUpdatePrimGroupRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2572. client.OnUpdatePrimGroupMouseRotation += m_sceneGraph.UpdatePrimGroupRotation;
  2573. client.OnUpdatePrimSingleRotation += m_sceneGraph.UpdatePrimSingleRotation;
  2574. client.OnUpdatePrimSingleRotationPosition += m_sceneGraph.UpdatePrimSingleRotationPosition;
  2575. client.OnUpdatePrimScale += m_sceneGraph.UpdatePrimScale;
  2576. client.OnUpdatePrimGroupScale += m_sceneGraph.UpdatePrimGroupScale;
  2577. client.OnUpdateExtraParams += m_sceneGraph.UpdateExtraParam;
  2578. client.OnUpdatePrimShape += m_sceneGraph.UpdatePrimShape;
  2579. client.OnUpdatePrimTexture += m_sceneGraph.UpdatePrimTexture;
  2580. client.OnObjectRequest += RequestPrim;
  2581. client.OnObjectSelect += SelectPrim;
  2582. client.OnObjectDeselect += DeselectPrim;
  2583. client.OnGrabUpdate += m_sceneGraph.MoveObject;
  2584. client.OnSpinStart += m_sceneGraph.SpinStart;
  2585. client.OnSpinUpdate += m_sceneGraph.SpinObject;
  2586. client.OnDeRezObject += DeRezObjects;
  2587. client.OnObjectName += m_sceneGraph.PrimName;
  2588. client.OnObjectClickAction += m_sceneGraph.PrimClickAction;
  2589. client.OnObjectMaterial += m_sceneGraph.PrimMaterial;
  2590. client.OnLinkObjects += LinkObjects;
  2591. client.OnDelinkObjects += DelinkObjects;
  2592. client.OnObjectDuplicate += DuplicateObject;
  2593. client.OnObjectDuplicateOnRay += doObjectDuplicateOnRay;
  2594. client.OnUpdatePrimFlags += m_sceneGraph.UpdatePrimFlags;
  2595. client.OnRequestObjectPropertiesFamily += m_sceneGraph.RequestObjectPropertiesFamily;
  2596. client.OnObjectPermissions += HandleObjectPermissionsUpdate;
  2597. client.OnGrabObject += ProcessObjectGrab;
  2598. client.OnGrabUpdate += ProcessObjectGrabUpdate;
  2599. client.OnDeGrabObject += ProcessObjectDeGrab;
  2600. client.OnUndo += m_sceneGraph.HandleUndo;
  2601. client.OnRedo += m_sceneGraph.HandleRedo;
  2602. client.OnObjectDescription += m_sceneGraph.PrimDescription;
  2603. client.OnObjectIncludeInSearch += m_sceneGraph.MakeObjectSearchable;
  2604. client.OnObjectOwner += ObjectOwner;
  2605. client.OnObjectGroupRequest += HandleObjectGroupUpdate;
  2606. }
  2607. public virtual void SubscribeToClientPrimRezEvents(IClientAPI client)
  2608. {
  2609. client.OnAddPrim += AddNewPrim;
  2610. client.OnRezObject += RezObject;
  2611. }
  2612. public virtual void SubscribeToClientInventoryEvents(IClientAPI client)
  2613. {
  2614. client.OnLinkInventoryItem += HandleLinkInventoryItem;
  2615. client.OnCreateNewInventoryFolder += HandleCreateInventoryFolder;
  2616. client.OnUpdateInventoryFolder += HandleUpdateInventoryFolder;
  2617. client.OnMoveInventoryFolder += HandleMoveInventoryFolder; // 2; //!!
  2618. client.OnFetchInventoryDescendents += HandleFetchInventoryDescendents;
  2619. client.OnPurgeInventoryDescendents += HandlePurgeInventoryDescendents; // 2; //!!
  2620. client.OnFetchInventory += m_asyncInventorySender.HandleFetchInventory;
  2621. client.OnUpdateInventoryItem += UpdateInventoryItemAsset;
  2622. client.OnCopyInventoryItem += CopyInventoryItem;
  2623. client.OnMoveInventoryItem += MoveInventoryItem;
  2624. client.OnRemoveInventoryItem += RemoveInventoryItem;
  2625. client.OnRemoveInventoryFolder += RemoveInventoryFolder;
  2626. client.OnRezScript += RezScript;
  2627. client.OnRequestTaskInventory += RequestTaskInventory;
  2628. client.OnRemoveTaskItem += RemoveTaskInventory;
  2629. client.OnUpdateTaskInventory += UpdateTaskInventory;
  2630. client.OnMoveTaskItem += ClientMoveTaskInventoryItem;
  2631. }
  2632. public virtual void SubscribeToClientTeleportEvents(IClientAPI client)
  2633. {
  2634. client.OnTeleportLocationRequest += RequestTeleportLocation;
  2635. }
  2636. public virtual void SubscribeToClientScriptEvents(IClientAPI client)
  2637. {
  2638. client.OnScriptReset += ProcessScriptReset;
  2639. client.OnGetScriptRunning += GetScriptRunning;
  2640. client.OnSetScriptRunning += SetScriptRunning;
  2641. }
  2642. public virtual void SubscribeToClientParcelEvents(IClientAPI client)
  2643. {
  2644. client.OnParcelReturnObjectsRequest += LandChannel.ReturnObjectsInParcel;
  2645. client.OnParcelSetOtherCleanTime += LandChannel.SetParcelOtherCleanTime;
  2646. client.OnParcelBuy += ProcessParcelBuy;
  2647. }
  2648. public virtual void SubscribeToClientGridEvents(IClientAPI client)
  2649. {
  2650. //client.OnNameFromUUIDRequest += HandleUUIDNameRequest;
  2651. client.OnMoneyTransferRequest += ProcessMoneyTransferRequest;
  2652. }
  2653. public virtual void SubscribeToClientNetworkEvents(IClientAPI client)
  2654. {
  2655. client.OnNetworkStatsUpdate += StatsReporter.AddPacketsStats;
  2656. client.OnViewerEffect += ProcessViewerEffect;
  2657. }
  2658. /// <summary>
  2659. /// Unsubscribe the client from events.
  2660. /// </summary>
  2661. /// FIXME: Not called anywhere!
  2662. /// <param name="client">The IClientAPI of the client</param>
  2663. public virtual void UnSubscribeToClientEvents(IClientAPI client)
  2664. {
  2665. UnSubscribeToClientTerrainEvents(client);
  2666. UnSubscribeToClientPrimEvents(client);
  2667. UnSubscribeToClientPrimRezEvents(client);
  2668. UnSubscribeToClientInventoryEvents(client);
  2669. UnSubscribeToClientTeleportEvents(client);
  2670. UnSubscribeToClientScriptEvents(client);
  2671. UnSubscribeToClientParcelEvents(client);
  2672. UnSubscribeToClientGridEvents(client);
  2673. UnSubscribeToClientNetworkEvents(client);
  2674. }
  2675. public virtual void UnSubscribeToClientTerrainEvents(IClientAPI client)
  2676. {
  2677. client.OnRegionHandShakeReply -= SendLayerData;
  2678. }
  2679. public virtual void UnSubscribeToClientPrimEvents(IClientAPI client)
  2680. {
  2681. client.OnUpdatePrimGroupPosition -= m_sceneGraph.UpdatePrimGroupPosition;
  2682. client.OnUpdatePrimSinglePosition -= m_sceneGraph.UpdatePrimSinglePosition;
  2683. client.OnUpdatePrimGroupRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2684. client.OnUpdatePrimGroupMouseRotation -= m_sceneGraph.UpdatePrimGroupRotation;
  2685. client.OnUpdatePrimSingleRotation -= m_sceneGraph.UpdatePrimSingleRotation;
  2686. client.OnUpdatePrimSingleRotationPosition -= m_sceneGraph.UpdatePrimSingleRotationPosition;
  2687. client.OnUpdatePrimScale -= m_sceneGraph.UpdatePrimScale;
  2688. client.OnUpdatePrimGroupScale -= m_sceneGraph.UpdatePrimGroupScale;
  2689. client.OnUpdateExtraParams -= m_sceneGraph.UpdateExtraParam;
  2690. client.OnUpdatePrimShape -= m_sceneGraph.UpdatePrimShape;
  2691. client.OnUpdatePrimTexture -= m_sceneGraph.UpdatePrimTexture;
  2692. client.OnObjectRequest -= RequestPrim;
  2693. client.OnObjectSelect -= SelectPrim;
  2694. client.OnObjectDeselect -= DeselectPrim;
  2695. client.OnGrabUpdate -= m_sceneGraph.MoveObject;
  2696. client.OnSpinStart -= m_sceneGraph.SpinStart;
  2697. client.OnSpinUpdate -= m_sceneGraph.SpinObject;
  2698. client.OnDeRezObject -= DeRezObjects;
  2699. client.OnObjectName -= m_sceneGraph.PrimName;
  2700. client.OnObjectClickAction -= m_sceneGraph.PrimClickAction;
  2701. client.OnObjectMaterial -= m_sceneGraph.PrimMaterial;
  2702. client.OnLinkObjects -= LinkObjects;
  2703. client.OnDelinkObjects -= DelinkObjects;
  2704. client.OnObjectDuplicate -= DuplicateObject;
  2705. client.OnObjectDuplicateOnRay -= doObjectDuplicateOnRay;
  2706. client.OnUpdatePrimFlags -= m_sceneGraph.UpdatePrimFlags;
  2707. client.OnRequestObjectPropertiesFamily -= m_sceneGraph.RequestObjectPropertiesFamily;
  2708. client.OnObjectPermissions -= HandleObjectPermissionsUpdate;
  2709. client.OnGrabObject -= ProcessObjectGrab;
  2710. client.OnDeGrabObject -= ProcessObjectDeGrab;
  2711. client.OnUndo -= m_sceneGraph.HandleUndo;
  2712. client.OnRedo -= m_sceneGraph.HandleRedo;
  2713. client.OnObjectDescription -= m_sceneGraph.PrimDescription;
  2714. client.OnObjectIncludeInSearch -= m_sceneGraph.MakeObjectSearchable;
  2715. client.OnObjectOwner -= ObjectOwner;
  2716. }
  2717. public virtual void UnSubscribeToClientPrimRezEvents(IClientAPI client)
  2718. {
  2719. client.OnAddPrim -= AddNewPrim;
  2720. client.OnRezObject -= RezObject;
  2721. }
  2722. public virtual void UnSubscribeToClientInventoryEvents(IClientAPI client)
  2723. {
  2724. client.OnCreateNewInventoryFolder -= HandleCreateInventoryFolder;
  2725. client.OnUpdateInventoryFolder -= HandleUpdateInventoryFolder;
  2726. client.OnMoveInventoryFolder -= HandleMoveInventoryFolder; // 2; //!!
  2727. client.OnFetchInventoryDescendents -= HandleFetchInventoryDescendents;
  2728. client.OnPurgeInventoryDescendents -= HandlePurgeInventoryDescendents; // 2; //!!
  2729. client.OnFetchInventory -= m_asyncInventorySender.HandleFetchInventory;
  2730. client.OnUpdateInventoryItem -= UpdateInventoryItemAsset;
  2731. client.OnCopyInventoryItem -= CopyInventoryItem;
  2732. client.OnMoveInventoryItem -= MoveInventoryItem;
  2733. client.OnRemoveInventoryItem -= RemoveInventoryItem;
  2734. client.OnRemoveInventoryFolder -= RemoveInventoryFolder;
  2735. client.OnRezScript -= RezScript;
  2736. client.OnRequestTaskInventory -= RequestTaskInventory;
  2737. client.OnRemoveTaskItem -= RemoveTaskInventory;
  2738. client.OnUpdateTaskInventory -= UpdateTaskInventory;
  2739. client.OnMoveTaskItem -= ClientMoveTaskInventoryItem;
  2740. }
  2741. public virtual void UnSubscribeToClientTeleportEvents(IClientAPI client)
  2742. {
  2743. client.OnTeleportLocationRequest -= RequestTeleportLocation;
  2744. //client.OnTeleportLandmarkRequest -= RequestTeleportLandmark;
  2745. //client.OnTeleportHomeRequest -= TeleportClientHome;
  2746. }
  2747. public virtual void UnSubscribeToClientScriptEvents(IClientAPI client)
  2748. {
  2749. client.OnScriptReset -= ProcessScriptReset;
  2750. client.OnGetScriptRunning -= GetScriptRunning;
  2751. client.OnSetScriptRunning -= SetScriptRunning;
  2752. }
  2753. public virtual void UnSubscribeToClientParcelEvents(IClientAPI client)
  2754. {
  2755. client.OnParcelReturnObjectsRequest -= LandChannel.ReturnObjectsInParcel;
  2756. client.OnParcelSetOtherCleanTime -= LandChannel.SetParcelOtherCleanTime;
  2757. client.OnParcelBuy -= ProcessParcelBuy;
  2758. }
  2759. public virtual void UnSubscribeToClientGridEvents(IClientAPI client)
  2760. {
  2761. //client.OnNameFromUUIDRequest -= HandleUUIDNameRequest;
  2762. client.OnMoneyTransferRequest -= ProcessMoneyTransferRequest;
  2763. }
  2764. public virtual void UnSubscribeToClientNetworkEvents(IClientAPI client)
  2765. {
  2766. client.OnNetworkStatsUpdate -= StatsReporter.AddPacketsStats;
  2767. client.OnViewerEffect -= ProcessViewerEffect;
  2768. }
  2769. /// <summary>
  2770. /// Teleport an avatar to their home region
  2771. /// </summary>
  2772. /// <param name="agentId">The avatar's Unique ID</param>
  2773. /// <param name="client">The IClientAPI for the client</param>
  2774. public virtual bool TeleportClientHome(UUID agentId, IClientAPI client)
  2775. {
  2776. if (EntityTransferModule != null)
  2777. {
  2778. return EntityTransferModule.TeleportHome(agentId, client);
  2779. }
  2780. else
  2781. {
  2782. m_log.DebugFormat("[SCENE]: Unable to teleport user home: no AgentTransferModule is active");
  2783. client.SendTeleportFailed("Unable to perform teleports on this simulator.");
  2784. }
  2785. return false;
  2786. }
  2787. /// <summary>
  2788. /// Duplicates object specified by localID. This is the event handler for IClientAPI.
  2789. /// </summary>
  2790. /// <param name="originalPrim">ID of object to duplicate</param>
  2791. /// <param name="offset"></param>
  2792. /// <param name="flags"></param>
  2793. /// <param name="AgentID">Agent doing the duplication</param>
  2794. /// <param name="GroupID">Group of new object</param>
  2795. public void DuplicateObject(uint originalPrim, Vector3 offset, uint flags, UUID AgentID, UUID GroupID)
  2796. {
  2797. SceneObjectGroup copy = SceneGraph.DuplicateObject(originalPrim, offset, flags, AgentID, GroupID, Quaternion.Identity);
  2798. if (copy != null)
  2799. EventManager.TriggerObjectAddedToScene(copy);
  2800. }
  2801. /// <summary>
  2802. /// Duplicates object specified by localID at position raycasted against RayTargetObject using
  2803. /// RayEnd and RayStart to determine what the angle of the ray is
  2804. /// </summary>
  2805. /// <param name="localID">ID of object to duplicate</param>
  2806. /// <param name="dupeFlags"></param>
  2807. /// <param name="AgentID">Agent doing the duplication</param>
  2808. /// <param name="GroupID">Group of new object</param>
  2809. /// <param name="RayTargetObj">The target of the Ray</param>
  2810. /// <param name="RayEnd">The ending of the ray (farthest away point)</param>
  2811. /// <param name="RayStart">The Beginning of the ray (closest point)</param>
  2812. /// <param name="BypassRaycast">Bool to bypass raycasting</param>
  2813. /// <param name="RayEndIsIntersection">The End specified is the place to add the object</param>
  2814. /// <param name="CopyCenters">Position the object at the center of the face that it's colliding with</param>
  2815. /// <param name="CopyRotates">Rotate the object the same as the localID object</param>
  2816. public void doObjectDuplicateOnRay(uint localID, uint dupeFlags, UUID AgentID, UUID GroupID,
  2817. UUID RayTargetObj, Vector3 RayEnd, Vector3 RayStart,
  2818. bool BypassRaycast, bool RayEndIsIntersection, bool CopyCenters, bool CopyRotates)
  2819. {
  2820. Vector3 pos;
  2821. const bool frontFacesOnly = true;
  2822. //m_log.Info("HITTARGET: " + RayTargetObj.ToString() + ", COPYTARGET: " + localID.ToString());
  2823. SceneObjectPart target = GetSceneObjectPart(localID);
  2824. SceneObjectPart target2 = GetSceneObjectPart(RayTargetObj);
  2825. if (target != null && target2 != null)
  2826. {
  2827. Vector3 direction = Vector3.Normalize(RayEnd - RayStart);
  2828. Vector3 AXOrigin = new Vector3(RayStart.X, RayStart.Y, RayStart.Z);
  2829. Vector3 AXdirection = new Vector3(direction.X, direction.Y, direction.Z);
  2830. pos = target2.AbsolutePosition;
  2831. //m_log.Info("[OBJECT_REZ]: TargetPos: " + pos.ToString() + ", RayStart: " + RayStart.ToString() + ", RayEnd: " + RayEnd.ToString() + ", Volume: " + Util.GetDistanceTo(RayStart,RayEnd).ToString() + ", mag1: " + Util.GetMagnitude(RayStart).ToString() + ", mag2: " + Util.GetMagnitude(RayEnd).ToString());
  2832. // TODO: Raytrace better here
  2833. //EntityIntersection ei = m_sceneGraph.GetClosestIntersectingPrim(new Ray(AXOrigin, AXdirection));
  2834. Ray NewRay = new Ray(AXOrigin, AXdirection);
  2835. // Ray Trace against target here
  2836. EntityIntersection ei = target2.TestIntersectionOBB(NewRay, Quaternion.Identity, frontFacesOnly, CopyCenters);
  2837. // Un-comment out the following line to Get Raytrace results printed to the console.
  2838. //m_log.Info("[RAYTRACERESULTS]: Hit:" + ei.HitTF.ToString() + " Point: " + ei.ipoint.ToString() + " Normal: " + ei.normal.ToString());
  2839. float ScaleOffset = 0.5f;
  2840. // If we hit something
  2841. if (ei.HitTF)
  2842. {
  2843. Vector3 scale = target.Scale;
  2844. Vector3 scaleComponent = new Vector3(ei.AAfaceNormal.X, ei.AAfaceNormal.Y, ei.AAfaceNormal.Z);
  2845. if (scaleComponent.X != 0) ScaleOffset = scale.X;
  2846. if (scaleComponent.Y != 0) ScaleOffset = scale.Y;
  2847. if (scaleComponent.Z != 0) ScaleOffset = scale.Z;
  2848. ScaleOffset = Math.Abs(ScaleOffset);
  2849. Vector3 intersectionpoint = new Vector3(ei.ipoint.X, ei.ipoint.Y, ei.ipoint.Z);
  2850. Vector3 normal = new Vector3(ei.normal.X, ei.normal.Y, ei.normal.Z);
  2851. Vector3 offset = normal * (ScaleOffset / 2f);
  2852. pos = intersectionpoint + offset;
  2853. // stick in offset format from the original prim
  2854. pos = pos - target.ParentGroup.AbsolutePosition;
  2855. SceneObjectGroup copy;
  2856. if (CopyRotates)
  2857. {
  2858. Quaternion worldRot = target2.GetWorldRotation();
  2859. // SceneObjectGroup obj = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2860. copy = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, worldRot);
  2861. //obj.Rotation = worldRot;
  2862. //obj.UpdateGroupRotationR(worldRot);
  2863. }
  2864. else
  2865. {
  2866. copy = m_sceneGraph.DuplicateObject(localID, pos, target.GetEffectiveObjectFlags(), AgentID, GroupID, Quaternion.Identity);
  2867. }
  2868. if (copy != null)
  2869. EventManager.TriggerObjectAddedToScene(copy);
  2870. }
  2871. }
  2872. }
  2873. /// <summary>
  2874. /// Get the avatar apperance for the given client.
  2875. /// </summary>
  2876. /// <param name="client"></param>
  2877. /// <param name="appearance"></param>
  2878. public void GetAvatarAppearance(IClientAPI client, out AvatarAppearance appearance)
  2879. {
  2880. AgentCircuitData aCircuit = m_authenticateHandler.GetAgentCircuitData(client.CircuitCode);
  2881. if (aCircuit == null)
  2882. {
  2883. m_log.DebugFormat("[APPEARANCE] Client did not supply a circuit. Non-Linden? Creating default appearance.");
  2884. appearance = new AvatarAppearance();
  2885. return;
  2886. }
  2887. appearance = aCircuit.Appearance;
  2888. if (appearance == null)
  2889. {
  2890. m_log.DebugFormat("[APPEARANCE]: Appearance not found in {0}, returning default", RegionInfo.RegionName);
  2891. appearance = new AvatarAppearance();
  2892. }
  2893. }
  2894. public override void RemoveClient(UUID agentID, bool closeChildAgents)
  2895. {
  2896. AgentCircuitData acd = m_authenticateHandler.GetAgentCircuitData(agentID);
  2897. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  2898. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  2899. // However, will keep for now just in case.
  2900. if (acd == null)
  2901. {
  2902. m_log.ErrorFormat(
  2903. "[SCENE]: No agent circuit found for {0} in {1}, aborting Scene.RemoveClient", agentID, Name);
  2904. return;
  2905. }
  2906. else
  2907. {
  2908. m_authenticateHandler.RemoveCircuit(agentID);
  2909. }
  2910. // TODO: Can we now remove this lock?
  2911. lock (acd)
  2912. {
  2913. bool isChildAgent = false;
  2914. ScenePresence avatar = GetScenePresence(agentID);
  2915. // Shouldn't be necessary since RemoveClient() is currently only called by IClientAPI.Close() which
  2916. // in turn is only called by Scene.IncomingCloseAgent() which checks whether the presence exists or not
  2917. // However, will keep for now just in case.
  2918. if (avatar == null)
  2919. {
  2920. m_log.ErrorFormat(
  2921. "[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in the scene.", agentID);
  2922. return;
  2923. }
  2924. try
  2925. {
  2926. isChildAgent = avatar.IsChildAgent;
  2927. m_log.DebugFormat(
  2928. "[SCENE]: Removing {0} agent {1} {2} from {3}",
  2929. isChildAgent ? "child" : "root", avatar.Name, agentID, Name);
  2930. // Don't do this to root agents, it's not nice for the viewer
  2931. if (closeChildAgents && isChildAgent)
  2932. {
  2933. // Tell a single agent to disconnect from the region.
  2934. // Let's do this via UDP
  2935. avatar.ControllingClient.SendShutdownConnectionNotice();
  2936. }
  2937. // Only applies to root agents.
  2938. if (avatar.ParentID != 0)
  2939. {
  2940. avatar.StandUp();
  2941. }
  2942. m_sceneGraph.removeUserCount(!isChildAgent);
  2943. // TODO: We shouldn't use closeChildAgents here - it's being used by the NPC module to stop
  2944. // unnecessary operations. This should go away once NPCs have no accompanying IClientAPI
  2945. if (closeChildAgents && CapsModule != null)
  2946. CapsModule.RemoveCaps(agentID);
  2947. if (closeChildAgents && !isChildAgent)
  2948. {
  2949. List<ulong> regions = avatar.KnownRegionHandles;
  2950. regions.Remove(RegionInfo.RegionHandle);
  2951. // This ends up being done asynchronously so that a logout isn't held up where there are many present but unresponsive neighbours.
  2952. m_sceneGridService.SendCloseChildAgentConnections(agentID, acd.SessionID.ToString(), regions);
  2953. }
  2954. m_eventManager.TriggerClientClosed(agentID, this);
  2955. m_eventManager.TriggerOnRemovePresence(agentID);
  2956. if (!isChildAgent)
  2957. {
  2958. if (AttachmentsModule != null)
  2959. {
  2960. AttachmentsModule.DeRezAttachments(avatar);
  2961. }
  2962. ForEachClient(
  2963. delegate(IClientAPI client)
  2964. {
  2965. //We can safely ignore null reference exceptions. It means the avatar is dead and cleaned up anyway
  2966. try { client.SendKillObject(new List<uint> { avatar.LocalId }); }
  2967. catch (NullReferenceException) { }
  2968. });
  2969. }
  2970. // It's possible for child agents to have transactions if changes are being made cross-border.
  2971. if (AgentTransactionsModule != null)
  2972. AgentTransactionsModule.RemoveAgentAssetTransactions(agentID);
  2973. }
  2974. catch (Exception e)
  2975. {
  2976. m_log.Error(
  2977. string.Format("[SCENE]: Exception removing {0} from {1}. Cleaning up. Exception ", avatar.Name, Name), e);
  2978. }
  2979. finally
  2980. {
  2981. try
  2982. {
  2983. // Always clean these structures up so that any failure above doesn't cause them to remain in the
  2984. // scene with possibly bad effects (e.g. continually timing out on unacked packets and triggering
  2985. // the same cleanup exception continually.
  2986. m_sceneGraph.RemoveScenePresence(agentID);
  2987. m_clientManager.Remove(agentID);
  2988. avatar.Close();
  2989. }
  2990. catch (Exception e)
  2991. {
  2992. m_log.Error(
  2993. string.Format("[SCENE]: Exception in final clean up of {0} in {1}. Exception ", avatar.Name, Name), e);
  2994. }
  2995. }
  2996. }
  2997. //m_log.InfoFormat("[SCENE] Memory pre GC {0}", System.GC.GetTotalMemory(false));
  2998. //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
  2999. }
  3000. /// <summary>
  3001. /// Removes region from an avatar's known region list. This coincides with child agents. For each child agent, there will be a known region entry.
  3002. ///
  3003. /// </summary>
  3004. /// <param name="avatarID"></param>
  3005. /// <param name="regionslst"></param>
  3006. public void HandleRemoveKnownRegionsFromAvatar(UUID avatarID, List<ulong> regionslst)
  3007. {
  3008. ScenePresence av = GetScenePresence(avatarID);
  3009. if (av != null)
  3010. {
  3011. lock (av)
  3012. {
  3013. for (int i = 0; i < regionslst.Count; i++)
  3014. {
  3015. av.RemoveNeighbourRegion(regionslst[i]);
  3016. }
  3017. }
  3018. }
  3019. }
  3020. #endregion
  3021. #region Entities
  3022. public void SendKillObject(List<uint> localIDs)
  3023. {
  3024. List<uint> deleteIDs = new List<uint>();
  3025. foreach (uint localID in localIDs)
  3026. {
  3027. SceneObjectPart part = GetSceneObjectPart(localID);
  3028. if (part != null) // It is a prim
  3029. {
  3030. if (part.ParentGroup != null && !part.ParentGroup.IsDeleted) // Valid
  3031. {
  3032. if (part.ParentGroup.RootPart != part) // Child part
  3033. continue;
  3034. }
  3035. }
  3036. deleteIDs.Add(localID);
  3037. }
  3038. ForEachClient(c => c.SendKillObject(deleteIDs));
  3039. }
  3040. #endregion
  3041. #region RegionComms
  3042. /// <summary>
  3043. /// Do the work necessary to initiate a new user connection for a particular scene.
  3044. /// </summary>
  3045. /// <param name="agent">CircuitData of the agent who is connecting</param>
  3046. /// <param name="teleportFlags"></param>
  3047. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3048. /// <returns>True if the region accepts this agent. False if it does not. False will
  3049. /// also return a reason.</returns>
  3050. public bool NewUserConnection(AgentCircuitData agent, uint teleportFlags, out string reason)
  3051. {
  3052. return NewUserConnection(agent, teleportFlags, out reason, true);
  3053. }
  3054. /// <summary>
  3055. /// Do the work necessary to initiate a new user connection for a particular scene.
  3056. /// </summary>
  3057. /// <remarks>
  3058. /// The return bool should allow for connections to be refused, but as not all calling paths
  3059. /// take proper notice of it yet, we still allowed banned users in.
  3060. ///
  3061. /// At the moment this method consists of setting up the caps infrastructure
  3062. /// The return bool should allow for connections to be refused, but as not all calling paths
  3063. /// take proper notice of it let, we allowed banned users in still.
  3064. ///
  3065. /// This method is called by the login service (in the case of login) or another simulator (in the case of region
  3066. /// cross or teleport) to initiate the connection. It is not triggered by the viewer itself - the connection
  3067. /// is activated later when the viewer sends the initial UseCircuitCodePacket UDP packet (in the case of
  3068. /// the LLUDP stack).
  3069. /// </remarks>
  3070. /// <param name="acd">CircuitData of the agent who is connecting</param>
  3071. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3072. /// <param name="requirePresenceLookup">True for normal presence. False for NPC
  3073. /// or other applications where a full grid/Hypergrid presence may not be required.</param>
  3074. /// <returns>True if the region accepts this agent. False if it does not. False will
  3075. /// also return a reason.</returns>
  3076. public bool NewUserConnection(AgentCircuitData acd, uint teleportFlags, out string reason, bool requirePresenceLookup)
  3077. {
  3078. bool vialogin = ((teleportFlags & (uint)TPFlags.ViaLogin) != 0 ||
  3079. (teleportFlags & (uint)TPFlags.ViaHGLogin) != 0);
  3080. bool viahome = ((teleportFlags & (uint)TPFlags.ViaHome) != 0);
  3081. bool godlike = ((teleportFlags & (uint)TPFlags.Godlike) != 0);
  3082. reason = String.Empty;
  3083. //Teleport flags:
  3084. //
  3085. // TeleportFlags.ViaGodlikeLure - Border Crossing
  3086. // TeleportFlags.ViaLogin - Login
  3087. // TeleportFlags.TeleportFlags.ViaLure - Teleport request sent by another user
  3088. // TeleportFlags.ViaLandmark | TeleportFlags.ViaLocation | TeleportFlags.ViaLandmark | TeleportFlags.Default - Regular Teleport
  3089. // Don't disable this log message - it's too helpful
  3090. m_log.DebugFormat(
  3091. "[SCENE]: Region {0} told of incoming {1} agent {2} {3} {4} (circuit code {5}, IP {6}, viewer {7}, teleportflags ({8}), position {9})",
  3092. RegionInfo.RegionName,
  3093. (acd.child ? "child" : "root"),
  3094. acd.firstname,
  3095. acd.lastname,
  3096. acd.AgentID,
  3097. acd.circuitcode,
  3098. acd.IPAddress,
  3099. acd.Viewer,
  3100. ((TPFlags)teleportFlags).ToString(),
  3101. acd.startpos
  3102. );
  3103. if (!LoginsEnabled)
  3104. {
  3105. reason = "Logins Disabled";
  3106. return false;
  3107. }
  3108. //Check if the viewer is banned or in the viewer access list
  3109. //We check if the substring is listed for higher flexebility
  3110. bool ViewerDenied = true;
  3111. //Check if the specific viewer is listed in the allowed viewer list
  3112. if (m_AllowedViewers.Count > 0)
  3113. {
  3114. foreach (string viewer in m_AllowedViewers)
  3115. {
  3116. if (viewer == acd.Viewer.Substring(0, viewer.Length).Trim().ToLower())
  3117. {
  3118. ViewerDenied = false;
  3119. break;
  3120. }
  3121. }
  3122. }
  3123. else
  3124. {
  3125. ViewerDenied = false;
  3126. }
  3127. //Check if the viewer is in the banned list
  3128. if (m_BannedViewers.Count > 0)
  3129. {
  3130. foreach (string viewer in m_BannedViewers)
  3131. {
  3132. if (viewer == acd.Viewer.Substring(0, viewer.Length).Trim().ToLower())
  3133. {
  3134. ViewerDenied = true;
  3135. break;
  3136. }
  3137. }
  3138. }
  3139. if (ViewerDenied)
  3140. {
  3141. m_log.DebugFormat(
  3142. "[SCENE]: Access denied for {0} {1} using {2}",
  3143. acd.firstname, acd.lastname, acd.Viewer);
  3144. reason = "Access denied, your viewer is banned by the region owner";
  3145. return false;
  3146. }
  3147. ILandObject land;
  3148. ScenePresence sp;
  3149. lock (m_removeClientLock)
  3150. {
  3151. sp = GetScenePresence(acd.AgentID);
  3152. // We need to ensure that we are not already removing the scene presence before we ask it not to be
  3153. // closed.
  3154. if (sp != null && sp.IsChildAgent && sp.LifecycleState == ScenePresenceState.Running)
  3155. {
  3156. m_log.DebugFormat(
  3157. "[SCENE]: Reusing existing child scene presence for {0} in {1}", sp.Name, Name);
  3158. // In the case where, for example, an A B C D region layout, an avatar may
  3159. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. When C
  3160. // renews the lease on the child agent at B, we must make sure that the close from A does not succeed.
  3161. if (!acd.ChildrenCapSeeds.ContainsKey(RegionInfo.RegionHandle))
  3162. {
  3163. m_log.DebugFormat(
  3164. "[SCENE]: Setting DoNotCloseAfterTeleport for child scene presence {0} in {1} because source will attempt close.",
  3165. sp.Name, Name);
  3166. sp.DoNotCloseAfterTeleport = true;
  3167. }
  3168. else if (EntityTransferModule.IsInTransit(sp.UUID))
  3169. {
  3170. m_log.DebugFormat(
  3171. "[SCENE]: Setting DoNotCloseAfterTeleport for child scene presence {0} in {1} because this region will attempt previous end-of-teleport close.",
  3172. sp.Name, Name);
  3173. sp.DoNotCloseAfterTeleport = true;
  3174. }
  3175. }
  3176. }
  3177. // Need to poll here in case we are currently deleting an sp. Letting threads run over each other will
  3178. // allow unpredictable things to happen.
  3179. if (sp != null)
  3180. {
  3181. const int polls = 10;
  3182. const int pollInterval = 1000;
  3183. int pollsLeft = polls;
  3184. while (sp.LifecycleState == ScenePresenceState.Removing && pollsLeft-- > 0)
  3185. Thread.Sleep(pollInterval);
  3186. if (sp.LifecycleState == ScenePresenceState.Removing)
  3187. {
  3188. m_log.WarnFormat(
  3189. "[SCENE]: Agent {0} in {1} was still being removed after {2}s. Aborting NewUserConnection.",
  3190. sp.Name, Name, polls * pollInterval / 1000);
  3191. return false;
  3192. }
  3193. else if (polls != pollsLeft)
  3194. {
  3195. m_log.DebugFormat(
  3196. "[SCENE]: NewUserConnection for agent {0} in {1} had to wait {2}s for in-progress removal to complete on an old presence.",
  3197. sp.Name, Name, polls * pollInterval / 1000);
  3198. }
  3199. }
  3200. // TODO: can we remove this lock?
  3201. lock (acd)
  3202. {
  3203. if (sp != null && !sp.IsChildAgent)
  3204. {
  3205. // We have a root agent. Is it in transit?
  3206. if (!EntityTransferModule.IsInTransit(sp.UUID))
  3207. {
  3208. // We have a zombie from a crashed session.
  3209. // Or the same user is trying to be root twice here, won't work.
  3210. // Kill it.
  3211. m_log.WarnFormat(
  3212. "[SCENE]: Existing root scene presence detected for {0} {1} in {2} when connecting. Removing existing presence.",
  3213. sp.Name, sp.UUID, RegionInfo.RegionName);
  3214. if (sp.ControllingClient != null)
  3215. IncomingCloseAgent(sp.UUID, true);
  3216. sp = null;
  3217. }
  3218. //else
  3219. // m_log.WarnFormat("[SCENE]: Existing root scene presence for {0} {1} in {2}, but agent is in trasit", sp.Name, sp.UUID, RegionInfo.RegionName);
  3220. }
  3221. // Optimistic: add or update the circuit data with the new agent circuit data and teleport flags.
  3222. // We need the circuit data here for some of the subsequent checks. (groups, for example)
  3223. // If the checks fail, we remove the circuit.
  3224. acd.teleportFlags = teleportFlags;
  3225. m_authenticateHandler.AddNewCircuit(acd.circuitcode, acd);
  3226. land = LandChannel.GetLandObject(acd.startpos.X, acd.startpos.Y);
  3227. // On login test land permisions
  3228. if (vialogin)
  3229. {
  3230. if (land != null && !TestLandRestrictions(acd.AgentID, out reason, ref acd.startpos.X, ref acd.startpos.Y))
  3231. {
  3232. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3233. return false;
  3234. }
  3235. }
  3236. if (sp == null) // We don't have an [child] agent here already
  3237. {
  3238. if (requirePresenceLookup)
  3239. {
  3240. try
  3241. {
  3242. if (!VerifyUserPresence(acd, out reason))
  3243. {
  3244. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3245. return false;
  3246. }
  3247. }
  3248. catch (Exception e)
  3249. {
  3250. m_log.ErrorFormat(
  3251. "[SCENE]: Exception verifying presence {0}{1}", e.Message, e.StackTrace);
  3252. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3253. return false;
  3254. }
  3255. }
  3256. try
  3257. {
  3258. if (!AuthorizeUser(acd, SeeIntoRegion, out reason))
  3259. {
  3260. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3261. return false;
  3262. }
  3263. }
  3264. catch (Exception e)
  3265. {
  3266. m_log.ErrorFormat(
  3267. "[SCENE]: Exception authorizing user {0}{1}", e.Message, e.StackTrace);
  3268. m_authenticateHandler.RemoveCircuit(acd.circuitcode);
  3269. return false;
  3270. }
  3271. m_log.InfoFormat(
  3272. "[SCENE]: Region {0} authenticated and authorized incoming {1} agent {2} {3} {4} (circuit code {5})",
  3273. Name, (acd.child ? "child" : "root"), acd.firstname, acd.lastname,
  3274. acd.AgentID, acd.circuitcode);
  3275. if (CapsModule != null)
  3276. {
  3277. CapsModule.SetAgentCapsSeeds(acd);
  3278. CapsModule.CreateCaps(acd.AgentID);
  3279. }
  3280. }
  3281. else
  3282. {
  3283. // Let the SP know how we got here. This has a lot of interesting
  3284. // uses down the line.
  3285. sp.TeleportFlags = (TPFlags)teleportFlags;
  3286. if (sp.IsChildAgent)
  3287. {
  3288. m_log.DebugFormat(
  3289. "[SCENE]: Adjusting known seeds for existing agent {0} in {1}",
  3290. acd.AgentID, RegionInfo.RegionName);
  3291. sp.AdjustKnownSeeds();
  3292. if (CapsModule != null)
  3293. {
  3294. CapsModule.SetAgentCapsSeeds(acd);
  3295. CapsModule.CreateCaps(acd.AgentID);
  3296. }
  3297. }
  3298. }
  3299. // Try caching an incoming user name much earlier on to see if this helps with an issue
  3300. // where HG users are occasionally seen by others as "Unknown User" because their UUIDName
  3301. // request for the HG avatar appears to trigger before the user name is cached.
  3302. CacheUserName(null, acd);
  3303. }
  3304. if (vialogin)
  3305. {
  3306. // CleanDroppedAttachments();
  3307. if (TestBorderCross(acd.startpos, Cardinals.E))
  3308. {
  3309. Border crossedBorder = GetCrossedBorder(acd.startpos, Cardinals.E);
  3310. acd.startpos.X = crossedBorder.BorderLine.Z - 1;
  3311. }
  3312. if (TestBorderCross(acd.startpos, Cardinals.N))
  3313. {
  3314. Border crossedBorder = GetCrossedBorder(acd.startpos, Cardinals.N);
  3315. acd.startpos.Y = crossedBorder.BorderLine.Z - 1;
  3316. }
  3317. //Mitigate http://opensimulator.org/mantis/view.php?id=3522
  3318. // Check if start position is outside of region
  3319. // If it is, check the Z start position also.. if not, leave it alone.
  3320. if (BordersLocked)
  3321. {
  3322. lock (EastBorders)
  3323. {
  3324. if (acd.startpos.X > EastBorders[0].BorderLine.Z)
  3325. {
  3326. m_log.Warn("FIX AGENT POSITION");
  3327. acd.startpos.X = EastBorders[0].BorderLine.Z * 0.5f;
  3328. if (acd.startpos.Z > 720)
  3329. acd.startpos.Z = 720;
  3330. }
  3331. }
  3332. lock (NorthBorders)
  3333. {
  3334. if (acd.startpos.Y > NorthBorders[0].BorderLine.Z)
  3335. {
  3336. m_log.Warn("FIX Agent POSITION");
  3337. acd.startpos.Y = NorthBorders[0].BorderLine.Z * 0.5f;
  3338. if (acd.startpos.Z > 720)
  3339. acd.startpos.Z = 720;
  3340. }
  3341. }
  3342. } else
  3343. {
  3344. if (acd.startpos.X > EastBorders[0].BorderLine.Z)
  3345. {
  3346. m_log.Warn("FIX AGENT POSITION");
  3347. acd.startpos.X = EastBorders[0].BorderLine.Z * 0.5f;
  3348. if (acd.startpos.Z > 720)
  3349. acd.startpos.Z = 720;
  3350. }
  3351. if (acd.startpos.Y > NorthBorders[0].BorderLine.Z)
  3352. {
  3353. m_log.Warn("FIX Agent POSITION");
  3354. acd.startpos.Y = NorthBorders[0].BorderLine.Z * 0.5f;
  3355. if (acd.startpos.Z > 720)
  3356. acd.startpos.Z = 720;
  3357. }
  3358. }
  3359. // Honor Estate teleport routing via Telehubs excluding ViaHome and GodLike TeleportFlags
  3360. if (RegionInfo.RegionSettings.TelehubObject != UUID.Zero &&
  3361. RegionInfo.EstateSettings.AllowDirectTeleport == false &&
  3362. !viahome && !godlike)
  3363. {
  3364. SceneObjectGroup telehub = GetSceneObjectGroup(RegionInfo.RegionSettings.TelehubObject);
  3365. // Can have multiple SpawnPoints
  3366. List<SpawnPoint> spawnpoints = RegionInfo.RegionSettings.SpawnPoints();
  3367. if (spawnpoints.Count > 1)
  3368. {
  3369. // We have multiple SpawnPoints, Route the agent to a random or sequential one
  3370. if (SpawnPointRouting == "random")
  3371. acd.startpos = spawnpoints[Util.RandomClass.Next(spawnpoints.Count) - 1].GetLocation(
  3372. telehub.AbsolutePosition,
  3373. telehub.GroupRotation
  3374. );
  3375. else
  3376. acd.startpos = spawnpoints[SpawnPoint()].GetLocation(
  3377. telehub.AbsolutePosition,
  3378. telehub.GroupRotation
  3379. );
  3380. }
  3381. else
  3382. {
  3383. // We have a single SpawnPoint and will route the agent to it
  3384. acd.startpos = spawnpoints[0].GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  3385. }
  3386. return true;
  3387. }
  3388. // Honor parcel landing type and position.
  3389. if (land != null)
  3390. {
  3391. if (land.LandData.LandingType == (byte)1 && land.LandData.UserLocation != Vector3.Zero)
  3392. {
  3393. acd.startpos = land.LandData.UserLocation;
  3394. }
  3395. }
  3396. }
  3397. return true;
  3398. }
  3399. public bool TestLandRestrictions(UUID agentID, out string reason, ref float posX, ref float posY)
  3400. {
  3401. if (posX < 0)
  3402. posX = 0;
  3403. else if (posX >= 256)
  3404. posX = 255.999f;
  3405. if (posY < 0)
  3406. posY = 0;
  3407. else if (posY >= 256)
  3408. posY = 255.999f;
  3409. reason = String.Empty;
  3410. if (Permissions.IsGod(agentID))
  3411. return true;
  3412. ILandObject land = LandChannel.GetLandObject(posX, posY);
  3413. if (land == null)
  3414. return false;
  3415. bool banned = land.IsBannedFromLand(agentID);
  3416. bool restricted = land.IsRestrictedFromLand(agentID);
  3417. if (banned || restricted)
  3418. {
  3419. ILandObject nearestParcel = GetNearestAllowedParcel(agentID, posX, posY);
  3420. if (nearestParcel != null)
  3421. {
  3422. //Move agent to nearest allowed
  3423. Vector3 newPosition = GetParcelCenterAtGround(nearestParcel);
  3424. posX = newPosition.X;
  3425. posY = newPosition.Y;
  3426. }
  3427. else
  3428. {
  3429. if (banned)
  3430. {
  3431. reason = "Cannot regioncross into banned parcel.";
  3432. }
  3433. else
  3434. {
  3435. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3436. RegionInfo.RegionName);
  3437. }
  3438. return false;
  3439. }
  3440. }
  3441. reason = "";
  3442. return true;
  3443. }
  3444. /// <summary>
  3445. /// Verifies that the user has a presence on the Grid
  3446. /// </summary>
  3447. /// <param name="agent">Circuit Data of the Agent we're verifying</param>
  3448. /// <param name="reason">Outputs the reason for the false response on this string</param>
  3449. /// <returns>True if the user has a session on the grid. False if it does not. False will
  3450. /// also return a reason.</returns>
  3451. public virtual bool VerifyUserPresence(AgentCircuitData agent, out string reason)
  3452. {
  3453. reason = String.Empty;
  3454. IPresenceService presence = RequestModuleInterface<IPresenceService>();
  3455. if (presence == null)
  3456. {
  3457. reason = String.Format("Failed to verify user presence in the grid for {0} {1} in region {2}. Presence service does not exist.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3458. return false;
  3459. }
  3460. OpenSim.Services.Interfaces.PresenceInfo pinfo = presence.GetAgent(agent.SessionID);
  3461. if (pinfo == null)
  3462. {
  3463. reason = String.Format("Failed to verify user presence in the grid for {0} {1}, access denied to region {2}.", agent.firstname, agent.lastname, RegionInfo.RegionName);
  3464. return false;
  3465. }
  3466. return true;
  3467. }
  3468. /// <summary>
  3469. /// Verify if the user can connect to this region. Checks the banlist and ensures that the region is set for public access
  3470. /// </summary>
  3471. /// <param name="agent">The circuit data for the agent</param>
  3472. /// <param name="reason">outputs the reason to this string</param>
  3473. /// <returns>True if the region accepts this agent. False if it does not. False will
  3474. /// also return a reason.</returns>
  3475. protected virtual bool AuthorizeUser(AgentCircuitData agent, bool bypassAccessControl, out string reason)
  3476. {
  3477. reason = String.Empty;
  3478. if (!m_strictAccessControl) return true;
  3479. if (Permissions.IsGod(agent.AgentID)) return true;
  3480. if (AuthorizationService != null)
  3481. {
  3482. if (!AuthorizationService.IsAuthorizedForRegion(
  3483. agent.AgentID.ToString(), agent.firstname, agent.lastname, RegionInfo.RegionID.ToString(), out reason))
  3484. {
  3485. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because {4}",
  3486. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName, reason);
  3487. return false;
  3488. }
  3489. }
  3490. // We only test the things below when we want to cut off
  3491. // child agents from being present in the scene for which their root
  3492. // agent isn't allowed. Otherwise, we allow child agents. The test for
  3493. // the root is done elsewhere (QueryAccess)
  3494. if (!bypassAccessControl)
  3495. {
  3496. if (RegionInfo.EstateSettings != null)
  3497. {
  3498. if (RegionInfo.EstateSettings.IsBanned(agent.AgentID))
  3499. {
  3500. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user is on the banlist",
  3501. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3502. reason = String.Format("Denied access to region {0}: You have been banned from that region.",
  3503. RegionInfo.RegionName);
  3504. return false;
  3505. }
  3506. }
  3507. else
  3508. {
  3509. m_log.ErrorFormat("[CONNECTION BEGIN]: Estate Settings is null!");
  3510. }
  3511. List<UUID> agentGroups = new List<UUID>();
  3512. if (m_groupsModule != null)
  3513. {
  3514. GroupMembershipData[] GroupMembership = m_groupsModule.GetMembershipData(agent.AgentID);
  3515. if (GroupMembership != null)
  3516. {
  3517. for (int i = 0; i < GroupMembership.Length; i++)
  3518. agentGroups.Add(GroupMembership[i].GroupID);
  3519. }
  3520. else
  3521. {
  3522. m_log.ErrorFormat("[CONNECTION BEGIN]: GroupMembership is null!");
  3523. }
  3524. }
  3525. bool groupAccess = false;
  3526. UUID[] estateGroups = RegionInfo.EstateSettings.EstateGroups;
  3527. if (estateGroups != null)
  3528. {
  3529. foreach (UUID group in estateGroups)
  3530. {
  3531. if (agentGroups.Contains(group))
  3532. {
  3533. groupAccess = true;
  3534. break;
  3535. }
  3536. }
  3537. }
  3538. else
  3539. {
  3540. m_log.ErrorFormat("[CONNECTION BEGIN]: EstateGroups is null!");
  3541. }
  3542. if (!RegionInfo.EstateSettings.PublicAccess &&
  3543. !RegionInfo.EstateSettings.HasAccess(agent.AgentID) &&
  3544. !groupAccess)
  3545. {
  3546. m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the estate",
  3547. agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3548. reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3549. RegionInfo.RegionName);
  3550. return false;
  3551. }
  3552. }
  3553. // TODO: estate/region settings are not properly hooked up
  3554. // to ILandObject.isRestrictedFromLand()
  3555. // if (null != LandChannel)
  3556. // {
  3557. // // region seems to have local Id of 1
  3558. // ILandObject land = LandChannel.GetLandObject(1);
  3559. // if (null != land)
  3560. // {
  3561. // if (land.isBannedFromLand(agent.AgentID))
  3562. // {
  3563. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user has been banned from land",
  3564. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3565. // reason = String.Format("Denied access to private region {0}: You are banned from that region.",
  3566. // RegionInfo.RegionName);
  3567. // return false;
  3568. // }
  3569. // if (land.isRestrictedFromLand(agent.AgentID))
  3570. // {
  3571. // m_log.WarnFormat("[CONNECTION BEGIN]: Denied access to: {0} ({1} {2}) at {3} because the user does not have access to the region",
  3572. // agent.AgentID, agent.firstname, agent.lastname, RegionInfo.RegionName);
  3573. // reason = String.Format("Denied access to private region {0}: You are not on the access list for that region.",
  3574. // RegionInfo.RegionName);
  3575. // return false;
  3576. // }
  3577. // }
  3578. // }
  3579. return true;
  3580. }
  3581. /// <summary>
  3582. /// Update an AgentCircuitData object with new information
  3583. /// </summary>
  3584. /// <param name="data">Information to update the AgentCircuitData with</param>
  3585. public void UpdateCircuitData(AgentCircuitData data)
  3586. {
  3587. m_authenticateHandler.UpdateAgentData(data);
  3588. }
  3589. /// <summary>
  3590. /// Change the Circuit Code for the user's Circuit Data
  3591. /// </summary>
  3592. /// <param name="oldcc">The old Circuit Code. Must match a previous circuit code</param>
  3593. /// <param name="newcc">The new Circuit Code. Must not be an already existing circuit code</param>
  3594. /// <returns>True if we successfully changed it. False if we did not</returns>
  3595. public bool ChangeCircuitCode(uint oldcc, uint newcc)
  3596. {
  3597. return m_authenticateHandler.TryChangeCiruitCode(oldcc, newcc);
  3598. }
  3599. // /// <summary>
  3600. // /// The Grid has requested that we log-off a user. Log them off.
  3601. // /// </summary>
  3602. // /// <param name="AvatarID">Unique ID of the avatar to log-off</param>
  3603. // /// <param name="RegionSecret">SecureSessionID of the user, or the RegionSecret text when logging on to the grid</param>
  3604. // /// <param name="message">message to display to the user. Reason for being logged off</param>
  3605. // public void HandleLogOffUserFromGrid(UUID AvatarID, UUID RegionSecret, string message)
  3606. // {
  3607. // ScenePresence loggingOffUser = GetScenePresence(AvatarID);
  3608. // if (loggingOffUser != null)
  3609. // {
  3610. // UUID localRegionSecret = UUID.Zero;
  3611. // bool parsedsecret = UUID.TryParse(RegionInfo.regionSecret, out localRegionSecret);
  3612. //
  3613. // // Region Secret is used here in case a new sessionid overwrites an old one on the user server.
  3614. // // Will update the user server in a few revisions to use it.
  3615. //
  3616. // if (RegionSecret == loggingOffUser.ControllingClient.SecureSessionId || (parsedsecret && RegionSecret == localRegionSecret))
  3617. // {
  3618. // m_sceneGridService.SendCloseChildAgentConnections(loggingOffUser.UUID, loggingOffUser.KnownRegionHandles);
  3619. // loggingOffUser.ControllingClient.Kick(message);
  3620. // // Give them a second to receive the message!
  3621. // Thread.Sleep(1000);
  3622. // loggingOffUser.ControllingClient.Close();
  3623. // }
  3624. // else
  3625. // {
  3626. // m_log.Info("[USERLOGOFF]: System sending the LogOff user message failed to sucessfully authenticate");
  3627. // }
  3628. // }
  3629. // else
  3630. // {
  3631. // m_log.InfoFormat("[USERLOGOFF]: Got a logoff request for {0} but the user isn't here. The user might already have been logged out", AvatarID.ToString());
  3632. // }
  3633. // }
  3634. // /// <summary>
  3635. // /// Triggered when an agent crosses into this sim. Also happens on initial login.
  3636. // /// </summary>
  3637. // /// <param name="agentID"></param>
  3638. // /// <param name="position"></param>
  3639. // /// <param name="isFlying"></param>
  3640. // public virtual void AgentCrossing(UUID agentID, Vector3 position, bool isFlying)
  3641. // {
  3642. // ScenePresence presence = GetScenePresence(agentID);
  3643. // if (presence != null)
  3644. // {
  3645. // try
  3646. // {
  3647. // presence.MakeRootAgent(position, isFlying);
  3648. // }
  3649. // catch (Exception e)
  3650. // {
  3651. // m_log.ErrorFormat("[SCENE]: Unable to do agent crossing, exception {0}{1}", e.Message, e.StackTrace);
  3652. // }
  3653. // }
  3654. // else
  3655. // {
  3656. // m_log.ErrorFormat(
  3657. // "[SCENE]: Could not find presence for agent {0} crossing into scene {1}",
  3658. // agentID, RegionInfo.RegionName);
  3659. // }
  3660. // }
  3661. /// <summary>
  3662. /// We've got an update about an agent that sees into this region,
  3663. /// send it to ScenePresence for processing It's the full data.
  3664. /// </summary>
  3665. /// <param name="cAgentData">Agent that contains all of the relevant things about an agent.
  3666. /// Appearance, animations, position, etc.</param>
  3667. /// <returns>true if we handled it.</returns>
  3668. public virtual bool IncomingChildAgentDataUpdate(AgentData cAgentData)
  3669. {
  3670. m_log.DebugFormat(
  3671. "[SCENE]: Incoming child agent update for {0} in {1}", cAgentData.AgentID, RegionInfo.RegionName);
  3672. // TODO: This check should probably be in QueryAccess().
  3673. ILandObject nearestParcel = GetNearestAllowedParcel(cAgentData.AgentID, Constants.RegionSize / 2, Constants.RegionSize / 2);
  3674. if (nearestParcel == null)
  3675. {
  3676. m_log.DebugFormat(
  3677. "[SCENE]: Denying root agent entry to {0} in {1}: no allowed parcel",
  3678. cAgentData.AgentID, RegionInfo.RegionName);
  3679. return false;
  3680. }
  3681. // We have to wait until the viewer contacts this region
  3682. // after receiving the EnableSimulator HTTP Event Queue message (for the v1 teleport protocol)
  3683. // or TeleportFinish (for the v2 teleport protocol). This triggers the viewer to send
  3684. // a UseCircuitCode packet which in turn calls AddNewClient which finally creates the ScenePresence.
  3685. ScenePresence sp = WaitGetScenePresence(cAgentData.AgentID);
  3686. if (sp != null)
  3687. {
  3688. if (cAgentData.SessionID != sp.ControllingClient.SessionId)
  3689. {
  3690. m_log.WarnFormat(
  3691. "[SCENE]: Attempt to update agent {0} with invalid session id {1} (possibly from simulator in older version; tell them to update).",
  3692. sp.UUID, cAgentData.SessionID);
  3693. Console.WriteLine(String.Format("[SCENE]: Attempt to update agent {0} ({1}) with invalid session id {2}",
  3694. sp.UUID, sp.ControllingClient.SessionId, cAgentData.SessionID));
  3695. }
  3696. sp.ChildAgentDataUpdate(cAgentData);
  3697. int ntimes = 20;
  3698. if (cAgentData.SenderWantsToWaitForRoot)
  3699. {
  3700. while (sp.IsChildAgent && ntimes-- > 0)
  3701. Thread.Sleep(1000);
  3702. m_log.DebugFormat(
  3703. "[SCENE]: Found presence {0} {1} {2} in {3} after {4} waits",
  3704. sp.Name, sp.UUID, sp.IsChildAgent ? "child" : "root", Name, 20 - ntimes);
  3705. if (sp.IsChildAgent)
  3706. return false;
  3707. }
  3708. return true;
  3709. }
  3710. return false;
  3711. }
  3712. /// <summary>
  3713. /// We've got an update about an agent that sees into this region,
  3714. /// send it to ScenePresence for processing It's only positional data
  3715. /// </summary>
  3716. /// <param name="cAgentData">AgentPosition that contains agent positional data so we can know what to send</param>
  3717. /// <returns>true if we handled it.</returns>
  3718. public virtual bool IncomingChildAgentDataUpdate(AgentPosition cAgentData)
  3719. {
  3720. //m_log.Debug(" XXX Scene IncomingChildAgentDataUpdate POSITION in " + RegionInfo.RegionName);
  3721. ScenePresence childAgentUpdate = GetScenePresence(cAgentData.AgentID);
  3722. if (childAgentUpdate != null)
  3723. {
  3724. if (childAgentUpdate.ControllingClient.SessionId == cAgentData.SessionID)
  3725. {
  3726. // I can't imagine *yet* why we would get an update if the agent is a root agent..
  3727. // however to avoid a race condition crossing borders..
  3728. if (childAgentUpdate.IsChildAgent)
  3729. {
  3730. uint rRegionX = (uint)(cAgentData.RegionHandle >> 40);
  3731. uint rRegionY = (((uint)(cAgentData.RegionHandle)) >> 8);
  3732. uint tRegionX = RegionInfo.RegionLocX;
  3733. uint tRegionY = RegionInfo.RegionLocY;
  3734. //Send Data to ScenePresence
  3735. childAgentUpdate.ChildAgentDataUpdate(cAgentData, tRegionX, tRegionY, rRegionX, rRegionY);
  3736. // Not Implemented:
  3737. //TODO: Do we need to pass the message on to one of our neighbors?
  3738. }
  3739. }
  3740. else
  3741. m_log.WarnFormat("[SCENE]: Attempt at updating position of agent {0} with invalid session id {1}", childAgentUpdate.UUID, cAgentData.SessionID);
  3742. return true;
  3743. }
  3744. return false;
  3745. }
  3746. /// <summary>
  3747. /// Poll until the requested ScenePresence appears or we timeout.
  3748. /// </summary>
  3749. /// <returns>The scene presence is found, else null.</returns>
  3750. /// <param name='agentID'></param>
  3751. protected virtual ScenePresence WaitGetScenePresence(UUID agentID)
  3752. {
  3753. int ntimes = 20;
  3754. ScenePresence sp = null;
  3755. while ((sp = GetScenePresence(agentID)) == null && (ntimes-- > 0))
  3756. Thread.Sleep(1000);
  3757. if (sp == null)
  3758. m_log.WarnFormat(
  3759. "[SCENE PRESENCE]: Did not find presence with id {0} in {1} before timeout",
  3760. agentID, RegionInfo.RegionName);
  3761. return sp;
  3762. }
  3763. public virtual bool IncomingRetrieveRootAgent(UUID id, out IAgentData agent)
  3764. {
  3765. agent = null;
  3766. ScenePresence sp = GetScenePresence(id);
  3767. if ((sp != null) && (!sp.IsChildAgent))
  3768. {
  3769. sp.IsChildAgent = true;
  3770. return sp.CopyAgent(out agent);
  3771. }
  3772. return false;
  3773. }
  3774. /// <summary>
  3775. /// Authenticated close (via network)
  3776. /// </summary>
  3777. /// <param name="agentID"></param>
  3778. /// <param name="force"></param>
  3779. /// <param name="auth_token"></param>
  3780. /// <returns></returns>
  3781. public bool IncomingCloseAgent(UUID agentID, bool force, string auth_token)
  3782. {
  3783. //m_log.DebugFormat("[SCENE]: Processing incoming close agent {0} in region {1} with auth_token {2}", agentID, RegionInfo.RegionName, auth_token);
  3784. // Check that the auth_token is valid
  3785. AgentCircuitData acd = AuthenticateHandler.GetAgentCircuitData(agentID);
  3786. if (acd != null && acd.SessionID.ToString() == auth_token)
  3787. return IncomingCloseAgent(agentID, force);
  3788. else
  3789. m_log.ErrorFormat("[SCENE]: Request to close agent {0} with invalid authorization token {1}", agentID, auth_token);
  3790. return false;
  3791. }
  3792. /// <summary>
  3793. /// Tell a single agent to disconnect from the region.
  3794. /// </summary>
  3795. /// <param name="agentID"></param>
  3796. /// <param name="force">
  3797. /// Force the agent to close even if it might be in the middle of some other operation. You do not want to
  3798. /// force unless you are absolutely sure that the agent is dead and a normal close is not working.
  3799. /// </param>
  3800. public bool IncomingCloseAgent(UUID agentID, bool force)
  3801. {
  3802. ScenePresence sp;
  3803. lock (m_removeClientLock)
  3804. {
  3805. sp = GetScenePresence(agentID);
  3806. if (sp == null)
  3807. {
  3808. m_log.DebugFormat(
  3809. "[SCENE]: Called RemoveClient() with agent ID {0} but no such presence is in {1}",
  3810. agentID, Name);
  3811. return false;
  3812. }
  3813. if (sp.LifecycleState != ScenePresenceState.Running)
  3814. {
  3815. m_log.DebugFormat(
  3816. "[SCENE]: Called RemoveClient() for {0} in {1} but presence is already in state {2}",
  3817. sp.Name, Name, sp.LifecycleState);
  3818. return false;
  3819. }
  3820. // We need to avoid a race condition where in, for example, an A B C D region layout, an avatar may
  3821. // teleport from A -> D, but then -> C before A has asked B to close its old child agent. We do not
  3822. // want to obey this close since C may have renewed the child agent lease on B.
  3823. if (sp.DoNotCloseAfterTeleport)
  3824. {
  3825. m_log.DebugFormat(
  3826. "[SCENE]: Not closing {0} agent {1} in {2} since another simulator has re-established the child connection",
  3827. sp.IsChildAgent ? "child" : "root", sp.Name, Name);
  3828. // Need to reset the flag so that a subsequent close after another teleport can succeed.
  3829. sp.DoNotCloseAfterTeleport = false;
  3830. return false;
  3831. }
  3832. sp.LifecycleState = ScenePresenceState.Removing;
  3833. }
  3834. if (sp != null)
  3835. {
  3836. sp.ControllingClient.Close(force);
  3837. return true;
  3838. }
  3839. // Agent not here
  3840. return false;
  3841. }
  3842. /// <summary>
  3843. /// Tries to teleport agent to another region.
  3844. /// </summary>
  3845. /// <remarks>
  3846. /// The region name must exactly match that given.
  3847. /// </remarks>
  3848. /// <param name="remoteClient"></param>
  3849. /// <param name="regionName"></param>
  3850. /// <param name="position"></param>
  3851. /// <param name="lookAt"></param>
  3852. /// <param name="teleportFlags"></param>
  3853. public void RequestTeleportLocation(IClientAPI remoteClient, string regionName, Vector3 position,
  3854. Vector3 lookat, uint teleportFlags)
  3855. {
  3856. GridRegion region = GridService.GetRegionByName(RegionInfo.ScopeID, regionName);
  3857. if (region == null)
  3858. {
  3859. // can't find the region: Tell viewer and abort
  3860. remoteClient.SendTeleportFailed("The region '" + regionName + "' could not be found.");
  3861. return;
  3862. }
  3863. RequestTeleportLocation(remoteClient, region.RegionHandle, position, lookat, teleportFlags);
  3864. }
  3865. /// <summary>
  3866. /// Tries to teleport agent to other region.
  3867. /// </summary>
  3868. /// <param name="remoteClient"></param>
  3869. /// <param name="regionHandle"></param>
  3870. /// <param name="position"></param>
  3871. /// <param name="lookAt"></param>
  3872. /// <param name="teleportFlags"></param>
  3873. public void RequestTeleportLocation(IClientAPI remoteClient, ulong regionHandle, Vector3 position,
  3874. Vector3 lookAt, uint teleportFlags)
  3875. {
  3876. ScenePresence sp = GetScenePresence(remoteClient.AgentId);
  3877. if (sp != null)
  3878. {
  3879. uint regionX = RegionInfo.RegionLocX;
  3880. uint regionY = RegionInfo.RegionLocY;
  3881. Utils.LongToUInts(regionHandle, out regionX, out regionY);
  3882. int shiftx = (int) regionX - (int) RegionInfo.RegionLocX * (int)Constants.RegionSize;
  3883. int shifty = (int) regionY - (int) RegionInfo.RegionLocY * (int)Constants.RegionSize;
  3884. position.X += shiftx;
  3885. position.Y += shifty;
  3886. bool result = false;
  3887. if (TestBorderCross(position,Cardinals.N))
  3888. result = true;
  3889. if (TestBorderCross(position, Cardinals.S))
  3890. result = true;
  3891. if (TestBorderCross(position, Cardinals.E))
  3892. result = true;
  3893. if (TestBorderCross(position, Cardinals.W))
  3894. result = true;
  3895. // bordercross if position is outside of region
  3896. if (!result)
  3897. {
  3898. regionHandle = RegionInfo.RegionHandle;
  3899. }
  3900. else
  3901. {
  3902. // not in this region, undo the shift!
  3903. position.X -= shiftx;
  3904. position.Y -= shifty;
  3905. }
  3906. if (EntityTransferModule != null)
  3907. {
  3908. EntityTransferModule.Teleport(sp, regionHandle, position, lookAt, teleportFlags);
  3909. }
  3910. else
  3911. {
  3912. m_log.DebugFormat("[SCENE]: Unable to perform teleports: no AgentTransferModule is active");
  3913. sp.ControllingClient.SendTeleportFailed("Unable to perform teleports on this simulator.");
  3914. }
  3915. }
  3916. }
  3917. public bool CrossAgentToNewRegion(ScenePresence agent, bool isFlying)
  3918. {
  3919. if (EntityTransferModule != null)
  3920. {
  3921. return EntityTransferModule.Cross(agent, isFlying);
  3922. }
  3923. else
  3924. {
  3925. m_log.DebugFormat("[SCENE]: Unable to cross agent to neighbouring region, because there is no AgentTransferModule");
  3926. }
  3927. return false;
  3928. }
  3929. public void SendOutChildAgentUpdates(AgentPosition cadu, ScenePresence presence)
  3930. {
  3931. m_sceneGridService.SendChildAgentDataUpdate(cadu, presence);
  3932. }
  3933. #endregion
  3934. #region Other Methods
  3935. protected override IConfigSource GetConfig()
  3936. {
  3937. return m_config;
  3938. }
  3939. #endregion
  3940. public void HandleObjectPermissionsUpdate(IClientAPI controller, UUID agentID, UUID sessionID, byte field, uint localId, uint mask, byte set)
  3941. {
  3942. // Check for spoofing.. since this is permissions we're talking about here!
  3943. if ((controller.SessionId == sessionID) && (controller.AgentId == agentID))
  3944. {
  3945. // Tell the object to do permission update
  3946. if (localId != 0)
  3947. {
  3948. SceneObjectGroup chObjectGroup = GetGroupByPrim(localId);
  3949. if (chObjectGroup != null)
  3950. {
  3951. chObjectGroup.UpdatePermissions(agentID, field, localId, mask, set);
  3952. }
  3953. }
  3954. }
  3955. }
  3956. /// <summary>
  3957. /// Causes all clients to get a full object update on all of the objects in the scene.
  3958. /// </summary>
  3959. public void ForceClientUpdate()
  3960. {
  3961. EntityBase[] entityList = GetEntities();
  3962. foreach (EntityBase ent in entityList)
  3963. {
  3964. if (ent is SceneObjectGroup)
  3965. {
  3966. ((SceneObjectGroup)ent).ScheduleGroupForFullUpdate();
  3967. }
  3968. }
  3969. }
  3970. /// <summary>
  3971. /// This is currently only used for scale (to scale to MegaPrim size)
  3972. /// There is a console command that calls this in OpenSimMain
  3973. /// </summary>
  3974. /// <param name="cmdparams"></param>
  3975. public void HandleEditCommand(string[] cmdparams)
  3976. {
  3977. m_log.DebugFormat("Searching for Primitive: '{0}'", cmdparams[2]);
  3978. EntityBase[] entityList = GetEntities();
  3979. foreach (EntityBase ent in entityList)
  3980. {
  3981. if (ent is SceneObjectGroup)
  3982. {
  3983. SceneObjectPart part = ((SceneObjectGroup)ent).GetPart(((SceneObjectGroup)ent).UUID);
  3984. if (part != null)
  3985. {
  3986. if (part.Name == cmdparams[2])
  3987. {
  3988. part.Resize(
  3989. new Vector3(Convert.ToSingle(cmdparams[3]), Convert.ToSingle(cmdparams[4]),
  3990. Convert.ToSingle(cmdparams[5])));
  3991. m_log.DebugFormat("Edited scale of Primitive: {0}", part.Name);
  3992. }
  3993. }
  3994. }
  3995. }
  3996. }
  3997. #region Script Handling Methods
  3998. /// <summary>
  3999. /// Console command handler to send script command to script engine.
  4000. /// </summary>
  4001. /// <param name="args"></param>
  4002. public void SendCommandToPlugins(string[] args)
  4003. {
  4004. m_eventManager.TriggerOnPluginConsole(args);
  4005. }
  4006. public LandData GetLandData(float x, float y)
  4007. {
  4008. return LandChannel.GetLandObject(x, y).LandData;
  4009. }
  4010. /// <summary>
  4011. /// Get LandData by position.
  4012. /// </summary>
  4013. /// <param name="pos"></param>
  4014. /// <returns></returns>
  4015. public LandData GetLandData(Vector3 pos)
  4016. {
  4017. return GetLandData(pos.X, pos.Y);
  4018. }
  4019. public LandData GetLandData(uint x, uint y)
  4020. {
  4021. m_log.DebugFormat("[SCENE]: returning land for {0},{1}", x, y);
  4022. return LandChannel.GetLandObject((int)x, (int)y).LandData;
  4023. }
  4024. #endregion
  4025. #region Script Engine
  4026. private bool ScriptDanger(SceneObjectPart part,Vector3 pos)
  4027. {
  4028. ILandObject parcel = LandChannel.GetLandObject(pos.X, pos.Y);
  4029. if (part != null)
  4030. {
  4031. if (parcel != null)
  4032. {
  4033. if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowOtherScripts) != 0)
  4034. {
  4035. return true;
  4036. }
  4037. else if ((parcel.LandData.Flags & (uint)ParcelFlags.AllowGroupScripts) != 0)
  4038. {
  4039. if (part.OwnerID == parcel.LandData.OwnerID
  4040. || (parcel.LandData.IsGroupOwned && part.GroupID == parcel.LandData.GroupID)
  4041. || Permissions.IsGod(part.OwnerID))
  4042. {
  4043. return true;
  4044. }
  4045. else
  4046. {
  4047. return false;
  4048. }
  4049. }
  4050. else
  4051. {
  4052. if (part.OwnerID == parcel.LandData.OwnerID)
  4053. {
  4054. return true;
  4055. }
  4056. else
  4057. {
  4058. return false;
  4059. }
  4060. }
  4061. }
  4062. else
  4063. {
  4064. if (pos.X > 0f && pos.X < Constants.RegionSize && pos.Y > 0f && pos.Y < Constants.RegionSize)
  4065. {
  4066. // The only time parcel != null when an object is inside a region is when
  4067. // there is nothing behind the landchannel. IE, no land plugin loaded.
  4068. return true;
  4069. }
  4070. else
  4071. {
  4072. // The object is outside of this region. Stop piping events to it.
  4073. return false;
  4074. }
  4075. }
  4076. }
  4077. else
  4078. {
  4079. return false;
  4080. }
  4081. }
  4082. public bool ScriptDanger(uint localID, Vector3 pos)
  4083. {
  4084. SceneObjectPart part = GetSceneObjectPart(localID);
  4085. if (part != null)
  4086. {
  4087. return ScriptDanger(part, pos);
  4088. }
  4089. else
  4090. {
  4091. return false;
  4092. }
  4093. }
  4094. public bool PipeEventsForScript(uint localID)
  4095. {
  4096. SceneObjectPart part = GetSceneObjectPart(localID);
  4097. if (part != null)
  4098. {
  4099. SceneObjectPart parent = part.ParentGroup.RootPart;
  4100. return ScriptDanger(parent, parent.GetWorldPosition());
  4101. }
  4102. else
  4103. {
  4104. return false;
  4105. }
  4106. }
  4107. #endregion
  4108. #region SceneGraph wrapper methods
  4109. /// <summary>
  4110. ///
  4111. /// </summary>
  4112. /// <param name="localID"></param>
  4113. /// <returns></returns>
  4114. public UUID ConvertLocalIDToFullID(uint localID)
  4115. {
  4116. return m_sceneGraph.ConvertLocalIDToFullID(localID);
  4117. }
  4118. public void SwapRootAgentCount(bool rootChildChildRootTF)
  4119. {
  4120. m_sceneGraph.SwapRootChildAgent(rootChildChildRootTF);
  4121. }
  4122. public void AddPhysicalPrim(int num)
  4123. {
  4124. m_sceneGraph.AddPhysicalPrim(num);
  4125. }
  4126. public void RemovePhysicalPrim(int num)
  4127. {
  4128. m_sceneGraph.RemovePhysicalPrim(num);
  4129. }
  4130. public int GetRootAgentCount()
  4131. {
  4132. return m_sceneGraph.GetRootAgentCount();
  4133. }
  4134. public int GetChildAgentCount()
  4135. {
  4136. return m_sceneGraph.GetChildAgentCount();
  4137. }
  4138. /// <summary>
  4139. /// Request a scene presence by UUID. Fast, indexed lookup.
  4140. /// </summary>
  4141. /// <param name="agentID"></param>
  4142. /// <returns>null if the presence was not found</returns>
  4143. public ScenePresence GetScenePresence(UUID agentID)
  4144. {
  4145. return m_sceneGraph.GetScenePresence(agentID);
  4146. }
  4147. /// <summary>
  4148. /// Request the scene presence by name.
  4149. /// </summary>
  4150. /// <param name="firstName"></param>
  4151. /// <param name="lastName"></param>
  4152. /// <returns>null if the presence was not found</returns>
  4153. public ScenePresence GetScenePresence(string firstName, string lastName)
  4154. {
  4155. return m_sceneGraph.GetScenePresence(firstName, lastName);
  4156. }
  4157. /// <summary>
  4158. /// Request the scene presence by localID.
  4159. /// </summary>
  4160. /// <param name="localID"></param>
  4161. /// <returns>null if the presence was not found</returns>
  4162. public ScenePresence GetScenePresence(uint localID)
  4163. {
  4164. return m_sceneGraph.GetScenePresence(localID);
  4165. }
  4166. /// <summary>
  4167. /// Gets all the scene presences in this scene.
  4168. /// </summary>
  4169. /// <remarks>
  4170. /// This method will return both root and child scene presences.
  4171. ///
  4172. /// Consider using ForEachScenePresence() or ForEachRootScenePresence() if possible since these will not
  4173. /// involving creating a new List object.
  4174. /// </remarks>
  4175. /// <returns>
  4176. /// A list of the scene presences. Adding or removing from the list will not affect the presences in the scene.
  4177. /// </returns>
  4178. public List<ScenePresence> GetScenePresences()
  4179. {
  4180. return new List<ScenePresence>(m_sceneGraph.GetScenePresences());
  4181. }
  4182. /// <summary>
  4183. /// Performs action on all avatars in the scene (root scene presences)
  4184. /// Avatars may be an NPC or a 'real' client.
  4185. /// </summary>
  4186. /// <param name="action"></param>
  4187. public void ForEachRootScenePresence(Action<ScenePresence> action)
  4188. {
  4189. m_sceneGraph.ForEachAvatar(action);
  4190. }
  4191. /// <summary>
  4192. /// Performs action on all scene presences (root and child)
  4193. /// </summary>
  4194. /// <param name="action"></param>
  4195. public void ForEachScenePresence(Action<ScenePresence> action)
  4196. {
  4197. m_sceneGraph.ForEachScenePresence(action);
  4198. }
  4199. /// <summary>
  4200. /// Get all the scene object groups.
  4201. /// </summary>
  4202. /// <returns>
  4203. /// The scene object groups. If the scene is empty then an empty list is returned.
  4204. /// </returns>
  4205. public List<SceneObjectGroup> GetSceneObjectGroups()
  4206. {
  4207. return m_sceneGraph.GetSceneObjectGroups();
  4208. }
  4209. /// <summary>
  4210. /// Get a group via its UUID
  4211. /// </summary>
  4212. /// <param name="fullID"></param>
  4213. /// <returns>null if no group with that id exists</returns>
  4214. public SceneObjectGroup GetSceneObjectGroup(UUID fullID)
  4215. {
  4216. return m_sceneGraph.GetSceneObjectGroup(fullID);
  4217. }
  4218. /// <summary>
  4219. /// Get a group via its local ID
  4220. /// </summary>
  4221. /// <remarks>This will only return a group if the local ID matches a root part</remarks>
  4222. /// <param name="localID"></param>
  4223. /// <returns>null if no group with that id exists</returns>
  4224. public SceneObjectGroup GetSceneObjectGroup(uint localID)
  4225. {
  4226. return m_sceneGraph.GetSceneObjectGroup(localID);
  4227. }
  4228. /// <summary>
  4229. /// Get a group by name from the scene (will return the first
  4230. /// found, if there are more than one prim with the same name)
  4231. /// </summary>
  4232. /// <param name="name"></param>
  4233. /// <returns>null if no group with that name exists</returns>
  4234. public SceneObjectGroup GetSceneObjectGroup(string name)
  4235. {
  4236. return m_sceneGraph.GetSceneObjectGroup(name);
  4237. }
  4238. /// <summary>
  4239. /// Attempt to get the SOG via its UUID
  4240. /// </summary>
  4241. /// <param name="fullID"></param>
  4242. /// <param name="sog"></param>
  4243. /// <returns></returns>
  4244. public bool TryGetSceneObjectGroup(UUID fullID, out SceneObjectGroup sog)
  4245. {
  4246. sog = GetSceneObjectGroup(fullID);
  4247. return sog != null;
  4248. }
  4249. /// <summary>
  4250. /// Get a prim by name from the scene (will return the first
  4251. /// found, if there are more than one prim with the same name)
  4252. /// </summary>
  4253. /// <param name="name"></param>
  4254. /// <returns></returns>
  4255. public SceneObjectPart GetSceneObjectPart(string name)
  4256. {
  4257. return m_sceneGraph.GetSceneObjectPart(name);
  4258. }
  4259. /// <summary>
  4260. /// Get a prim via its local id
  4261. /// </summary>
  4262. /// <param name="localID"></param>
  4263. /// <returns></returns>
  4264. public SceneObjectPart GetSceneObjectPart(uint localID)
  4265. {
  4266. return m_sceneGraph.GetSceneObjectPart(localID);
  4267. }
  4268. /// <summary>
  4269. /// Get a prim via its UUID
  4270. /// </summary>
  4271. /// <param name="fullID"></param>
  4272. /// <returns></returns>
  4273. public SceneObjectPart GetSceneObjectPart(UUID fullID)
  4274. {
  4275. return m_sceneGraph.GetSceneObjectPart(fullID);
  4276. }
  4277. /// <summary>
  4278. /// Attempt to get a prim via its UUID
  4279. /// </summary>
  4280. /// <param name="fullID"></param>
  4281. /// <param name="sop"></param>
  4282. /// <returns></returns>
  4283. public bool TryGetSceneObjectPart(UUID fullID, out SceneObjectPart sop)
  4284. {
  4285. sop = GetSceneObjectPart(fullID);
  4286. return sop != null;
  4287. }
  4288. /// <summary>
  4289. /// Get a scene object group that contains the prim with the given local id
  4290. /// </summary>
  4291. /// <param name="localID"></param>
  4292. /// <returns>null if no scene object group containing that prim is found</returns>
  4293. public SceneObjectGroup GetGroupByPrim(uint localID)
  4294. {
  4295. return m_sceneGraph.GetGroupByPrim(localID);
  4296. }
  4297. /// <summary>
  4298. /// Get a scene object group that contains the prim with the given uuid
  4299. /// </summary>
  4300. /// <param name="fullID"></param>
  4301. /// <returns>null if no scene object group containing that prim is found</returns>
  4302. public SceneObjectGroup GetGroupByPrim(UUID fullID)
  4303. {
  4304. return m_sceneGraph.GetGroupByPrim(fullID);
  4305. }
  4306. public override bool TryGetScenePresence(UUID agentID, out ScenePresence sp)
  4307. {
  4308. return m_sceneGraph.TryGetScenePresence(agentID, out sp);
  4309. }
  4310. public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar)
  4311. {
  4312. return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
  4313. }
  4314. /// <summary>
  4315. /// Perform an action on all clients with an avatar in this scene (root only)
  4316. /// </summary>
  4317. /// <param name="action"></param>
  4318. public void ForEachRootClient(Action<IClientAPI> action)
  4319. {
  4320. ForEachRootScenePresence(delegate(ScenePresence presence)
  4321. {
  4322. action(presence.ControllingClient);
  4323. });
  4324. }
  4325. /// <summary>
  4326. /// Perform an action on all clients connected to the region (root and child)
  4327. /// </summary>
  4328. /// <param name="action"></param>
  4329. public void ForEachClient(Action<IClientAPI> action)
  4330. {
  4331. m_clientManager.ForEachSync(action);
  4332. }
  4333. public bool TryGetClient(UUID avatarID, out IClientAPI client)
  4334. {
  4335. return m_clientManager.TryGetValue(avatarID, out client);
  4336. }
  4337. public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
  4338. {
  4339. return m_clientManager.TryGetValue(remoteEndPoint, out client);
  4340. }
  4341. public void ForEachSOG(Action<SceneObjectGroup> action)
  4342. {
  4343. m_sceneGraph.ForEachSOG(action);
  4344. }
  4345. /// <summary>
  4346. /// Returns a list of the entities in the scene. This is a new list so operations perform on the list itself
  4347. /// will not affect the original list of objects in the scene.
  4348. /// </summary>
  4349. /// <returns></returns>
  4350. public EntityBase[] GetEntities()
  4351. {
  4352. return m_sceneGraph.GetEntities();
  4353. }
  4354. #endregion
  4355. // Commented pending deletion since this method no longer appears to do anything at all
  4356. // public bool NeedSceneCacheClear(UUID agentID)
  4357. // {
  4358. // IInventoryTransferModule inv = RequestModuleInterface<IInventoryTransferModule>();
  4359. // if (inv == null)
  4360. // return true;
  4361. //
  4362. // return inv.NeedSceneCacheClear(agentID, this);
  4363. // }
  4364. public void CleanTempObjects()
  4365. {
  4366. EntityBase[] entities = GetEntities();
  4367. foreach (EntityBase obj in entities)
  4368. {
  4369. if (obj is SceneObjectGroup)
  4370. {
  4371. SceneObjectGroup grp = (SceneObjectGroup)obj;
  4372. if (!grp.IsDeleted)
  4373. {
  4374. if ((grp.RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  4375. {
  4376. if (grp.RootPart.Expires <= DateTime.Now)
  4377. DeleteSceneObject(grp, false);
  4378. }
  4379. }
  4380. }
  4381. }
  4382. }
  4383. public void DeleteFromStorage(UUID uuid)
  4384. {
  4385. SimulationDataService.RemoveObject(uuid, RegionInfo.RegionID);
  4386. }
  4387. public int GetHealth()
  4388. {
  4389. // Returns:
  4390. // 1 = sim is up and accepting http requests. The heartbeat has
  4391. // stopped and the sim is probably locked up, but a remote
  4392. // admin restart may succeed
  4393. //
  4394. // 2 = Sim is up and the heartbeat is running. The sim is likely
  4395. // usable for people within and logins _may_ work
  4396. //
  4397. // 3 = We have seen a new user enter within the past 4 minutes
  4398. // which can be seen as positive confirmation of sim health
  4399. //
  4400. int health=1; // Start at 1, means we're up
  4401. if ((Util.EnvironmentTickCountSubtract(m_lastFrameTick)) < 1000)
  4402. health += 1;
  4403. else
  4404. return health;
  4405. // A login in the last 4 mins? We can't be doing too badly
  4406. //
  4407. if ((Util.EnvironmentTickCountSubtract(m_LastLogin)) < 240000)
  4408. health++;
  4409. else
  4410. return health;
  4411. // CheckHeartbeat();
  4412. return health;
  4413. }
  4414. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4415. // update non-physical objects like the joint proxy objects that represent the position
  4416. // of the joints in the scene.
  4417. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4418. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4419. // from within the OdePhysicsScene.
  4420. protected internal void jointMoved(PhysicsJoint joint)
  4421. {
  4422. // m_parentScene.PhysicsScene.DumpJointInfo(); // non-thread-locked version; we should already be in a lock (OdeLock) when this callback is invoked
  4423. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4424. if (jointProxyObject == null)
  4425. {
  4426. jointErrorMessage(joint, "WARNING, joint proxy not found, name " + joint.ObjectNameInScene);
  4427. return;
  4428. }
  4429. // now update the joint proxy object in the scene to have the position of the joint as returned by the physics engine
  4430. SceneObjectPart trackedBody = GetSceneObjectPart(joint.TrackedBodyName); // FIXME: causes a sequential lookup
  4431. if (trackedBody == null) return; // the actor may have been deleted but the joint still lingers around a few frames waiting for deletion. during this time, trackedBody is NULL to prevent further motion of the joint proxy.
  4432. jointProxyObject.Velocity = trackedBody.Velocity;
  4433. jointProxyObject.AngularVelocity = trackedBody.AngularVelocity;
  4434. switch (joint.Type)
  4435. {
  4436. case PhysicsJointType.Ball:
  4437. {
  4438. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4439. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  4440. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4441. }
  4442. break;
  4443. case PhysicsJointType.Hinge:
  4444. {
  4445. Vector3 jointAnchor = PhysicsScene.GetJointAnchor(joint);
  4446. // Normally, we would just ask the physics scene to return the axis for the joint.
  4447. // Unfortunately, ODE sometimes returns <0,0,0> for the joint axis, which should
  4448. // never occur. Therefore we cannot rely on ODE to always return a correct joint axis.
  4449. // Therefore the following call does not always work:
  4450. //PhysicsVector phyJointAxis = _PhyScene.GetJointAxis(joint);
  4451. // instead we compute the joint orientation by saving the original joint orientation
  4452. // relative to one of the jointed bodies, and applying this transformation
  4453. // to the current position of the jointed bodies (the tracked body) to compute the
  4454. // current joint orientation.
  4455. if (joint.TrackedBodyName == null)
  4456. {
  4457. jointErrorMessage(joint, "joint.TrackedBodyName is null, joint " + joint.ObjectNameInScene);
  4458. }
  4459. Vector3 proxyPos = new Vector3(jointAnchor.X, jointAnchor.Y, jointAnchor.Z);
  4460. Quaternion q = trackedBody.RotationOffset * joint.LocalRotation;
  4461. jointProxyObject.ParentGroup.UpdateGroupPosition(proxyPos); // schedules the entire group for a terse update
  4462. jointProxyObject.ParentGroup.UpdateGroupRotationR(q); // schedules the entire group for a terse update
  4463. }
  4464. break;
  4465. }
  4466. }
  4467. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4468. // update non-physical objects like the joint proxy objects that represent the position
  4469. // of the joints in the scene.
  4470. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4471. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4472. // from within the OdePhysicsScene.
  4473. protected internal void jointDeactivated(PhysicsJoint joint)
  4474. {
  4475. //m_log.Debug("[NINJA] SceneGraph.jointDeactivated, joint:" + joint.ObjectNameInScene);
  4476. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4477. if (jointProxyObject == null)
  4478. {
  4479. jointErrorMessage(joint, "WARNING, trying to deactivate (stop interpolation of) joint proxy, but not found, name " + joint.ObjectNameInScene);
  4480. return;
  4481. }
  4482. // turn the proxy non-physical, which also stops its client-side interpolation
  4483. bool wasUsingPhysics = ((jointProxyObject.Flags & PrimFlags.Physics) != 0);
  4484. if (wasUsingPhysics)
  4485. {
  4486. jointProxyObject.UpdatePrimFlags(false, false, true, false); // FIXME: possible deadlock here; check to make sure all the scene alterations set into motion here won't deadlock
  4487. }
  4488. }
  4489. // This callback allows the PhysicsScene to call back to its caller (the SceneGraph) and
  4490. // alert the user of errors by using the debug channel in the same way that scripts alert
  4491. // the user of compile errors.
  4492. // This routine is normally called from within a lock (OdeLock) from within the OdePhysicsScene
  4493. // WARNING: be careful of deadlocks here if you manipulate the scene. Remember you are being called
  4494. // from within the OdePhysicsScene.
  4495. public void jointErrorMessage(PhysicsJoint joint, string message)
  4496. {
  4497. if (joint != null)
  4498. {
  4499. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4500. return;
  4501. SceneObjectPart jointProxyObject = GetSceneObjectPart(joint.ObjectNameInScene);
  4502. if (jointProxyObject != null)
  4503. {
  4504. SimChat(Utils.StringToBytes("[NINJA]: " + message),
  4505. ChatTypeEnum.DebugChannel,
  4506. 2147483647,
  4507. jointProxyObject.AbsolutePosition,
  4508. jointProxyObject.Name,
  4509. jointProxyObject.UUID,
  4510. false);
  4511. joint.ErrorMessageCount++;
  4512. if (joint.ErrorMessageCount > PhysicsJoint.maxErrorMessages)
  4513. {
  4514. SimChat(Utils.StringToBytes("[NINJA]: Too many messages for this joint, suppressing further messages."),
  4515. ChatTypeEnum.DebugChannel,
  4516. 2147483647,
  4517. jointProxyObject.AbsolutePosition,
  4518. jointProxyObject.Name,
  4519. jointProxyObject.UUID,
  4520. false);
  4521. }
  4522. }
  4523. else
  4524. {
  4525. // couldn't find the joint proxy object; the error message is silently suppressed
  4526. }
  4527. }
  4528. }
  4529. public Scene ConsoleScene()
  4530. {
  4531. if (MainConsole.Instance == null)
  4532. return null;
  4533. if (MainConsole.Instance.ConsoleScene is Scene)
  4534. return (Scene)MainConsole.Instance.ConsoleScene;
  4535. return null;
  4536. }
  4537. public float GetGroundHeight(float x, float y)
  4538. {
  4539. if (x < 0)
  4540. x = 0;
  4541. if (x >= Heightmap.Width)
  4542. x = Heightmap.Width - 1;
  4543. if (y < 0)
  4544. y = 0;
  4545. if (y >= Heightmap.Height)
  4546. y = Heightmap.Height - 1;
  4547. Vector3 p0 = new Vector3(x, y, (float)Heightmap[(int)x, (int)y]);
  4548. Vector3 p1 = new Vector3(p0);
  4549. Vector3 p2 = new Vector3(p0);
  4550. p1.X += 1.0f;
  4551. if (p1.X < Heightmap.Width)
  4552. p1.Z = (float)Heightmap[(int)p1.X, (int)p1.Y];
  4553. p2.Y += 1.0f;
  4554. if (p2.Y < Heightmap.Height)
  4555. p2.Z = (float)Heightmap[(int)p2.X, (int)p2.Y];
  4556. Vector3 v0 = new Vector3(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
  4557. Vector3 v1 = new Vector3(p2.X - p0.X, p2.Y - p0.Y, p2.Z - p0.Z);
  4558. v0.Normalize();
  4559. v1.Normalize();
  4560. Vector3 vsn = new Vector3();
  4561. vsn.X = (v0.Y * v1.Z) - (v0.Z * v1.Y);
  4562. vsn.Y = (v0.Z * v1.X) - (v0.X * v1.Z);
  4563. vsn.Z = (v0.X * v1.Y) - (v0.Y * v1.X);
  4564. vsn.Normalize();
  4565. float xdiff = x - (float)((int)x);
  4566. float ydiff = y - (float)((int)y);
  4567. return (((vsn.X * xdiff) + (vsn.Y * ydiff)) / (-1 * vsn.Z)) + p0.Z;
  4568. }
  4569. // private void CheckHeartbeat()
  4570. // {
  4571. // if (m_firstHeartbeat)
  4572. // return;
  4573. //
  4574. // if (Util.EnvironmentTickCountSubtract(m_lastFrameTick) > 2000)
  4575. // StartTimer();
  4576. // }
  4577. public override ISceneObject DeserializeObject(string representation)
  4578. {
  4579. return SceneObjectSerializer.FromXml2Format(representation);
  4580. }
  4581. public override bool AllowScriptCrossings
  4582. {
  4583. get { return m_allowScriptCrossings; }
  4584. }
  4585. public Vector3 GetNearestAllowedPosition(ScenePresence avatar)
  4586. {
  4587. return GetNearestAllowedPosition(avatar, null);
  4588. }
  4589. public Vector3 GetNearestAllowedPosition(ScenePresence avatar, ILandObject excludeParcel)
  4590. {
  4591. ILandObject nearestParcel = GetNearestAllowedParcel(avatar.UUID, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, excludeParcel);
  4592. if (nearestParcel != null)
  4593. {
  4594. Vector3 dir = Vector3.Normalize(Vector3.Multiply(avatar.Velocity, -1));
  4595. //Try to get a location that feels like where they came from
  4596. Vector3? nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
  4597. if (nearestPoint != null)
  4598. {
  4599. Debug.WriteLine("Found a sane previous position based on velocity, sending them to: " + nearestPoint.ToString());
  4600. return nearestPoint.Value;
  4601. }
  4602. //Sometimes velocity might be zero (local teleport), so try finding point along path from avatar to center of nearest parcel
  4603. Vector3 directionToParcelCenter = Vector3.Subtract(GetParcelCenterAtGround(nearestParcel), avatar.AbsolutePosition);
  4604. dir = Vector3.Normalize(directionToParcelCenter);
  4605. nearestPoint = GetNearestPointInParcelAlongDirectionFromPoint(avatar.AbsolutePosition, dir, nearestParcel);
  4606. if (nearestPoint != null)
  4607. {
  4608. Debug.WriteLine("They had a zero velocity, sending them to: " + nearestPoint.ToString());
  4609. return nearestPoint.Value;
  4610. }
  4611. ILandObject dest = LandChannel.GetLandObject(avatar.lastKnownAllowedPosition.X, avatar.lastKnownAllowedPosition.Y);
  4612. if (dest != excludeParcel)
  4613. {
  4614. // Ultimate backup if we have no idea where they are and
  4615. // the last allowed position was in another parcel
  4616. Debug.WriteLine("Have no idea where they are, sending them to: " + avatar.lastKnownAllowedPosition.ToString());
  4617. return avatar.lastKnownAllowedPosition;
  4618. }
  4619. // else fall through to region edge
  4620. }
  4621. //Go to the edge, this happens in teleporting to a region with no available parcels
  4622. Vector3 nearestRegionEdgePoint = GetNearestRegionEdgePosition(avatar);
  4623. //Debug.WriteLine("They are really in a place they don't belong, sending them to: " + nearestRegionEdgePoint.ToString());
  4624. return nearestRegionEdgePoint;
  4625. }
  4626. private Vector3 GetParcelCenterAtGround(ILandObject parcel)
  4627. {
  4628. Vector2 center = GetParcelCenter(parcel);
  4629. return GetPositionAtGround(center.X, center.Y);
  4630. }
  4631. private Vector3? GetNearestPointInParcelAlongDirectionFromPoint(Vector3 pos, Vector3 direction, ILandObject parcel)
  4632. {
  4633. Vector3 unitDirection = Vector3.Normalize(direction);
  4634. //Making distance to search go through some sane limit of distance
  4635. for (float distance = 0; distance < Constants.RegionSize * 2; distance += .5f)
  4636. {
  4637. Vector3 testPos = Vector3.Add(pos, Vector3.Multiply(unitDirection, distance));
  4638. if (parcel.ContainsPoint((int)testPos.X, (int)testPos.Y))
  4639. {
  4640. return testPos;
  4641. }
  4642. }
  4643. return null;
  4644. }
  4645. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y)
  4646. {
  4647. return GetNearestAllowedParcel(avatarId, x, y, null);
  4648. }
  4649. public ILandObject GetNearestAllowedParcel(UUID avatarId, float x, float y, ILandObject excludeParcel)
  4650. {
  4651. List<ILandObject> all = AllParcels();
  4652. float minParcelDistance = float.MaxValue;
  4653. ILandObject nearestParcel = null;
  4654. foreach (var parcel in all)
  4655. {
  4656. if (!parcel.IsEitherBannedOrRestricted(avatarId) && parcel != excludeParcel)
  4657. {
  4658. float parcelDistance = GetParcelDistancefromPoint(parcel, x, y);
  4659. if (parcelDistance < minParcelDistance)
  4660. {
  4661. minParcelDistance = parcelDistance;
  4662. nearestParcel = parcel;
  4663. }
  4664. }
  4665. }
  4666. return nearestParcel;
  4667. }
  4668. private List<ILandObject> AllParcels()
  4669. {
  4670. return LandChannel.AllParcels();
  4671. }
  4672. private float GetParcelDistancefromPoint(ILandObject parcel, float x, float y)
  4673. {
  4674. return Vector2.Distance(new Vector2(x, y), GetParcelCenter(parcel));
  4675. }
  4676. //calculate the average center point of a parcel
  4677. private Vector2 GetParcelCenter(ILandObject parcel)
  4678. {
  4679. int count = 0;
  4680. int avgx = 0;
  4681. int avgy = 0;
  4682. for (int x = 0; x < Constants.RegionSize; x++)
  4683. {
  4684. for (int y = 0; y < Constants.RegionSize; y++)
  4685. {
  4686. //Just keep a running average as we check if all the points are inside or not
  4687. if (parcel.ContainsPoint(x, y))
  4688. {
  4689. if (count == 0)
  4690. {
  4691. avgx = x;
  4692. avgy = y;
  4693. }
  4694. else
  4695. {
  4696. avgx = (avgx * count + x) / (count + 1);
  4697. avgy = (avgy * count + y) / (count + 1);
  4698. }
  4699. count += 1;
  4700. }
  4701. }
  4702. }
  4703. return new Vector2(avgx, avgy);
  4704. }
  4705. private Vector3 GetNearestRegionEdgePosition(ScenePresence avatar)
  4706. {
  4707. float xdistance = avatar.AbsolutePosition.X < Constants.RegionSize / 2 ? avatar.AbsolutePosition.X : Constants.RegionSize - avatar.AbsolutePosition.X;
  4708. float ydistance = avatar.AbsolutePosition.Y < Constants.RegionSize / 2 ? avatar.AbsolutePosition.Y : Constants.RegionSize - avatar.AbsolutePosition.Y;
  4709. //find out what vertical edge to go to
  4710. if (xdistance < ydistance)
  4711. {
  4712. if (avatar.AbsolutePosition.X < Constants.RegionSize / 2)
  4713. {
  4714. return GetPositionAtAvatarHeightOrGroundHeight(avatar, 0.0f, avatar.AbsolutePosition.Y);
  4715. }
  4716. else
  4717. {
  4718. return GetPositionAtAvatarHeightOrGroundHeight(avatar, Constants.RegionSize, avatar.AbsolutePosition.Y);
  4719. }
  4720. }
  4721. //find out what horizontal edge to go to
  4722. else
  4723. {
  4724. if (avatar.AbsolutePosition.Y < Constants.RegionSize / 2)
  4725. {
  4726. return GetPositionAtAvatarHeightOrGroundHeight(avatar, avatar.AbsolutePosition.X, 0.0f);
  4727. }
  4728. else
  4729. {
  4730. return GetPositionAtAvatarHeightOrGroundHeight(avatar, avatar.AbsolutePosition.X, Constants.RegionSize);
  4731. }
  4732. }
  4733. }
  4734. private Vector3 GetPositionAtAvatarHeightOrGroundHeight(ScenePresence avatar, float x, float y)
  4735. {
  4736. Vector3 ground = GetPositionAtGround(x, y);
  4737. if (avatar.AbsolutePosition.Z > ground.Z)
  4738. {
  4739. ground.Z = avatar.AbsolutePosition.Z;
  4740. }
  4741. return ground;
  4742. }
  4743. private Vector3 GetPositionAtGround(float x, float y)
  4744. {
  4745. return new Vector3(x, y, GetGroundHeight(x, y));
  4746. }
  4747. public List<UUID> GetEstateRegions(int estateID)
  4748. {
  4749. IEstateDataService estateDataService = EstateDataService;
  4750. if (estateDataService == null)
  4751. return new List<UUID>(0);
  4752. return estateDataService.GetRegions(estateID);
  4753. }
  4754. public void ReloadEstateData()
  4755. {
  4756. IEstateDataService estateDataService = EstateDataService;
  4757. if (estateDataService != null)
  4758. {
  4759. RegionInfo.EstateSettings = estateDataService.LoadEstateSettings(RegionInfo.RegionID, false);
  4760. TriggerEstateSunUpdate();
  4761. }
  4762. }
  4763. public void TriggerEstateSunUpdate()
  4764. {
  4765. EventManager.TriggerEstateToolsSunUpdate(RegionInfo.RegionHandle);
  4766. }
  4767. private void HandleReloadEstate(string module, string[] cmd)
  4768. {
  4769. if (MainConsole.Instance.ConsoleScene == null ||
  4770. (MainConsole.Instance.ConsoleScene is Scene &&
  4771. (Scene)MainConsole.Instance.ConsoleScene == this))
  4772. {
  4773. ReloadEstateData();
  4774. }
  4775. }
  4776. /// <summary>
  4777. /// Get the volume of space that will encompass all the given objects.
  4778. /// </summary>
  4779. /// <param name="objects"></param>
  4780. /// <param name="minX"></param>
  4781. /// <param name="maxX"></param>
  4782. /// <param name="minY"></param>
  4783. /// <param name="maxY"></param>
  4784. /// <param name="minZ"></param>
  4785. /// <param name="maxZ"></param>
  4786. /// <returns></returns>
  4787. public static Vector3[] GetCombinedBoundingBox(
  4788. List<SceneObjectGroup> objects,
  4789. out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  4790. {
  4791. minX = float.MaxValue;
  4792. maxX = float.MinValue;
  4793. minY = float.MaxValue;
  4794. maxY = float.MinValue;
  4795. minZ = float.MaxValue;
  4796. maxZ = float.MinValue;
  4797. List<Vector3> offsets = new List<Vector3>();
  4798. foreach (SceneObjectGroup g in objects)
  4799. {
  4800. float ominX, ominY, ominZ, omaxX, omaxY, omaxZ;
  4801. Vector3 vec = g.AbsolutePosition;
  4802. g.GetAxisAlignedBoundingBoxRaw(out ominX, out omaxX, out ominY, out omaxY, out ominZ, out omaxZ);
  4803. // m_log.DebugFormat(
  4804. // "[SCENE]: For {0} found AxisAlignedBoundingBoxRaw {1}, {2}",
  4805. // g.Name, new Vector3(ominX, ominY, ominZ), new Vector3(omaxX, omaxY, omaxZ));
  4806. ominX += vec.X;
  4807. omaxX += vec.X;
  4808. ominY += vec.Y;
  4809. omaxY += vec.Y;
  4810. ominZ += vec.Z;
  4811. omaxZ += vec.Z;
  4812. if (minX > ominX)
  4813. minX = ominX;
  4814. if (minY > ominY)
  4815. minY = ominY;
  4816. if (minZ > ominZ)
  4817. minZ = ominZ;
  4818. if (maxX < omaxX)
  4819. maxX = omaxX;
  4820. if (maxY < omaxY)
  4821. maxY = omaxY;
  4822. if (maxZ < omaxZ)
  4823. maxZ = omaxZ;
  4824. }
  4825. foreach (SceneObjectGroup g in objects)
  4826. {
  4827. Vector3 vec = g.AbsolutePosition;
  4828. vec.X -= minX;
  4829. vec.Y -= minY;
  4830. vec.Z -= minZ;
  4831. offsets.Add(vec);
  4832. }
  4833. return offsets.ToArray();
  4834. }
  4835. /// <summary>
  4836. /// Regenerate the maptile for this scene.
  4837. /// </summary>
  4838. /// <param name="sender"></param>
  4839. /// <param name="e"></param>
  4840. private void RegenerateMaptile()
  4841. {
  4842. IWorldMapModule mapModule = RequestModuleInterface<IWorldMapModule>();
  4843. if (mapModule != null)
  4844. mapModule.GenerateMaptile();
  4845. }
  4846. private void RegenerateMaptileAndReregister(object sender, ElapsedEventArgs e)
  4847. {
  4848. RegenerateMaptile();
  4849. // We need to propagate the new image UUID to the grid service
  4850. // so that all simulators can retrieve it
  4851. string error = GridService.RegisterRegion(RegionInfo.ScopeID, new GridRegion(RegionInfo));
  4852. if (error != string.Empty)
  4853. throw new Exception(error);
  4854. }
  4855. /// <summary>
  4856. /// This method is called across the simulation connector to
  4857. /// determine if a given agent is allowed in this region
  4858. /// AS A ROOT AGENT
  4859. /// </summary>
  4860. /// <remarks>
  4861. /// Returning false here will prevent them
  4862. /// from logging into the region, teleporting into the region
  4863. /// or corssing the broder walking, but will NOT prevent
  4864. /// child agent creation, thereby emulating the SL behavior.
  4865. /// </remarks>
  4866. /// <param name='agentID'></param>
  4867. /// <param name='position'></param>
  4868. /// <param name='reason'></param>
  4869. /// <returns></returns>
  4870. public bool QueryAccess(UUID agentID, Vector3 position, out string reason)
  4871. {
  4872. reason = "You are banned from the region";
  4873. if (Permissions.IsGod(agentID))
  4874. {
  4875. reason = String.Empty;
  4876. return true;
  4877. }
  4878. // FIXME: Root agent count is currently known to be inaccurate. This forces a recount before we check.
  4879. // However, the long term fix is to make sure root agent count is always accurate.
  4880. m_sceneGraph.RecalculateStats();
  4881. int num = m_sceneGraph.GetRootAgentCount();
  4882. if (num >= RegionInfo.RegionSettings.AgentLimit)
  4883. {
  4884. if (!Permissions.IsAdministrator(agentID))
  4885. {
  4886. reason = "The region is full";
  4887. m_log.DebugFormat(
  4888. "[SCENE]: Denying presence with id {0} entry into {1} since region is at agent limit of {2}",
  4889. agentID, RegionInfo.RegionName, RegionInfo.RegionSettings.AgentLimit);
  4890. return false;
  4891. }
  4892. }
  4893. ScenePresence presence = GetScenePresence(agentID);
  4894. IClientAPI client = null;
  4895. AgentCircuitData aCircuit = null;
  4896. if (presence != null)
  4897. {
  4898. client = presence.ControllingClient;
  4899. if (client != null)
  4900. aCircuit = client.RequestClientInfo();
  4901. }
  4902. // We may be called before there is a presence or a client.
  4903. // Fake AgentCircuitData to keep IAuthorizationModule smiling
  4904. if (client == null)
  4905. {
  4906. aCircuit = new AgentCircuitData();
  4907. aCircuit.AgentID = agentID;
  4908. aCircuit.firstname = String.Empty;
  4909. aCircuit.lastname = String.Empty;
  4910. }
  4911. try
  4912. {
  4913. if (!AuthorizeUser(aCircuit, false, out reason))
  4914. {
  4915. // m_log.DebugFormat("[SCENE]: Denying access for {0}", agentID);
  4916. return false;
  4917. }
  4918. }
  4919. catch (Exception e)
  4920. {
  4921. m_log.DebugFormat("[SCENE]: Exception authorizing agent: {0} "+ e.StackTrace, e.Message);
  4922. return false;
  4923. }
  4924. if (position == Vector3.Zero) // Teleport
  4925. {
  4926. if (!RegionInfo.EstateSettings.AllowDirectTeleport)
  4927. {
  4928. SceneObjectGroup telehub;
  4929. if (RegionInfo.RegionSettings.TelehubObject != UUID.Zero && (telehub = GetSceneObjectGroup(RegionInfo.RegionSettings.TelehubObject)) != null)
  4930. {
  4931. List<SpawnPoint> spawnPoints = RegionInfo.RegionSettings.SpawnPoints();
  4932. bool banned = true;
  4933. foreach (SpawnPoint sp in spawnPoints)
  4934. {
  4935. Vector3 spawnPoint = sp.GetLocation(telehub.AbsolutePosition, telehub.GroupRotation);
  4936. ILandObject land = LandChannel.GetLandObject(spawnPoint.X, spawnPoint.Y);
  4937. if (land == null)
  4938. continue;
  4939. if (land.IsEitherBannedOrRestricted(agentID))
  4940. continue;
  4941. banned = false;
  4942. break;
  4943. }
  4944. if (banned)
  4945. {
  4946. if(Permissions.IsAdministrator(agentID) == false || Permissions.IsGridGod(agentID) == false)
  4947. {
  4948. reason = "No suitable landing point found";
  4949. return false;
  4950. }
  4951. reason = "Administrative access only";
  4952. return true;
  4953. }
  4954. }
  4955. }
  4956. float posX = 128.0f;
  4957. float posY = 128.0f;
  4958. if (!TestLandRestrictions(agentID, out reason, ref posX, ref posY))
  4959. {
  4960. // m_log.DebugFormat("[SCENE]: Denying {0} because they are banned on all parcels", agentID);
  4961. return false;
  4962. }
  4963. }
  4964. else // Walking
  4965. {
  4966. ILandObject land = LandChannel.GetLandObject(position.X, position.Y);
  4967. if (land == null)
  4968. return false;
  4969. bool banned = land.IsBannedFromLand(agentID);
  4970. bool restricted = land.IsRestrictedFromLand(agentID);
  4971. if (banned || restricted)
  4972. return false;
  4973. }
  4974. reason = String.Empty;
  4975. return true;
  4976. }
  4977. /// <summary>
  4978. /// This method deals with movement when an avatar is automatically moving (but this is distinct from the
  4979. /// autopilot that moves an avatar to a sit target!.
  4980. /// </summary>
  4981. /// <remarks>
  4982. /// This is not intended as a permament location for this method.
  4983. /// </remarks>
  4984. /// <param name="presence"></param>
  4985. private void HandleOnSignificantClientMovement(ScenePresence presence)
  4986. {
  4987. if (presence.MovingToTarget)
  4988. {
  4989. double distanceToTarget = Util.GetDistanceTo(presence.AbsolutePosition, presence.MoveToPositionTarget);
  4990. // m_log.DebugFormat(
  4991. // "[SCENE]: Abs pos of {0} is {1}, target {2}, distance {3}",
  4992. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget, distanceToTarget);
  4993. // Check the error term of the current position in relation to the target position
  4994. if (distanceToTarget <= ScenePresence.SIGNIFICANT_MOVEMENT)
  4995. {
  4996. // We are close enough to the target
  4997. // m_log.DebugFormat("[SCENEE]: Stopping autopilot of {0}", presence.Name);
  4998. presence.Velocity = Vector3.Zero;
  4999. presence.AbsolutePosition = presence.MoveToPositionTarget;
  5000. presence.ResetMoveToTarget();
  5001. if (presence.Flying)
  5002. {
  5003. // A horrible hack to stop the avatar dead in its tracks rather than having them overshoot
  5004. // the target if flying.
  5005. // We really need to be more subtle (slow the avatar as it approaches the target) or at
  5006. // least be able to set collision status once, rather than 5 times to give it enough
  5007. // weighting so that that PhysicsActor thinks it really is colliding.
  5008. for (int i = 0; i < 5; i++)
  5009. presence.IsColliding = true;
  5010. if (presence.LandAtTarget)
  5011. presence.Flying = false;
  5012. // Vector3 targetPos = presence.MoveToPositionTarget;
  5013. // float terrainHeight = (float)presence.Scene.Heightmap[(int)targetPos.X, (int)targetPos.Y];
  5014. // if (targetPos.Z - terrainHeight < 0.2)
  5015. // {
  5016. // presence.Flying = false;
  5017. // }
  5018. }
  5019. // m_log.DebugFormat(
  5020. // "[SCENE]: AgentControlFlags {0}, MovementFlag {1} for {2}",
  5021. // presence.AgentControlFlags, presence.MovementFlag, presence.Name);
  5022. }
  5023. else
  5024. {
  5025. // m_log.DebugFormat(
  5026. // "[SCENE]: Updating npc {0} at {1} for next movement to {2}",
  5027. // presence.Name, presence.AbsolutePosition, presence.MoveToPositionTarget);
  5028. Vector3 agent_control_v3 = new Vector3();
  5029. presence.HandleMoveToTargetUpdate(1, ref agent_control_v3);
  5030. presence.AddNewMovement(agent_control_v3);
  5031. }
  5032. }
  5033. }
  5034. // manage and select spawn points in sequence
  5035. public int SpawnPoint()
  5036. {
  5037. int spawnpoints = RegionInfo.RegionSettings.SpawnPoints().Count;
  5038. if (spawnpoints == 0)
  5039. return 0;
  5040. m_SpawnPoint++;
  5041. if (m_SpawnPoint > spawnpoints)
  5042. m_SpawnPoint = 1;
  5043. return m_SpawnPoint - 1;
  5044. }
  5045. /// <summary>
  5046. /// Wrappers to get physics modules retrieve assets.
  5047. /// </summary>
  5048. /// <remarks>
  5049. /// Has to be done this way
  5050. /// because we can't assign the asset service to physics directly - at the
  5051. /// time physics are instantiated it's not registered but it will be by
  5052. /// the time the first prim exists.
  5053. /// </remarks>
  5054. /// <param name="assetID"></param>
  5055. /// <param name="callback"></param>
  5056. public void PhysicsRequestAsset(UUID assetID, AssetReceivedDelegate callback)
  5057. {
  5058. AssetService.Get(assetID.ToString(), callback, PhysicsAssetReceived);
  5059. }
  5060. private void PhysicsAssetReceived(string id, Object sender, AssetBase asset)
  5061. {
  5062. AssetReceivedDelegate callback = (AssetReceivedDelegate)sender;
  5063. callback(asset);
  5064. }
  5065. public string GetExtraSetting(string name)
  5066. {
  5067. if (m_extraSettings == null)
  5068. return String.Empty;
  5069. string val;
  5070. if (!m_extraSettings.TryGetValue(name, out val))
  5071. return String.Empty;
  5072. return val;
  5073. }
  5074. public void StoreExtraSetting(string name, string val)
  5075. {
  5076. if (m_extraSettings == null)
  5077. return;
  5078. string oldVal;
  5079. if (m_extraSettings.TryGetValue(name, out oldVal))
  5080. {
  5081. if (oldVal == val)
  5082. return;
  5083. }
  5084. m_extraSettings[name] = val;
  5085. m_SimulationDataService.SaveExtra(RegionInfo.RegionID, name, val);
  5086. m_eventManager.TriggerExtraSettingChanged(this, name, val);
  5087. }
  5088. public void RemoveExtraSetting(string name)
  5089. {
  5090. if (m_extraSettings == null)
  5091. return;
  5092. if (!m_extraSettings.ContainsKey(name))
  5093. return;
  5094. m_extraSettings.Remove(name);
  5095. m_SimulationDataService.RemoveExtra(RegionInfo.RegionID, name);
  5096. m_eventManager.TriggerExtraSettingChanged(this, name, String.Empty);
  5097. }
  5098. }
  5099. }