SceneObjectGroup.cs 195 KB

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