Scene.cs 231 KB

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