Scene.cs 245 KB

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