SceneObjectGroup.cs 197 KB

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