SceneObjectGroup.cs 193 KB

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