SceneObjectGroup.cs 194 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.ComponentModel;
  29. using System.Collections.Generic;
  30. using System.Drawing;
  31. using System.IO;
  32. using System.Diagnostics;
  33. using System.Linq;
  34. using System.Threading;
  35. using System.Xml;
  36. using System.Xml.Serialization;
  37. using OpenMetaverse;
  38. using OpenMetaverse.Packets;
  39. using OpenSim.Framework;
  40. using OpenSim.Region.Framework.Interfaces;
  41. using OpenSim.Region.PhysicsModules.SharedBase;
  42. using OpenSim.Region.Framework.Scenes.Serialization;
  43. using PermissionMask = OpenSim.Framework.PermissionMask;
  44. using OpenSim.Services.Interfaces;
  45. namespace OpenSim.Region.Framework.Scenes
  46. {
  47. [Flags]
  48. public enum scriptEvents
  49. {
  50. None = 0,
  51. attach = 1,
  52. collision = 16,
  53. collision_end = 32,
  54. collision_start = 64,
  55. control = 128,
  56. dataserver = 256,
  57. email = 512,
  58. http_response = 1024,
  59. land_collision = 2048,
  60. land_collision_end = 4096,
  61. land_collision_start = 8192,
  62. at_target = 16384,
  63. at_rot_target = 16777216,
  64. listen = 32768,
  65. money = 65536,
  66. moving_end = 131072,
  67. moving_start = 262144,
  68. not_at_rot_target = 524288,
  69. not_at_target = 1048576,
  70. remote_data = 8388608,
  71. run_time_permissions = 268435456,
  72. state_entry = 1073741824,
  73. state_exit = 2,
  74. timer = 4,
  75. touch = 8,
  76. touch_end = 536870912,
  77. touch_start = 2097152,
  78. transaction_result = 33554432,
  79. object_rez = 4194304,
  80. anytouch = touch | touch_end | touch_start,
  81. anyTarget = at_target | not_at_target | at_rot_target | not_at_rot_target
  82. }
  83. public struct scriptPosTarget
  84. {
  85. public Vector3 targetPos;
  86. public float tolerance;
  87. public int handle;
  88. public UUID scriptID;
  89. }
  90. public struct scriptRotTarget
  91. {
  92. public Quaternion targetRot;
  93. public float tolerance;
  94. public int handle;
  95. public UUID scriptID;
  96. }
  97. public delegate void PrimCountTaintedDelegate();
  98. /// <summary>
  99. /// A scene object group is conceptually an object in the scene. The object is constituted of SceneObjectParts
  100. /// (often known as prims), one of which is considered the root part.
  101. /// </summary>
  102. public partial class SceneObjectGroup : EntityBase, ISceneObject, IDisposable
  103. {
  104. // Axis selection bitmask used by SetAxisRotation()
  105. // Just happen to be the same bits used by llSetStatus() and defined in ScriptBaseClass.
  106. public enum axisSelect : int
  107. {
  108. STATUS_ROTATE_X = 0x002,
  109. STATUS_ROTATE_Y = 0x004,
  110. STATUS_ROTATE_Z = 0x008,
  111. NOT_STATUS_ROTATE_X = 0xFD,
  112. NOT_STATUS_ROTATE_Y = 0xFB,
  113. NOT_STATUS_ROTATE_Z = 0xF7
  114. }
  115. // private PrimCountTaintedDelegate handlerPrimCountTainted = null;
  116. public bool IsViewerCachable
  117. {
  118. get
  119. {
  120. // needs more exclusion ?
  121. return(Backup && !IsTemporary && !inTransit && !IsSelected && !UsesPhysics && !IsAttachmentCheckFull() &&
  122. !RootPart.Shape.MeshFlagEntry && // animations are not sent correctly for now
  123. RootPart.KeyframeMotion == null &&
  124. (DateTime.UtcNow.Ticks - timeLastChanged > 36000000000) && //36000000000 is one hour
  125. RootPart.Velocity.LengthSquared() < 1e8f && // should not be needed
  126. RootPart.Acceleration.LengthSquared() < 1e4f // should not be needed
  127. );
  128. }
  129. }
  130. /// <summary>
  131. /// Signal whether the non-inventory attributes of any prims in the group have changed
  132. /// since the group's last persistent backup
  133. /// </summary>
  134. private bool m_hasGroupChanged = false;
  135. private long timeFirstChanged = 0;
  136. private long timeLastChanged = 0;
  137. private long m_maxPersistTime = 0;
  138. private long m_minPersistTime = 0;
  139. /// <summary>
  140. /// This indicates whether the object has changed such that it needs to be repersisted to permenant storage
  141. /// (the database).
  142. /// </summary>
  143. /// <remarks>
  144. /// Ultimately, this should be managed such that region modules can change it at the end of a set of operations
  145. /// so that either all changes are preserved or none at all. However, currently, a large amount of internal
  146. /// code will set this anyway when some object properties are changed.
  147. /// </remarks>
  148. public bool HasGroupChanged
  149. {
  150. set
  151. {
  152. if (value)
  153. {
  154. if (Backup)
  155. m_scene.SceneGraph.FireChangeBackup(this);
  156. timeLastChanged = DateTime.UtcNow.Ticks;
  157. if (!m_hasGroupChanged)
  158. timeFirstChanged = timeLastChanged;
  159. if (m_rootPart != null && m_scene != null)
  160. {
  161. if (m_scene.GetRootAgentCount() == 0)
  162. {
  163. //If the region is empty, this change has been made by an automated process
  164. //and thus we delay the persist time by a random amount between 1.5 and 2.5.
  165. float factor = 2.0f;
  166. m_maxPersistTime = (long)(m_scene.m_persistAfter * factor);
  167. m_minPersistTime = (long)(m_scene.m_dontPersistBefore * factor);
  168. }
  169. else
  170. {
  171. m_maxPersistTime = m_scene.m_persistAfter;
  172. m_minPersistTime = m_scene.m_dontPersistBefore;
  173. }
  174. }
  175. }
  176. m_hasGroupChanged = value;
  177. // m_log.DebugFormat(
  178. // "[SCENE OBJECT GROUP]: HasGroupChanged set to {0} for {1} {2}", m_hasGroupChanged, Name, LocalId);
  179. }
  180. get { return m_hasGroupChanged; }
  181. }
  182. public bool TemporaryInstance = false;
  183. private bool m_groupContainsForeignPrims = false;
  184. /// <summary>
  185. /// Whether the group contains prims that came from a different group. This happens when
  186. /// linking or delinking groups. The implication is that until the group is persisted,
  187. /// the prims in the database still use the old SceneGroupID. That's a problem if the group
  188. /// is deleted, because we delete groups by searching for prims by their SceneGroupID.
  189. /// </summary>
  190. public bool GroupContainsForeignPrims
  191. {
  192. private set
  193. {
  194. m_groupContainsForeignPrims = value;
  195. if (m_groupContainsForeignPrims)
  196. HasGroupChanged = true;
  197. }
  198. get { return m_groupContainsForeignPrims; }
  199. }
  200. public bool HasGroupChangedDueToDelink { get; set; }
  201. private bool isTimeToPersist()
  202. {
  203. if (IsSelected || IsDeleted || IsAttachment)
  204. return false;
  205. if (!m_hasGroupChanged)
  206. return false;
  207. if (m_scene.ShuttingDown)
  208. return true;
  209. if (m_minPersistTime == 0 || m_maxPersistTime == 0)
  210. {
  211. m_maxPersistTime = m_scene.m_persistAfter;
  212. m_minPersistTime = m_scene.m_dontPersistBefore;
  213. }
  214. long currentTime = DateTime.UtcNow.Ticks;
  215. if (timeLastChanged == 0) timeLastChanged = currentTime;
  216. if (timeFirstChanged == 0) timeFirstChanged = currentTime;
  217. if (currentTime - timeLastChanged > m_minPersistTime || currentTime - timeFirstChanged > m_maxPersistTime)
  218. return true;
  219. return false;
  220. }
  221. /// <summary>
  222. /// Is this scene object acting as an attachment?
  223. /// </summary>
  224. public bool IsAttachment { get; set; }
  225. /// <summary>
  226. /// The avatar to which this scene object is attached.
  227. /// </summary>
  228. /// <remarks>
  229. /// If we're not attached to an avatar then this is UUID.Zero
  230. /// </remarks>
  231. public UUID AttachedAvatar { get; set; }
  232. /// <summary>
  233. /// Attachment point of this scene object to an avatar.
  234. /// </summary>
  235. /// <remarks>
  236. /// 0 if we're not attached to anything
  237. /// </remarks>
  238. public uint AttachmentPoint
  239. {
  240. get
  241. {
  242. return m_rootPart.Shape.State;
  243. }
  244. set
  245. {
  246. IsAttachment = value != 0;
  247. m_rootPart.Shape.State = (byte)value;
  248. }
  249. }
  250. /// <summary>
  251. /// If this scene object has an attachment point then indicate whether there is a point where
  252. /// attachments are perceivable by avatars other than the avatar to which this object is attached.
  253. /// </summary>
  254. /// <remarks>
  255. /// HUDs are not perceivable by other avatars.
  256. /// </remarks>
  257. public bool HasPrivateAttachmentPoint
  258. {
  259. get
  260. {
  261. return AttachmentPoint >= (uint)OpenMetaverse.AttachmentPoint.HUDCenter2
  262. && AttachmentPoint <= (uint)OpenMetaverse.AttachmentPoint.HUDBottomRight;
  263. }
  264. }
  265. public void ClearPartAttachmentData()
  266. {
  267. AttachmentPoint = 0;
  268. // Don't zap trees
  269. if (RootPart.Shape.PCode == (byte)PCode.Tree ||
  270. RootPart.Shape.PCode == (byte)PCode.NewTree)
  271. return;
  272. // Even though we don't use child part state parameters for attachments any more, we still need to set
  273. // these to zero since having them non-zero in rezzed scene objects will crash some clients. Even if
  274. // we store them correctly, scene objects that we receive from elsewhere might not.
  275. foreach (SceneObjectPart part in Parts)
  276. part.Shape.State = 0;
  277. }
  278. /// <summary>
  279. /// Is this scene object phantom?
  280. /// </summary>
  281. /// <remarks>
  282. /// Updating must currently take place through UpdatePrimFlags()
  283. /// </remarks>
  284. public bool IsPhantom
  285. {
  286. get { return (RootPart.Flags & PrimFlags.Phantom) != 0; }
  287. }
  288. /// <summary>
  289. /// Does this scene object use physics?
  290. /// </summary>
  291. /// <remarks>
  292. /// Updating must currently take place through UpdatePrimFlags()
  293. /// </remarks>
  294. public bool UsesPhysics
  295. {
  296. get { return (RootPart.Flags & PrimFlags.Physics) != 0; }
  297. }
  298. /// <summary>
  299. /// Is this scene object temporary?
  300. /// </summary>
  301. /// <remarks>
  302. /// Updating must currently take place through UpdatePrimFlags()
  303. /// </remarks>
  304. public bool IsTemporary
  305. {
  306. get { return (RootPart.Flags & PrimFlags.TemporaryOnRez) != 0; }
  307. }
  308. public bool IsVolumeDetect
  309. {
  310. get { return RootPart.VolumeDetectActive; }
  311. }
  312. /// <summary>
  313. /// Is this entity set to be saved in persistent storage?
  314. /// </summary>
  315. public bool Backup { get; private set; }
  316. protected MapAndArray<UUID, SceneObjectPart> m_parts = new MapAndArray<UUID, SceneObjectPart>();
  317. protected ulong m_regionHandle;
  318. protected SceneObjectPart m_rootPart;
  319. // private Dictionary<UUID, scriptEvents> m_scriptEvents = new Dictionary<UUID, scriptEvents>();
  320. private SortedDictionary<int, scriptPosTarget> m_targets = new SortedDictionary<int, scriptPosTarget>();
  321. private SortedDictionary<int, scriptRotTarget> m_rotTargets = new SortedDictionary<int, scriptRotTarget>();
  322. private Dictionary<UUID, List<int>> m_targetsByScript = new Dictionary<UUID, List<int>>();
  323. public SortedDictionary<int, scriptPosTarget> AtTargets
  324. {
  325. get { return m_targets; }
  326. }
  327. public SortedDictionary<int, scriptRotTarget> RotTargets
  328. {
  329. get { return m_rotTargets; }
  330. }
  331. private bool m_scriptListens_atTarget;
  332. private bool m_scriptListens_notAtTarget;
  333. private bool m_scriptListens_atRotTarget;
  334. private bool m_scriptListens_notAtRotTarget;
  335. public bool m_dupeInProgress = false;
  336. internal Dictionary<UUID, string> m_savedScriptState;
  337. public UUID MonitoringObject { get; set; }
  338. #region Properties
  339. /// <summary>
  340. /// The name of an object grouping is always the same as its root part
  341. /// </summary>
  342. public override string Name
  343. {
  344. get { return RootPart.Name; }
  345. set { RootPart.Name = value; }
  346. }
  347. public string Description
  348. {
  349. get { return RootPart.Description; }
  350. set { RootPart.Description = value; }
  351. }
  352. /// <summary>
  353. /// Added because the Parcel code seems to use it
  354. /// but not sure a object should have this
  355. /// as what does it tell us? that some avatar has selected it (but not what Avatar/user)
  356. /// think really there should be a list (or whatever) in each scenepresence
  357. /// saying what prim(s) that user has selected.
  358. /// </summary>
  359. protected bool m_isSelected = false;
  360. /// <summary>
  361. /// Number of prims in this group
  362. /// </summary>
  363. public int PrimCount
  364. {
  365. get { return m_parts.Count; }
  366. }
  367. // protected Quaternion m_rotation = Quaternion.Identity;
  368. //
  369. // public virtual Quaternion Rotation
  370. // {
  371. // get { return m_rotation; }
  372. // set {
  373. // m_rotation = value;
  374. // }
  375. // }
  376. public Quaternion GroupRotation
  377. {
  378. get { return m_rootPart.RotationOffset; }
  379. }
  380. public Vector3 GroupScale
  381. {
  382. get
  383. {
  384. Vector3 finalScale = new Vector3();
  385. SceneObjectPart[] parts = m_parts.GetArray();
  386. SceneObjectPart part;
  387. Vector3 partscale;
  388. float ftmp;
  389. float minScaleX = float.MaxValue;
  390. float minScaleY = float.MaxValue;
  391. float minScaleZ = float.MaxValue;
  392. float maxScaleX = 0f;
  393. float maxScaleY = 0f;
  394. float maxScaleZ = 0f;
  395. for (int i = 0; i < parts.Length; i++)
  396. {
  397. part = parts[i];
  398. partscale = part.Scale + part.OffsetPosition;
  399. ftmp = partscale.X;
  400. if (ftmp < minScaleX)
  401. minScaleX = ftmp;
  402. if (ftmp > maxScaleX)
  403. maxScaleX = ftmp;
  404. ftmp = partscale.Y;
  405. if (ftmp < minScaleY)
  406. minScaleY = ftmp;
  407. if (ftmp > maxScaleY)
  408. maxScaleY = ftmp;
  409. ftmp = partscale.Z;
  410. if (ftmp < minScaleZ)
  411. minScaleZ = ftmp;
  412. if (ftmp > maxScaleZ)
  413. maxScaleZ = ftmp;
  414. }
  415. finalScale.X = (minScaleX > maxScaleX) ? minScaleX : maxScaleX;
  416. finalScale.Y = (minScaleY > maxScaleY) ? minScaleY : maxScaleY;
  417. finalScale.Z = (minScaleZ > maxScaleZ) ? minScaleZ : maxScaleZ;
  418. return finalScale;
  419. }
  420. }
  421. public UUID GroupID
  422. {
  423. get { return m_rootPart.GroupID; }
  424. set { m_rootPart.GroupID = value; }
  425. }
  426. public SceneObjectPart[] Parts
  427. {
  428. get { return m_parts.GetArray(); }
  429. }
  430. public bool ContainsPart(UUID partID)
  431. {
  432. return m_parts.ContainsKey(partID);
  433. }
  434. /// <summary>
  435. /// Does this group contain the given part?
  436. /// should be able to remove these methods once we have a entity index in scene
  437. /// </summary>
  438. /// <param name="localID"></param>
  439. /// <returns></returns>
  440. public bool ContainsPart(uint localID)
  441. {
  442. SceneObjectPart[] parts = m_parts.GetArray();
  443. for (int i = 0; i < parts.Length; i++)
  444. {
  445. if (parts[i].LocalId == localID)
  446. return true;
  447. }
  448. return false;
  449. }
  450. /// <value>
  451. /// The root part of this scene object
  452. /// </value>
  453. public SceneObjectPart RootPart
  454. {
  455. get { return m_rootPart; }
  456. }
  457. public ulong RegionHandle
  458. {
  459. get { return m_regionHandle; }
  460. set
  461. {
  462. m_regionHandle = value;
  463. SceneObjectPart[] parts = m_parts.GetArray();
  464. for (int i = 0; i < parts.Length; i++)
  465. parts[i].RegionHandle = value;
  466. }
  467. }
  468. /// <summary>
  469. /// Check both the attachment property and the relevant properties of the underlying root part.
  470. /// </summary>
  471. /// <remarks>
  472. /// This is necessary in some cases, particularly when a scene object has just crossed into a region and doesn't
  473. /// have the IsAttachment property yet checked.
  474. ///
  475. /// FIXME: However, this should be fixed so that this property
  476. /// propertly reflects the underlying status.
  477. /// </remarks>
  478. /// <returns></returns>
  479. public bool IsAttachmentCheckFull()
  480. {
  481. return (IsAttachment ||
  482. (m_rootPart.Shape.PCode == (byte)PCodeEnum.Primitive && m_rootPart.Shape.State != 0));
  483. }
  484. private struct avtocrossInfo
  485. {
  486. public ScenePresence av;
  487. public uint ParentID;
  488. }
  489. public bool inTransit = false;
  490. private delegate SceneObjectGroup SOGCrossDelegate(SceneObjectGroup sog,Vector3 pos, TeleportObjectData tpData);
  491. /// <summary>
  492. /// The absolute position of this scene object in the scene
  493. /// </summary>
  494. public override Vector3 AbsolutePosition
  495. {
  496. get { return m_rootPart.GroupPosition; }
  497. set
  498. {
  499. Vector3 val = value;
  500. if (Scene != null
  501. && !Scene.PositionIsInCurrentRegion(val)
  502. && !IsAttachmentCheckFull()
  503. && !Scene.LoadingPrims
  504. && !Scene.DisableObjectTransfer
  505. )
  506. {
  507. if (!inTransit)
  508. {
  509. inTransit = true;
  510. SOGCrossDelegate d = CrossAsync;
  511. d.BeginInvoke(this, val, null, CrossAsyncCompleted, d);
  512. }
  513. return;
  514. }
  515. if (RootPart.GetStatusSandbox())
  516. {
  517. if (Vector3.DistanceSquared(RootPart.StatusSandboxPos, value) > 100)
  518. {
  519. RootPart.ScriptSetPhysicsStatus(false);
  520. if (Scene != null)
  521. Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"),
  522. ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false);
  523. return;
  524. }
  525. }
  526. bool triggerScriptEvent = m_rootPart.GroupPosition != val;
  527. if (m_dupeInProgress || IsDeleted)
  528. triggerScriptEvent = false;
  529. m_rootPart.GroupPosition = val;
  530. // Restuff the new GroupPosition into each child SOP of the linkset.
  531. // this is needed because physics may not have linksets but just loose SOPs in world
  532. SceneObjectPart[] parts = m_parts.GetArray();
  533. foreach (SceneObjectPart part in parts)
  534. {
  535. if (part != m_rootPart)
  536. part.GroupPosition = val;
  537. }
  538. foreach (ScenePresence av in m_sittingAvatars)
  539. {
  540. av.sitSOGmoved();
  541. }
  542. // now that position is changed tell it to scripts
  543. if (triggerScriptEvent)
  544. {
  545. foreach (SceneObjectPart part in parts)
  546. {
  547. part.TriggerScriptChangedEvent(Changed.POSITION);
  548. }
  549. }
  550. if (Scene != null)
  551. Scene.EventManager.TriggerParcelPrimCountTainted();
  552. }
  553. }
  554. private SceneObjectGroup CrossAsync(SceneObjectGroup sog, Vector3 val, TeleportObjectData tpdata)
  555. {
  556. Scene sogScene = sog.m_scene;
  557. SceneObjectPart root = sog.RootPart;
  558. bool isTeleport = tpdata != null;
  559. if(!isTeleport)
  560. {
  561. if (root.DIE_AT_EDGE)
  562. {
  563. try
  564. {
  565. sogScene.DeleteSceneObject(sog, false);
  566. }
  567. catch (Exception)
  568. {
  569. m_log.Warn("[SCENE]: exception when trying to remove the prim that crossed the border.");
  570. }
  571. return sog;
  572. }
  573. if (root.RETURN_AT_EDGE)
  574. {
  575. // We remove the object here
  576. try
  577. {
  578. List<uint> localIDs = new List<uint>();
  579. localIDs.Add(root.LocalId);
  580. sogScene.AddReturn(sog.OwnerID, sog.Name, sog.AbsolutePosition,
  581. "Returned at region cross");
  582. sogScene.DeRezObjects(null, localIDs, UUID.Zero, DeRezAction.Return, UUID.Zero, false);
  583. }
  584. catch (Exception)
  585. {
  586. m_log.Warn("[SCENE]: exception when trying to return the prim that crossed the border.");
  587. }
  588. return sog;
  589. }
  590. }
  591. // if(!m_scene.IsRunning)
  592. // return sog;
  593. if (root.KeyframeMotion != null)
  594. root.KeyframeMotion.StartCrossingCheck();
  595. if(root.PhysActor != null)
  596. root.PhysActor.CrossingStart();
  597. IEntityTransferModule entityTransfer = sogScene.RequestModuleInterface<IEntityTransferModule>();
  598. if (entityTransfer == null)
  599. return sog;
  600. Vector3 newpos = Vector3.Zero;
  601. OpenSim.Services.Interfaces.GridRegion destination = null;
  602. destination = entityTransfer.GetObjectDestination(sog, val, out newpos);
  603. if (destination == null)
  604. return sog;
  605. if (sog.m_sittingAvatars.Count == 0)
  606. {
  607. entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, !isTeleport, true);
  608. return sog;
  609. }
  610. string reason = String.Empty;
  611. EntityTransferContext ctx = new EntityTransferContext();
  612. Vector3 curPos = root.GroupPosition;
  613. foreach (ScenePresence av in sog.m_sittingAvatars)
  614. {
  615. // We need to cross these agents. First, let's find
  616. // out if any of them can't cross for some reason.
  617. // We have to deny the crossing entirely if any
  618. // of them are banned. Alternatively, we could
  619. // unsit banned agents....
  620. // We set the avatar position as being the object
  621. // position to get the region to send to
  622. if(av.IsNPC)
  623. continue;
  624. if(av.IsInTransit)
  625. return sog;
  626. if(!entityTransfer.checkAgentAccessToRegion(av, destination, newpos, ctx, out reason))
  627. return sog;
  628. m_log.DebugFormat("[SCENE OBJECT]: Avatar {0} needs to be crossed to {1}", av.Name, destination.RegionName);
  629. }
  630. // We unparent the SP quietly so that it won't
  631. // be made to stand up
  632. List<avtocrossInfo> avsToCross = new List<avtocrossInfo>();
  633. List<ScenePresence> avsToCrossFar = new List<ScenePresence>();
  634. ulong destHandle = destination.RegionHandle;
  635. List<ScenePresence> sittingAvatars = GetSittingAvatars();
  636. foreach (ScenePresence av in sittingAvatars)
  637. {
  638. byte cflags = 1;
  639. avtocrossInfo avinfo = new avtocrossInfo();
  640. SceneObjectPart parentPart = sogScene.GetSceneObjectPart(av.ParentID);
  641. if (parentPart != null)
  642. {
  643. av.ParentUUID = parentPart.UUID;
  644. if(parentPart.SitTargetAvatar == av.UUID)
  645. cflags = 7; // low 3 bits set
  646. else
  647. cflags = 3;
  648. }
  649. if(!av.knowsNeighbourRegion(destHandle))
  650. cflags |= 8;
  651. // 1 is crossing
  652. // 2 is sitting
  653. // 4 is sitting at sittarget
  654. // 8 far crossing
  655. avinfo.av = av;
  656. avinfo.ParentID = av.ParentID;
  657. avsToCross.Add(avinfo);
  658. if(!av.knowsNeighbourRegion(destHandle))
  659. {
  660. cflags |= 8;
  661. avsToCrossFar.Add(av);
  662. }
  663. if(av.IsNPC)
  664. av.m_crossingFlags = 0;
  665. else
  666. av.m_crossingFlags = cflags;
  667. av.PrevSitOffset = av.OffsetPosition;
  668. av.ParentID = 0;
  669. }
  670. Vector3 vel = root.Velocity;
  671. Vector3 avel = root.AngularVelocity;
  672. Vector3 acc = root.Acceleration;
  673. Quaternion ori = root.RotationOffset;
  674. if(isTeleport)
  675. {
  676. root.Stop();
  677. sogScene.ForEachScenePresence(delegate(ScenePresence av)
  678. {
  679. av.ControllingClient.SendEntityUpdate(root,PrimUpdateFlags.SendInTransit);
  680. av.ControllingClient.SendEntityTerseUpdateImmediate(root);
  681. });
  682. root.Velocity = tpdata.vel;
  683. root.AngularVelocity = tpdata.avel;
  684. root.Acceleration = tpdata.acc;
  685. root.RotationOffset = tpdata.ori;
  686. }
  687. if (entityTransfer.CrossPrimGroupIntoNewRegion(destination, newpos, sog, true, false))
  688. {
  689. if(isTeleport)
  690. {
  691. sogScene.ForEachScenePresence(delegate(ScenePresence oav)
  692. {
  693. if(sittingAvatars.Contains(oav))
  694. return;
  695. if(oav.knowsNeighbourRegion(destHandle))
  696. return;
  697. oav.ControllingClient.SendEntityUpdate(root, PrimUpdateFlags.Kill);
  698. foreach (ScenePresence sav in sittingAvatars)
  699. {
  700. sav.SendKillTo(oav);
  701. }
  702. });
  703. }
  704. bool crossedfar = false;
  705. foreach (ScenePresence av in avsToCrossFar)
  706. {
  707. if(entityTransfer.CrossAgentCreateFarChild(av,destination, newpos, ctx))
  708. crossedfar = true;
  709. else
  710. av.m_crossingFlags = 0;
  711. }
  712. if(crossedfar)
  713. Thread.Sleep(1000);
  714. foreach (avtocrossInfo avinfo in avsToCross)
  715. {
  716. ScenePresence av = avinfo.av;
  717. av.IsInLocalTransit = true;
  718. av.IsInTransit = true;
  719. m_log.DebugFormat("[SCENE OBJECT]: Crossing avatar {0} to {1}", av.Name, val);
  720. if(av.m_crossingFlags > 0)
  721. entityTransfer.CrossAgentToNewRegionAsync(av, newpos, destination, false, ctx);
  722. if (av.IsChildAgent)
  723. {
  724. // avatar crossed do some extra cleanup
  725. if (av.ParentUUID != UUID.Zero)
  726. {
  727. av.ClearControls();
  728. av.ParentPart = null;
  729. }
  730. av.ParentUUID = UUID.Zero;
  731. av.ParentPart = null;
  732. // In any case
  733. av.IsInTransit = false;
  734. av.m_crossingFlags = 0;
  735. m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} completed.", av.Firstname, av.Lastname);
  736. }
  737. else
  738. {
  739. // avatar cross failed we need do dedicated standUp
  740. // part of it was done at CrossAgentToNewRegionAsync
  741. // so for now just remove the sog controls
  742. // this may need extra care
  743. av.UnRegisterSeatControls(sog.UUID);
  744. av.ParentUUID = UUID.Zero;
  745. av.ParentPart = null;
  746. Vector3 oldp = curPos;
  747. oldp.X = Util.Clamp<float>(oldp.X, 0.5f, sog.m_scene.RegionInfo.RegionSizeX - 0.5f);
  748. oldp.Y = Util.Clamp<float>(oldp.Y, 0.5f, sog.m_scene.RegionInfo.RegionSizeY - 0.5f);
  749. av.AbsolutePosition = oldp;
  750. av.m_crossingFlags = 0;
  751. av.sitAnimation = "SIT";
  752. av.IsInTransit = false;
  753. if(av.Animator!= null)
  754. av.Animator.SetMovementAnimations("STAND");
  755. av.AddToPhysicalScene(false);
  756. sogScene.ForEachScenePresence(delegate(ScenePresence oav)
  757. {
  758. if(sittingAvatars.Contains(oav))
  759. return;
  760. if(oav.knowsNeighbourRegion(destHandle))
  761. av.SendAvatarDataToAgent(oav);
  762. else
  763. {
  764. av.SendAvatarDataToAgent(oav);
  765. av.SendAppearanceToAgent(oav);
  766. if (av.Animator != null)
  767. av.Animator.SendAnimPackToClient(oav.ControllingClient);
  768. av.SendAttachmentsToAgentNF(oav); // not ok
  769. }
  770. });
  771. m_log.DebugFormat("[SCENE OBJECT]: Crossing agent {0} {1} failed.", av.Firstname, av.Lastname);
  772. }
  773. }
  774. if(crossedfar)
  775. {
  776. Thread.Sleep(10000);
  777. foreach (ScenePresence av in avsToCrossFar)
  778. {
  779. if(av.IsChildAgent)
  780. {
  781. av.Scene.CloseAgent(av.UUID, false);
  782. }
  783. else
  784. av.RemoveNeighbourRegion(destHandle);
  785. }
  786. }
  787. avsToCrossFar.Clear();
  788. avsToCross.Clear();
  789. sog.RemoveScriptInstances(true);
  790. sog.Dispose();
  791. return sog;
  792. }
  793. else
  794. {
  795. if(isTeleport)
  796. {
  797. if((tpdata.flags & OSTPOBJ_STOPONFAIL) == 0)
  798. {
  799. root.Velocity = vel;
  800. root.AngularVelocity = avel;
  801. root.Acceleration = acc;
  802. }
  803. root.RotationOffset = ori;
  804. }
  805. foreach (avtocrossInfo avinfo in avsToCross)
  806. {
  807. ScenePresence av = avinfo.av;
  808. av.ParentUUID = UUID.Zero;
  809. av.ParentID = avinfo.ParentID;
  810. av.m_crossingFlags = 0;
  811. }
  812. }
  813. avsToCross.Clear();
  814. return sog;
  815. }
  816. public void CrossAsyncCompleted(IAsyncResult iar)
  817. {
  818. SOGCrossDelegate icon = (SOGCrossDelegate)iar.AsyncState;
  819. SceneObjectGroup sog = icon.EndInvoke(iar);
  820. if (!sog.IsDeleted)
  821. {
  822. SceneObjectPart rootp = sog.m_rootPart;
  823. Vector3 oldp = rootp.GroupPosition;
  824. oldp.X = Util.Clamp<float>(oldp.X, 0.5f, sog.m_scene.RegionInfo.RegionSizeX - 0.5f);
  825. oldp.Y = Util.Clamp<float>(oldp.Y, 0.5f, sog.m_scene.RegionInfo.RegionSizeY - 0.5f);
  826. rootp.GroupPosition = oldp;
  827. rootp.Stop();
  828. SceneObjectPart[] parts = sog.m_parts.GetArray();
  829. foreach (SceneObjectPart part in parts)
  830. {
  831. if (part != rootp)
  832. part.GroupPosition = oldp;
  833. }
  834. foreach (ScenePresence av in sog.m_sittingAvatars)
  835. {
  836. av.sitSOGmoved();
  837. }
  838. if (sog.m_rootPart.KeyframeMotion != null)
  839. sog.m_rootPart.KeyframeMotion.CrossingFailure();
  840. if (sog.RootPart.PhysActor != null)
  841. sog.RootPart.PhysActor.CrossingFailure();
  842. sog.inTransit = false;
  843. AttachToBackup();
  844. sog.ScheduleGroupForFullAnimUpdate();
  845. }
  846. }
  847. private class TeleportObjectData
  848. {
  849. public int flags;
  850. public Vector3 vel;
  851. public Vector3 avel;
  852. public Vector3 acc;
  853. public Quaternion ori;
  854. public UUID sourceID;
  855. }
  856. // copy from LSL_constants.cs
  857. const int OSTPOBJ_STOPATTARGET = 0x1; // stops at destination
  858. const int OSTPOBJ_STOPONFAIL = 0x2; // stops at start if tp fails
  859. const int OSTPOBJ_SETROT = 0x4; // the rotation is the final rotation, otherwise is a added rotation
  860. public int TeleportObject(UUID sourceID, Vector3 targetPosition, Quaternion rotation, int flags)
  861. {
  862. if(inTransit || IsDeleted || IsAttachmentCheckFull() || IsSelected || Scene == null)
  863. return -1;
  864. inTransit = true;
  865. PhysicsActor pa = RootPart.PhysActor;
  866. if(pa == null || RootPart.KeyframeMotion != null /*|| m_sittingAvatars.Count == 0*/)
  867. {
  868. inTransit = false;
  869. return -1;
  870. }
  871. bool stop = (flags & OSTPOBJ_STOPATTARGET) != 0;
  872. bool setrot = (flags & OSTPOBJ_SETROT) != 0;
  873. rotation.Normalize();
  874. Quaternion currentRot = RootPart.RotationOffset;
  875. if(setrot)
  876. rotation = Quaternion.Conjugate(currentRot) * rotation;
  877. bool dorot = setrot | (Math.Abs(rotation.W) < 0.99999);
  878. Vector3 vel = Vector3.Zero;
  879. Vector3 avel = Vector3.Zero;
  880. Vector3 acc = Vector3.Zero;
  881. if(!stop)
  882. {
  883. vel = RootPart.Velocity;
  884. avel = RootPart.AngularVelocity;
  885. acc = RootPart.Acceleration;
  886. }
  887. Quaternion ori = RootPart.RotationOffset;
  888. if(dorot)
  889. {
  890. if(!stop)
  891. {
  892. vel *= rotation;
  893. avel *= rotation;
  894. acc *= rotation;
  895. }
  896. ori *= rotation;
  897. }
  898. if(Scene.PositionIsInCurrentRegion(targetPosition))
  899. {
  900. if(Scene.InTeleportTargetsCoolDown(UUID, sourceID, 1.0))
  901. {
  902. inTransit = false;
  903. return -2;
  904. }
  905. Vector3 curPos = AbsolutePosition;
  906. ILandObject curLand = Scene.LandChannel.GetLandObject(curPos.X, curPos.Y);
  907. float posX = targetPosition.X;
  908. float posY = targetPosition.Y;
  909. ILandObject land = Scene.LandChannel.GetLandObject(posX, posY);
  910. if(land != null && land != curLand)
  911. {
  912. if(!Scene.Permissions.CanObjectEnterWithScripts(this, land))
  913. {
  914. inTransit = false;
  915. return -3;
  916. }
  917. UUID agentID;
  918. foreach (ScenePresence av in m_sittingAvatars)
  919. {
  920. agentID = av.UUID;
  921. if(land.IsRestrictedFromLand(agentID) || land.IsBannedFromLand(agentID))
  922. {
  923. inTransit = false;
  924. return -4;
  925. }
  926. }
  927. }
  928. RootPart.Velocity = vel;
  929. RootPart.AngularVelocity = avel;
  930. RootPart.Acceleration = acc;
  931. RootPart.RotationOffset = ori;
  932. Vector3 s = RootPart.Scale * RootPart.RotationOffset;
  933. float h = Scene.GetGroundHeight(posX, posY) + 0.5f * (float)Math.Abs(s.Z) + 0.01f;
  934. if(targetPosition.Z < h)
  935. targetPosition.Z = h;
  936. inTransit = false;
  937. AbsolutePosition = targetPosition;
  938. RootPart.ScheduleTerseUpdate();
  939. return 1;
  940. }
  941. if(Scene.InTeleportTargetsCoolDown(UUID, sourceID, 20.0))
  942. {
  943. inTransit = false;
  944. return -1;
  945. }
  946. TeleportObjectData tdata = new TeleportObjectData();
  947. tdata.flags = flags;
  948. tdata.vel = vel;
  949. tdata.avel = avel;
  950. tdata.acc = acc;
  951. tdata.ori = ori;
  952. tdata.sourceID = sourceID;
  953. SOGCrossDelegate d = CrossAsync;
  954. d.BeginInvoke(this, targetPosition, tdata, CrossAsyncCompleted, d);
  955. return 0;
  956. }
  957. public override Vector3 Velocity
  958. {
  959. get { return RootPart.Velocity; }
  960. set { RootPart.Velocity = value; }
  961. }
  962. public override uint LocalId
  963. {
  964. get { return m_rootPart.LocalId; }
  965. set { m_rootPart.LocalId = value; }
  966. }
  967. public override UUID UUID
  968. {
  969. get { return m_rootPart.UUID; }
  970. set
  971. {
  972. lock (m_parts.SyncRoot)
  973. {
  974. m_parts.Remove(m_rootPart.UUID);
  975. m_rootPart.UUID = value;
  976. m_parts.Add(value, m_rootPart);
  977. }
  978. }
  979. }
  980. public UUID LastOwnerID
  981. {
  982. get { return m_rootPart.LastOwnerID; }
  983. set { m_rootPart.LastOwnerID = value; }
  984. }
  985. public UUID RezzerID
  986. {
  987. get { return m_rootPart.RezzerID; }
  988. set { m_rootPart.RezzerID = value; }
  989. }
  990. public UUID OwnerID
  991. {
  992. get { return m_rootPart.OwnerID; }
  993. set { m_rootPart.OwnerID = value; }
  994. }
  995. public float Damage
  996. {
  997. get { return m_rootPart.Damage; }
  998. set { m_rootPart.Damage = value; }
  999. }
  1000. public Color Color
  1001. {
  1002. get { return m_rootPart.Color; }
  1003. set { m_rootPart.Color = value; }
  1004. }
  1005. public string Text
  1006. {
  1007. get {
  1008. string returnstr = m_rootPart.Text;
  1009. if (returnstr.Length > 255)
  1010. {
  1011. returnstr = returnstr.Substring(0, 255);
  1012. }
  1013. return returnstr;
  1014. }
  1015. set { m_rootPart.Text = value; }
  1016. }
  1017. /// <summary>
  1018. /// If set to true then the scene object can be backed up in principle, though this will only actually occur
  1019. /// if Backup is set. If false then the scene object will never be backed up, Backup will always be false.
  1020. /// </summary>
  1021. protected virtual bool CanBeBackedUp
  1022. {
  1023. get { return true; }
  1024. }
  1025. public bool IsSelected
  1026. {
  1027. get { return m_isSelected; }
  1028. set
  1029. {
  1030. m_isSelected = value;
  1031. // Tell physics engine that group is selected
  1032. // this is not right
  1033. // but ode engines should only really need to know about root part
  1034. // so they can put entire object simulation on hold and not colliding
  1035. // keep as was for now
  1036. PhysicsActor pa = m_rootPart.PhysActor;
  1037. if (pa != null)
  1038. {
  1039. pa.Selected = value;
  1040. // Pass it on to the children.
  1041. SceneObjectPart[] parts = m_parts.GetArray();
  1042. for (int i = 0; i < parts.Length; i++)
  1043. {
  1044. SceneObjectPart child = parts[i];
  1045. PhysicsActor childPa = child.PhysActor;
  1046. if (childPa != null)
  1047. childPa.Selected = value;
  1048. }
  1049. }
  1050. if (RootPart.KeyframeMotion != null)
  1051. RootPart.KeyframeMotion.Selected = value;
  1052. }
  1053. }
  1054. public void PartSelectChanged(bool partSelect)
  1055. {
  1056. // any part selected makes group selected
  1057. if (m_isSelected == partSelect)
  1058. return;
  1059. if (partSelect)
  1060. {
  1061. IsSelected = partSelect;
  1062. // if (!IsAttachment)
  1063. // ScheduleGroupForFullUpdate();
  1064. }
  1065. else
  1066. {
  1067. // bad bad bad 2 heavy for large linksets
  1068. // since viewer does send lot of (un)selects
  1069. // this needs to be replaced by a specific list or count ?
  1070. // but that will require extra code in several places
  1071. SceneObjectPart[] parts = m_parts.GetArray();
  1072. for (int i = 0; i < parts.Length; i++)
  1073. {
  1074. SceneObjectPart part = parts[i];
  1075. if (part.IsSelected)
  1076. return;
  1077. }
  1078. IsSelected = partSelect;
  1079. // if (!IsAttachment)
  1080. // {
  1081. // ScheduleGroupForFullUpdate();
  1082. // }
  1083. }
  1084. }
  1085. private double m_lastCollisionSoundMS;
  1086. /// <summary>
  1087. /// The UUID for the region this object is in.
  1088. /// </summary>
  1089. public UUID RegionUUID
  1090. {
  1091. get
  1092. {
  1093. if (m_scene != null)
  1094. {
  1095. return m_scene.RegionInfo.RegionID;
  1096. }
  1097. return UUID.Zero;
  1098. }
  1099. }
  1100. /// <summary>
  1101. /// The item ID that this object was rezzed from, if applicable.
  1102. /// </summary>
  1103. /// <remarks>
  1104. /// If not applicable will be UUID.Zero
  1105. /// </remarks>
  1106. public UUID FromItemID { get; set; }
  1107. /// <summary>
  1108. /// Refers to the SceneObjectPart.UUID property of the object that this object was rezzed from, if applicable.
  1109. /// </summary>
  1110. /// <remarks>
  1111. /// If not applicable will be UUID.Zero
  1112. /// </remarks>
  1113. /// obsolete use RezzerID
  1114. public UUID FromPartID
  1115. {
  1116. get { return RezzerID; }
  1117. set {RezzerID = value; }
  1118. }
  1119. /// <summary>
  1120. /// The folder ID that this object was rezzed from, if applicable.
  1121. /// </summary>
  1122. /// <remarks>
  1123. /// If not applicable will be UUID.Zero
  1124. /// </remarks>
  1125. public UUID FromFolderID { get; set; }
  1126. /// <summary>
  1127. /// If true then grabs are blocked no matter what the individual part BlockGrab setting.
  1128. /// </summary>
  1129. /// <value><c>true</c> if block grab override; otherwise, <c>false</c>.</value>
  1130. public bool BlockGrabOverride { get; set; }
  1131. /// <summary>
  1132. /// IDs of all avatars sat on this scene object.
  1133. /// </summary>
  1134. /// <remarks>
  1135. /// We need this so that we can maintain a linkset wide ordering of avatars sat on different parts.
  1136. /// This must be locked before it is read or written.
  1137. /// SceneObjectPart sitting avatar add/remove code also locks on this object to avoid race conditions.
  1138. /// No avatar should appear more than once in this list.
  1139. /// Do not manipulate this list directly - use the Add/Remove sitting avatar methods on SceneObjectPart.
  1140. /// </remarks>
  1141. protected internal List<ScenePresence> m_sittingAvatars = new List<ScenePresence>();
  1142. #endregion
  1143. // ~SceneObjectGroup()
  1144. // {
  1145. // //m_log.DebugFormat("[SCENE OBJECT GROUP]: Destructor called for {0}, local id {1}", Name, LocalId);
  1146. // Console.WriteLine("Destructor called for {0}, local id {1}", Name, LocalId);
  1147. // }
  1148. #region Constructors
  1149. /// <summary>
  1150. /// Constructor
  1151. /// </summary>
  1152. public SceneObjectGroup()
  1153. {
  1154. m_lastCollisionSoundMS = Util.GetTimeStampMS() + 1000.0;
  1155. }
  1156. /// <summary>
  1157. /// This constructor creates a SceneObjectGroup using a pre-existing SceneObjectPart.
  1158. /// The original SceneObjectPart will be used rather than a copy, preserving
  1159. /// its existing localID and UUID.
  1160. /// </summary>
  1161. /// <param name='part'>Root part for this scene object.</param>
  1162. public SceneObjectGroup(SceneObjectPart part) : this()
  1163. {
  1164. SetRootPart(part);
  1165. }
  1166. /// <summary>
  1167. /// Constructor. This object is added to the scene later via AttachToScene()
  1168. /// </summary>
  1169. public SceneObjectGroup(UUID ownerID, Vector3 pos, Quaternion rot, PrimitiveBaseShape shape)
  1170. {
  1171. SetRootPart(new SceneObjectPart(ownerID, shape, pos, rot, Vector3.Zero));
  1172. }
  1173. /// <summary>
  1174. /// Constructor.
  1175. /// </summary>
  1176. public SceneObjectGroup(UUID ownerID, Vector3 pos, PrimitiveBaseShape shape)
  1177. : this(ownerID, pos, Quaternion.Identity, shape)
  1178. {
  1179. }
  1180. ~SceneObjectGroup()
  1181. {
  1182. Dispose(false);
  1183. }
  1184. private bool disposed = false;
  1185. public void Dispose()
  1186. {
  1187. Dispose(true);
  1188. GC.SuppressFinalize(this);
  1189. }
  1190. protected void Dispose(bool disposing)
  1191. {
  1192. // Check to see if Dispose has already been called.
  1193. if (!disposed)
  1194. {
  1195. IsDeleted = true;
  1196. SceneObjectPart[] parts = m_parts.GetArray();
  1197. for(int i= 0; i < parts.Length; ++i)
  1198. parts[i].Dispose();
  1199. m_parts.Clear();
  1200. m_sittingAvatars.Clear();
  1201. // m_rootPart = null;
  1202. m_targets.Clear();
  1203. m_partsNameToLinkMap.Clear();
  1204. disposed = true;
  1205. }
  1206. }
  1207. public void LoadScriptState(XmlDocument doc)
  1208. {
  1209. XmlNodeList nodes = doc.GetElementsByTagName("SavedScriptState");
  1210. if (nodes.Count > 0)
  1211. {
  1212. if (m_savedScriptState == null)
  1213. m_savedScriptState = new Dictionary<UUID, string>();
  1214. foreach (XmlNode node in nodes)
  1215. {
  1216. if (node.Attributes["UUID"] != null)
  1217. {
  1218. UUID itemid = new UUID(node.Attributes["UUID"].Value);
  1219. if (itemid != UUID.Zero)
  1220. m_savedScriptState[itemid] = node.InnerXml;
  1221. }
  1222. }
  1223. }
  1224. }
  1225. public void LoadScriptState(XmlReader reader)
  1226. {
  1227. // m_log.DebugFormat("[SCENE OBJECT GROUP]: Looking for script state for {0}", Name);
  1228. while (true)
  1229. {
  1230. if (reader.Name == "SavedScriptState" && reader.NodeType == XmlNodeType.Element)
  1231. {
  1232. // m_log.DebugFormat("[SCENE OBJECT GROUP]: Loading script state for {0}", Name);
  1233. if (m_savedScriptState == null)
  1234. m_savedScriptState = new Dictionary<UUID, string>();
  1235. string uuid = reader.GetAttribute("UUID");
  1236. // Even if there is no UUID attribute for some strange reason, we must always read the inner XML
  1237. // so we don't continually keep checking the same SavedScriptedState element.
  1238. string innerXml = reader.ReadInnerXml();
  1239. if (uuid != null)
  1240. {
  1241. // m_log.DebugFormat("[SCENE OBJECT GROUP]: Found state for item ID {0} in object {1}", uuid, Name);
  1242. UUID itemid = new UUID(uuid);
  1243. if (itemid != UUID.Zero)
  1244. m_savedScriptState[itemid] = innerXml;
  1245. }
  1246. else
  1247. {
  1248. m_log.WarnFormat("[SCENE OBJECT GROUP]: SavedScriptState element had no UUID in object {0} id: {1}", Name,UUID);
  1249. }
  1250. }
  1251. else
  1252. {
  1253. if (!reader.Read())
  1254. break;
  1255. }
  1256. }
  1257. }
  1258. /// <summary>
  1259. /// Hooks this object up to the backup event so that it is persisted to the database when the update thread executes.
  1260. /// </summary>
  1261. public virtual void AttachToBackup()
  1262. {
  1263. if (IsAttachment) return;
  1264. m_scene.SceneGraph.FireAttachToBackup(this);
  1265. // if (InSceneBackup)
  1266. {
  1267. // m_log.DebugFormat(
  1268. // "[SCENE OBJECT GROUP]: Attaching object {0} {1} to scene presistence sweep", Name, UUID);
  1269. if (!Backup)
  1270. m_scene.EventManager.OnBackup += ProcessBackup;
  1271. Backup = true;
  1272. }
  1273. }
  1274. /// <summary>
  1275. /// Attach this object to a scene. It will also now appear to agents.
  1276. /// </summary>
  1277. /// <param name="scene"></param>
  1278. public void AttachToScene(Scene scene)
  1279. {
  1280. m_scene = scene;
  1281. RegionHandle = m_scene.RegionInfo.RegionHandle;
  1282. if (m_rootPart.Shape.PCode != 9 || m_rootPart.Shape.State == 0)
  1283. m_rootPart.ParentID = 0;
  1284. if (m_rootPart.LocalId == 0)
  1285. m_rootPart.LocalId = m_scene.AllocateLocalId();
  1286. SceneObjectPart[] parts = m_parts.GetArray();
  1287. SceneObjectPart part;
  1288. for (int i = 0; i < parts.Length; i++)
  1289. {
  1290. part = parts[i];
  1291. if (part.KeyframeMotion != null)
  1292. {
  1293. part.KeyframeMotion.UpdateSceneObject(this);
  1294. }
  1295. if (Object.ReferenceEquals(part, m_rootPart))
  1296. continue;
  1297. if (part.LocalId == 0)
  1298. part.LocalId = m_scene.AllocateLocalId();
  1299. part.ParentID = m_rootPart.LocalId;
  1300. //m_log.DebugFormat("[SCENE]: Given local id {0} to part {1}, linknum {2}, parent {3} {4}", part.LocalId, part.UUID, part.LinkNum, part.ParentID, part.ParentUUID);
  1301. }
  1302. ApplyPhysics();
  1303. // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
  1304. // for the same object with very different properties. The caller must schedule the update.
  1305. //ScheduleGroupForFullUpdate();
  1306. }
  1307. public EntityIntersection TestIntersection(Ray hRay, bool frontFacesOnly, bool faceCenters)
  1308. {
  1309. // We got a request from the inner_scene to raytrace along the Ray hRay
  1310. // We're going to check all of the prim in this group for intersection with the ray
  1311. // If we get a result, we're going to find the closest result to the origin of the ray
  1312. // and send back the intersection information back to the innerscene.
  1313. EntityIntersection result = new EntityIntersection();
  1314. SceneObjectPart[] parts = m_parts.GetArray();
  1315. // Find closest hit here
  1316. float idist = float.MaxValue;
  1317. for (int i = 0; i < parts.Length; i++)
  1318. {
  1319. SceneObjectPart part = parts[i];
  1320. // Temporary commented to stop compiler warning
  1321. //Vector3 partPosition =
  1322. // new Vector3(part.AbsolutePosition.X, part.AbsolutePosition.Y, part.AbsolutePosition.Z);
  1323. Quaternion parentrotation = GroupRotation;
  1324. // Telling the prim to raytrace.
  1325. //EntityIntersection inter = part.TestIntersection(hRay, parentrotation);
  1326. EntityIntersection inter = part.TestIntersectionOBB(hRay, parentrotation, frontFacesOnly, faceCenters);
  1327. if (inter.HitTF)
  1328. {
  1329. // We need to find the closest prim to return to the testcaller along the ray
  1330. if (inter.distance < idist)
  1331. {
  1332. result.HitTF = true;
  1333. result.ipoint = inter.ipoint;
  1334. result.obj = part;
  1335. result.normal = inter.normal;
  1336. result.distance = inter.distance;
  1337. idist = inter.distance;
  1338. }
  1339. }
  1340. }
  1341. return result;
  1342. }
  1343. public void GetBoundingBox(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  1344. {
  1345. uint rootid = RootPart.LocalId;
  1346. Vector3 scale = RootPart.Scale * 0.5f;
  1347. minX = -scale.X;
  1348. maxX = scale.X;
  1349. minY = -scale.Y;
  1350. maxY = scale.Y;
  1351. minZ = -scale.Z;
  1352. maxZ = scale.Z;
  1353. SceneObjectPart[] parts = m_parts.GetArray();
  1354. SceneObjectPart part;
  1355. for (int i = 0; i < parts.Length; ++i)
  1356. {
  1357. part = parts[i];
  1358. if(part.LocalId == rootid)
  1359. continue;
  1360. Vector3 offset = part.OffsetPosition;
  1361. scale = part.Scale * 0.5f;
  1362. Matrix4 m = Matrix4.CreateFromQuaternion(Quaternion.Conjugate(part.RotationOffset));
  1363. Vector3 a = m.AtAxis;
  1364. a.X = Math.Abs(a.X);
  1365. a.Y = Math.Abs(a.Y);
  1366. a.Z = Math.Abs(a.Z);
  1367. float tmpS = Vector3.Dot(a, scale);
  1368. float tmp = offset.X - tmpS;
  1369. if (tmp < minX)
  1370. minX = tmp;
  1371. tmp = offset.X + tmpS;
  1372. if (tmp > maxX)
  1373. maxX = tmp;
  1374. a = m.LeftAxis;
  1375. a.X = Math.Abs(a.X);
  1376. a.Y = Math.Abs(a.Y);
  1377. a.Z = Math.Abs(a.Z);
  1378. tmpS = Vector3.Dot(a, scale);
  1379. tmp = offset.Y - tmpS;
  1380. if (tmp < minY)
  1381. minY = tmp;
  1382. tmp = offset.Y + tmpS;
  1383. if (tmp > maxY)
  1384. maxY = tmp;
  1385. a = m.UpAxis;
  1386. a.X = Math.Abs(a.X);
  1387. a.Y = Math.Abs(a.Y);
  1388. a.Z = Math.Abs(a.Z);
  1389. tmpS = Vector3.Dot(a, scale);
  1390. tmp = offset.Z - tmpS;
  1391. if (tmp < minZ)
  1392. minZ = tmp;
  1393. tmp = offset.Z + tmpS;
  1394. if (tmp > maxZ)
  1395. maxZ = tmp;
  1396. }
  1397. }
  1398. /// <summary>
  1399. /// Gets a vector representing the size of the bounding box containing all the prims in the group
  1400. /// Treats all prims as rectangular, so no shape (cut etc) is taken into account
  1401. /// </summary>
  1402. /// <returns></returns>
  1403. public void GetAxisAlignedBoundingBoxRaw(out float minX, out float maxX, out float minY, out float maxY, out float minZ, out float maxZ)
  1404. {
  1405. maxX = float.MinValue;
  1406. maxY = float.MinValue;
  1407. maxZ = float.MinValue;
  1408. minX = float.MaxValue;
  1409. minY = float.MaxValue;
  1410. minZ = float.MaxValue;
  1411. Vector3 absPos = AbsolutePosition;
  1412. SceneObjectPart[] parts = m_parts.GetArray();
  1413. SceneObjectPart part;
  1414. for(int i = 0; i< parts.Length; ++i)
  1415. {
  1416. part = parts[i];
  1417. Vector3 offset = part.GetWorldPosition() - absPos;
  1418. Vector3 scale = part.Scale * 0.5f;
  1419. Matrix4 m = Matrix4.CreateFromQuaternion(Quaternion.Conjugate(part.GetWorldRotation()));
  1420. Vector3 a = m.AtAxis;
  1421. a.X = Math.Abs(a.X);
  1422. a.Y = Math.Abs(a.Y);
  1423. a.Z = Math.Abs(a.Z);
  1424. float tmpS = Vector3.Dot(a, scale);
  1425. float tmp = offset.X - tmpS;
  1426. if (tmp < minX)
  1427. minX = tmp;
  1428. tmp = offset.X + tmpS;
  1429. if (tmp > maxX)
  1430. maxX = tmp;
  1431. a = m.LeftAxis;
  1432. a.X = Math.Abs(a.X);
  1433. a.Y = Math.Abs(a.Y);
  1434. a.Z = Math.Abs(a.Z);
  1435. tmpS = Vector3.Dot(a, scale);
  1436. tmp = offset.Y - tmpS;
  1437. if (tmp < minY)
  1438. minY = tmp;
  1439. tmp = offset.Y + tmpS;
  1440. if (tmp > maxY)
  1441. maxY = tmp;
  1442. a = m.UpAxis;
  1443. a.X = Math.Abs(a.X);
  1444. a.Y = Math.Abs(a.Y);
  1445. a.Z = Math.Abs(a.Z);
  1446. tmpS = Vector3.Dot(a, scale);
  1447. tmp = offset.Z - tmpS;
  1448. if (tmp < minZ)
  1449. minZ = tmp;
  1450. tmp = offset.Z + tmpS;
  1451. if (tmp > maxZ)
  1452. maxZ = tmp;
  1453. }
  1454. }
  1455. /// <summary>
  1456. /// Gets a vector representing the size of the bounding box containing all the prims in the group
  1457. /// Treats all prims as rectangular, so no shape (cut etc) is taken into account
  1458. /// offsetHeight is the offset in the Z axis from the centre of the bounding box to the centre of the root prim
  1459. /// </summary>
  1460. /// <returns></returns>
  1461. public Vector3 GetAxisAlignedBoundingBox(out float offsetHeight)
  1462. {
  1463. float minX;
  1464. float maxX;
  1465. float minY;
  1466. float maxY;
  1467. float minZ;
  1468. float maxZ;
  1469. GetAxisAlignedBoundingBoxRaw(out minX, out maxX, out minY, out maxY, out minZ, out maxZ);
  1470. Vector3 boundingBox = new Vector3(maxX - minX, maxY - minY, maxZ - minZ);
  1471. offsetHeight = 0;
  1472. float lower = -minZ;
  1473. if (lower > maxZ)
  1474. offsetHeight = lower - 0.5f * boundingBox.Z;
  1475. else if (maxZ > lower)
  1476. offsetHeight = 0.5f * boundingBox.Z - maxZ;
  1477. // m_log.InfoFormat("BoundingBox is {0} , {1} , {2} ", boundingBox.X, boundingBox.Y, boundingBox.Z);
  1478. return boundingBox;
  1479. }
  1480. #endregion
  1481. private float? m_boundsRadius = null;
  1482. public void InvalidBoundsRadius()
  1483. {
  1484. m_boundsRadius = null;
  1485. }
  1486. private Vector3 m_boundsCenter;
  1487. private Vector3 m_LastCenterOffset;
  1488. private Vector3 last_boundsRot = new Vector3(-10, -10, -10);
  1489. public Vector3 getCenterOffset()
  1490. {
  1491. // math is done in GetBoundsRadius();
  1492. if(m_boundsRadius == null)
  1493. GetBoundsRadius();
  1494. Quaternion rot = m_rootPart.RotationOffset;
  1495. if (last_boundsRot.X != rot.X ||
  1496. last_boundsRot.Y != rot.Y ||
  1497. last_boundsRot.Z != rot.Z)
  1498. {
  1499. m_LastCenterOffset = m_boundsCenter * rot;
  1500. last_boundsRot.X = rot.X;
  1501. last_boundsRot.Y = rot.Y;
  1502. last_boundsRot.Z = rot.Z;
  1503. }
  1504. return m_rootPart.GroupPosition + m_LastCenterOffset;
  1505. }
  1506. private float m_areaFactor;
  1507. public float getAreaFactor()
  1508. {
  1509. // math is done in GetBoundsRadius();
  1510. if(m_boundsRadius == null)
  1511. GetBoundsRadius();
  1512. return m_areaFactor;
  1513. }
  1514. public float GetBoundsRadius()
  1515. {
  1516. // this may need more threading work
  1517. if(m_boundsRadius == null)
  1518. {
  1519. float res = 0;
  1520. float areaF = 0;
  1521. float partR;
  1522. Vector3 offset = Vector3.Zero;
  1523. SceneObjectPart p;
  1524. SceneObjectPart[] parts = m_parts.GetArray();
  1525. int nparts = parts.Length;
  1526. for (int i = 0; i < nparts; i++)
  1527. {
  1528. p = parts[i];
  1529. partR = 0.5f * p.Scale.Length();
  1530. if(p != RootPart)
  1531. {
  1532. partR += p.OffsetPosition.Length();
  1533. offset += p.OffsetPosition;
  1534. }
  1535. if(partR > res)
  1536. res = partR;
  1537. if(p.maxSimpleArea() > areaF)
  1538. areaF = p.maxSimpleArea();
  1539. }
  1540. if(parts.Length > 1)
  1541. {
  1542. offset /= parts.Length; // basicly geometric center
  1543. }
  1544. areaF = 0.5f / areaF; // scale it
  1545. areaF = Util.Clamp(areaF, 0.05f, 100f); // clamp it
  1546. m_areaFactor = (float)Math.Sqrt(areaF);
  1547. m_boundsCenter = offset;
  1548. m_boundsRadius = res;
  1549. return res;
  1550. }
  1551. return m_boundsRadius.Value;
  1552. }
  1553. public void GetResourcesCosts(SceneObjectPart apart,
  1554. out float linksetResCost, out float linksetPhysCost, out float partCost, out float partPhysCost)
  1555. {
  1556. // this information may need to be cached
  1557. float cost;
  1558. float tmpcost;
  1559. bool ComplexCost = false;
  1560. SceneObjectPart p;
  1561. SceneObjectPart[] parts = m_parts.GetArray();
  1562. int nparts = parts.Length;
  1563. for (int i = 0; i < nparts; i++)
  1564. {
  1565. p = parts[i];
  1566. if (p.UsesComplexCost)
  1567. {
  1568. ComplexCost = true;
  1569. break;
  1570. }
  1571. }
  1572. if (ComplexCost)
  1573. {
  1574. linksetResCost = 0;
  1575. linksetPhysCost = 0;
  1576. partCost = 0;
  1577. partPhysCost = 0;
  1578. for (int i = 0; i < nparts; i++)
  1579. {
  1580. p = parts[i];
  1581. cost = p.StreamingCost;
  1582. tmpcost = p.SimulationCost;
  1583. if (tmpcost > cost)
  1584. cost = tmpcost;
  1585. tmpcost = p.PhysicsCost;
  1586. if (tmpcost > cost)
  1587. cost = tmpcost;
  1588. linksetPhysCost += tmpcost;
  1589. linksetResCost += cost;
  1590. if (p == apart)
  1591. {
  1592. partCost = cost;
  1593. partPhysCost = tmpcost;
  1594. }
  1595. }
  1596. }
  1597. else
  1598. {
  1599. partPhysCost = 1.0f;
  1600. partCost = 1.0f;
  1601. linksetResCost = (float)nparts;
  1602. linksetPhysCost = linksetResCost;
  1603. }
  1604. }
  1605. public void GetSelectedCosts(out float PhysCost, out float StreamCost, out float SimulCost)
  1606. {
  1607. SceneObjectPart p;
  1608. SceneObjectPart[] parts = m_parts.GetArray();
  1609. int nparts = parts.Length;
  1610. PhysCost = 0;
  1611. StreamCost = 0;
  1612. SimulCost = 0;
  1613. for (int i = 0; i < nparts; i++)
  1614. {
  1615. p = parts[i];
  1616. StreamCost += p.StreamingCost;
  1617. SimulCost += p.SimulationCost;
  1618. PhysCost += p.PhysicsCost;
  1619. }
  1620. }
  1621. public void SaveScriptedState(XmlTextWriter writer)
  1622. {
  1623. SaveScriptedState(writer, false);
  1624. }
  1625. public void SaveScriptedState(XmlTextWriter writer, bool oldIDs)
  1626. {
  1627. XmlDocument doc = new XmlDocument();
  1628. Dictionary<UUID,string> states = new Dictionary<UUID,string>();
  1629. SceneObjectPart[] parts = m_parts.GetArray();
  1630. for (int i = 0; i < parts.Length; i++)
  1631. {
  1632. Dictionary<UUID, string> pstates = parts[i].Inventory.GetScriptStates(oldIDs);
  1633. foreach (KeyValuePair<UUID, string> kvp in pstates)
  1634. states[kvp.Key] = kvp.Value;
  1635. }
  1636. if (states.Count > 0)
  1637. {
  1638. // Now generate the necessary XML wrappings
  1639. writer.WriteStartElement(String.Empty, "GroupScriptStates", String.Empty);
  1640. foreach (UUID itemid in states.Keys)
  1641. {
  1642. doc.LoadXml(states[itemid]);
  1643. writer.WriteStartElement(String.Empty, "SavedScriptState", String.Empty);
  1644. writer.WriteAttributeString(String.Empty, "UUID", String.Empty, itemid.ToString());
  1645. writer.WriteRaw(doc.DocumentElement.OuterXml); // Writes ScriptState element
  1646. writer.WriteEndElement(); // End of SavedScriptState
  1647. }
  1648. writer.WriteEndElement(); // End of GroupScriptStates
  1649. }
  1650. }
  1651. public byte GetAttachmentPoint()
  1652. {
  1653. return m_rootPart.Shape.State;
  1654. }
  1655. public void DetachToGround()
  1656. {
  1657. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  1658. if (avatar == null)
  1659. return;
  1660. m_rootPart.Shape.LastAttachPoint = m_rootPart.Shape.State;
  1661. m_rootPart.AttachedPos = m_rootPart.OffsetPosition;
  1662. avatar.RemoveAttachment(this);
  1663. Vector3 detachedpos = new Vector3(127f,127f,127f);
  1664. if (avatar == null)
  1665. return;
  1666. detachedpos = avatar.AbsolutePosition;
  1667. FromItemID = UUID.Zero;
  1668. AbsolutePosition = detachedpos;
  1669. AttachedAvatar = UUID.Zero;
  1670. //SceneObjectPart[] parts = m_parts.GetArray();
  1671. //for (int i = 0; i < parts.Length; i++)
  1672. // parts[i].AttachedAvatar = UUID.Zero;
  1673. m_rootPart.SetParentLocalId(0);
  1674. AttachmentPoint = (byte)0;
  1675. // must check if buildind should be true or false here
  1676. // m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive,false);
  1677. ApplyPhysics();
  1678. HasGroupChanged = true;
  1679. RootPart.Rezzed = DateTime.Now;
  1680. RootPart.RemFlag(PrimFlags.TemporaryOnRez);
  1681. AttachToBackup();
  1682. m_scene.EventManager.TriggerParcelPrimCountTainted();
  1683. m_rootPart.ScheduleFullUpdate();
  1684. m_rootPart.ClearUndoState();
  1685. }
  1686. public void DetachToInventoryPrep()
  1687. {
  1688. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  1689. //Vector3 detachedpos = new Vector3(127f, 127f, 127f);
  1690. if (avatar != null)
  1691. {
  1692. //detachedpos = avatar.AbsolutePosition;
  1693. avatar.RemoveAttachment(this);
  1694. }
  1695. AttachedAvatar = UUID.Zero;
  1696. /*SceneObjectPart[] parts = m_parts.GetArray();
  1697. for (int i = 0; i < parts.Length; i++)
  1698. parts[i].AttachedAvatar = UUID.Zero;*/
  1699. m_rootPart.SetParentLocalId(0);
  1700. //m_rootPart.SetAttachmentPoint((byte)0);
  1701. IsAttachment = false;
  1702. AbsolutePosition = m_rootPart.AttachedPos;
  1703. //m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_scene.m_physicalPrim);
  1704. //AttachToBackup();
  1705. //m_rootPart.ScheduleFullUpdate();
  1706. }
  1707. /// <summary>
  1708. ///
  1709. /// </summary>
  1710. /// <param name="part"></param>
  1711. private void SetPartAsNonRoot(SceneObjectPart part)
  1712. {
  1713. part.ParentID = m_rootPart.LocalId;
  1714. part.ClearUndoState();
  1715. }
  1716. /// <summary>
  1717. /// Set a part to act as the root part for this scene object
  1718. /// </summary>
  1719. /// <param name="part"></param>
  1720. public void SetRootPart(SceneObjectPart part)
  1721. {
  1722. if (part == null)
  1723. throw new ArgumentNullException("Cannot give SceneObjectGroup a null root SceneObjectPart");
  1724. part.SetParent(this);
  1725. m_rootPart = part;
  1726. if (!IsAttachment)
  1727. part.ParentID = 0;
  1728. part.LinkNum = 0;
  1729. m_parts.Add(m_rootPart.UUID, m_rootPart);
  1730. }
  1731. /// <summary>
  1732. /// Add a new part to this scene object. The part must already be correctly configured.
  1733. /// </summary>
  1734. /// <param name="part"></param>
  1735. public void AddPart(SceneObjectPart part)
  1736. {
  1737. part.SetParent(this);
  1738. m_parts.Add(part.UUID, part);
  1739. part.LinkNum = m_parts.Count;
  1740. if (part.LinkNum == 2)
  1741. RootPart.LinkNum = 1;
  1742. InvalidatePartsLinkMaps();
  1743. }
  1744. /// <summary>
  1745. /// Make sure that every non root part has the proper parent root part local id
  1746. /// </summary>
  1747. private void UpdateParentIDs()
  1748. {
  1749. SceneObjectPart[] parts = m_parts.GetArray();
  1750. for (int i = 0; i < parts.Length; i++)
  1751. {
  1752. SceneObjectPart part = parts[i];
  1753. if (part.UUID != m_rootPart.UUID)
  1754. part.ParentID = m_rootPart.LocalId;
  1755. }
  1756. }
  1757. public void RegenerateFullIDs()
  1758. {
  1759. SceneObjectPart[] parts = m_parts.GetArray();
  1760. for (int i = 0; i < parts.Length; i++)
  1761. parts[i].UUID = UUID.Random();
  1762. }
  1763. // helper provided for parts.
  1764. public int GetSceneMaxUndo()
  1765. {
  1766. if (m_scene != null)
  1767. return m_scene.MaxUndoCount;
  1768. return 5;
  1769. }
  1770. // justincc: I don't believe this hack is needed any longer, especially since the physics
  1771. // parts of set AbsolutePosition were already commented out. By changing HasGroupChanged to false
  1772. // this method was preventing proper reload of scene objects.
  1773. // dahlia: I had to uncomment it, without it meshing was failing on some prims and objects
  1774. // at region startup
  1775. // teravus: After this was removed from the linking algorithm, Linked prims no longer collided
  1776. // properly when non-physical if they havn't been moved. This breaks ALL builds.
  1777. // see: http://opensimulator.org/mantis/view.php?id=3108
  1778. // Here's the deal, this is ABSOLUTELY CRITICAL so the physics scene gets the update about the
  1779. // position of linkset prims. IF YOU CHANGE THIS, YOU MUST TEST colliding with just linked and
  1780. // unmoved prims! As soon as you move a Prim/group, it will collide properly because Absolute
  1781. // Position has been set!
  1782. public void ResetChildPrimPhysicsPositions()
  1783. {
  1784. // Setting this SOG's absolute position also loops through and sets the positions
  1785. // of the SOP's in this SOG's linkset. This has the side affect of making sure
  1786. // the physics world matches the simulated world.
  1787. // AbsolutePosition = AbsolutePosition; // could someone in the know please explain how this works?
  1788. // teravus: AbsolutePosition is NOT a normal property!
  1789. // the code in the getter of AbsolutePosition is significantly different then the code in the setter!
  1790. // jhurliman: Then why is it a property instead of two methods?
  1791. // do only what is supposed to do
  1792. Vector3 groupPosition = m_rootPart.GroupPosition;
  1793. SceneObjectPart[] parts = m_parts.GetArray();
  1794. foreach (SceneObjectPart part in parts)
  1795. {
  1796. if (part != m_rootPart)
  1797. part.GroupPosition = groupPosition;
  1798. }
  1799. }
  1800. public UUID GetPartsFullID(uint localID)
  1801. {
  1802. SceneObjectPart part = GetPart(localID);
  1803. if (part != null)
  1804. {
  1805. return part.UUID;
  1806. }
  1807. return UUID.Zero;
  1808. }
  1809. public void ObjectGrabHandler(uint localId, Vector3 offsetPos, IClientAPI remoteClient)
  1810. {
  1811. if (m_rootPart.LocalId == localId)
  1812. {
  1813. if((RootPart.ScriptEvents & scriptEvents.anytouch) != 0)
  1814. lastTouchTime = Util.GetTimeStampMS();
  1815. OnGrabGroup(offsetPos, remoteClient);
  1816. }
  1817. else
  1818. {
  1819. SceneObjectPart part = GetPart(localId);
  1820. if (((part.ScriptEvents & scriptEvents.anytouch) != 0) || (RootPart.ScriptEvents & scriptEvents.anytouch) != 0)
  1821. lastTouchTime = Util.GetTimeStampMS();
  1822. OnGrabPart(part, offsetPos, remoteClient);
  1823. }
  1824. }
  1825. public virtual void OnGrabPart(SceneObjectPart part, Vector3 offsetPos, IClientAPI remoteClient)
  1826. {
  1827. // m_log.DebugFormat(
  1828. // "[SCENE OBJECT GROUP]: Processing OnGrabPart for {0} on {1} {2}, offsetPos {3}",
  1829. // remoteClient.Name, part.Name, part.LocalId, offsetPos);
  1830. // part.StoreUndoState();
  1831. part.OnGrab(offsetPos, remoteClient);
  1832. }
  1833. public virtual void OnGrabGroup(Vector3 offsetPos, IClientAPI remoteClient)
  1834. {
  1835. m_scene.EventManager.TriggerGroupGrab(UUID, offsetPos, remoteClient.AgentId);
  1836. }
  1837. /// <summary>
  1838. /// Delete this group from its scene.
  1839. /// </summary>
  1840. /// <remarks>
  1841. /// This only handles the in-world consequences of deletion (e.g. any avatars sitting on it are forcibly stood
  1842. /// up and all avatars receive notification of its removal. Removal of the scene object from database backup
  1843. /// must be handled by the caller.
  1844. /// </remarks>
  1845. /// <param name="silent">If true then deletion is not broadcast to clients</param>
  1846. public void DeleteGroupFromScene(bool silent)
  1847. {
  1848. // We need to keep track of this state in case this group is still queued for backup.
  1849. IsDeleted = true;
  1850. DetachFromBackup();
  1851. if(Scene == null) // should not happen unless restart/shutdown ?
  1852. return;
  1853. SceneObjectPart[] parts = m_parts.GetArray();
  1854. for (int i = 0; i < parts.Length; i++)
  1855. {
  1856. SceneObjectPart part = parts[i];
  1857. Scene.ForEachScenePresence(delegate(ScenePresence avatar)
  1858. {
  1859. if (!avatar.IsChildAgent && avatar.ParentID == part.LocalId && avatar.ParentUUID == UUID.Zero)
  1860. avatar.StandUp();
  1861. if (!silent)
  1862. {
  1863. part.ClearUpdateSchedule();
  1864. if (part == m_rootPart)
  1865. {
  1866. if (!IsAttachment
  1867. || AttachedAvatar == avatar.ControllingClient.AgentId
  1868. || !HasPrivateAttachmentPoint)
  1869. {
  1870. // Send a kill object immediately
  1871. avatar.ControllingClient.SendKillObject(new List<uint> { part.LocalId });
  1872. //direct enqueue another delayed kill
  1873. avatar.ControllingClient.SendEntityUpdate(part,PrimUpdateFlags.Kill);
  1874. }
  1875. }
  1876. }
  1877. });
  1878. }
  1879. }
  1880. public void AddScriptLPS(int count)
  1881. {
  1882. m_scene.SceneGraph.AddToScriptLPS(count);
  1883. }
  1884. public void AddActiveScriptCount(int count)
  1885. {
  1886. SceneGraph d = m_scene.SceneGraph;
  1887. d.AddActiveScripts(count);
  1888. }
  1889. private const scriptEvents PhysicsNeeedSubsEvents = (
  1890. scriptEvents.collision | scriptEvents.collision_start | scriptEvents.collision_end |
  1891. scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end);
  1892. private scriptEvents lastRootPartPhysEvents = 0;
  1893. public void aggregateScriptEvents()
  1894. {
  1895. PrimFlags objectflagupdate = (PrimFlags)RootPart.GetEffectiveObjectFlags();
  1896. scriptEvents aggregatedScriptEvents = 0;
  1897. SceneObjectPart[] parts = m_parts.GetArray();
  1898. for (int i = 0; i < parts.Length; i++)
  1899. {
  1900. SceneObjectPart part = parts[i];
  1901. if (part != RootPart)
  1902. part.Flags = objectflagupdate;
  1903. aggregatedScriptEvents |= part.AggregatedScriptEvents;
  1904. }
  1905. m_scriptListens_atTarget = ((aggregatedScriptEvents & scriptEvents.at_target) != 0);
  1906. m_scriptListens_notAtTarget = ((aggregatedScriptEvents & scriptEvents.not_at_target) != 0);
  1907. if (!m_scriptListens_atTarget && !m_scriptListens_notAtTarget)
  1908. {
  1909. lock (m_targets)
  1910. {
  1911. if (m_targets.Count > 0)
  1912. {
  1913. m_targets.Clear();
  1914. m_scene.RemoveGroupTarget(this);
  1915. }
  1916. }
  1917. }
  1918. m_scriptListens_atRotTarget = ((aggregatedScriptEvents & scriptEvents.at_rot_target) != 0);
  1919. m_scriptListens_notAtRotTarget = ((aggregatedScriptEvents & scriptEvents.not_at_rot_target) != 0);
  1920. if (!m_scriptListens_atRotTarget && !m_scriptListens_notAtRotTarget)
  1921. {
  1922. lock (m_rotTargets)
  1923. {
  1924. if (m_rotTargets.Count > 0)
  1925. {
  1926. m_rotTargets.Clear();
  1927. m_scene.RemoveGroupTarget(this);
  1928. }
  1929. }
  1930. }
  1931. scriptEvents rootPartPhysEvents = RootPart.AggregatedScriptEvents;
  1932. rootPartPhysEvents &= PhysicsNeeedSubsEvents;
  1933. if (rootPartPhysEvents != lastRootPartPhysEvents)
  1934. {
  1935. lastRootPartPhysEvents = rootPartPhysEvents;
  1936. for (int i = 0; i < parts.Length; i++)
  1937. parts[i].UpdatePhysicsSubscribedEvents();
  1938. }
  1939. ScheduleGroupForFullUpdate();
  1940. }
  1941. public void SetText(string text, Vector3 color, double alpha)
  1942. {
  1943. Color = Color.FromArgb(0xff - (int) (alpha * 0xff),
  1944. (int) (color.X * 0xff),
  1945. (int) (color.Y * 0xff),
  1946. (int) (color.Z * 0xff));
  1947. Text = text;
  1948. HasGroupChanged = true;
  1949. m_rootPart.ScheduleFullUpdate();
  1950. }
  1951. /// <summary>
  1952. /// Apply physics to this group
  1953. /// </summary>
  1954. public void ApplyPhysics()
  1955. {
  1956. SceneObjectPart[] parts = m_parts.GetArray();
  1957. if (parts.Length > 1)
  1958. {
  1959. ResetChildPrimPhysicsPositions();
  1960. // Apply physics to the root prim
  1961. m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, true);
  1962. for (int i = 0; i < parts.Length; i++)
  1963. {
  1964. SceneObjectPart part = parts[i];
  1965. if (part.LocalId != m_rootPart.LocalId)
  1966. part.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), part.VolumeDetectActive, true);
  1967. }
  1968. // Hack to get the physics scene geometries in the right spot
  1969. // ResetChildPrimPhysicsPositions();
  1970. if (m_rootPart.PhysActor != null)
  1971. m_rootPart.PhysActor.Building = false;
  1972. }
  1973. else
  1974. {
  1975. // Apply physics to the root prim
  1976. m_rootPart.ApplyPhysics(m_rootPart.GetEffectiveObjectFlags(), m_rootPart.VolumeDetectActive, false);
  1977. }
  1978. }
  1979. public void SetOwnerId(UUID userId)
  1980. {
  1981. ForEachPart(delegate(SceneObjectPart part)
  1982. {
  1983. if (part.OwnerID != userId)
  1984. {
  1985. if(part.GroupID != part.OwnerID)
  1986. part.LastOwnerID = part.OwnerID;
  1987. part.OwnerID = userId;
  1988. }
  1989. });
  1990. }
  1991. public void ForEachPart(Action<SceneObjectPart> whatToDo)
  1992. {
  1993. SceneObjectPart[] parts = m_parts.GetArray();
  1994. for (int i = 0; i < parts.Length; i++)
  1995. whatToDo(parts[i]);
  1996. }
  1997. #region Events
  1998. /// <summary>
  1999. /// Processes backup.
  2000. /// </summary>
  2001. /// <param name="datastore"></param>
  2002. public virtual void ProcessBackup(ISimulationDataService datastore, bool forcedBackup)
  2003. {
  2004. if (!Backup)
  2005. {
  2006. // m_log.DebugFormat(
  2007. // "[WATER WARS]: Ignoring backup of {0} {1} since object is not marked to be backed up", Name, UUID);
  2008. return;
  2009. }
  2010. if (IsDeleted || inTransit || UUID == UUID.Zero)
  2011. {
  2012. // m_log.DebugFormat(
  2013. // "[WATER WARS]: Ignoring backup of {0} {1} since object is marked as already deleted", Name, UUID);
  2014. return;
  2015. }
  2016. if ((RootPart.Flags & PrimFlags.TemporaryOnRez) != 0)
  2017. return;
  2018. // Since this is the top of the section of call stack for backing up a particular scene object, don't let
  2019. // any exception propogate upwards.
  2020. try
  2021. {
  2022. // if shutting down then there will be nothing to handle the return so leave till next restart
  2023. if (!m_scene.ShuttingDown &&
  2024. m_scene.LoginsEnabled && // We're starting up or doing maintenance, don't mess with things
  2025. !m_scene.LoadingPrims) // Land may not be valid yet
  2026. {
  2027. ILandObject parcel = m_scene.LandChannel.GetLandObject(
  2028. m_rootPart.GroupPosition.X, m_rootPart.GroupPosition.Y);
  2029. if (parcel != null && parcel.LandData != null &&
  2030. parcel.LandData.OtherCleanTime != 0)
  2031. {
  2032. if (parcel.LandData.OwnerID != OwnerID &&
  2033. (parcel.LandData.GroupID != GroupID ||
  2034. parcel.LandData.GroupID == UUID.Zero))
  2035. {
  2036. if ((DateTime.UtcNow - RootPart.Rezzed).TotalMinutes >
  2037. parcel.LandData.OtherCleanTime)
  2038. {
  2039. // don't autoreturn if we have a sitting avatar
  2040. // mantis 7828 (but none the provided patchs)
  2041. if(GetSittingAvatarsCount() > 0)
  2042. {
  2043. // do not respect npcs
  2044. List<ScenePresence> sitters = GetSittingAvatars();
  2045. foreach(ScenePresence sp in sitters)
  2046. {
  2047. if(!sp.IsDeleted && !sp.IsNPC && sp.IsSatOnObject)
  2048. return;
  2049. }
  2050. }
  2051. DetachFromBackup();
  2052. m_log.DebugFormat(
  2053. "[SCENE OBJECT GROUP]: Returning object {0} due to parcel autoreturn",
  2054. RootPart.UUID);
  2055. m_scene.AddReturn(OwnerID == GroupID ? LastOwnerID : OwnerID, Name, AbsolutePosition, "parcel autoreturn");
  2056. m_scene.DeRezObjects(null, new List<uint>() { RootPart.LocalId }, UUID.Zero,
  2057. DeRezAction.Return, UUID.Zero, false);
  2058. return;
  2059. }
  2060. }
  2061. }
  2062. }
  2063. if (m_scene.UseBackup && HasGroupChanged)
  2064. {
  2065. // don't backup while it's selected or you're asking for changes mid stream.
  2066. if (isTimeToPersist() || forcedBackup)
  2067. {
  2068. if (RootPart.Shape.PCode == 9 && RootPart.Shape.State != 0)
  2069. {
  2070. RootPart.Shape.LastAttachPoint = RootPart.Shape.State;
  2071. RootPart.Shape.State = 0;
  2072. ScheduleGroupForFullUpdate();
  2073. }
  2074. SceneObjectGroup backup_group = Copy(false);
  2075. backup_group.RootPart.Velocity = RootPart.Velocity;
  2076. backup_group.RootPart.Acceleration = RootPart.Acceleration;
  2077. backup_group.RootPart.AngularVelocity = RootPart.AngularVelocity;
  2078. HasGroupChanged = false;
  2079. GroupContainsForeignPrims = false;
  2080. m_scene.EventManager.TriggerOnSceneObjectPreSave(backup_group, this);
  2081. datastore.StoreObject(backup_group, m_scene.RegionInfo.RegionID);
  2082. backup_group.ForEachPart(delegate(SceneObjectPart part)
  2083. {
  2084. part.Inventory.ProcessInventoryBackup(datastore);
  2085. if(part.KeyframeMotion != null)
  2086. {
  2087. part.KeyframeMotion.Delete();
  2088. part.KeyframeMotion = null;
  2089. }
  2090. });
  2091. backup_group.Dispose();
  2092. backup_group = null;
  2093. }
  2094. }
  2095. }
  2096. catch (Exception e)
  2097. {
  2098. m_log.ErrorFormat(
  2099. "[SCENE]: Storing of {0}, {1} in {2} failed with exception {3}{4}",
  2100. Name, UUID, m_scene.RegionInfo.RegionName, e.Message, e.StackTrace);
  2101. }
  2102. }
  2103. #endregion
  2104. /// <summary>
  2105. /// Send the parts of this SOG to a single client
  2106. /// </summary>
  2107. /// <remarks>
  2108. /// Used when the client initially connects and when client sends RequestPrim packet
  2109. /// </remarks>
  2110. /// <param name="remoteClient"></param>
  2111. public void SendFullAnimUpdateToClient(IClientAPI remoteClient)
  2112. {
  2113. PrimUpdateFlags update = PrimUpdateFlags.FullUpdate;
  2114. if (RootPart.Shape.MeshFlagEntry)
  2115. update = PrimUpdateFlags.FullUpdatewithAnim;
  2116. RootPart.SendUpdate(remoteClient, update);
  2117. SceneObjectPart[] parts = m_parts.GetArray();
  2118. for (int i = 0; i < parts.Length; i++)
  2119. {
  2120. SceneObjectPart part = parts[i];
  2121. if (part != RootPart)
  2122. part.SendUpdate(remoteClient, update);
  2123. }
  2124. }
  2125. public void SendUpdateProbes(IClientAPI remoteClient)
  2126. {
  2127. PrimUpdateFlags update = PrimUpdateFlags.UpdateProbe;
  2128. RootPart.SendUpdate(remoteClient, update);
  2129. SceneObjectPart[] parts = m_parts.GetArray();
  2130. for (int i = 0; i < parts.Length; i++)
  2131. {
  2132. SceneObjectPart part = parts[i];
  2133. if (part != RootPart)
  2134. part.SendUpdate(remoteClient, update);
  2135. }
  2136. }
  2137. #region Copying
  2138. /// <summary>
  2139. /// Duplicates this object, including operations such as physics set up and attaching to the backup event.
  2140. /// </summary>
  2141. /// <param name="userExposed">True if the duplicate will immediately be in the scene, false otherwise</param>
  2142. /// <returns></returns>
  2143. public SceneObjectGroup Copy(bool userExposed)
  2144. {
  2145. m_dupeInProgress = true;
  2146. SceneObjectGroup dupe = (SceneObjectGroup)MemberwiseClone();
  2147. dupe.m_parts = new MapAndArray<OpenMetaverse.UUID, SceneObjectPart>();
  2148. // a copy isnt backedup
  2149. dupe.Backup = false;
  2150. dupe.InvalidBoundsRadius();
  2151. // a copy is not in transit hopefully
  2152. dupe.inTransit = false;
  2153. // new group as no sitting avatars
  2154. dupe.m_sittingAvatars = new List<ScenePresence>();
  2155. dupe.CopyRootPart(m_rootPart, OwnerID, GroupID, userExposed);
  2156. dupe.m_rootPart.LinkNum = m_rootPart.LinkNum;
  2157. if (userExposed)
  2158. dupe.m_rootPart.TrimPermissions();
  2159. List<SceneObjectPart> partList = new List<SceneObjectPart>(m_parts.GetArray());
  2160. partList.Sort(delegate(SceneObjectPart p1, SceneObjectPart p2)
  2161. {
  2162. return p1.LinkNum.CompareTo(p2.LinkNum);
  2163. }
  2164. );
  2165. foreach (SceneObjectPart part in partList)
  2166. {
  2167. SceneObjectPart newPart;
  2168. if (part.UUID != m_rootPart.UUID)
  2169. {
  2170. newPart = dupe.CopyPart(part, OwnerID, GroupID, userExposed);
  2171. newPart.LinkNum = part.LinkNum;
  2172. // if (userExposed)
  2173. newPart.ParentID = dupe.m_rootPart.LocalId;
  2174. }
  2175. else
  2176. {
  2177. newPart = dupe.m_rootPart;
  2178. }
  2179. if (userExposed)
  2180. newPart.ApplyPhysics((uint)newPart.Flags,newPart.VolumeDetectActive,true);
  2181. // copy keyframemotion
  2182. if (part.KeyframeMotion != null)
  2183. newPart.KeyframeMotion = part.KeyframeMotion.Copy(dupe);
  2184. }
  2185. if (userExposed)
  2186. {
  2187. if (dupe.m_rootPart.PhysActor != null)
  2188. dupe.m_rootPart.PhysActor.Building = false; // tell physics to finish building
  2189. dupe.InvalidateDeepEffectivePerms();
  2190. dupe.HasGroupChanged = true;
  2191. dupe.AttachToBackup();
  2192. dupe.ScheduleGroupForFullAnimUpdate();
  2193. }
  2194. dupe.InvalidatePartsLinkMaps();
  2195. m_dupeInProgress = false;
  2196. return dupe;
  2197. }
  2198. /// <summary>
  2199. /// Copy the given part as the root part of this scene object.
  2200. /// </summary>
  2201. /// <param name="part"></param>
  2202. /// <param name="cAgentID"></param>
  2203. /// <param name="cGroupID"></param>
  2204. public void CopyRootPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
  2205. {
  2206. SceneObjectPart newpart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, 0, userExposed);
  2207. // SceneObjectPart newpart = part.Copy(part.LocalId, OwnerID, GroupID, 0, userExposed);
  2208. // newpart.LocalId = m_scene.AllocateLocalId();
  2209. SetRootPart(newpart);
  2210. if (userExposed)
  2211. RootPart.Velocity = Vector3.Zero; // In case source is moving
  2212. }
  2213. public void ScriptSetPhysicsStatus(bool usePhysics)
  2214. {
  2215. if (usePhysics)
  2216. {
  2217. if (RootPart.KeyframeMotion != null)
  2218. RootPart.KeyframeMotion.Stop();
  2219. RootPart.KeyframeMotion = null;
  2220. }
  2221. UpdateFlags(usePhysics, IsTemporary, IsPhantom, IsVolumeDetect);
  2222. }
  2223. public void ScriptSetTemporaryStatus(bool makeTemporary)
  2224. {
  2225. UpdateFlags(UsesPhysics, makeTemporary, IsPhantom, IsVolumeDetect);
  2226. }
  2227. public void ScriptSetPhantomStatus(bool makePhantom)
  2228. {
  2229. UpdateFlags(UsesPhysics, IsTemporary, makePhantom, IsVolumeDetect);
  2230. }
  2231. public void ScriptSetVolumeDetect(bool makeVolumeDetect)
  2232. {
  2233. UpdateFlags(UsesPhysics, IsTemporary, IsPhantom, makeVolumeDetect);
  2234. }
  2235. public void applyImpulse(Vector3 impulse)
  2236. {
  2237. if (IsAttachment)
  2238. {
  2239. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2240. if (avatar != null)
  2241. {
  2242. avatar.PushForce(impulse);
  2243. }
  2244. }
  2245. else
  2246. {
  2247. PhysicsActor pa = RootPart.PhysActor;
  2248. if (pa != null)
  2249. {
  2250. // false to be applied as a impulse
  2251. pa.AddForce(impulse, false);
  2252. m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
  2253. }
  2254. }
  2255. }
  2256. public void ApplyAngularImpulse(Vector3 impulse)
  2257. {
  2258. PhysicsActor pa = RootPart.PhysActor;
  2259. if (pa != null)
  2260. {
  2261. if (!IsAttachment)
  2262. {
  2263. // false to be applied as a impulse
  2264. pa.AddAngularForce(impulse, false);
  2265. m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
  2266. }
  2267. }
  2268. }
  2269. public Vector3 GetTorque()
  2270. {
  2271. return RootPart.Torque;
  2272. }
  2273. // This is used by both Double-Click Auto-Pilot and llMoveToTarget() in an attached object
  2274. public void MoveToTarget(Vector3 target, float tau)
  2275. {
  2276. if(tau > 0)
  2277. {
  2278. if (IsAttachment)
  2279. {
  2280. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2281. if (avatar != null && !avatar.IsSatOnObject)
  2282. avatar.MoveToTarget(target, false, false, false, tau);
  2283. }
  2284. else
  2285. {
  2286. PhysicsActor pa = RootPart.PhysActor;
  2287. if (pa != null)
  2288. {
  2289. pa.PIDTarget = target;
  2290. pa.PIDTau = tau;
  2291. pa.PIDActive = true;
  2292. }
  2293. }
  2294. }
  2295. else
  2296. StopMoveToTarget();
  2297. }
  2298. public void StopMoveToTarget()
  2299. {
  2300. if (IsAttachment)
  2301. {
  2302. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2303. if (avatar != null)
  2304. {
  2305. avatar.ResetMoveToTarget();
  2306. }
  2307. }
  2308. else
  2309. {
  2310. PhysicsActor pa = RootPart.PhysActor;
  2311. if (pa != null)
  2312. pa.PIDActive = false;
  2313. RootPart.ScheduleTerseUpdate(); // send a stop information
  2314. }
  2315. }
  2316. public void RotLookAt(Quaternion target, float strength, float damping)
  2317. {
  2318. if(IsDeleted)
  2319. return;
  2320. // non physical is handle in LSL api
  2321. if(!UsesPhysics || IsAttachment)
  2322. return;
  2323. SceneObjectPart rootpart = m_rootPart;
  2324. if (rootpart != null)
  2325. {
  2326. /* physics still doesnt suport this
  2327. if (rootpart.PhysActor != null)
  2328. {
  2329. rootpart.PhysActor.APIDTarget = new Quaternion(target.X, target.Y, target.Z, target.W);
  2330. rootpart.PhysActor.APIDStrength = strength;
  2331. rootpart.PhysActor.APIDDamping = damping;
  2332. rootpart.PhysActor.APIDActive = true;
  2333. }
  2334. */
  2335. // so do it in rootpart
  2336. rootpart.RotLookAt(target, strength, damping);
  2337. }
  2338. }
  2339. public void StartLookAt(Quaternion target, float strength, float damping)
  2340. {
  2341. if(IsDeleted)
  2342. return;
  2343. // non physical is done by LSL APi
  2344. if(!UsesPhysics || IsAttachment)
  2345. return;
  2346. if (m_rootPart != null)
  2347. m_rootPart.RotLookAt(target, strength, damping);
  2348. }
  2349. public void StopLookAt()
  2350. {
  2351. SceneObjectPart rootpart = m_rootPart;
  2352. if (rootpart != null)
  2353. {
  2354. if (rootpart.PhysActor != null)
  2355. {
  2356. rootpart.PhysActor.APIDActive = false;
  2357. }
  2358. rootpart.StopLookAt();
  2359. }
  2360. }
  2361. /// <summary>
  2362. /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
  2363. /// </summary>
  2364. /// <param name="height">Height to hover. Height of zero disables hover.</param>
  2365. /// <param name="hoverType">Determines what the height is relative to </param>
  2366. /// <param name="tau">Number of seconds over which to reach target</param>
  2367. public void SetHoverHeight(float height, PIDHoverType hoverType, float tau)
  2368. {
  2369. PhysicsActor pa = null;
  2370. if(IsAttachment)
  2371. {
  2372. ScenePresence avatar = m_scene.GetScenePresence(AttachedAvatar);
  2373. if (avatar != null)
  2374. pa = avatar.PhysicsActor;
  2375. }
  2376. else
  2377. pa = RootPart.PhysActor;
  2378. if (pa != null)
  2379. {
  2380. if (height != 0f)
  2381. {
  2382. pa.PIDHoverHeight = height;
  2383. pa.PIDHoverType = hoverType;
  2384. pa.PIDHoverTau = tau;
  2385. pa.PIDHoverActive = true;
  2386. }
  2387. else
  2388. {
  2389. pa.PIDHoverActive = false;
  2390. }
  2391. }
  2392. }
  2393. /// <summary>
  2394. /// Set the owner of all linkset.
  2395. /// </summary>
  2396. /// <param name="cAgentID"></param>
  2397. /// <param name="cGroupID"></param>
  2398. public void SetOwner(UUID cAgentID, UUID cGroupID)
  2399. {
  2400. SceneObjectPart rpart = RootPart;
  2401. UUID oldowner = rpart.OwnerID;
  2402. ForEachPart(delegate(SceneObjectPart part)
  2403. {
  2404. if(part.GroupID != part.OwnerID)
  2405. part.LastOwnerID = part.OwnerID;
  2406. part.OwnerID = cAgentID;
  2407. part.GroupID = cGroupID;
  2408. });
  2409. if (oldowner != cAgentID)
  2410. {
  2411. // Apply Next Owner Permissions if we're not bypassing permissions
  2412. if (!m_scene.Permissions.BypassPermissions())
  2413. {
  2414. ApplyNextOwnerPermissions();
  2415. InvalidateEffectivePerms();
  2416. }
  2417. }
  2418. rpart.ScheduleFullUpdate();
  2419. }
  2420. /// <summary>
  2421. /// Make a copy of the given part.
  2422. /// </summary>
  2423. /// <param name="part"></param>
  2424. /// <param name="cAgentID"></param>
  2425. /// <param name="cGroupID"></param>
  2426. public SceneObjectPart CopyPart(SceneObjectPart part, UUID cAgentID, UUID cGroupID, bool userExposed)
  2427. {
  2428. SceneObjectPart newPart = part.Copy(m_scene.AllocateLocalId(), OwnerID, GroupID, m_parts.Count, userExposed);
  2429. // SceneObjectPart newPart = part.Copy(part.LocalId, OwnerID, GroupID, m_parts.Count, userExposed);
  2430. // newPart.LocalId = m_scene.AllocateLocalId();
  2431. AddPart(newPart);
  2432. SetPartAsNonRoot(newPart);
  2433. return newPart;
  2434. }
  2435. /// <summary>
  2436. /// Reset the UUIDs for all the prims that make up this group.
  2437. /// </summary>
  2438. /// <remarks>
  2439. /// This is called by methods which want to add a new group to an existing scene, in order
  2440. /// to ensure that there are no clashes with groups already present.
  2441. /// </remarks>
  2442. public void ResetIDs()
  2443. {
  2444. lock (m_parts.SyncRoot)
  2445. {
  2446. List<SceneObjectPart> partsList = new List<SceneObjectPart>(m_parts.GetArray());
  2447. m_parts.Clear();
  2448. foreach (SceneObjectPart part in partsList)
  2449. {
  2450. part.ResetIDs(part.LinkNum); // Don't change link nums
  2451. m_parts.Add(part.UUID, part);
  2452. }
  2453. }
  2454. }
  2455. /// <summary>
  2456. ///
  2457. /// </summary>
  2458. /// <param name="part"></param>
  2459. public void ServiceObjectPropertiesFamilyRequest(IClientAPI remoteClient, UUID AgentID, uint RequestFlags)
  2460. {
  2461. remoteClient.SendObjectPropertiesFamilyData(RootPart, RequestFlags);
  2462. // remoteClient.SendObjectPropertiesFamilyData(RequestFlags, RootPart.UUID, RootPart.OwnerID, RootPart.GroupID, RootPart.BaseMask,
  2463. // RootPart.OwnerMask, RootPart.GroupMask, RootPart.EveryoneMask, RootPart.NextOwnerMask,
  2464. // RootPart.OwnershipCost, RootPart.ObjectSaleType, RootPart.SalePrice, RootPart.Category,
  2465. // RootPart.CreatorID, RootPart.Name, RootPart.Description);
  2466. }
  2467. public void SetPartOwner(SceneObjectPart part, UUID cAgentID, UUID cGroupID)
  2468. {
  2469. part.OwnerID = cAgentID;
  2470. part.GroupID = cGroupID;
  2471. }
  2472. #endregion
  2473. public override void Update()
  2474. {
  2475. // Check that the group was not deleted before the scheduled update
  2476. // FIXME: This is merely a temporary measure to reduce the incidence of failure when
  2477. // an object has been deleted from a scene before update was processed.
  2478. // A more fundamental overhaul of the update mechanism is required to eliminate all
  2479. // the race conditions.
  2480. if (IsDeleted || inTransit)
  2481. return;
  2482. if (IsAttachment)
  2483. {
  2484. ScenePresence sp = m_scene.GetScenePresence(AttachedAvatar);
  2485. if (sp != null)
  2486. sp.SendAttachmentScheduleUpdate(this);
  2487. return;
  2488. }
  2489. // while physics doesn't suports LookAt, we do it in RootPart
  2490. if (!IsSelected)
  2491. RootPart.UpdateLookAt();
  2492. double now = Util.GetTimeStampMS();
  2493. RootPart.SendScheduledUpdates(now);
  2494. SceneObjectPart[] parts = m_parts.GetArray();
  2495. for (int i = 0; i < parts.Length; i++)
  2496. {
  2497. SceneObjectPart part = parts[i];
  2498. if(part != RootPart)
  2499. part.SendScheduledUpdates(now);
  2500. }
  2501. }
  2502. /// <summary>
  2503. /// Schedule a full update for this scene object to all interested viewers.
  2504. /// </summary>
  2505. /// <remarks>
  2506. /// Ultimately, this should be managed such that region modules can invoke it at the end of a set of operations
  2507. /// so that either all changes are sent at once. However, currently, a large amount of internal
  2508. /// code will set this anyway when some object properties are changed.
  2509. /// </remarks>
  2510. public void ScheduleGroupForFullUpdate()
  2511. {
  2512. // if (IsAttachment)
  2513. // m_log.DebugFormat("[SOG]: Scheduling full update for {0} {1}", Name, LocalId);
  2514. if (Scene.GetNumberOfClients() == 0)
  2515. return;
  2516. RootPart.ScheduleFullUpdate();
  2517. SceneObjectPart[] parts = m_parts.GetArray();
  2518. for (int i = 0; i < parts.Length; i++)
  2519. {
  2520. SceneObjectPart part = parts[i];
  2521. if (part != RootPart)
  2522. part.ScheduleFullUpdate();
  2523. }
  2524. }
  2525. public void ScheduleGroupForFullAnimUpdate()
  2526. {
  2527. // if (IsAttachment)
  2528. // m_log.DebugFormat("[SOG]: Scheduling full update for {0} {1}", Name, LocalId);
  2529. if (Scene.GetNumberOfClients() == 0)
  2530. return;
  2531. SceneObjectPart[] parts = m_parts.GetArray();
  2532. if (!RootPart.Shape.MeshFlagEntry)
  2533. {
  2534. RootPart.ScheduleFullUpdate();
  2535. for (int i = 0; i < parts.Length; i++)
  2536. {
  2537. SceneObjectPart part = parts[i];
  2538. if (part != RootPart)
  2539. part.ScheduleFullUpdate();
  2540. }
  2541. return;
  2542. }
  2543. RootPart.ScheduleFullAnimUpdate();
  2544. for (int i = 0; i < parts.Length; i++)
  2545. {
  2546. SceneObjectPart part = parts[i];
  2547. if (part != RootPart)
  2548. part.ScheduleFullAnimUpdate();
  2549. }
  2550. }
  2551. /// <summary>
  2552. /// Schedule a terse update for this scene object to all interested viewers.
  2553. /// </summary>
  2554. /// <remarks>
  2555. /// Ultimately, this should be managed such that region modules can invoke it at the end of a set of operations
  2556. /// so that either all changes are sent at once. However, currently, a large amount of internal
  2557. /// code will set this anyway when some object properties are changed.
  2558. /// </remarks>
  2559. public void ScheduleGroupForTerseUpdate()
  2560. {
  2561. // m_log.DebugFormat("[SOG]: Scheduling terse update for {0} {1}", Name, UUID);
  2562. SceneObjectPart[] parts = m_parts.GetArray();
  2563. for (int i = 0; i < parts.Length; i++)
  2564. parts[i].ScheduleTerseUpdate();
  2565. }
  2566. /// <summary>
  2567. /// Immediately send an update for this scene object's root prim only.
  2568. /// This is for updates regarding the object as a whole, and none of its parts in particular.
  2569. /// Note: this may not be used by opensim (it probably should) but it's used by
  2570. /// external modules.
  2571. /// </summary>
  2572. public void SendGroupRootTerseUpdate()
  2573. {
  2574. if (IsDeleted || inTransit)
  2575. return;
  2576. RootPart.SendTerseUpdateToAllClients();
  2577. }
  2578. public void QueueForUpdateCheck()
  2579. {
  2580. if (m_scene == null) // Need to check here as it's null during object creation
  2581. return;
  2582. m_scene.SceneGraph.AddToUpdateList(this);
  2583. }
  2584. /// <summary>
  2585. /// Immediately send a terse update for this scene object.
  2586. /// </summary>
  2587. public void SendGroupTerseUpdate()
  2588. {
  2589. if (IsDeleted || inTransit)
  2590. return;
  2591. if (IsAttachment)
  2592. {
  2593. ScenePresence sp = m_scene.GetScenePresence(AttachedAvatar);
  2594. if (sp != null)
  2595. {
  2596. sp.SendAttachmentUpdate(this, PrimUpdateFlags.TerseUpdate);
  2597. return;
  2598. }
  2599. }
  2600. SceneObjectPart[] parts = m_parts.GetArray();
  2601. for (int i = 0; i < parts.Length; i++)
  2602. parts[i].SendTerseUpdateToAllClientsInternal();
  2603. }
  2604. /// <summary>
  2605. /// Send metadata about the root prim (name, description, sale price, permissions, etc.) to a client.
  2606. /// </summary>
  2607. /// <param name="client"></param>
  2608. public void SendPropertiesToClient(IClientAPI client)
  2609. {
  2610. m_rootPart.SendPropertiesToClient(client);
  2611. }
  2612. #region SceneGroupPart Methods
  2613. /// <summary>
  2614. /// Get the child part by LinkNum
  2615. /// </summary>
  2616. /// <param name="linknum"></param>
  2617. /// <returns>null if no child part with that linknum or child part</returns>
  2618. public SceneObjectPart GetLinkNumPart(int linknum)
  2619. {
  2620. SceneObjectPart[] parts = m_parts.GetArray();
  2621. for (int i = 0; i < parts.Length; i++)
  2622. {
  2623. if (parts[i].LinkNum == linknum)
  2624. return parts[i];
  2625. }
  2626. return null;
  2627. }
  2628. /// <summary>
  2629. /// Get a part with a given UUID
  2630. /// </summary>
  2631. /// <param name="primID"></param>
  2632. /// <returns>null if a part with the primID was not found</returns>
  2633. public SceneObjectPart GetPart(UUID primID)
  2634. {
  2635. SceneObjectPart childPart;
  2636. m_parts.TryGetValue(primID, out childPart);
  2637. return childPart;
  2638. }
  2639. /// <summary>
  2640. /// Get a part with a given local ID
  2641. /// </summary>
  2642. /// <param name="localID"></param>
  2643. /// <returns>null if a part with the local ID was not found</returns>
  2644. public SceneObjectPart GetPart(uint localID)
  2645. {
  2646. SceneObjectPart sop = m_scene.GetSceneObjectPart(localID);
  2647. if(sop.ParentGroup.Equals(this))
  2648. return sop;
  2649. return null;
  2650. }
  2651. #endregion
  2652. #region Packet Handlers
  2653. /// <summary>
  2654. /// Link the prims in a given group to this group
  2655. /// </summary>
  2656. /// <remarks>
  2657. /// Do not call this method directly - use Scene.LinkObjects() instead to avoid races between threads.
  2658. /// FIXME: There are places where scripts call these methods directly without locking. This is a potential race condition.
  2659. /// </remarks>
  2660. /// <param name="objectGroup">The group of prims which should be linked to this group</param>
  2661. public void LinkToGroup(SceneObjectGroup objectGroup)
  2662. {
  2663. LinkToGroup(objectGroup, false);
  2664. }
  2665. // Link an existing group to this group.
  2666. // The group being linked need not be a linkset -- it can have just one prim.
  2667. public void LinkToGroup(SceneObjectGroup objectGroup, bool insert)
  2668. {
  2669. // m_log.DebugFormat(
  2670. // "[SCENE OBJECT GROUP]: Linking group with root part {0}, {1} to group with root part {2}, {3}",
  2671. // objectGroup.RootPart.Name, objectGroup.RootPart.UUID, RootPart.Name, RootPart.UUID);
  2672. // Linking to ourselves is not a valid operation.
  2673. if (objectGroup == this)
  2674. return;
  2675. // If the configured linkset capacity is greater than zero,
  2676. // and the new linkset would have a prim count higher than this
  2677. // value, do not link it.
  2678. if (m_scene.m_linksetCapacity > 0 &&
  2679. (PrimCount + objectGroup.PrimCount) >
  2680. m_scene.m_linksetCapacity)
  2681. {
  2682. m_log.DebugFormat(
  2683. "[SCENE OBJECT GROUP]: Cannot link group with root" +
  2684. " part {0}, {1} ({2} prims) to group with root part" +
  2685. " {3}, {4} ({5} prims) because the new linkset" +
  2686. " would exceed the configured maximum of {6}",
  2687. objectGroup.RootPart.Name, objectGroup.RootPart.UUID,
  2688. objectGroup.PrimCount, RootPart.Name, RootPart.UUID,
  2689. PrimCount, m_scene.m_linksetCapacity);
  2690. return;
  2691. }
  2692. // physical prims count limit
  2693. // not very eficient :(
  2694. if (UsesPhysics && m_scene.m_linksetPhysCapacity > 0 && (PrimCount + objectGroup.PrimCount) >
  2695. m_scene.m_linksetPhysCapacity)
  2696. {
  2697. int cntr = 0;
  2698. foreach (SceneObjectPart part in Parts)
  2699. {
  2700. if (part.PhysicsShapeType != (byte)PhysicsShapeType.None)
  2701. cntr++;
  2702. }
  2703. foreach (SceneObjectPart part in objectGroup.Parts)
  2704. {
  2705. if (part.PhysicsShapeType != (byte)PhysicsShapeType.None)
  2706. cntr++;
  2707. }
  2708. if (cntr > m_scene.m_linksetPhysCapacity)
  2709. {
  2710. // cancel physics
  2711. RootPart.Flags &= ~PrimFlags.Physics;
  2712. ApplyPhysics();
  2713. }
  2714. }
  2715. // 'linkPart' == the root of the group being linked into this group
  2716. SceneObjectPart linkPart = objectGroup.m_rootPart;
  2717. if (m_rootPart.PhysActor != null)
  2718. m_rootPart.PhysActor.Building = true;
  2719. if (linkPart.PhysActor != null)
  2720. linkPart.PhysActor.Building = true;
  2721. // physics flags from group to be applied to linked parts
  2722. bool grpusephys = UsesPhysics;
  2723. bool grptemporary = IsTemporary;
  2724. // Remember where the group being linked thought it was
  2725. Vector3 oldGroupPosition = linkPart.GroupPosition;
  2726. Quaternion oldRootRotation = linkPart.RotationOffset;
  2727. // A linked SOP remembers its location and rotation relative to the root of a group.
  2728. // Convert the root of the group being linked to be relative to the
  2729. // root of the group being linked to.
  2730. // Note: Some of the assignments have complex side effects.
  2731. // First move the new group's root SOP's position to be relative to ours
  2732. // (radams1: Not sure if the multiple setting of OffsetPosition is required. If not,
  2733. // this code can be reordered to have a more logical flow.)
  2734. linkPart.setOffsetPosition(linkPart.GroupPosition - AbsolutePosition);
  2735. // Assign the new parent to the root of the old group
  2736. linkPart.ParentID = m_rootPart.LocalId;
  2737. // Now that it's a child, it's group position is our root position
  2738. linkPart.setGroupPosition(AbsolutePosition);
  2739. // Rotate the linking root SOP's position to be relative to the new root prim
  2740. Quaternion parentRot = m_rootPart.RotationOffset;
  2741. // Make the linking root SOP's rotation relative to the new root prim
  2742. Quaternion oldRot = linkPart.RotationOffset;
  2743. Quaternion newRot = Quaternion.Conjugate(parentRot) * oldRot;
  2744. linkPart.setRotationOffset(newRot);
  2745. Vector3 axPos = linkPart.OffsetPosition;
  2746. axPos *= Quaternion.Conjugate(parentRot);
  2747. linkPart.OffsetPosition = axPos;
  2748. // If there is only one SOP in a SOG, the LinkNum is zero. I.e., not a linkset.
  2749. // Now that we know this SOG has at least two SOPs in it, the new root
  2750. // SOP becomes the first in the linkset.
  2751. if (m_rootPart.LinkNum == 0)
  2752. m_rootPart.LinkNum = 1;
  2753. lock (m_parts.SyncRoot)
  2754. {
  2755. // Calculate the new link number for the old root SOP
  2756. int linkNum;
  2757. if (insert)
  2758. {
  2759. linkNum = 2;
  2760. int insertSize = objectGroup.PrimCount;
  2761. foreach (SceneObjectPart part in Parts)
  2762. {
  2763. if (part.LinkNum > 1)
  2764. part.LinkNum += insertSize;
  2765. }
  2766. }
  2767. else
  2768. {
  2769. linkNum = PrimCount + 1;
  2770. }
  2771. // Add the old root SOP as a part in our group's list
  2772. m_parts.Add(linkPart.UUID, linkPart);
  2773. linkPart.SetParent(this);
  2774. //linkPart.CreateSelected = true;
  2775. linkPart.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (linkPart.Flags & PrimFlags.Phantom) != 0), linkPart.VolumeDetectActive || RootPart.VolumeDetectActive, true);
  2776. // If the added SOP is physical, also tell the physics engine about the link relationship.
  2777. if (linkPart.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
  2778. {
  2779. linkPart.PhysActor.link(m_rootPart.PhysActor);
  2780. this.Scene.PhysicsScene.AddPhysicsActorTaint(linkPart.PhysActor);
  2781. }
  2782. linkPart.LinkNum = linkNum++;
  2783. linkPart.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
  2784. // Get a list of the SOP's in the source group in order of their linknum's.
  2785. SceneObjectPart[] ogParts = objectGroup.Parts;
  2786. Array.Sort(ogParts, delegate(SceneObjectPart a, SceneObjectPart b)
  2787. {
  2788. return a.LinkNum - b.LinkNum;
  2789. });
  2790. // Add each of the SOP's from the source linkset to our linkset
  2791. for (int i = 0; i < ogParts.Length; i++)
  2792. {
  2793. SceneObjectPart part = ogParts[i];
  2794. if (part.UUID != objectGroup.m_rootPart.UUID)
  2795. {
  2796. LinkNonRootPart(part, oldGroupPosition, oldRootRotation, linkNum++);
  2797. // Update the physics flags for the newly added SOP
  2798. // (Is this necessary? LinkNonRootPart() has already called UpdatePrimFlags but with different flags!??)
  2799. part.UpdatePrimFlags(grpusephys, grptemporary, (IsPhantom || (part.Flags & PrimFlags.Phantom) != 0), part.VolumeDetectActive, true);
  2800. // If the added SOP is physical, also tell the physics engine about the link relationship.
  2801. if (part.PhysActor != null && m_rootPart.PhysActor != null && m_rootPart.PhysActor.IsPhysical)
  2802. {
  2803. part.PhysActor.link(m_rootPart.PhysActor);
  2804. this.Scene.PhysicsScene.AddPhysicsActorTaint(part.PhysActor);
  2805. }
  2806. }
  2807. part.ClearUndoState();
  2808. }
  2809. }
  2810. // Now that we've aquired all of the old SOG's parts, remove the old SOG from the scene.
  2811. m_scene.UnlinkSceneObject(objectGroup, true);
  2812. objectGroup.m_parts.Clear(); // do not dispose the parts moved to new group
  2813. objectGroup.Dispose();
  2814. // Can't do this yet since backup still makes use of the root part without any synchronization
  2815. // objectGroup.m_rootPart = null;
  2816. // If linking prims with different permissions, fix them
  2817. AdjustChildPrimPermissions(false);
  2818. GroupContainsForeignPrims = true;
  2819. AttachToBackup();
  2820. // Here's the deal, this is ABSOLUTELY CRITICAL so the physics scene gets the update about the
  2821. // position of linkset prims. IF YOU CHANGE THIS, YOU MUST TEST colliding with just linked and
  2822. // unmoved prims!
  2823. ResetChildPrimPhysicsPositions();
  2824. InvalidBoundsRadius();
  2825. InvalidatePartsLinkMaps();
  2826. if (m_rootPart.PhysActor != null)
  2827. m_rootPart.PhysActor.Building = false;
  2828. //HasGroupChanged = true;
  2829. //ScheduleGroupForFullUpdate();
  2830. }
  2831. /// <summary>
  2832. /// Delink the given prim from this group. The delinked prim is established as
  2833. /// an independent SceneObjectGroup.
  2834. /// </summary>
  2835. /// <remarks>
  2836. /// FIXME: This method should not be called directly since it bypasses update locking, allowing a potential race
  2837. /// condition. But currently there is no
  2838. /// alternative method that does take a lonk to delink a single prim.
  2839. /// </remarks>
  2840. /// <param name="partID"></param>
  2841. /// <returns>The object group of the newly delinked prim. Null if part could not be found</returns>
  2842. public SceneObjectGroup DelinkFromGroup(uint partID)
  2843. {
  2844. return DelinkFromGroup(partID, true);
  2845. }
  2846. /// <summary>
  2847. /// Delink the given prim from this group. The delinked prim is established as
  2848. /// an independent SceneObjectGroup.
  2849. /// </summary>
  2850. /// <remarks>
  2851. /// FIXME: This method should not be called directly since it bypasses update locking, allowing a potential race
  2852. /// condition. But currently there is no
  2853. /// alternative method that does take a lonk to delink a single prim.
  2854. /// </remarks>
  2855. /// <param name="partID"></param>
  2856. /// <param name="sendEvents"></param>
  2857. /// <returns>The object group of the newly delinked prim. Null if part could not be found</returns>
  2858. public SceneObjectGroup DelinkFromGroup(uint partID, bool sendEvents)
  2859. {
  2860. SceneObjectPart linkPart = GetPart(partID);
  2861. if (linkPart != null)
  2862. {
  2863. return DelinkFromGroup(linkPart, sendEvents);
  2864. }
  2865. else
  2866. {
  2867. m_log.WarnFormat("[SCENE OBJECT GROUP]: " +
  2868. "DelinkFromGroup(): Child prim {0} not found in object {1}, {2}",
  2869. partID, LocalId, UUID);
  2870. return null;
  2871. }
  2872. }
  2873. /// <summary>
  2874. /// Delink the given prim from this group. The delinked prim is established as
  2875. /// an independent SceneObjectGroup.
  2876. /// </summary>
  2877. /// <remarks>
  2878. /// FIXME: This method should not be called directly since it bypasses update locking, allowing a potential race
  2879. /// condition. But currently there is no
  2880. /// alternative method that does take a lock to delink a single prim.
  2881. /// </remarks>
  2882. /// <param name="partID"></param>
  2883. /// <param name="sendEvents"></param>
  2884. /// <returns>The object group of the newly delinked prim.</returns>
  2885. public SceneObjectGroup DelinkFromGroup(SceneObjectPart linkPart, bool sendEvents)
  2886. {
  2887. // m_log.DebugFormat(
  2888. // "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
  2889. // linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
  2890. if (m_rootPart.PhysActor != null)
  2891. m_rootPart.PhysActor.Building = true;
  2892. linkPart.ClearUndoState();
  2893. Vector3 worldPos = linkPart.GetWorldPosition();
  2894. Quaternion worldRot = linkPart.GetWorldRotation();
  2895. // Remove the part from this object
  2896. lock (m_parts.SyncRoot)
  2897. {
  2898. m_parts.Remove(linkPart.UUID);
  2899. SceneObjectPart[] parts = m_parts.GetArray();
  2900. // Rejigger the linknum's of the remaining SOP's to fill any gap
  2901. if (parts.Length == 1 && RootPart != null)
  2902. {
  2903. // Single prim left
  2904. RootPart.LinkNum = 0;
  2905. }
  2906. else
  2907. {
  2908. for (int i = 0; i < parts.Length; i++)
  2909. {
  2910. SceneObjectPart part = parts[i];
  2911. if (part.LinkNum > linkPart.LinkNum)
  2912. part.LinkNum--;
  2913. }
  2914. }
  2915. }
  2916. linkPart.ParentID = 0;
  2917. linkPart.LinkNum = 0;
  2918. PhysicsActor linkPartPa = linkPart.PhysActor;
  2919. // Remove the SOP from the physical scene.
  2920. // If the new SOG is physical, it is re-created later.
  2921. // (There is a problem here in that we have not yet told the physics
  2922. // engine about the delink. Someday, linksets should be made first
  2923. // class objects in the physics engine interface).
  2924. if (linkPartPa != null)
  2925. {
  2926. m_scene.PhysicsScene.RemovePrim(linkPartPa);
  2927. linkPart.PhysActor = null;
  2928. }
  2929. // We need to reset the child part's position
  2930. // ready for life as a separate object after being a part of another object
  2931. /* This commented out code seems to recompute what GetWorldPosition already does.
  2932. * Replace with a call to GetWorldPosition (before unlinking)
  2933. Quaternion parentRot = m_rootPart.RotationOffset;
  2934. Vector3 axPos = linkPart.OffsetPosition;
  2935. axPos *= parentRot;
  2936. linkPart.OffsetPosition = new Vector3(axPos.X, axPos.Y, axPos.Z);
  2937. linkPart.GroupPosition = AbsolutePosition + linkPart.OffsetPosition;
  2938. linkPart.OffsetPosition = new Vector3(0, 0, 0);
  2939. */
  2940. linkPart.setGroupPosition(worldPos);
  2941. linkPart.setOffsetPosition(Vector3.Zero);
  2942. linkPart.setRotationOffset(worldRot);
  2943. // Create a new SOG to go around this unlinked and unattached SOP
  2944. SceneObjectGroup objectGroup = new SceneObjectGroup(linkPart);
  2945. m_scene.AddNewSceneObject(objectGroup, true);
  2946. linkPart.Rezzed = RootPart.Rezzed;
  2947. InvalidBoundsRadius();
  2948. InvalidatePartsLinkMaps();
  2949. InvalidateEffectivePerms();
  2950. if (m_rootPart.PhysActor != null)
  2951. m_rootPart.PhysActor.Building = false;
  2952. objectGroup.HasGroupChangedDueToDelink = true;
  2953. if (sendEvents)
  2954. linkPart.TriggerScriptChangedEvent(Changed.LINK);
  2955. return objectGroup;
  2956. }
  2957. /* working on it
  2958. public void DelinkFromGroup(List<SceneObjectPart> linkParts, bool sendEvents)
  2959. {
  2960. // m_log.DebugFormat(
  2961. // "[SCENE OBJECT GROUP]: Delinking part {0}, {1} from group with root part {2}, {3}",
  2962. // linkPart.Name, linkPart.UUID, RootPart.Name, RootPart.UUID);
  2963. if(PrimCount == 1)
  2964. return;
  2965. if (m_rootPart.PhysActor != null)
  2966. m_rootPart.PhysActor.Building = true;
  2967. bool unlinkroot = false;
  2968. foreach(SceneObjectPart linkPart in linkParts)
  2969. {
  2970. // first we only remove child parts
  2971. if(linkPart.LocalId == m_rootPart.LocalId)
  2972. {
  2973. unlinkroot = true;
  2974. continue;
  2975. }
  2976. lock (m_parts.SyncRoot)
  2977. if(!m_parts.Remove(linkPart.UUID))
  2978. continue;
  2979. linkPart.ClearUndoState();
  2980. Vector3 worldPos = linkPart.GetWorldPosition();
  2981. Quaternion worldRot = linkPart.GetWorldRotation();
  2982. linkPart.ParentID = 0;
  2983. linkPart.LinkNum = 0;
  2984. PhysicsActor linkPartPa = linkPart.PhysActor;
  2985. // Remove the SOP from the physical scene.
  2986. // If the new SOG is physical, it is re-created later.
  2987. // (There is a problem here in that we have not yet told the physics
  2988. // engine about the delink. Someday, linksets should be made first
  2989. // class objects in the physics engine interface).
  2990. if (linkPartPa != null)
  2991. {
  2992. m_scene.PhysicsScene.RemovePrim(linkPartPa);
  2993. linkPart.PhysActor = null;
  2994. }
  2995. linkPart.setGroupPosition(worldPos);
  2996. linkPart.setOffsetPosition(Vector3.Zero);
  2997. linkPart.setRotationOffset(worldRot);
  2998. // Create a new SOG to go around this unlinked and unattached SOP
  2999. SceneObjectGroup objectGroup = new SceneObjectGroup(linkPart);
  3000. m_scene.AddNewSceneObject(objectGroup, true);
  3001. linkPart.Rezzed = RootPart.Rezzed;
  3002. // this is as it seems to be in sl now
  3003. if(linkPart.PhysicsShapeType == (byte)PhysShapeType.none)
  3004. linkPart.PhysicsShapeType = linkPart.DefaultPhysicsShapeType(); // root prims can't have type none for now
  3005. objectGroup.HasGroupChangedDueToDelink = true;
  3006. if (sendEvents)
  3007. linkPart.TriggerScriptChangedEvent(Changed.LINK);
  3008. }
  3009. if(unlinkroot)
  3010. {
  3011. //TODO
  3012. }
  3013. lock (m_parts.SyncRoot)
  3014. {
  3015. SceneObjectPart[] parts = m_parts.GetArray();
  3016. if (parts.Length == 1)
  3017. {
  3018. // Single prim left
  3019. m_rootPart.LinkNum = 0;
  3020. }
  3021. else
  3022. {
  3023. m_rootPart.LinkNum = 1;
  3024. int linknum = 2;
  3025. for (int i = 1; i < parts.Length; i++)
  3026. parts[i].LinkNum = linknum++;
  3027. }
  3028. }
  3029. InvalidBoundsRadius();
  3030. if (m_rootPart.PhysActor != null)
  3031. m_rootPart.PhysActor.Building = false;
  3032. // When we delete a group, we currently have to force persist to the database if the object id has changed
  3033. // (since delete works by deleting all rows which have a given object id)
  3034. Scene.SimulationDataService.RemoveObject(UUID, Scene.RegionInfo.RegionID);
  3035. HasGroupChangedDueToDelink = true;
  3036. TriggerScriptChangedEvent(Changed.LINK);
  3037. return;
  3038. }
  3039. */
  3040. /// <summary>
  3041. /// Stop this object from being persisted over server restarts.
  3042. /// </summary>
  3043. /// <param name="objectGroup"></param>
  3044. public virtual void DetachFromBackup()
  3045. {
  3046. if (m_scene != null)
  3047. {
  3048. m_scene.SceneGraph.FireDetachFromBackup(this);
  3049. if (Backup)
  3050. m_scene.EventManager.OnBackup -= ProcessBackup;
  3051. }
  3052. Backup = false;
  3053. }
  3054. // This links an SOP from a previous linkset into my linkset.
  3055. // The trick is that the SOP's position and rotation are relative to the old root SOP's
  3056. // so we are passed in the position and rotation of the old linkset so this can
  3057. // unjigger this SOP's position and rotation from the previous linkset and
  3058. // then make them relative to my linkset root.
  3059. private void LinkNonRootPart(SceneObjectPart part, Vector3 oldGroupPosition, Quaternion oldGroupRotation, int linkNum)
  3060. {
  3061. Quaternion parentRot = oldGroupRotation;
  3062. Quaternion oldRot = part.RotationOffset;
  3063. // Move our position in world
  3064. Vector3 axPos = part.OffsetPosition;
  3065. axPos *= parentRot;
  3066. Vector3 newPos = oldGroupPosition + axPos;
  3067. part.setGroupPosition(newPos);
  3068. part.setOffsetPosition(Vector3.Zero);
  3069. // Compution our rotation in world
  3070. Quaternion worldRot = parentRot * oldRot;
  3071. part.RotationOffset = worldRot;
  3072. // Add this SOP to our linkset
  3073. part.SetParent(this);
  3074. part.ParentID = m_rootPart.LocalId;
  3075. m_parts.Add(part.UUID, part);
  3076. part.LinkNum = linkNum;
  3077. // Compute the new position of this SOP relative to the group position
  3078. part.setOffsetPosition(newPos - AbsolutePosition);
  3079. // (radams1 20120711: I don't know why part.OffsetPosition is set multiple times.
  3080. // It would have the affect of setting the physics engine position multiple
  3081. // times. In theory, that is not necessary but I don't have a good linkset
  3082. // test to know that cleaning up this code wouldn't break things.)
  3083. // Compute the SOP's rotation relative to the rotation of the group.
  3084. parentRot = m_rootPart.RotationOffset;
  3085. oldRot = part.RotationOffset;
  3086. Quaternion newRot = Quaternion.Conjugate(parentRot) * worldRot;
  3087. part.setRotationOffset(newRot);
  3088. Vector3 pos = part.OffsetPosition;
  3089. pos *= Quaternion.Conjugate(parentRot);
  3090. part.OffsetPosition = pos; // update position and orientation on physics also
  3091. // Since this SOP's state has changed, push those changes into the physics engine
  3092. // and the simulator.
  3093. // done on caller
  3094. // part.UpdatePrimFlags(UsesPhysics, IsTemporary, IsPhantom, IsVolumeDetect, false);
  3095. }
  3096. double lastTouchTime = 0;
  3097. /// <summary>
  3098. /// If object is physical, apply force to move it around
  3099. /// If object is not physical, just put it at the resulting location
  3100. /// </summary>
  3101. /// <param name="partID">Part ID to check for grab</param>
  3102. /// <param name="offset">Always seems to be 0,0,0, so ignoring</param>
  3103. /// <param name="pos">New position. We do the math here to turn it into a force</param>
  3104. /// <param name="remoteClient"></param>
  3105. public void GrabMovement(UUID partID, Vector3 offset, Vector3 pos, IClientAPI remoteClienth)
  3106. {
  3107. if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
  3108. {
  3109. if (BlockGrabOverride)
  3110. return;
  3111. SceneObjectPart part = GetPart(partID);
  3112. if (part == null)
  3113. return;
  3114. if (part.BlockGrab)
  3115. return;
  3116. PhysicsActor pa = m_rootPart.PhysActor;
  3117. if (pa != null && pa.IsPhysical)
  3118. {
  3119. // empirically convert distance diference to a impulse
  3120. Vector3 grabforce = pos - AbsolutePosition;
  3121. grabforce = grabforce * (pa.Mass * 0.1f);
  3122. pa.AddForce(grabforce, false);
  3123. m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
  3124. }
  3125. else
  3126. {
  3127. if(IsAttachment)
  3128. return;
  3129. // block movement if there was a touch at start
  3130. double now = Util.GetTimeStampMS();
  3131. if (now - lastTouchTime < 250)
  3132. {
  3133. lastTouchTime = now;
  3134. return;
  3135. }
  3136. // a touch or pass may had become active ??
  3137. if (((part.ScriptEvents & scriptEvents.anytouch) != 0) || (RootPart.ScriptEvents & scriptEvents.anytouch) != 0)
  3138. {
  3139. lastTouchTime = now;
  3140. return;
  3141. }
  3142. lastTouchTime = 0;
  3143. UpdateGroupPosition(pos);
  3144. }
  3145. }
  3146. }
  3147. /// <summary>
  3148. /// If object is physical, prepare for spinning torques (set flag to save old orientation)
  3149. /// </summary>
  3150. /// <param name="rotation">Rotation. We do the math here to turn it into a torque</param>
  3151. /// <param name="remoteClient"></param>
  3152. public void SpinStart(IClientAPI remoteClient)
  3153. {
  3154. if (BlockGrabOverride || m_rootPart.BlockGrab)
  3155. return;
  3156. if (m_scene.EventManager.TriggerGroupSpinStart(UUID))
  3157. {
  3158. PhysicsActor pa = m_rootPart.PhysActor;
  3159. if (pa != null)
  3160. {
  3161. if (pa.IsPhysical)
  3162. {
  3163. m_rootPart.IsWaitingForFirstSpinUpdatePacket = true;
  3164. }
  3165. }
  3166. }
  3167. }
  3168. /// <summary>
  3169. /// If object is physical, apply torque to spin it around
  3170. /// </summary>
  3171. /// <param name="rotation">Rotation. We do the math here to turn it into a torque</param>
  3172. /// <param name="remoteClient"></param>
  3173. public void SpinMovement(Quaternion newOrientation, IClientAPI remoteClient)
  3174. {
  3175. // The incoming newOrientation, sent by the client, "seems" to be the
  3176. // desired target orientation. This needs further verification; in particular,
  3177. // one would expect that the initial incoming newOrientation should be
  3178. // fairly close to the original prim's physical orientation,
  3179. // m_rootPart.PhysActor.Orientation. This however does not seem to be the
  3180. // case (might just be an issue with different quaternions representing the
  3181. // same rotation, or it might be a coordinate system issue).
  3182. //
  3183. // Since it's not clear what the relationship is between the PhysActor.Orientation
  3184. // and the incoming orientations sent by the client, we take an alternative approach
  3185. // of calculating the delta rotation between the orientations being sent by the
  3186. // client. (Since a spin is invoked by ctrl+shift+drag in the client, we expect
  3187. // a steady stream of several new orientations coming in from the client.)
  3188. // This ensures that the delta rotations are being calculated from self-consistent
  3189. // pairs of old/new rotations. Given the delta rotation, we apply a torque around
  3190. // the delta rotation axis, scaled by the object mass times an arbitrary scaling
  3191. // factor (to ensure the resulting torque is not "too strong" or "too weak").
  3192. //
  3193. // Ideally we need to calculate (probably iteratively) the exact torque or series
  3194. // of torques needed to arrive exactly at the destination orientation. However, since
  3195. // it is not yet clear how to map the destination orientation (provided by the viewer)
  3196. // into PhysActor orientations (needed by the physics engine), we omit this step.
  3197. // This means that the resulting torque will at least be in the correct direction,
  3198. // but it will result in over-shoot or under-shoot of the target orientation.
  3199. // For the end user, this means that ctrl+shift+drag can be used for relative,
  3200. // but not absolute, adjustments of orientation for physical prims.
  3201. if (BlockGrabOverride || m_rootPart.BlockGrab)
  3202. return;
  3203. if (m_scene.EventManager.TriggerGroupSpin(UUID, newOrientation))
  3204. {
  3205. PhysicsActor pa = m_rootPart.PhysActor;
  3206. if (pa != null && pa.IsPhysical)
  3207. {
  3208. if (m_rootPart.IsWaitingForFirstSpinUpdatePacket)
  3209. {
  3210. // first time initialization of "old" orientation for calculation of delta rotations
  3211. m_rootPart.SpinOldOrientation = newOrientation;
  3212. m_rootPart.IsWaitingForFirstSpinUpdatePacket = false;
  3213. }
  3214. else
  3215. {
  3216. // save and update old orientation
  3217. Quaternion old = m_rootPart.SpinOldOrientation;
  3218. m_rootPart.SpinOldOrientation = newOrientation;
  3219. //m_log.Error("[SCENE OBJECT GROUP]: Old orientation is " + old);
  3220. //m_log.Error("[SCENE OBJECT GROUP]: Incoming new orientation is " + newOrientation);
  3221. // compute difference between previous old rotation and new incoming rotation
  3222. Quaternion minimalRotationFromQ1ToQ2 = newOrientation * Quaternion.Inverse(old);
  3223. float rotationAngle;
  3224. Vector3 spinforce;
  3225. minimalRotationFromQ1ToQ2.GetAxisAngle(out spinforce, out rotationAngle);
  3226. if(Math.Abs(rotationAngle)< 0.001)
  3227. return;
  3228. spinforce.Normalize();
  3229. //m_log.Error("SCENE OBJECT GROUP]: rotation axis is " + rotationAxis);
  3230. if(rotationAngle > 0)
  3231. spinforce = spinforce * pa.Mass * 0.1f; // 0.1 is an arbitrary torque scaling factor
  3232. else
  3233. spinforce = spinforce * pa.Mass * -0.1f; // 0.1 is an arbitrary torque scaling
  3234. pa.AddAngularForce(spinforce,true);
  3235. m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
  3236. }
  3237. }
  3238. else
  3239. {
  3240. NonPhysicalSpinMovement(newOrientation);
  3241. }
  3242. }
  3243. }
  3244. /// <summary>
  3245. /// Apply rotation for spinning non-physical linksets (Ctrl+Shift+Drag)
  3246. /// As with dragging, scripted objects must be blocked from spinning
  3247. /// </summary>
  3248. /// <param name="newOrientation">New Rotation</param>
  3249. private void NonPhysicalSpinMovement(Quaternion newOrientation)
  3250. {
  3251. if(!IsAttachment && ScriptCount() == 0)
  3252. UpdateGroupRotationR(newOrientation);
  3253. }
  3254. /// <summary>
  3255. /// Set the name of a prim
  3256. /// </summary>
  3257. /// <param name="name"></param>
  3258. /// <param name="localID"></param>
  3259. public void SetPartName(string name, uint localID)
  3260. {
  3261. SceneObjectPart part = GetPart(localID);
  3262. if (part != null)
  3263. {
  3264. part.Name = name;
  3265. }
  3266. }
  3267. public void SetPartDescription(string des, uint localID)
  3268. {
  3269. SceneObjectPart part = GetPart(localID);
  3270. if (part != null)
  3271. {
  3272. part.Description = des;
  3273. }
  3274. }
  3275. public void SetPartText(string text, uint localID)
  3276. {
  3277. SceneObjectPart part = GetPart(localID);
  3278. if (part != null)
  3279. {
  3280. part.SetText(text);
  3281. }
  3282. }
  3283. public void SetPartText(string text, UUID partID)
  3284. {
  3285. SceneObjectPart part = GetPart(partID);
  3286. if (part != null)
  3287. {
  3288. part.SetText(text);
  3289. }
  3290. }
  3291. public string GetPartName(uint localID)
  3292. {
  3293. SceneObjectPart part = GetPart(localID);
  3294. if (part != null)
  3295. {
  3296. return part.Name;
  3297. }
  3298. return String.Empty;
  3299. }
  3300. public string GetPartDescription(uint localID)
  3301. {
  3302. SceneObjectPart part = GetPart(localID);
  3303. if (part != null)
  3304. {
  3305. return part.Description;
  3306. }
  3307. return String.Empty;
  3308. }
  3309. /// <summary>
  3310. /// Update prim flags for this group.
  3311. /// </summary>
  3312. /// <param name="localID"></param>
  3313. /// <param name="UsePhysics"></param>
  3314. /// <param name="SetTemporary"></param>
  3315. /// <param name="SetPhantom"></param>
  3316. /// <param name="SetVolumeDetect"></param>
  3317. public void UpdateFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVolumeDetect)
  3318. {
  3319. if (m_scene == null || IsDeleted)
  3320. return;
  3321. HasGroupChanged = true;
  3322. if (SetTemporary)
  3323. {
  3324. DetachFromBackup();
  3325. // Remove from database and parcel prim count
  3326. //
  3327. m_scene.DeleteFromStorage(UUID);
  3328. }
  3329. else if (!Backup)
  3330. {
  3331. // Previously been temporary now switching back so make it
  3332. // available for persisting again
  3333. AttachToBackup();
  3334. }
  3335. SceneObjectPart[] parts = m_parts.GetArray();
  3336. if (UsePhysics)
  3337. {
  3338. int maxprims = m_scene.m_linksetPhysCapacity;
  3339. bool checkShape = (maxprims > 0 &&
  3340. parts.Length > maxprims);
  3341. for (int i = 0; i < parts.Length; i++)
  3342. {
  3343. SceneObjectPart part = parts[i];
  3344. if(part.PhysicsShapeType == (byte)PhysicsShapeType.None)
  3345. continue; // assuming root type was checked elsewhere
  3346. if (checkShape)
  3347. {
  3348. if (--maxprims < 0)
  3349. {
  3350. UsePhysics = false;
  3351. break;
  3352. }
  3353. }
  3354. if (part.Scale.X > m_scene.m_maxPhys ||
  3355. part.Scale.Y > m_scene.m_maxPhys ||
  3356. part.Scale.Z > m_scene.m_maxPhys )
  3357. {
  3358. UsePhysics = false; // Reset physics
  3359. break;
  3360. }
  3361. }
  3362. }
  3363. if (parts.Length > 1)
  3364. {
  3365. m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
  3366. for (int i = 0; i < parts.Length; i++)
  3367. {
  3368. if (parts[i].UUID != m_rootPart.UUID)
  3369. parts[i].UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, true);
  3370. }
  3371. if (m_rootPart.PhysActor != null)
  3372. m_rootPart.PhysActor.Building = false;
  3373. }
  3374. else
  3375. m_rootPart.UpdatePrimFlags(UsePhysics, SetTemporary, SetPhantom, SetVolumeDetect, false);
  3376. m_scene.EventManager.TriggerParcelPrimCountTainted();
  3377. }
  3378. public void UpdateExtraParam(uint localID, ushort type, bool inUse, byte[] data)
  3379. {
  3380. SceneObjectPart part = GetPart(localID);
  3381. if (part != null)
  3382. {
  3383. part.UpdateExtraParam(type, inUse, data);
  3384. }
  3385. }
  3386. /// <summary>
  3387. /// Gets the number of parts
  3388. /// </summary>
  3389. /// <returns></returns>
  3390. public int GetPartCount()
  3391. {
  3392. return Parts.Count();
  3393. }
  3394. public void AdjustChildPrimPermissions(bool forceTaskInventoryPermissive)
  3395. {
  3396. uint newOwnerMask = (uint)(PermissionMask.All | PermissionMask.Export) & 0xfffffff0; // Mask folded bits
  3397. uint foldedPerms = RootPart.OwnerMask & (uint)PermissionMask.FoldedMask;
  3398. ForEachPart(part =>
  3399. {
  3400. newOwnerMask &= part.BaseMask;
  3401. if (part != RootPart)
  3402. part.ClonePermissions(RootPart);
  3403. if (forceTaskInventoryPermissive)
  3404. part.Inventory.ApplyGodPermissions(part.BaseMask);
  3405. });
  3406. uint lockMask = ~(uint)(PermissionMask.Move);
  3407. uint lockBit = RootPart.OwnerMask & (uint)(PermissionMask.Move);
  3408. RootPart.OwnerMask = (RootPart.OwnerMask & lockBit) | ((newOwnerMask | foldedPerms) & lockMask);
  3409. // m_log.DebugFormat(
  3410. // "[SCENE OBJECT GROUP]: RootPart.OwnerMask now {0} for {1} in {2}",
  3411. // (OpenMetaverse.PermissionMask)RootPart.OwnerMask, Name, Scene.Name);
  3412. InvalidateEffectivePerms();
  3413. RootPart.ScheduleFullUpdate();
  3414. }
  3415. public void UpdatePermissions(UUID AgentID, byte field, uint localID,
  3416. uint mask, byte addRemTF)
  3417. {
  3418. RootPart.UpdatePermissions(AgentID, field, localID, mask, addRemTF);
  3419. bool god = Scene.Permissions.IsGod(AgentID);
  3420. if (field == 1 && god)
  3421. {
  3422. ForEachPart(part =>
  3423. {
  3424. part.BaseMask = RootPart.BaseMask;
  3425. });
  3426. }
  3427. AdjustChildPrimPermissions(false);
  3428. if (field == 1 && god) // Base mask was set. Update all child part inventories
  3429. {
  3430. foreach (SceneObjectPart part in Parts)
  3431. part.Inventory.ApplyGodPermissions(RootPart.BaseMask);
  3432. InvalidateEffectivePerms();
  3433. }
  3434. HasGroupChanged = true;
  3435. // Send the group's properties to all clients once all parts are updated
  3436. IClientAPI client;
  3437. if (Scene.TryGetClient(AgentID, out client))
  3438. SendPropertiesToClient(client);
  3439. }
  3440. #endregion
  3441. #region Shape
  3442. /// <summary>
  3443. ///
  3444. /// </summary>
  3445. /// <param name="shapeBlock"></param>
  3446. public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock, uint localID)
  3447. {
  3448. SceneObjectPart part = GetPart(localID);
  3449. if (part != null)
  3450. {
  3451. part.UpdateShape(shapeBlock);
  3452. PhysicsActor pa = m_rootPart.PhysActor;
  3453. if (pa != null)
  3454. m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
  3455. }
  3456. InvalidBoundsRadius();
  3457. }
  3458. #endregion
  3459. #region Resize
  3460. /// <summary>
  3461. /// Resize the entire group of prims.
  3462. /// </summary>
  3463. /// <param name="scale"></param>
  3464. public void GroupResize(Vector3 scale)
  3465. {
  3466. // m_log.DebugFormat(
  3467. // "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, scale);
  3468. if (Scene == null)
  3469. return;
  3470. PhysicsActor pa = m_rootPart.PhysActor;
  3471. float minsize = Scene.m_minNonphys;
  3472. float maxsize = Scene.m_maxNonphys;
  3473. if (pa != null && pa.IsPhysical)
  3474. {
  3475. minsize = Scene.m_minPhys;
  3476. maxsize = Scene.m_maxPhys;
  3477. }
  3478. scale.X = Util.Clamp(scale.X, minsize, maxsize);
  3479. scale.Y = Util.Clamp(scale.Y, minsize, maxsize);
  3480. scale.Z = Util.Clamp(scale.Z, minsize, maxsize);
  3481. // requested scaling factors
  3482. float x = (scale.X / RootPart.Scale.X);
  3483. float y = (scale.Y / RootPart.Scale.Y);
  3484. float z = (scale.Z / RootPart.Scale.Z);
  3485. SceneObjectPart[] parts = m_parts.GetArray();
  3486. // fix scaling factors so parts don't violate dimensions
  3487. for(int i = 0;i < parts.Length;i++)
  3488. {
  3489. SceneObjectPart obPart = parts[i];
  3490. if(obPart.UUID != m_rootPart.UUID)
  3491. {
  3492. Vector3 oldSize = new Vector3(obPart.Scale);
  3493. float f = 1.0f;
  3494. float a = 1.0f;
  3495. if(oldSize.X * x > maxsize)
  3496. {
  3497. f = maxsize / oldSize.X;
  3498. a = f / x;
  3499. x *= a;
  3500. y *= a;
  3501. z *= a;
  3502. }
  3503. else if(oldSize.X * x < minsize)
  3504. {
  3505. f = minsize / oldSize.X;
  3506. a = f / x;
  3507. x *= a;
  3508. y *= a;
  3509. z *= a;
  3510. }
  3511. if(oldSize.Y * y > maxsize)
  3512. {
  3513. f = maxsize / oldSize.Y;
  3514. a = f / y;
  3515. x *= a;
  3516. y *= a;
  3517. z *= a;
  3518. }
  3519. else if(oldSize.Y * y < minsize)
  3520. {
  3521. f = minsize / oldSize.Y;
  3522. a = f / y;
  3523. x *= a;
  3524. y *= a;
  3525. z *= a;
  3526. }
  3527. if(oldSize.Z * z > maxsize)
  3528. {
  3529. f = maxsize / oldSize.Z;
  3530. a = f / z;
  3531. x *= a;
  3532. y *= a;
  3533. z *= a;
  3534. }
  3535. else if(oldSize.Z * z < minsize)
  3536. {
  3537. f = minsize / oldSize.Z;
  3538. a = f / z;
  3539. x *= a;
  3540. y *= a;
  3541. z *= a;
  3542. }
  3543. }
  3544. }
  3545. Vector3 rootScale = RootPart.Scale;
  3546. rootScale.X *= x;
  3547. rootScale.Y *= y;
  3548. rootScale.Z *= z;
  3549. RootPart.Scale = rootScale;
  3550. for (int i = 0; i < parts.Length; i++)
  3551. {
  3552. SceneObjectPart obPart = parts[i];
  3553. if (obPart.UUID != m_rootPart.UUID)
  3554. {
  3555. Vector3 currentpos = new Vector3(obPart.OffsetPosition);
  3556. currentpos.X *= x;
  3557. currentpos.Y *= y;
  3558. currentpos.Z *= z;
  3559. Vector3 newSize = new Vector3(obPart.Scale);
  3560. newSize.X *= x;
  3561. newSize.Y *= y;
  3562. newSize.Z *= z;
  3563. obPart.Scale = newSize;
  3564. obPart.UpdateOffSet(currentpos);
  3565. }
  3566. }
  3567. InvalidBoundsRadius();
  3568. HasGroupChanged = true;
  3569. m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
  3570. ScheduleGroupForFullUpdate();
  3571. }
  3572. public bool GroupResize(double fscale)
  3573. {
  3574. // m_log.DebugFormat(
  3575. // "[SCENE OBJECT GROUP]: Group resizing {0} {1} from {2} to {3}", Name, LocalId, RootPart.Scale, fscale);
  3576. if (Scene == null || IsDeleted || inTransit || fscale < 0)
  3577. return false;
  3578. // ignore lsl restrictions. let them be done a LSL
  3579. PhysicsActor pa = m_rootPart.PhysActor;
  3580. if(RootPart.KeyframeMotion != null)
  3581. RootPart.KeyframeMotion.Suspend();
  3582. float minsize = Scene.m_minNonphys;
  3583. float maxsize = Scene.m_maxNonphys;
  3584. // assuming physics is more restrictive
  3585. if (pa != null && pa.IsPhysical)
  3586. {
  3587. minsize = Scene.m_minPhys;
  3588. maxsize = Scene.m_maxPhys;
  3589. }
  3590. SceneObjectPart[] parts = m_parts.GetArray();
  3591. float tmp;
  3592. // check scaling factor so parts don't violate dimensions
  3593. for(int i = 0; i < parts.Length; i++)
  3594. {
  3595. SceneObjectPart obPart = parts[i];
  3596. Vector3 oldSize = new Vector3(obPart.Scale);
  3597. tmp = (float)(oldSize.X * fscale);
  3598. if(tmp > maxsize)
  3599. return false;
  3600. if(tmp < minsize)
  3601. return false;
  3602. tmp = (float)(oldSize.Y * fscale);
  3603. if(tmp > maxsize)
  3604. return false;
  3605. if(tmp < minsize)
  3606. return false;
  3607. tmp = (float)(oldSize.Z * fscale);
  3608. if(tmp > maxsize)
  3609. return false;
  3610. if(tmp < minsize)
  3611. return false;
  3612. }
  3613. Vector3 newSize = RootPart.Scale;
  3614. newSize.X = (float)(newSize.X * fscale);
  3615. newSize.Y = (float)(newSize.Y * fscale);
  3616. newSize.Z = (float)(newSize.Z * fscale);
  3617. if(pa != null)
  3618. pa.Building = true;
  3619. RootPart.Scale = newSize;
  3620. Vector3 currentpos;
  3621. for (int i = 0; i < parts.Length; i++)
  3622. {
  3623. SceneObjectPart obPart = parts[i];
  3624. if (obPart.UUID != m_rootPart.UUID)
  3625. {
  3626. currentpos = obPart.OffsetPosition;
  3627. currentpos.X = (float)(currentpos.X * fscale);
  3628. currentpos.Y = (float)(currentpos.Y * fscale);
  3629. currentpos.Z = (float)(currentpos.Z * fscale);
  3630. newSize = obPart.Scale;
  3631. newSize.X = (float)(newSize.X * fscale);
  3632. newSize.Y = (float)(newSize.Y * fscale);
  3633. newSize.Z = (float)(newSize.Z * fscale);
  3634. obPart.Scale = newSize;
  3635. obPart.UpdateOffSet(currentpos);
  3636. }
  3637. }
  3638. if(pa != null)
  3639. pa.Building = false;
  3640. InvalidBoundsRadius();
  3641. HasGroupChanged = true;
  3642. m_rootPart.TriggerScriptChangedEvent(Changed.SCALE);
  3643. ScheduleGroupForFullUpdate();
  3644. if(RootPart.KeyframeMotion != null)
  3645. RootPart.KeyframeMotion.Resume();
  3646. return true;
  3647. }
  3648. public float GetMaxGroupResizeScale()
  3649. {
  3650. if (Scene == null || IsDeleted || inTransit)
  3651. return 1.0f;
  3652. float maxsize = Scene.m_maxNonphys;
  3653. PhysicsActor pa = m_rootPart.PhysActor;
  3654. // assuming physics is more restrictive
  3655. if (pa != null && pa.IsPhysical)
  3656. maxsize = Scene.m_maxPhys;
  3657. SceneObjectPart[] parts = m_parts.GetArray();
  3658. float larger = float.MinValue;
  3659. for(int i = 0; i < parts.Length; i++)
  3660. {
  3661. SceneObjectPart obPart = parts[i];
  3662. Vector3 oldSize = new Vector3(obPart.Scale);
  3663. if(larger < oldSize.X)
  3664. larger = oldSize.X;
  3665. if(larger < oldSize.Y)
  3666. larger = oldSize.Y;
  3667. if(larger < oldSize.Z)
  3668. larger = oldSize.Z;
  3669. }
  3670. if(larger >= maxsize)
  3671. return 1.0f;
  3672. larger += 1e-3f;
  3673. float fscale = maxsize / larger;
  3674. return fscale;
  3675. }
  3676. public float GetMinGroupResizeScale()
  3677. {
  3678. if (Scene == null || IsDeleted || inTransit)
  3679. return 1.0f;
  3680. float minsize = Scene.m_minNonphys;
  3681. PhysicsActor pa = m_rootPart.PhysActor;
  3682. // assuming physics is more restrictive
  3683. if (pa != null && pa.IsPhysical)
  3684. minsize = Scene.m_minPhys;
  3685. SceneObjectPart[] parts = m_parts.GetArray();
  3686. float smaller = float.MaxValue;
  3687. for(int i = 0; i < parts.Length; i++)
  3688. {
  3689. SceneObjectPart obPart = parts[i];
  3690. Vector3 oldSize = new Vector3(obPart.Scale);
  3691. if(smaller > oldSize.X)
  3692. smaller = oldSize.X;
  3693. if(smaller > oldSize.Y)
  3694. smaller = oldSize.Y;
  3695. if(smaller > oldSize.Z)
  3696. smaller = oldSize.Z;
  3697. }
  3698. if(smaller <= minsize)
  3699. return 1.0f;
  3700. if(smaller > 2e-3f)
  3701. smaller -= 1e-3f;
  3702. float fscale = minsize / smaller;
  3703. if(fscale < 1e-8f)
  3704. fscale = 1e-8f;
  3705. return fscale;
  3706. }
  3707. #endregion
  3708. #region Position
  3709. /// <summary>
  3710. /// Move this scene object
  3711. /// </summary>
  3712. /// <param name="pos"></param>
  3713. public void UpdateGroupPosition(Vector3 pos)
  3714. {
  3715. if (m_scene.EventManager.TriggerGroupMove(UUID, pos))
  3716. {
  3717. if (IsAttachment)
  3718. {
  3719. m_rootPart.AttachedPos = pos;
  3720. }
  3721. if (RootPart.GetStatusSandbox())
  3722. {
  3723. if (Vector3.DistanceSquared(RootPart.StatusSandboxPos, pos) > 100)
  3724. {
  3725. RootPart.ScriptSetPhysicsStatus(false);
  3726. pos = AbsolutePosition;
  3727. Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"),
  3728. ChatTypeEnum.DebugChannel, 0x7FFFFFFF, RootPart.AbsolutePosition, Name, UUID, false);
  3729. }
  3730. }
  3731. AbsolutePosition = pos;
  3732. HasGroupChanged = true;
  3733. }
  3734. //we need to do a terse update even if the move wasn't allowed
  3735. // so that the position is reset in the client (the object snaps back)
  3736. RootPart.ScheduleTerseUpdate();
  3737. }
  3738. /// <summary>
  3739. /// Update the position of a single part of this scene object
  3740. /// </summary>
  3741. /// <param name="pos"></param>
  3742. /// <param name="localID"></param>
  3743. ///
  3744. public void UpdateSinglePosition(Vector3 pos, uint localID)
  3745. {
  3746. SceneObjectPart part = GetPart(localID);
  3747. if (part != null)
  3748. {
  3749. // unlock parts position change
  3750. if (m_rootPart.PhysActor != null)
  3751. m_rootPart.PhysActor.Building = true;
  3752. if (part.UUID == m_rootPart.UUID)
  3753. {
  3754. UpdateRootPosition(pos);
  3755. }
  3756. else
  3757. {
  3758. part.UpdateOffSet(pos);
  3759. }
  3760. if (m_rootPart.PhysActor != null)
  3761. m_rootPart.PhysActor.Building = false;
  3762. HasGroupChanged = true;
  3763. }
  3764. }
  3765. /// <summary>
  3766. /// Update just the root prim position in a linkset
  3767. /// </summary>
  3768. /// <param name="newPos"></param>
  3769. public void UpdateRootPosition(Vector3 newPos)
  3770. {
  3771. // needs to be called with phys building true
  3772. Vector3 oldPos;
  3773. if (IsAttachment)
  3774. oldPos = m_rootPart.AttachedPos + m_rootPart.OffsetPosition; // OffsetPosition should always be 0 in an attachments's root prim
  3775. else
  3776. oldPos = AbsolutePosition + m_rootPart.OffsetPosition;
  3777. Vector3 diff = oldPos - newPos;
  3778. Quaternion partRotation = m_rootPart.RotationOffset;
  3779. diff *= Quaternion.Inverse(partRotation);
  3780. SceneObjectPart[] parts = m_parts.GetArray();
  3781. for (int i = 0; i < parts.Length; i++)
  3782. {
  3783. SceneObjectPart obPart = parts[i];
  3784. if (obPart.UUID != m_rootPart.UUID)
  3785. obPart.OffsetPosition = obPart.OffsetPosition + diff;
  3786. }
  3787. AbsolutePosition = newPos;
  3788. if (IsAttachment)
  3789. m_rootPart.AttachedPos = newPos;
  3790. HasGroupChanged = true;
  3791. if (m_rootPart.Undoing)
  3792. {
  3793. ScheduleGroupForFullUpdate();
  3794. }
  3795. else
  3796. {
  3797. ScheduleGroupForTerseUpdate();
  3798. }
  3799. }
  3800. #endregion
  3801. #region Rotation
  3802. /// <summary>
  3803. /// Update the rotation of the group.
  3804. /// </summary>
  3805. /// <param name="rot"></param>
  3806. public void UpdateGroupRotationR(Quaternion rot)
  3807. {
  3808. m_rootPart.UpdateRotation(rot);
  3809. /* this is done by rootpart RotationOffset set called by UpdateRotation
  3810. PhysicsActor actor = m_rootPart.PhysActor;
  3811. if (actor != null)
  3812. {
  3813. actor.Orientation = m_rootPart.RotationOffset;
  3814. m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
  3815. }
  3816. */
  3817. HasGroupChanged = true;
  3818. ScheduleGroupForTerseUpdate();
  3819. }
  3820. /// <summary>
  3821. /// Update the position and rotation of a group simultaneously.
  3822. /// </summary>
  3823. /// <param name="pos"></param>
  3824. /// <param name="rot"></param>
  3825. public void UpdateGroupRotationPR(Vector3 pos, Quaternion rot)
  3826. {
  3827. m_rootPart.UpdateRotation(rot);
  3828. PhysicsActor actor = m_rootPart.PhysActor;
  3829. if (actor != null)
  3830. {
  3831. actor.Orientation = m_rootPart.RotationOffset;
  3832. m_scene.PhysicsScene.AddPhysicsActorTaint(actor);
  3833. }
  3834. if (IsAttachment)
  3835. {
  3836. m_rootPart.AttachedPos = pos;
  3837. }
  3838. AbsolutePosition = pos;
  3839. HasGroupChanged = true;
  3840. ScheduleGroupForTerseUpdate();
  3841. }
  3842. /// <summary>
  3843. /// Update the rotation of a single prim within the group.
  3844. /// </summary>
  3845. /// <param name="rot"></param>
  3846. /// <param name="localID"></param>
  3847. public void UpdateSingleRotation(Quaternion rot, uint localID)
  3848. {
  3849. SceneObjectPart part = GetPart(localID);
  3850. SceneObjectPart[] parts = m_parts.GetArray();
  3851. if (part != null)
  3852. {
  3853. if (m_rootPart.PhysActor != null)
  3854. m_rootPart.PhysActor.Building = true;
  3855. if (part.UUID == m_rootPart.UUID)
  3856. {
  3857. UpdateRootRotation(rot);
  3858. }
  3859. else
  3860. {
  3861. part.UpdateRotation(rot);
  3862. }
  3863. if (m_rootPart.PhysActor != null)
  3864. m_rootPart.PhysActor.Building = false;
  3865. }
  3866. }
  3867. /// <summary>
  3868. /// Update the position and rotation simultaneously of a single prim within the group.
  3869. /// </summary>
  3870. /// <param name="rot"></param>
  3871. /// <param name="localID"></param>
  3872. public void UpdateSingleRotation(Quaternion rot, Vector3 pos, uint localID)
  3873. {
  3874. SceneObjectPart part = GetPart(localID);
  3875. if (part != null)
  3876. {
  3877. if (m_rootPart.PhysActor != null)
  3878. m_rootPart.PhysActor.Building = true;
  3879. if (part.UUID == m_rootPart.UUID)
  3880. {
  3881. UpdateRootRotation(rot);
  3882. AbsolutePosition = pos;
  3883. }
  3884. else
  3885. {
  3886. part.UpdateRotation(rot);
  3887. part.OffsetPosition = pos;
  3888. }
  3889. if (m_rootPart.PhysActor != null)
  3890. m_rootPart.PhysActor.Building = false;
  3891. }
  3892. }
  3893. /// <summary>
  3894. /// Update the rotation of just the root prim of a linkset.
  3895. /// </summary>
  3896. /// <param name="rot"></param>
  3897. public void UpdateRootRotation(Quaternion rot)
  3898. {
  3899. // needs to be called with phys building true
  3900. Quaternion axRot = rot;
  3901. Quaternion oldParentRot = m_rootPart.RotationOffset;
  3902. //Don't use UpdateRotation because it schedules an update prematurely
  3903. m_rootPart.RotationOffset = rot;
  3904. PhysicsActor pa = m_rootPart.PhysActor;
  3905. if (pa != null)
  3906. {
  3907. pa.Orientation = m_rootPart.RotationOffset;
  3908. m_scene.PhysicsScene.AddPhysicsActorTaint(pa);
  3909. }
  3910. SceneObjectPart[] parts = m_parts.GetArray();
  3911. for (int i = 0; i < parts.Length; i++)
  3912. {
  3913. SceneObjectPart prim = parts[i];
  3914. if (prim.UUID != m_rootPart.UUID)
  3915. {
  3916. Quaternion NewRot = oldParentRot * prim.RotationOffset;
  3917. NewRot = Quaternion.Inverse(axRot) * NewRot;
  3918. prim.RotationOffset = NewRot;
  3919. Vector3 axPos = prim.OffsetPosition;
  3920. axPos *= oldParentRot;
  3921. axPos *= Quaternion.Inverse(axRot);
  3922. prim.OffsetPosition = axPos;
  3923. }
  3924. }
  3925. HasGroupChanged = true;
  3926. ScheduleGroupForFullUpdate();
  3927. }
  3928. private enum updatetype :int
  3929. {
  3930. none = 0,
  3931. partterse = 1,
  3932. partfull = 2,
  3933. groupterse = 3,
  3934. groupfull = 4
  3935. }
  3936. public void doChangeObject(SceneObjectPart part, ObjectChangeData data)
  3937. {
  3938. // TODO this still as excessive *.Schedule*Update()s
  3939. if (part != null && part.ParentGroup != null)
  3940. {
  3941. ObjectChangeType change = data.change;
  3942. bool togroup = ((change & ObjectChangeType.Group) != 0);
  3943. // bool uniform = ((what & ObjectChangeType.UniformScale) != 0); not in use
  3944. SceneObjectGroup group = part.ParentGroup;
  3945. PhysicsActor pha = group.RootPart.PhysActor;
  3946. updatetype updateType = updatetype.none;
  3947. if (togroup)
  3948. {
  3949. // related to group
  3950. if ((change & (ObjectChangeType.Rotation | ObjectChangeType.Position)) != 0)
  3951. {
  3952. if ((change & ObjectChangeType.Rotation) != 0)
  3953. {
  3954. group.RootPart.UpdateRotation(data.rotation);
  3955. updateType = updatetype.none;
  3956. }
  3957. if ((change & ObjectChangeType.Position) != 0)
  3958. {
  3959. if (IsAttachment || m_scene.Permissions.CanObjectEntry(group, false, data.position))
  3960. UpdateGroupPosition(data.position);
  3961. updateType = updatetype.groupterse;
  3962. }
  3963. else
  3964. // ugly rotation update of all parts
  3965. {
  3966. group.ResetChildPrimPhysicsPositions();
  3967. }
  3968. }
  3969. if ((change & ObjectChangeType.Scale) != 0)
  3970. {
  3971. if (pha != null)
  3972. pha.Building = true;
  3973. group.GroupResize(data.scale);
  3974. updateType = updatetype.none;
  3975. if (pha != null)
  3976. pha.Building = false;
  3977. }
  3978. }
  3979. else
  3980. {
  3981. // related to single prim in a link-set ( ie group)
  3982. if (pha != null)
  3983. pha.Building = true;
  3984. // root part is special
  3985. // parts offset positions or rotations need to change also
  3986. if (part == group.RootPart)
  3987. {
  3988. if ((change & ObjectChangeType.Rotation) != 0)
  3989. group.UpdateRootRotation(data.rotation);
  3990. if ((change & ObjectChangeType.Position) != 0)
  3991. group.UpdateRootPosition(data.position);
  3992. if ((change & ObjectChangeType.Scale) != 0)
  3993. part.Resize(data.scale);
  3994. }
  3995. else
  3996. {
  3997. if ((change & ObjectChangeType.Position) != 0)
  3998. {
  3999. part.OffsetPosition = data.position;
  4000. updateType = updatetype.partterse;
  4001. }
  4002. if ((change & ObjectChangeType.Rotation) != 0)
  4003. {
  4004. part.UpdateRotation(data.rotation);
  4005. updateType = updatetype.none;
  4006. }
  4007. if ((change & ObjectChangeType.Scale) != 0)
  4008. {
  4009. part.Resize(data.scale);
  4010. updateType = updatetype.none;
  4011. }
  4012. }
  4013. if (pha != null)
  4014. pha.Building = false;
  4015. }
  4016. if (updateType != updatetype.none)
  4017. {
  4018. group.HasGroupChanged = true;
  4019. switch (updateType)
  4020. {
  4021. case updatetype.partterse:
  4022. part.ScheduleTerseUpdate();
  4023. break;
  4024. case updatetype.partfull:
  4025. part.ScheduleFullUpdate();
  4026. break;
  4027. case updatetype.groupterse:
  4028. group.ScheduleGroupForTerseUpdate();
  4029. break;
  4030. case updatetype.groupfull:
  4031. group.ScheduleGroupForFullUpdate();
  4032. break;
  4033. default:
  4034. break;
  4035. }
  4036. }
  4037. }
  4038. }
  4039. #endregion
  4040. internal void SetAxisRotation(int axis, int rotate10)
  4041. {
  4042. bool setX = ((axis & (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_X) != 0);
  4043. bool setY = ((axis & (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_Y) != 0);
  4044. bool setZ = ((axis & (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_Z) != 0);
  4045. if (setX || setY || setZ)
  4046. {
  4047. bool lockaxis = (rotate10 == 0); // zero means axis locked
  4048. byte locks = RootPart.RotationAxisLocks;
  4049. if (setX)
  4050. {
  4051. if(lockaxis)
  4052. locks |= (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_X;
  4053. else
  4054. locks &= (byte)SceneObjectGroup.axisSelect.NOT_STATUS_ROTATE_X;
  4055. }
  4056. if (setY)
  4057. {
  4058. if(lockaxis)
  4059. locks |= (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_Y;
  4060. else
  4061. locks &= (byte)SceneObjectGroup.axisSelect.NOT_STATUS_ROTATE_Y;
  4062. }
  4063. if (setZ)
  4064. {
  4065. if(lockaxis)
  4066. locks |= (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_Z;
  4067. else
  4068. locks &= (byte)SceneObjectGroup.axisSelect.NOT_STATUS_ROTATE_Z;
  4069. }
  4070. RootPart.RotationAxisLocks = locks;
  4071. RootPart.SetPhysicsAxisRotation();
  4072. }
  4073. }
  4074. public int GetAxisRotation(int axis)
  4075. {
  4076. byte rotAxislocks = RootPart.RotationAxisLocks;
  4077. // if multiple return the one with higher id
  4078. if (axis == (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_Z)
  4079. return (rotAxislocks & (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_Z) == 0 ? 1:0;
  4080. if (axis == (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_Y)
  4081. return (rotAxislocks & (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_Y) == 0 ? 1:0;
  4082. if (axis == (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_X)
  4083. return (rotAxislocks & (byte)SceneObjectGroup.axisSelect.STATUS_ROTATE_X) == 0 ? 1:0;
  4084. return 0;
  4085. }
  4086. public int registerRotTargetWaypoint(UUID scriptID, Quaternion target, float tolerance)
  4087. {
  4088. scriptRotTarget waypoint = new scriptRotTarget();
  4089. waypoint.targetRot = target;
  4090. waypoint.tolerance = tolerance;
  4091. waypoint.scriptID = scriptID;
  4092. int handle = m_scene.AllocateIntId();
  4093. waypoint.handle = handle;
  4094. lock (m_rotTargets)
  4095. {
  4096. if(m_targetsByScript.TryGetValue(scriptID, out List<int> handles))
  4097. {
  4098. if (handles.Count >= 8)
  4099. {
  4100. int todel = handles[0];
  4101. handles.RemoveAt(0);
  4102. m_rotTargets.Remove(todel);
  4103. }
  4104. handles.Add(handle);
  4105. }
  4106. else
  4107. m_targetsByScript[scriptID] = new List<int>(){handle};
  4108. m_rotTargets.Add(handle, waypoint);
  4109. }
  4110. m_scene.AddGroupTarget(this);
  4111. return handle;
  4112. }
  4113. public void unregisterRotTargetWaypoint(int handle)
  4114. {
  4115. lock (m_targets)
  4116. {
  4117. if(m_rotTargets.TryGetValue(handle, out scriptRotTarget waypoint))
  4118. {
  4119. if(m_targetsByScript.TryGetValue(waypoint.scriptID, out List<int>handles))
  4120. {
  4121. handles.Remove(handle);
  4122. if(handles.Count() == 0)
  4123. m_targetsByScript.Remove(waypoint.scriptID);
  4124. }
  4125. m_rotTargets.Remove(handle);
  4126. }
  4127. if (m_targets.Count == 0 && m_rotTargets.Count == 0)
  4128. m_scene.RemoveGroupTarget(this);
  4129. }
  4130. }
  4131. public int registerTargetWaypoint(UUID scriptID, Vector3 target, float tolerance)
  4132. {
  4133. scriptPosTarget waypoint = new scriptPosTarget();
  4134. waypoint.targetPos = target;
  4135. waypoint.tolerance = tolerance * tolerance;
  4136. waypoint.scriptID = scriptID;
  4137. int handle = m_scene.AllocateIntId();
  4138. waypoint.handle = handle;
  4139. lock (m_targets)
  4140. {
  4141. if (m_targetsByScript.TryGetValue(scriptID, out List<int> handles))
  4142. {
  4143. if (handles.Count >= 8)
  4144. {
  4145. int todel = handles[0];
  4146. handles.RemoveAt(0);
  4147. m_rotTargets.Remove(todel);
  4148. }
  4149. handles.Add(handle);
  4150. }
  4151. else
  4152. m_targetsByScript[scriptID] = new List<int>() { handle };
  4153. m_targets.Add(handle, waypoint);
  4154. }
  4155. m_scene.AddGroupTarget(this);
  4156. return handle;
  4157. }
  4158. public void unregisterTargetWaypoint(int handle)
  4159. {
  4160. lock (m_targets)
  4161. {
  4162. if (m_targets.TryGetValue(handle, out scriptPosTarget waypoint))
  4163. {
  4164. if (m_targetsByScript.TryGetValue(waypoint.scriptID, out List<int> handles))
  4165. {
  4166. handles.Remove(handle);
  4167. if (handles.Count() == 0)
  4168. m_targetsByScript.Remove(waypoint.scriptID);
  4169. }
  4170. m_targets.Remove(handle);
  4171. }
  4172. if (m_targets.Count == 0 && m_rotTargets.Count == 0)
  4173. m_scene.RemoveGroupTarget(this);
  4174. }
  4175. }
  4176. public void RemoveScriptTargets(UUID scriptID)
  4177. {
  4178. lock (m_targets)
  4179. {
  4180. if(m_targetsByScript.TryGetValue(scriptID, out List<int> toremove))
  4181. {
  4182. if (toremove.Count > 0)
  4183. {
  4184. for (int i = 0; i < toremove.Count; ++i)
  4185. {
  4186. m_targets.Remove(toremove[i]);
  4187. m_rotTargets.Remove(toremove[i]);
  4188. }
  4189. }
  4190. m_targetsByScript.Remove(scriptID);
  4191. }
  4192. if (m_targets.Count == 0 && m_rotTargets.Count == 0)
  4193. m_scene.RemoveGroupTarget(this);
  4194. }
  4195. }
  4196. public void checkAtTargets()
  4197. {
  4198. int targetsCount = m_targets.Count;
  4199. if (targetsCount > 0 && (m_scriptListens_atTarget || m_scriptListens_notAtTarget))
  4200. {
  4201. List<scriptPosTarget> atTargets = new List<scriptPosTarget>();
  4202. HashSet<UUID> notatTargets = new HashSet<UUID>();
  4203. Vector3 pos = m_rootPart.GroupPosition;
  4204. lock (m_targets)
  4205. {
  4206. foreach (scriptPosTarget target in m_targets.Values)
  4207. {
  4208. if (Vector3.DistanceSquared(target.targetPos, pos) <= target.tolerance)
  4209. {
  4210. if (m_scriptListens_atTarget)
  4211. atTargets.Add(target);
  4212. notatTargets.Remove(target.scriptID);
  4213. }
  4214. else
  4215. {
  4216. if (m_scriptListens_notAtTarget)
  4217. notatTargets.Add(target.scriptID);
  4218. }
  4219. }
  4220. }
  4221. if (atTargets.Count > 0)
  4222. {
  4223. for (int target = 0; target < atTargets.Count; ++target)
  4224. {
  4225. scriptPosTarget att = atTargets[target];
  4226. m_scene.EventManager.TriggerAtTargetEvent(att.scriptID, (uint)att.handle, att.targetPos, pos);
  4227. }
  4228. }
  4229. if (notatTargets.Count > 0)
  4230. {
  4231. foreach (UUID id in notatTargets)
  4232. {
  4233. m_scene.EventManager.TriggerNotAtTargetEvent(id);
  4234. }
  4235. }
  4236. }
  4237. targetsCount = m_rotTargets.Count;
  4238. if (targetsCount > 0 && (m_scriptListens_atRotTarget || m_scriptListens_notAtRotTarget))
  4239. {
  4240. List<scriptRotTarget> atRotTargets = new List<scriptRotTarget>(targetsCount);
  4241. HashSet<UUID> notatRotTargets = new HashSet<UUID>();
  4242. Quaternion rot = m_rootPart.RotationOffset;
  4243. lock (m_rotTargets)
  4244. {
  4245. foreach (scriptRotTarget target in m_rotTargets.Values)
  4246. {
  4247. double angle = 2 * Math.Acos(Quaternion.Dot(target.targetRot, rot));
  4248. if (angle < 0)
  4249. angle = -angle;
  4250. if (angle > Math.PI)
  4251. angle = (2 * Math.PI - angle);
  4252. if (angle <= target.tolerance)
  4253. {
  4254. if (m_scriptListens_atRotTarget)
  4255. atRotTargets.Add(target);
  4256. notatRotTargets.Remove(target.scriptID);
  4257. }
  4258. else
  4259. {
  4260. if (m_scriptListens_notAtRotTarget)
  4261. notatRotTargets.Add(target.scriptID);
  4262. }
  4263. }
  4264. }
  4265. if (atRotTargets.Count > 0)
  4266. {
  4267. for (int target = 0; target < atRotTargets.Count; ++target)
  4268. {
  4269. scriptRotTarget att = atRotTargets[target];
  4270. m_scene.EventManager.TriggerAtRotTargetEvent(att.scriptID, (uint)att.handle, att.targetRot, rot);
  4271. }
  4272. }
  4273. if (notatRotTargets.Count > 0)
  4274. {
  4275. foreach (UUID id in notatRotTargets)
  4276. {
  4277. m_scene.EventManager.TriggerNotAtRotTargetEvent(id);
  4278. }
  4279. }
  4280. }
  4281. }
  4282. public Vector3 GetGeometricCenter()
  4283. {
  4284. // this is not real geometric center but a average of positions relative to root prim acording to
  4285. // http://wiki.secondlife.com/wiki/llGetGeometricCenter
  4286. // ignoring tortured prims details since sl also seems to ignore
  4287. // so no real use in doing it on physics
  4288. Vector3 gc = Vector3.Zero;
  4289. SceneObjectPart[] parts = m_parts.GetArray();
  4290. int nparts = parts.Length;
  4291. if (nparts < 2)
  4292. return gc;
  4293. // average all parts positions
  4294. for (int i = 0; i < nparts; i++)
  4295. {
  4296. if (parts[i] != RootPart)
  4297. gc += parts[i].OffsetPosition;
  4298. }
  4299. gc /= nparts;
  4300. return gc;
  4301. }
  4302. public float GetMass()
  4303. {
  4304. float retmass = 0f;
  4305. SceneObjectPart[] parts = m_parts.GetArray();
  4306. for (int i = 0; i < parts.Length; i++)
  4307. retmass += parts[i].GetMass();
  4308. return retmass;
  4309. }
  4310. // center of mass of full object
  4311. public Vector3 GetCenterOfMass()
  4312. {
  4313. PhysicsActor pa = RootPart.PhysActor;
  4314. if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
  4315. {
  4316. // physics knows better about center of mass of physical prims
  4317. Vector3 tmp = pa.CenterOfMass;
  4318. return tmp;
  4319. }
  4320. Vector3 Ptot = Vector3.Zero;
  4321. float totmass = 0f;
  4322. float m;
  4323. SceneObjectPart[] parts = m_parts.GetArray();
  4324. for (int i = 0; i < parts.Length; i++)
  4325. {
  4326. m = parts[i].GetMass();
  4327. Ptot += parts[i].GetPartCenterOfMass() * m;
  4328. totmass += m;
  4329. }
  4330. if (totmass == 0)
  4331. totmass = 0;
  4332. else
  4333. totmass = 1 / totmass;
  4334. Ptot *= totmass;
  4335. return Ptot;
  4336. }
  4337. public void GetInertiaData(out float TotalMass, out Vector3 CenterOfMass, out Vector3 Inertia, out Vector4 aux )
  4338. {
  4339. PhysicsActor pa = RootPart.PhysActor;
  4340. if(((RootPart.Flags & PrimFlags.Physics) !=0) && pa !=null)
  4341. {
  4342. PhysicsInertiaData inertia;
  4343. inertia = pa.GetInertiaData();
  4344. TotalMass = inertia.TotalMass;
  4345. CenterOfMass = inertia.CenterOfMass;
  4346. Inertia = inertia.Inertia;
  4347. aux = inertia.InertiaRotation;
  4348. return;
  4349. }
  4350. TotalMass = GetMass();
  4351. CenterOfMass = GetCenterOfMass() - AbsolutePosition;
  4352. CenterOfMass *= Quaternion.Conjugate(RootPart.RotationOffset);
  4353. Inertia = Vector3.Zero;
  4354. aux = Vector4.Zero;
  4355. }
  4356. public void SetInertiaData(float TotalMass, Vector3 CenterOfMass, Vector3 Inertia, Vector4 aux )
  4357. {
  4358. PhysicsInertiaData inertia = new PhysicsInertiaData();
  4359. inertia.TotalMass = TotalMass;
  4360. inertia.CenterOfMass = CenterOfMass;
  4361. inertia.Inertia = Inertia;
  4362. inertia.InertiaRotation = aux;
  4363. if(TotalMass < 0)
  4364. RootPart.PhysicsInertia = null;
  4365. else
  4366. RootPart.PhysicsInertia = new PhysicsInertiaData(inertia);
  4367. PhysicsActor pa = RootPart.PhysActor;
  4368. if(pa !=null)
  4369. pa.SetInertiaData(inertia);
  4370. }
  4371. /// <summary>
  4372. /// Set the user group to which this scene object belongs.
  4373. /// </summary>
  4374. /// <param name="GroupID"></param>
  4375. /// <param name="client"></param>
  4376. public void SetGroup(UUID GroupID, IClientAPI client)
  4377. {
  4378. SceneObjectPart[] parts = m_parts.GetArray();
  4379. for (int i = 0; i < parts.Length; i++)
  4380. {
  4381. SceneObjectPart part = parts[i];
  4382. part.SetGroup(GroupID, client);
  4383. part.Inventory.ChangeInventoryGroup(GroupID);
  4384. }
  4385. HasGroupChanged = true;
  4386. // Don't trigger the update here - otherwise some client issues occur when multiple updates are scheduled
  4387. // for the same object with very different properties. The caller must schedule the update.
  4388. //ScheduleGroupForFullUpdate();
  4389. }
  4390. public void TriggerScriptChangedEvent(Changed val)
  4391. {
  4392. SceneObjectPart[] parts = m_parts.GetArray();
  4393. for (int i = 0; i < parts.Length; i++)
  4394. parts[i].TriggerScriptChangedEvent(val);
  4395. }
  4396. /// <summary>
  4397. /// Returns a count of the number of scripts in this groups parts.
  4398. /// </summary>
  4399. public int ScriptCount()
  4400. {
  4401. int count = 0;
  4402. SceneObjectPart[] parts = m_parts.GetArray();
  4403. for (int i = 0; i < parts.Length; i++)
  4404. count += parts[i].Inventory.ScriptCount();
  4405. return count;
  4406. }
  4407. /// <summary>
  4408. /// A float the value is a representative execution time in milliseconds of all scripts in the link set.
  4409. /// </summary>
  4410. public float ScriptExecutionTime()
  4411. {
  4412. IScriptModule[] engines = Scene.RequestModuleInterfaces<IScriptModule>();
  4413. if (engines.Length == 0) // No engine at all
  4414. return 0.0f;
  4415. float time = 0.0f;
  4416. // get all the scripts in all parts
  4417. SceneObjectPart[] parts = m_parts.GetArray();
  4418. List<TaskInventoryItem> scripts = new List<TaskInventoryItem>();
  4419. for (int i = 0; i < parts.Length; i++)
  4420. {
  4421. scripts.AddRange(parts[i].Inventory.GetInventoryItems(InventoryType.LSL));
  4422. }
  4423. // extract the UUIDs
  4424. List<UUID> ids = new List<UUID>(scripts.Count);
  4425. foreach (TaskInventoryItem script in scripts)
  4426. {
  4427. if (!ids.Contains(script.ItemID))
  4428. {
  4429. ids.Add(script.ItemID);
  4430. }
  4431. }
  4432. // Offer the list of script UUIDs to each engine found and accumulate the time
  4433. foreach (IScriptModule e in engines)
  4434. {
  4435. if (e != null)
  4436. {
  4437. time += e.GetScriptExecutionTime(ids);
  4438. }
  4439. }
  4440. return time;
  4441. }
  4442. /// <summary>
  4443. /// Returns a count of the number of running scripts in this groups parts.
  4444. /// </summary>
  4445. public int RunningScriptCount()
  4446. {
  4447. int count = 0;
  4448. SceneObjectPart[] parts = m_parts.GetArray();
  4449. for (int i = 0; i < parts.Length; i++)
  4450. count += parts[i].Inventory.RunningScriptCount();
  4451. return count;
  4452. }
  4453. /// <summary>
  4454. /// Get a copy of the list of sitting avatars on all prims of this object.
  4455. /// </summary>
  4456. /// <remarks>
  4457. /// This is sorted by the order in which avatars sat down. If an avatar stands up then all avatars that sat
  4458. /// down after it move one place down the list.
  4459. /// </remarks>
  4460. /// <returns>A list of the sitting avatars. Returns an empty list if there are no sitting avatars.</returns>
  4461. public List<ScenePresence> GetSittingAvatars()
  4462. {
  4463. lock (m_sittingAvatars)
  4464. return new List<ScenePresence>(m_sittingAvatars);
  4465. }
  4466. /// <summary>
  4467. /// Gets the number of sitting avatars.
  4468. /// </summary>
  4469. /// <remarks>This applies to all sitting avatars whether there is a sit target set or not.</remarks>
  4470. /// <returns></returns>
  4471. public int GetSittingAvatarsCount()
  4472. {
  4473. lock (m_sittingAvatars)
  4474. return m_sittingAvatars.Count;
  4475. }
  4476. public override string ToString()
  4477. {
  4478. return String.Format("{0} {1} ({2})", Name, UUID, AbsolutePosition);
  4479. }
  4480. #region ISceneObject
  4481. public virtual ISceneObject CloneForNewScene()
  4482. {
  4483. SceneObjectGroup sog = Copy(false);
  4484. sog.IsDeleted = false;
  4485. return sog;
  4486. }
  4487. public virtual string ToXml2()
  4488. {
  4489. return SceneObjectSerializer.ToXml2Format(this);
  4490. }
  4491. public virtual string ExtraToXmlString()
  4492. {
  4493. return "<ExtraFromItemID>" + FromItemID.ToString() + "</ExtraFromItemID>";
  4494. }
  4495. public virtual void ExtraFromXmlString(string xmlstr)
  4496. {
  4497. string id = xmlstr.Substring(xmlstr.IndexOf("<ExtraFromItemID>"));
  4498. id = xmlstr.Replace("<ExtraFromItemID>", "");
  4499. id = id.Replace("</ExtraFromItemID>", "");
  4500. UUID uuid = UUID.Zero;
  4501. UUID.TryParse(id, out uuid);
  4502. FromItemID = uuid;
  4503. }
  4504. public void ResetOwnerChangeFlag()
  4505. {
  4506. ForEachPart(delegate(SceneObjectPart part)
  4507. {
  4508. part.ResetOwnerChangeFlag();
  4509. });
  4510. InvalidateEffectivePerms();
  4511. }
  4512. private Dictionary<string,int> m_partsNameToLinkMap = new Dictionary<string, int>();
  4513. private string GetLinkNumber_lastname;
  4514. private int GetLinkNumber_lastnumber;
  4515. public int GetLinkNumber(string name)
  4516. {
  4517. if(String.IsNullOrEmpty(name) || name == "Object" || name == "Primitive")
  4518. return -1;
  4519. lock(m_partsNameToLinkMap)
  4520. {
  4521. if (name == GetLinkNumber_lastname)
  4522. return GetLinkNumber_lastnumber;
  4523. if (m_partsNameToLinkMap.Count == 0)
  4524. {
  4525. GetLinkNumber_lastname = String.Empty;
  4526. GetLinkNumber_lastnumber = -1;
  4527. SceneObjectPart[] parts = m_parts.GetArray();
  4528. for (int i = 0; i < parts.Length; i++)
  4529. {
  4530. string s = parts[i].Name;
  4531. if(String.IsNullOrEmpty(s) || s == "Object" || s == "Primitive")
  4532. continue;
  4533. if(m_partsNameToLinkMap.ContainsKey(s))
  4534. {
  4535. int ol = parts[i].LinkNum;
  4536. if(ol < m_partsNameToLinkMap[s])
  4537. m_partsNameToLinkMap[s] = ol;
  4538. }
  4539. else
  4540. m_partsNameToLinkMap[s] = parts[i].LinkNum;
  4541. }
  4542. }
  4543. if(m_partsNameToLinkMap.ContainsKey(name))
  4544. {
  4545. GetLinkNumber_lastname = name;
  4546. GetLinkNumber_lastnumber = m_partsNameToLinkMap[name];
  4547. return GetLinkNumber_lastnumber;
  4548. }
  4549. }
  4550. if(m_sittingAvatars.Count > 0)
  4551. {
  4552. int j = m_parts.Count + 1;
  4553. ScenePresence[] avs = m_sittingAvatars.ToArray();
  4554. for (int i = 0; i < avs.Length; i++, j++)
  4555. {
  4556. if (avs[i].Name == name)
  4557. {
  4558. GetLinkNumber_lastname = name;
  4559. GetLinkNumber_lastnumber = j;
  4560. return j;
  4561. }
  4562. }
  4563. }
  4564. return -1;
  4565. }
  4566. public void InvalidatePartsLinkMaps(bool all = true)
  4567. {
  4568. lock(m_partsNameToLinkMap)
  4569. {
  4570. if(all)
  4571. m_partsNameToLinkMap.Clear();
  4572. GetLinkNumber_lastname = String.Empty;
  4573. GetLinkNumber_lastnumber = -1;
  4574. }
  4575. }
  4576. public bool CollisionSoundThrottled(int collisionSoundType)
  4577. {
  4578. double time = m_lastCollisionSoundMS;
  4579. // m_lastCollisionSoundMS = Util.GetTimeStampMS();
  4580. // time = m_lastCollisionSoundMS - time;
  4581. double now = Util.GetTimeStampMS();
  4582. time = now - time;
  4583. switch (collisionSoundType)
  4584. {
  4585. case 0: // default sounds
  4586. case 2: // default sounds with volume set by script
  4587. if(time < 300.0)
  4588. return true;
  4589. break;
  4590. case 1: // selected sound
  4591. if(time < 200.0)
  4592. return true;
  4593. break;
  4594. default:
  4595. break;
  4596. }
  4597. m_lastCollisionSoundMS = now;
  4598. return false;
  4599. }
  4600. #endregion
  4601. }
  4602. }