SceneObjectGroup.cs 193 KB

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