Scene.cs 243 KB

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