aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/Framework/Scenes/SceneObjectPart.cs
blob: 2c183ad241129927b80b1b2a9299c6e3afde2d7c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
/*
 * Copyright (c) Contributors, http://opensimulator.org/
 * See CONTRIBUTORS.TXT for a full list of copyright holders.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSimulator Project nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Xml;
using System.Xml.Serialization;
using log4net;
using OpenMetaverse;
using OpenMetaverse.Packets;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes.Scripting;
using OpenSim.Region.Framework.Scenes.Serialization;
using OpenSim.Region.PhysicsModules.SharedBase;
using PermissionMask = OpenSim.Framework.PermissionMask;

namespace OpenSim.Region.Framework.Scenes
{
    #region Enumerations

    [Flags]
    public enum Changed : uint
    {
        INVENTORY = 1,
        COLOR = 2,
        SHAPE = 4,
        SCALE = 8,
        TEXTURE = 16,
        LINK = 32,
        ALLOWED_DROP = 64,
        OWNER = 128,
        REGION = 256,
        TELEPORT = 512,
        REGION_RESTART = 1024,
        MEDIA = 2048,
        ANIMATION = 16384,
        POSITION = 32768
    }

    // I don't really know where to put this except here.
    // Can't access the OpenSim.Region.ScriptEngine.Common.LSL_BaseClass.Changed constants
    [Flags]
    public enum ExtraParamType
    {
        Something1 = 1,
        Something2 = 2,
        Something3 = 4,
        Something4 = 8,
        Flexible = 16,
        Light = 32,
        Sculpt = 48,
        Something5 = 64,
        Something6 = 128
    }

    [Flags]
    public enum TextureAnimFlags : byte
    {
        NONE = 0x00,
        ANIM_ON = 0x01,
        LOOP = 0x02,
        REVERSE = 0x04,
        PING_PONG = 0x08,
        SMOOTH = 0x10,
        ROTATE = 0x20,
        SCALE = 0x40
    }

    public enum PrimType : int
    {
        BOX = 0,
        CYLINDER = 1,
        PRISM = 2,
        SPHERE = 3,
        TORUS = 4,
        TUBE = 5,
        RING = 6,
        SCULPT = 7
    }

    public enum UpdateRequired : byte
    {
        NONE = 0,
        TERSE = 1,
        FULL = 2
    }

    #endregion Enumerations

    public class SceneObjectPart : ISceneEntity
    {
        /// <value>
        /// Denote all sides of the prim
        /// </value>
        public const int ALL_SIDES = -1;

        private const scriptEvents PhysicsNeededSubsEvents = (
                    scriptEvents.collision | scriptEvents.collision_start | scriptEvents.collision_end |
                    scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end
                    );
        private const scriptEvents PhyscicsPhantonSubsEvents = (
                    scriptEvents.land_collision | scriptEvents.land_collision_start | scriptEvents.land_collision_end
                    );
        private const scriptEvents PhyscicsVolumeDtcSubsEvents = (
                    scriptEvents.collision_start | scriptEvents.collision_end
                    );

        private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Dynamic attributes can be created and deleted as required.
        /// </summary>
        public DAMap DynAttrs { get; set; }

        private DOMap m_dynObjs;

        /// <summary>
        /// Dynamic objects that can be created and deleted as required.
        /// </summary>
        public DOMap DynObjs
        {
            get
            {
                if (m_dynObjs == null)
                    m_dynObjs = new DOMap();

                return m_dynObjs;
            }

            set
            {
                m_dynObjs = value;
            }
        }

        /// <value>
        /// Is this a root part?
        /// </value>
        /// <remarks>
        /// This will return true even if the whole object is attached to an avatar.
        /// </remarks>
        public bool IsRoot
        {
            get { return Object.ReferenceEquals(ParentGroup.RootPart, this); }
        }

        /// <summary>
        /// Is an explicit sit target set for this part?
        /// </summary>
        public bool IsSitTargetSet
        {
            get
            {
                return
                    !(SitTargetPosition == Vector3.Zero
                      && (SitTargetOrientation == Quaternion.Identity // Valid Zero Rotation quaternion
                       || (SitTargetOrientation.W == 0f && SitTargetOrientation.X == 0f && SitTargetOrientation.Y == 0f && SitTargetOrientation.Z == 0f ))); // Invalid Quaternion
            }
        }

        #region Fields

        public bool AllowedDrop;

        public bool DIE_AT_EDGE;

        public bool RETURN_AT_EDGE;

        public bool BlockGrab { get; set; }

        public bool StatusSandbox;

        public Vector3 StatusSandboxPos;

        [XmlIgnore]
        public int[] PayPrice = {-2,-2,-2,-2,-2};

        [XmlIgnore]
        /// <summary>
        /// The representation of this part in the physics scene.
        /// </summary>
        /// <remarks>
        /// If you use this property more than once in a section of code then you must take a reference and use that.
        /// If another thread is simultaneously turning physics off on this part then this refernece could become
        /// null at any time.
        /// </remarks>
        public PhysicsActor PhysActor { get; set; }

        //Xantor 20080528 Sound stuff:
        //  Note: This isn't persisted in the database right now, as the fields for that aren't just there yet.
        //        Not a big problem as long as the script that sets it remains in the prim on startup.
        //        for SL compatibility it should be persisted though (set sound / displaytext / particlesystem, kill script)

        public UUID Sound;

        public byte SoundFlags;

        public double SoundGain;

        public double SoundRadius;

        /// <summary>
        /// Should sounds played from this prim be queued?
        /// </summary>
        /// <remarks>
        /// This should only be changed by sound modules.  It is up to sound modules as to how they interpret this setting.
        /// </remarks>
        public bool SoundQueueing { get; set; }

        [XmlIgnore]
        public Quaternion AttachRotation = Quaternion.Identity;

        [XmlIgnore]
        public int STATUS_ROTATE_X; // this should not be used

        [XmlIgnore]
        public int STATUS_ROTATE_Y;  // this should not be used

        [XmlIgnore]
        public int STATUS_ROTATE_Z;  // this should not be used

        private Dictionary<int, string> m_CollisionFilter = new Dictionary<int, string>();

        /// <value>
        /// The UUID of the user inventory item from which this object was rezzed if this is a root part.
        /// If UUID.Zero then either this is not a root part or there is no connection with a user inventory item.
        /// </value>
        private UUID m_fromUserInventoryItemID;

        public UUID FromUserInventoryItemID
        {
            get { return m_fromUserInventoryItemID; }
            set { m_fromUserInventoryItemID = value; }
        }

        public scriptEvents AggregateScriptEvents;

        public Vector3 AttachedPos
        {
            get;
            set;
        }

        // rotation locks on local X,Y and or Z axis bit flags
        // bits are as in llSetStatus defined in SceneObjectGroup.axisSelect enum
        // but reversed logic: bit cleared means free to rotate
        public byte RotationAxisLocks = 0;

        // WRONG flag in libOmvPrimFlags
        private const uint primFlagVolumeDetect = (uint)PrimFlags.JointLP2P;

        public bool VolumeDetectActive
        {
            get
            {
                return (Flags & (PrimFlags)primFlagVolumeDetect) != 0;
            }
            set
            {
                if(value)
                    Flags |= (PrimFlags)primFlagVolumeDetect;
                else
                    Flags &= (PrimFlags)(~primFlagVolumeDetect);
            }
        }

        public bool IsWaitingForFirstSpinUpdatePacket;

        public Quaternion SpinOldOrientation = Quaternion.Identity;

        protected bool m_APIDActive = false;
        protected Quaternion m_APIDTarget = Quaternion.Identity;
        protected float m_APIDDamp = 0;
        protected float m_APIDStrength = 0;

        /// <summary>
        /// This part's inventory
        /// </summary>
        public IEntityInventory Inventory
        {
            get { return m_inventory; }
        }
        protected SceneObjectPartInventory m_inventory;

        public bool Undoing;

        public bool IgnoreUndoUpdate = false;

        public PrimFlags LocalFlags;

        private float m_damage = -1.0f;
        private byte[] m_TextureAnimation;
        private byte m_clickAction;
        private Color m_color = Color.Black;
        private List<uint> m_lastColliders = new List<uint>();
        private bool m_lastLandCollide;
        private int m_linkNum;

        private int m_scriptAccessPin;

        private readonly Dictionary<UUID, scriptEvents> m_scriptEvents = new Dictionary<UUID, scriptEvents>();
        private string m_sitName = String.Empty;
        private Quaternion m_sitTargetOrientation = Quaternion.Identity;
        private Vector3 m_sitTargetPosition;
        private string m_sitAnimation = "SIT";
        private bool m_occupied;					// KF if any av is sitting on this prim
        private string m_text = String.Empty;
        private string m_touchName = String.Empty;
        private UndoRedoState m_UndoRedo = null;
        private object m_UndoLock = new object();

        private bool m_passTouches = false;
        private bool m_passCollisions = false;

        protected Vector3 m_acceleration;
        protected Vector3 m_angularVelocity;

        //unkown if this will be kept, added as a way of removing the group position from the group class
        protected Vector3 m_groupPosition;
        protected uint m_localId;
        protected Material m_material = OpenMetaverse.Material.Wood;
        protected string m_name;
        protected Vector3 m_offsetPosition;

        protected SceneObjectGroup m_parentGroup;
        protected byte[] m_particleSystem = Utils.EmptyBytes;
        protected ulong m_regionHandle;
        protected Quaternion m_rotationOffset = Quaternion.Identity;
        protected PrimitiveBaseShape m_shape;
        protected UUID m_uuid;
        protected Vector3 m_velocity;

        protected Vector3 m_lastPosition;
        protected Quaternion m_lastRotation;
        protected Vector3 m_lastVelocity;
        protected Vector3 m_lastAcceleration; // acceleration is a derived var with high noise
        protected Vector3 m_lastAngularVelocity;
        protected double m_lastUpdateSentTime;
        protected float m_buoyancy = 0.0f;
        protected Vector3 m_force;
        protected Vector3 m_torque;

        protected byte m_physicsShapeType = (byte)PhysShapeType.prim;
        protected float m_density = 1000.0f; // in kg/m^3
        protected float m_gravitymod = 1.0f;
        protected float m_friction = 0.6f; // wood
        protected float m_bounce = 0.5f; // wood


        protected bool m_isSelected = false;

        /// <summary>
        /// Stores media texture data
        /// </summary>
        protected string m_mediaUrl;

        // TODO: Those have to be changed into persistent properties at some later point,
        // or sit-camera on vehicles will break on sim-crossing.
        private Vector3 m_cameraEyeOffset;
        private Vector3 m_cameraAtOffset;
        private bool m_forceMouselook;


        // 0 for default collision sounds, -1 for script disabled sound 1 for script defined sound
        private sbyte m_collisionSoundType = 0;
        private UUID m_collisionSound;
        private float m_collisionSoundVolume;

        private int LastColSoundSentTime;

        private SOPVehicle m_vehicleParams = null;

        private PhysicsInertiaData m_physicsInertia;

        public KeyframeMotion KeyframeMotion
        {
            get; set;
        }


        #endregion Fields

//        ~SceneObjectPart()
//        {
//            Console.WriteLine(
//                "[SCENE OBJECT PART]: Destructor called for {0}, local id {1}, parent {2} {3}",
//                Name, LocalId, ParentGroup.Name, ParentGroup.LocalId);
//            m_log.DebugFormat(
//                "[SCENE OBJECT PART]: Destructor called for {0}, local id {1}, parent {2} {3}",
//                Name, LocalId, ParentGroup.Name, ParentGroup.LocalId);
//        }

        #region Constructors

        /// <summary>
        /// No arg constructor called by region restore db code
        /// </summary>
        public SceneObjectPart()
        {
            m_TextureAnimation = Utils.EmptyBytes;
            m_particleSystem = Utils.EmptyBytes;
            Rezzed = DateTime.UtcNow;
            Description = String.Empty;
            DynAttrs = new DAMap();

            // Prims currently only contain a single folder (Contents).  From looking at the Second Life protocol,
            // this appears to have the same UUID (!) as the prim.  If this isn't the case, one can't drag items from
            // the prim into an agent inventory (Linden client reports that the "Object not found for drop" in its log
            m_inventory = new SceneObjectPartInventory(this);
            LastColSoundSentTime = Util.EnvironmentTickCount();
        }

        /// <summary>
        /// Create a completely new SceneObjectPart (prim).  This will need to be added separately to a SceneObjectGroup
        /// </summary>
        /// <param name="ownerID"></param>
        /// <param name="shape"></param>
        /// <param name="position"></param>
        /// <param name="rotationOffset"></param>
        /// <param name="offsetPosition"></param>
        public SceneObjectPart(
            UUID ownerID, PrimitiveBaseShape shape, Vector3 groupPosition,
            Quaternion rotationOffset, Vector3 offsetPosition) : this()
        {
            m_name = "Object";

            CreationDate = (int)Utils.DateTimeToUnixTime(Rezzed);
            RezzerID = LastOwnerID = CreatorID = OwnerID = ownerID;
            UUID = UUID.Random();
            Shape = shape;
            OwnershipCost = 0;
            ObjectSaleType = 0;
            SalePrice = 0;
            Category = 0;
            GroupPosition = groupPosition;
            OffsetPosition = offsetPosition;
            RotationOffset = rotationOffset;
            Velocity = Vector3.Zero;
            AngularVelocity = Vector3.Zero;
            Acceleration = Vector3.Zero;
            APIDActive = false;
            Flags = 0;
            CreateSelected = true;
            TrimPermissions();
            AggregateInnerPerms();
        }

        #endregion Constructors

        #region XML Schema

        private UUID _rezzerID;
        private UUID _lastOwnerID;
        private UUID _ownerID;
        private UUID _groupID;
        private int _ownershipCost;
        private byte _objectSaleType;
        private int _salePrice;
        private uint _category;
        private Int32 _creationDate;
        private uint _parentID = 0;
        private uint _baseMask = (uint)(PermissionMask.All | PermissionMask.Export);
        private uint _ownerMask = (uint)(PermissionMask.All | PermissionMask.Export);
        private uint _groupMask = (uint)PermissionMask.None;
        private uint _everyoneMask = (uint)PermissionMask.None;
        private uint _nextOwnerMask = (uint)(PermissionMask.Move | PermissionMask.Transfer);
        private PrimFlags _flags = PrimFlags.None;
        private DateTime m_expires;
        private DateTime m_rezzed;
        private bool m_createSelected = false;

        private UUID _creatorID;
        public UUID CreatorID
        {
            get { return _creatorID; }
            set { _creatorID = value; }
        }

        private string m_creatorData = string.Empty;
        /// <summary>
        /// Data about the creator in the form home_url;name
        /// </summary>
        public string CreatorData
        {
            get { return m_creatorData; }
            set { m_creatorData = value; }
        }

        /// <summary>
        /// Used by the DB layer to retrieve / store the entire user identification.
        /// The identification can either be a simple UUID or a string of the form
        /// uuid[;home_url[;name]]
        /// </summary>
        public string CreatorIdentification
        {
            get
            {
                if (!string.IsNullOrEmpty(CreatorData))
                    return CreatorID.ToString() + ';' + CreatorData;
                else
                    return CreatorID.ToString();
            }
            set
            {
                CreatorData = string.Empty;
                if ((value == null) || (value != null && value == string.Empty))
                    return;

                // value is uuid  or uuid;homeuri;firstname lastname
                string[] parts = value.Split(';');
                if (parts.Length > 0)
                {

                    UUID uuid = UUID.Zero;
                    UUID.TryParse(parts[0], out uuid);
                    CreatorID = uuid;

                    if (parts.Length > 1)
                    {
                        CreatorData = parts[1];
                        if (!CreatorData.EndsWith("/"))
                            CreatorData += "/";
                        if (parts.Length > 2)
                            CreatorData += ';' + parts[2];
                        else
                            CreatorData += ";Unknown User";
                    }
                }
            }
        }

        /// <summary>
        /// A relic from when we we thought that prims contained folder objects. In
        /// reality, prim == folder
        /// Exposing this is not particularly good, but it's one of the least evils at the moment to see
        /// folder id from prim inventory item data, since it's not (yet) actually stored with the prim.
        /// </summary>
        public UUID FolderID
        {
            get { return UUID; }
            set { } // Don't allow assignment, or legacy prims wil b0rk - but we need the setter for legacy serialization.
        }

        /// <value>
        /// Access should be via Inventory directly - this property temporarily remains for xml serialization purposes
        /// </value>
        public uint InventorySerial
        {
            get { return m_inventory.Serial; }
            set { m_inventory.Serial = value; }
        }

        /// <value>
        /// Get the inventory list
        /// </value>
        public TaskInventoryDictionary TaskInventory
        {
            get {
                return m_inventory.Items;
            }
            set {
                m_inventory.Items = value;
            }
        }

        /// <summary>
        /// This is idential to the Flags property, except that the returned value is uint rather than PrimFlags
        /// </summary>
        [Obsolete("Use Flags property instead")]
        public uint ObjectFlags
        {
            get { return (uint)Flags; }
            set { Flags = (PrimFlags)value; }
        }

        public UUID UUID
        {
            get { return m_uuid; }
            set
            {
                m_uuid = value;

                // This is necessary so that TaskInventoryItem parent ids correctly reference the new uuid of this part
                if (Inventory != null)
                    Inventory.ResetObjectID();
            }
        }

        public uint LocalId
        {
            get { return m_localId; }
            set
            {
                m_localId = value;
//                m_log.DebugFormat("[SCENE OBJECT PART]: Set part {0} to local id {1}", Name, m_localId);
            }
        }

        public virtual string Name
        {
            get { return m_name; }
            set
            {
                m_name = value;
                if(ParentGroup != null)
                    ParentGroup.InvalidatePartsLinkMaps();

                PhysicsActor pa = PhysActor;

                if (pa != null)
                    pa.SOPName = value;
            }
        }

        [XmlIgnore]
        public bool PassTouches
        {
            get { return m_passTouches; }
            set
            {
                m_passTouches = value;

                if (ParentGroup != null)
                    ParentGroup.HasGroupChanged = true;
            }
        }

        public bool PassCollisions
        {
            get { return m_passCollisions; }
            set
            {
                m_passCollisions = value;

                if (ParentGroup != null)
                    ParentGroup.HasGroupChanged = true;
            }
        }

        public bool IsSelected
        {
            get { return m_isSelected; }
            set
            {
                m_isSelected = value;
                if (ParentGroup != null)
                    ParentGroup.PartSelectChanged(value);

            }
        }


        public Dictionary<int, string> CollisionFilter
        {
            get { return m_CollisionFilter; }
            set
            {
                m_CollisionFilter = value;
            }
        }

        protected bool APIDActive
        {
            get { return m_APIDActive; }
            set { m_APIDActive = value; }
        }

        protected Quaternion APIDTarget
        {
            get { return m_APIDTarget; }
            set { m_APIDTarget = value; }
        }


        protected float APIDDamp
        {
            get { return m_APIDDamp; }
            set { m_APIDDamp = value; }
        }


        protected float APIDStrength
        {
            get { return m_APIDStrength; }
            set { m_APIDStrength = value; }
        }

        public ulong RegionHandle
        {
            get { return m_regionHandle; }
            set { m_regionHandle = value; }
        }

        public int ScriptAccessPin
        {
            get { return m_scriptAccessPin; }
            set { m_scriptAccessPin = (int)value; }
        }
        private SceneObjectPart m_PlaySoundMasterPrim = null;
        public SceneObjectPart PlaySoundMasterPrim
        {
            get { return m_PlaySoundMasterPrim; }
            set { m_PlaySoundMasterPrim = value; }
        }

        private List<SceneObjectPart> m_PlaySoundSlavePrims = new List<SceneObjectPart>();
        public List<SceneObjectPart> PlaySoundSlavePrims
        {
            get { return m_PlaySoundSlavePrims; }
            set { m_PlaySoundSlavePrims = value; }
        }

        private SceneObjectPart m_LoopSoundMasterPrim = null;
        public SceneObjectPart LoopSoundMasterPrim
        {
            get { return m_LoopSoundMasterPrim; }
            set { m_LoopSoundMasterPrim = value; }
        }

        private List<SceneObjectPart> m_LoopSoundSlavePrims = new List<SceneObjectPart>();
        public List<SceneObjectPart> LoopSoundSlavePrims
        {
            get { return m_LoopSoundSlavePrims; }
            set { m_LoopSoundSlavePrims = value; }
        }

        public Byte[] TextureAnimation
        {
            get { return m_TextureAnimation; }
            set { m_TextureAnimation = value; }
        }

        public Byte[] ParticleSystem
        {
            get { return m_particleSystem; }
            set { m_particleSystem = value; }
        }


        public DateTime Expires
        {
            get { return m_expires; }
            set { m_expires = value; }
        }


        public DateTime Rezzed
        {
            get { return m_rezzed; }
            set { m_rezzed = value; }
        }


        public float Damage
        {
            get { return m_damage; }
            set { m_damage = value; }
        }

        public void setGroupPosition(Vector3 pos)
        {
            m_groupPosition = pos;
        }

        /// <summary>
        /// The position of the entire group that this prim belongs to.
        /// </summary>
        ///

        public Vector3 GroupPosition
        {
            get
            {
                // If this is a linkset, we don't want the physics engine mucking up our group position here.
                PhysicsActor actor = PhysActor;
                if (_parentID == 0)
                {
                    if (actor != null)
                        m_groupPosition = actor.Position;
                    return m_groupPosition;
                }

                // If I'm an attachment, my position is reported as the position of who I'm attached to
                if (ParentGroup.IsAttachment)
                {
                    ScenePresence sp = ParentGroup.Scene.GetScenePresence(ParentGroup.AttachedAvatar);
                    if (sp != null)
                        return sp.AbsolutePosition;
                }

                // use root prim's group position. Physics may have updated it
                if (ParentGroup.RootPart != this)
                    m_groupPosition = ParentGroup.RootPart.GroupPosition;
                return m_groupPosition;
            }
            set
            {
                m_groupPosition = value;
                PhysicsActor actor = PhysActor;
                if (actor != null && ParentGroup.Scene.PhysicsScene != null)
                {
                    try
                    {
                        // Root prim actually goes at Position
                        if (_parentID == 0)
                        {
                            actor.Position = value;
                        }
                        else
                        {
                            // The physics engine always sees all objects (root or linked) in world coordinates.
                            actor.Position = GetWorldPosition();
                            actor.Orientation = GetWorldRotation();
                        }

                        // Tell the physics engines that this prim changed.
                        if (ParentGroup != null && ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene != null)
                            ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
                    }
                    catch (Exception e)
                    {
                        m_log.ErrorFormat("[SCENEOBJECTPART]: GROUP POSITION. {0}", e);
                    }
                }
            }
        }

        public void setOffsetPosition(Vector3 pos)
        {
            m_offsetPosition = pos;
        }

        public Vector3 OffsetPosition
        {
            get { return m_offsetPosition; }
            set
            {
                Vector3 oldpos = m_offsetPosition;
                m_offsetPosition = value;

                if (ParentGroup != null && !ParentGroup.IsDeleted)
                {
                    if((oldpos - m_offsetPosition).LengthSquared() > 1.0f)
                        ParentGroup.InvalidBoundsRadius();

                    PhysicsActor actor = PhysActor;
                    if (_parentID != 0 && actor != null)
                    {
                        actor.Position = GetWorldPosition();
                        actor.Orientation = GetWorldRotation();

                        // Tell the physics engines that this prim changed.
                        if (ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene != null)
                            ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
                    }

                    if (!m_parentGroup.m_dupeInProgress)
                    {
                        List<ScenePresence> avs = ParentGroup.GetSittingAvatars();
                        foreach (ScenePresence av in avs)
                        {
                            if (av.ParentID == m_localId)
                            {
                                Vector3 offset = (m_offsetPosition - oldpos);
                                av.AbsolutePosition += offset;
//                                av.SendAvatarDataToAllAgents();
                                av.SendTerseUpdateToAllClients();
                            }
                        }
                    }
                }
                TriggerScriptChangedEvent(Changed.POSITION);
            }
        }

        public Vector3 RelativePosition
        {
            get
            {
                if (IsRoot)
                {
                    if (ParentGroup.IsAttachment)
                        return AttachedPos;
                    else
                        return AbsolutePosition;
                }
                else
                {
                    return OffsetPosition;
                }
            }
        }

        public void setRotationOffset(Quaternion q)
        {
            m_rotationOffset = q;
        }

        public Quaternion RotationOffset
        {
            get
            {
                // We don't want the physics engine mucking up the rotations in a linkset
                PhysicsActor actor = PhysActor;
                // If this is a root of a linkset, the real rotation is what the physics engine thinks.
                // If not a root prim, the offset rotation is computed by SOG and is relative to the root.
                if (_parentID == 0 && (Shape.PCode != 9 || Shape.State == 0) && actor != null)
                    m_rotationOffset = actor.Orientation;

                return m_rotationOffset;
            }

            set
            {
//                StoreUndoState();
                m_rotationOffset = value;

                PhysicsActor actor = PhysActor;
                if (actor != null)
                {
                    try
                    {
                        // Root prim gets value directly
                        if (_parentID == 0)
                        {
                            actor.Orientation = value;
                            //m_log.Info("[PART]: RO1:" + actor.Orientation.ToString());
                        }
                        else
                        {
                            // Child prim we have to calculate it's world rotationwel
                            Quaternion resultingrotation = GetWorldRotation();
                            actor.Orientation = resultingrotation;
                            //m_log.Info("[PART]: RO2:" + actor.Orientation.ToString());
                        }

                        if (ParentGroup != null && ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene != null)
                            ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
                        //}
                    }
                    catch (Exception ex)
                    {
                        m_log.Error("[SCENEOBJECTPART]: ROTATIONOFFSET" + ex.Message);
                    }
                }

//                float roll, pitch, yaw = 0;
//                m_rotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
//
//                m_log.DebugFormat(
//                    "[SCENE OBJECT PART]: Set euler {0} for RotationOffset on {1} {2}",
//                    new Vector3(roll, pitch, yaw), Name, LocalId);
            }
        }

        /// <summary></summary>
        public Vector3 Velocity
        {
            get
            {
                PhysicsActor actor = PhysActor;
                if (actor != null)
                {
                    if (actor.IsPhysical)
                    {
                        m_velocity = actor.Velocity;
                    }
                }

                return m_velocity;
            }

            set
            {
                if (Util.IsNanOrInfinity(value))
                    m_velocity = Vector3.Zero;
                else
                    m_velocity = value;

                PhysicsActor actor = PhysActor;
                if (actor != null)
                {
                    if (actor.IsPhysical)
                    {
                        actor.Velocity = m_velocity;
                        ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
                    }
                }
            }
        }

        /// <summary>Update angular velocity and schedule terse update.</summary>
        public void UpdateAngularVelocity(Vector3 avel)
        {
            AngularVelocity = avel;
            ScheduleTerseUpdate();
            ParentGroup.HasGroupChanged = true;
        }

        /// <summary>Get or set angular velocity. Does not schedule update.</summary>
        public Vector3 AngularVelocity
        {
            get
            {
                PhysicsActor actor = PhysActor;
                if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
                {
                    m_angularVelocity = actor.RotationalVelocity;
                }
                return m_angularVelocity;
            }
            set
            {
                if (Util.IsNanOrInfinity(value))
                    m_angularVelocity = Vector3.Zero;
                else
                    m_angularVelocity = value;

                PhysicsActor actor = PhysActor;
                if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
                {
                    actor.RotationalVelocity = m_angularVelocity;
                }
            }
        }

        /// <summary></summary>
        public Vector3 Acceleration
        {
            get
            {
                PhysicsActor actor = PhysActor;
                if (actor != null)
                {
                    m_acceleration = actor.Acceleration;
                }
                return m_acceleration;
            }

            set
            {
                if (Util.IsNanOrInfinity(value))
                    m_acceleration = Vector3.Zero;
                else
                    m_acceleration = value;

                PhysicsActor actor = PhysActor;
                if ((actor != null) && actor.IsPhysical && ParentGroup.RootPart == this)
                {
                   actor.Acceleration = m_acceleration;
                }
            }
        }

        public string Description { get; set; }

        /// <value>
        /// Text color.
        /// </value>
        public Color Color
        {
            get { return m_color; }
            set { m_color = value; }
        }

        public string Text
        {
            get
            {
                if (m_text.Length > 256) // yes > 254
                    return m_text.Substring(0, 256);
                return m_text;
            }
            set { m_text = value; }
        }


        public string SitName
        {
            get { return m_sitName; }
            set { m_sitName = value; }
        }

        public string TouchName
        {
            get { return m_touchName; }
            set { m_touchName = value; }
        }

        public int LinkNum
        {
            get { return m_linkNum; }
            set
            {
//                if (ParentGroup != null)
//                {
//                    m_log.DebugFormat(
//                        "[SCENE OBJECT PART]: Setting linknum of {0}@{1} to {2} from {3}",
//                        Name, AbsolutePosition, value, m_linkNum);
//                    Util.PrintCallStack();
//                }

                m_linkNum = value;
            }
        }

        public byte ClickAction
        {
            get { return m_clickAction; }
            set
            {
                m_clickAction = value;
            }
        }

        public PrimitiveBaseShape Shape
        {
            get { return m_shape; }
            set
            {
                m_shape = value;
            }
        }

        /// <summary>
        /// Change the scale of this part.
        /// </summary>
        public Vector3 Scale
        {
            get { return m_shape.Scale; }
            set
            {
                if (m_shape != null)
                {
                    Vector3 oldscale = m_shape.Scale;
                    m_shape.Scale = value;
                    if (ParentGroup != null && ((value - oldscale).LengthSquared() >1.0f))
                        ParentGroup.InvalidBoundsRadius();
                    PhysicsActor actor = PhysActor;
                    if (actor != null)
                    {
                        if (ParentGroup.Scene != null)
                        {
                            if (ParentGroup.Scene.PhysicsScene != null)
                            {
                                actor.Size = m_shape.Scale;
                                ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(actor);
                            }
                        }
                    }
                }

                TriggerScriptChangedEvent(Changed.SCALE);
            }
        }

        public float maxSimpleArea()
        {
            float a,b;
            float sx = m_shape.Scale.X;
            float sy = m_shape.Scale.Y;
            float sz = m_shape.Scale.Z;

            if( sx > sy)
            {
                a = sx;
                if(sy  > sz)
                    b = sy;
                else
                    b = sz;
            }
            else
            {
                a = sy;
                if(sx  > sz)
                    b = sx;
                else
                    b = sz;
            }

            return a * b;
        }

        public UpdateRequired UpdateFlag { get; set; }
        private object UpdateFlagLock = new object();

        /// <summary>
        /// Used for media on a prim.
        /// </summary>
        /// Do not change this value directly - always do it through an IMoapModule.
        public string MediaUrl
        {
            get
            {
                return m_mediaUrl;
            }

            set
            {
                m_mediaUrl = value;

                if (ParentGroup != null)
                    ParentGroup.HasGroupChanged = true;
            }
        }

        public bool CreateSelected
        {
            get { return m_createSelected; }
            set
            {
//                m_log.DebugFormat("[SOP]: Setting CreateSelected to {0} for {1} {2}", value, Name, UUID);
                m_createSelected = value;
            }
        }

        #endregion

//---------------
#region Public Properties with only Get

        public Vector3 AbsolutePosition
        {
            get
            {
                if (_parentID == 0)
                    return GroupPosition;

                return GroupPosition + (m_offsetPosition * ParentGroup.RootPart.RotationOffset);
            }
        }

        public SceneObjectGroup ParentGroup
        {
            get { return m_parentGroup; }
            private set { m_parentGroup = value; }
        }

        public scriptEvents ScriptEvents
        {
            get { return AggregateScriptEvents; }
        }

        public Quaternion SitTargetOrientation
        {
            get { return m_sitTargetOrientation; }
            set
            {
                m_sitTargetOrientation = value;
//                m_log.DebugFormat("[SCENE OBJECT PART]: Set sit target orientation {0} for {1} {2}", m_sitTargetOrientation, Name, LocalId);
            }
        }

        public Vector3 SitTargetPosition
        {
            get { return m_sitTargetPosition; }
            set
            {
                m_sitTargetPosition = value;
//                m_log.DebugFormat("[SCENE OBJECT PART]: Set sit target position to {0} for {1} {2}", m_sitTargetPosition, Name, LocalId);
            }
        }

        // This sort of sucks, but I'm adding these in to make some of
        // the mappings more consistant.
        public Vector3 SitTargetPositionLL
        {
            get { return m_sitTargetPosition; }
            set { m_sitTargetPosition = value; }
        }

        public Quaternion SitTargetOrientationLL
        {
            get { return m_sitTargetOrientation; }
            set { m_sitTargetOrientation = value; }
        }

        public bool Stopped
        {
            get {
                double threshold = 0.02;
                return (Math.Abs(Velocity.X) < threshold &&
                        Math.Abs(Velocity.Y) < threshold &&
                        Math.Abs(Velocity.Z) < threshold &&
                        Math.Abs(AngularVelocity.X) < threshold &&
                        Math.Abs(AngularVelocity.Y) < threshold &&
                        Math.Abs(AngularVelocity.Z) < threshold);
            }
        }

        /// <summary>
        /// The parent ID of this part.
        /// </summary>
        /// <remarks>
        /// If this is a root part which is not attached to an avatar then the value will be 0.
        /// If this is a root part which is attached to an avatar then the value is the local id of that avatar.
        /// If this is a child part then the value is the local ID of the root part.
        /// </remarks>
        public uint ParentID
        {
            get { return _parentID; }
            set { _parentID = value; }
        }

        public int CreationDate
        {
            get { return _creationDate; }
            set { _creationDate = value; }
        }

        public uint Category
        {
            get { return _category; }
            set { _category = value; }
        }

        public int SalePrice
        {
            get { return _salePrice; }
            set { _salePrice = value; }
        }

        public byte ObjectSaleType
        {
            get { return _objectSaleType; }
            set { _objectSaleType = value; }
        }

        public int OwnershipCost
        {
            get { return _ownershipCost; }
            set { _ownershipCost = value; }
        }

        public UUID GroupID
        {
            get { return _groupID; }
            set { _groupID = value; }
        }

        public UUID OwnerID
        {
            get { return _ownerID; }
            set { _ownerID = value; }
        }

        public UUID LastOwnerID
        {
            get { return _lastOwnerID; }
            set {
             _lastOwnerID = value; }
        }

        public UUID RezzerID
        {
            get { return _rezzerID; }
            set { _rezzerID = value; }
        }

        public uint BaseMask
        {
            get { return _baseMask; }
            set { _baseMask = value; }
        }

        public uint OwnerMask
        {
            get { return _ownerMask; }
            set { _ownerMask = value; }
        }

        public uint GroupMask
        {
            get { return _groupMask; }
            set { _groupMask = value; }
        }

        public uint EveryoneMask
        {
            get { return _everyoneMask; }
            set { _everyoneMask = value; }
        }

        public uint NextOwnerMask
        {
            get { return _nextOwnerMask; }
            set { _nextOwnerMask = value; }
        }

        /// <summary>
        /// Property flags.  See OpenMetaverse.PrimFlags
        /// </summary>
        /// <remarks>
        /// Example properties are PrimFlags.Phantom and PrimFlags.DieAtEdge
        /// </remarks>
        public PrimFlags Flags
        {
            get { return _flags; }
            set
            {
//                m_log.DebugFormat("[SOP]: Setting flags for {0} {1} to {2}", UUID, Name, value);
                _flags = value;
            }
        }

        [XmlIgnore]
        public bool IsOccupied				// KF If an av is sittingon this prim
        {
            get { return m_occupied; }
            set { m_occupied = value; }
        }

        /// <summary>
        /// ID of the avatar that is sat on us if we have a sit target.  If there is no such avatar then is UUID.Zero
        /// </summary>
        public UUID SitTargetAvatar { get; set; }

        /// <summary>
        /// IDs of all avatars sat on this part.
        /// </summary>
        /// <remarks>
        /// We need to track this so that we can stop sat upon prims from being attached.
        /// </remarks>
        /// <value>
        /// null if there are no sitting avatars.  This is to save us create a hashset for every prim in a scene.
        /// </value>
        private HashSet<ScenePresence> m_sittingAvatars;

        public virtual UUID RegionID
        {
            get
            {
                if (ParentGroup.Scene != null)
                    return ParentGroup.Scene.RegionInfo.RegionID;
                else
                    return UUID.Zero;
            }
            set {} // read only
        }

        private UUID _parentUUID = UUID.Zero;

        public UUID ParentUUID
        {
            get
            {
                if (ParentGroup != null)
                    _parentUUID = ParentGroup.UUID;

                return _parentUUID;
            }

            set { _parentUUID = value; }
        }

        public string SitAnimation
        {
            get { return m_sitAnimation; }
            set { m_sitAnimation = value; }
        }

        public UUID invalidCollisionSoundUUID = new UUID("ffffffff-ffff-ffff-ffff-ffffffffffff");

        // 0 for default collision sounds, -1 for script disabled sound 1 for script defined sound
        // runtime thing.. do not persist
        [XmlIgnore]
        public sbyte CollisionSoundType
        {
            get
            {
                return m_collisionSoundType;
            }
            set
            {
                m_collisionSoundType = value;
                if (value == -1)
                    m_collisionSound = invalidCollisionSoundUUID;
                else if (value == 0)
                    m_collisionSound = UUID.Zero;
            }
        }

        public UUID CollisionSound
        {
            get { return m_collisionSound; }
            set
            {
                m_collisionSound = value;

                if (value == invalidCollisionSoundUUID)
                    m_collisionSoundType = -1;
                else if (value == UUID.Zero)
                    m_collisionSoundType = 0;
                else
                    m_collisionSoundType = 1;

            }
        }

        public float CollisionSoundVolume
        {
            get { return m_collisionSoundVolume; }
            set { m_collisionSoundVolume = value; }
        }

        public float Buoyancy
        {
            get
            {
                if (ParentGroup.RootPart == this)
                    return m_buoyancy;

                return ParentGroup.RootPart.Buoyancy;
            }
            set
            {
                if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
                {
                    ParentGroup.RootPart.Buoyancy = value;
                    return;
                }
                m_buoyancy = value;
                if (PhysActor != null)
                    PhysActor.Buoyancy = value;
            }
        }

        public Vector3 Force
        {
            get
            {
                if (ParentGroup.RootPart == this)
                    return m_force;

                return ParentGroup.RootPart.Force;
            }

            set
            {
                if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
                {
                    ParentGroup.RootPart.Force = value;
                    return;
                }
                m_force = value;
                if (PhysActor != null)
                    PhysActor.Force = value;
            }
        }

        public Vector3 Torque
        {
            get
            {
                if (ParentGroup.RootPart == this)
                    return m_torque;

                return ParentGroup.RootPart.Torque;
            }

            set
            {
                if (ParentGroup != null && ParentGroup.RootPart != null && ParentGroup.RootPart != this)
                {
                    ParentGroup.RootPart.Torque = value;
                    return;
                }
                m_torque = value;
                if (PhysActor != null)
                    PhysActor.Torque = value;
            }
        }

        public byte Material
        {
            get { return (byte)m_material; }
            set
            {
                if (value >= 0 && value <= (byte)SOPMaterialData.MaxMaterial)
                {
                    bool update = false;

                    if (m_material != (Material)value)
                    {
                        update = true;
                        m_material = (Material)value;
                    }

                    if (m_friction != SOPMaterialData.friction(m_material))
                    {
                        update = true;
                        m_friction = SOPMaterialData.friction(m_material);
                    }

                    if (m_bounce != SOPMaterialData.bounce(m_material))
                    {
                        update = true;
                        m_bounce = SOPMaterialData.bounce(m_material);
                    }

                    if (update)
                    {
                        if (PhysActor != null)
                        {
                            PhysActor.SetMaterial((int)value);
                        }
                        if(ParentGroup != null)
                        {
                            ParentGroup.HasGroupChanged = true;
                            ScheduleFullUpdate();
                        }
                    }
                }
            }
        }

        // not a propriety to move to methods place later
        private bool HasMesh()
        {
            if (Shape != null && (Shape.SculptType == (byte)SculptType.Mesh))
                return true;
            return false;
        }

        // not a propriety to move to methods place later
        public byte DefaultPhysicsShapeType()
        {
            byte type;

            if (Shape != null && (Shape.SculptType == (byte)SculptType.Mesh))
                type = (byte)PhysShapeType.convex;
            else
                type = (byte)PhysShapeType.prim;

            return type;
        }

        [XmlIgnore]
        public bool UsesComplexCost
        {
            get
            {
                byte pst = PhysicsShapeType;
                if(pst == (byte) PhysShapeType.none || HasMesh())
                    return true;
                return false;
            }
        }

        [XmlIgnore]
        public float PhysicsCost
        {
            get
            {
                if(PhysicsShapeType == (byte)PhysShapeType.none)
                    return 0;

                float cost = 0.1f;
                if (PhysActor != null)
                    cost = PhysActor.PhysicsCost;
                else
                    cost = 0.1f;

                if ((Flags & PrimFlags.Physics) != 0)
                    cost *= (1.0f + 0.01333f * Scale.LengthSquared()); // 0.01333 == 0.04/3
                return cost;
            }
        }

        [XmlIgnore]
        public float StreamingCost
        {
            get
            {
                float cost;
                if (PhysActor != null)
                    cost = PhysActor.StreamCost;
                else
                    cost = 1.0f;
                return 1.0f;
            }
        }

        [XmlIgnore]
        public float SimulationCost
        {
            get
            {
                // ignoring scripts. Don't like considering them for this
                if((Flags & PrimFlags.Physics) != 0)
                    return 1.0f;

                return 0.5f;
            }
        }

        public byte PhysicsShapeType
        {
            get
            {
//                if (PhysActor != null)
//                    m_physicsShapeType  = PhysActor.PhysicsShapeType;
                return m_physicsShapeType;
            }
            set
            {
                byte oldv = m_physicsShapeType;

                if (value >= 0 && value <= (byte)PhysShapeType.convex)
                {
                    if (value == (byte)PhysShapeType.none && ParentGroup != null && ParentGroup.RootPart == this)
                        m_physicsShapeType = DefaultPhysicsShapeType();
                    else
                        m_physicsShapeType = value;
                }
                else
                    m_physicsShapeType = DefaultPhysicsShapeType();

                if (m_physicsShapeType != oldv && ParentGroup != null)
                {
                    if (m_physicsShapeType == (byte)PhysShapeType.none)
                    {
                        if (PhysActor != null)
                        {
                            ParentGroup.Scene.RemovePhysicalPrim(1);
                            RemoveFromPhysics();
//                            Stop();
                        }
                    }
                    else if (PhysActor == null)
                    {
                        if(oldv == (byte)PhysShapeType.none)
                        {
                            ApplyPhysics((uint)Flags, VolumeDetectActive, false);
                            UpdatePhysicsSubscribedEvents();
                        }
                    }
                    else
                        PhysActor.PhysicsShapeType = m_physicsShapeType;

                    ParentGroup.HasGroupChanged = true;
                }
            }
        }

        public float Density // in kg/m^3
        {
            get { return m_density; }
            set
            {
                if (value >=1 && value <= 22587.0)
                {
                    m_density = value;


                    if (ParentGroup != null)
                    {
                        ParentGroup.HasGroupChanged = true;
                        ScheduleFullUpdate();
                    }

                    PhysicsActor pa = PhysActor;
                    if (pa != null)
                        pa.Density = m_density;
                }
            }
        }

        public float GravityModifier
        {
            get { return m_gravitymod; }
            set
            {
                if( value >= -1 && value <=28.0f)
                {
                    m_gravitymod = value;

                    if (ParentGroup != null)
                    {
                        ParentGroup.HasGroupChanged = true;
                        ScheduleFullUpdate();
                    }

                    PhysicsActor pa = PhysActor;
                    if (pa != null)
                        pa.GravModifier = m_gravitymod;
                }
            }
        }

        public float Friction
        {
            get { return m_friction; }
            set
            {
                if (value >= 0 && value <= 255.0f)
                {
                    m_friction = value;

                    if (ParentGroup != null)
                    {
                        ParentGroup.HasGroupChanged = true;
                        ScheduleFullUpdate();
                    }

                    PhysicsActor pa = PhysActor;
                    if (pa != null)
                        pa.Friction = m_friction;
                }
            }
        }

        public float Restitution
        {
            get { return m_bounce; }
            set
            {
                if (value >= 0 && value <= 1.0f)
                {
                    m_bounce = value;

                    if (ParentGroup != null)
                    {
                        ParentGroup.HasGroupChanged = true;
                        ScheduleFullUpdate();
                    }

                    PhysicsActor pa = PhysActor;
                    if (pa != null)
                        pa.Restitution = m_bounce;
                }
            }
        }


        #endregion Public Properties with only Get

        private uint ApplyMask(uint val, bool set, uint mask)
        {
            if (set)
            {
                return val |= mask;
            }
            else
            {
                return val &= ~mask;
            }
        }

        /// <summary>
        /// Clear all pending updates of parts to clients
        /// </summary>
        public void ClearUpdateSchedule()
        {
            lock(UpdateFlagLock)
                UpdateFlag = UpdateRequired.NONE;
        }

        /// <summary>
        /// Send this part's properties (name, description, inventory serial, base mask, etc.) to a client
        /// </summary>
        /// <param name="client"></param>
        public void SendPropertiesToClient(IClientAPI client)
        {
            client.SendObjectPropertiesReply(this);
        }

        // TODO: unused:
        // private void handleTimerAccounting(uint localID, double interval)
        // {
        //     if (localID == LocalId)
        //     {
        //         float sec = (float)interval;
        //         if (m_parentGroup != null)
        //         {
        //             if (sec == 0)
        //             {
        //                 if (m_parentGroup.scriptScore + 0.001f >= float.MaxValue - 0.001)
        //                     m_parentGroup.scriptScore = 0;
        //
        //                 m_parentGroup.scriptScore += 0.001f;
        //                 return;
        //             }
        //
        //             if (m_parentGroup.scriptScore + (0.001f / sec) >= float.MaxValue - (0.001f / sec))
        //                 m_parentGroup.scriptScore = 0;
        //             m_parentGroup.scriptScore += (0.001f / sec);
        //         }
        //     }
        // }

        #region Public Methods

        public void ResetExpire()
        {
            Expires = DateTime.UtcNow + new TimeSpan(600000000);
        }

        public void AddFlag(PrimFlags flag)
        {
            // PrimFlags prevflag = Flags;
            if ((Flags & flag) == 0)
            {
                //m_log.Debug("Adding flag: " + ((PrimFlags) flag).ToString());
                Flags |= flag;

                if (flag == PrimFlags.TemporaryOnRez)
                    ResetExpire();
            }
            // m_log.Debug("Aprev: " + prevflag.ToString() + " curr: " + Flags.ToString());
        }

        public void AddNewParticleSystem(Primitive.ParticleSystem pSystem)
        {
            m_particleSystem = pSystem.GetBytes();
        }

        public void RemoveParticleSystem()
        {
            m_particleSystem = new byte[0];
        }

        public void AddTextureAnimation(Primitive.TextureAnimation pTexAnim)
        {
            byte[] data;

            if (pTexAnim.Flags == Primitive.TextureAnimMode.ANIM_OFF)
            {
                data = Utils.EmptyBytes;
            }
            else
            {
                data = new byte[16];
                int pos = 0;

                // The flags don't like conversion from uint to byte, so we have to do
                // it the crappy way.  See the above function :(

                data[pos] = ConvertScriptUintToByte((uint)pTexAnim.Flags); pos++;
                data[pos] = (byte)pTexAnim.Face; pos++;
                data[pos] = (byte)pTexAnim.SizeX; pos++;
                data[pos] = (byte)pTexAnim.SizeY; pos++;

                Utils.FloatToBytes(pTexAnim.Start).CopyTo(data, pos);
                Utils.FloatToBytes(pTexAnim.Length).CopyTo(data, pos + 4);
                Utils.FloatToBytes(pTexAnim.Rate).CopyTo(data, pos + 8);

            }
            m_TextureAnimation = data;
        }

        public void AdjustSoundGain(double volume)
        {
            if (volume > 1)
                volume = 1;
            if (volume < 0)
                volume = 0;

            ParentGroup.Scene.ForEachRootClient(delegate(IClientAPI client)
            {
                client.SendAttachedSoundGainChange(UUID, (float)volume);
            });
        }

        /// <summary>
        /// hook to the physics scene to apply impulse
        /// This is sent up to the group, which then finds the root prim
        /// and applies the force on the root prim of the group
        /// </summary>
        /// <param name="impulsei">Vector force</param>
        /// <param name="localGlobalTF">true for the local frame, false for the global frame</param>
        public void ApplyImpulse(Vector3 impulsei, bool localGlobalTF)
        {
            Vector3 impulse = impulsei;

            if (localGlobalTF)
            {
                Quaternion grot = GetWorldRotation();
                Quaternion AXgrot = grot;
                Vector3 AXimpulsei = impulsei;
                Vector3 newimpulse = AXimpulsei * AXgrot;
                impulse = newimpulse;
            }

            if (ParentGroup != null)
            {
                ParentGroup.applyImpulse(impulse);
            }
        }

        //      SetVelocity for LSL llSetVelocity..  may need revision if having other uses in future
        public void SetVelocity(Vector3 pVel, bool localGlobalTF)
        {
            if (ParentGroup == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
                return;

            if (ParentGroup.IsAttachment)
                return;                         // don't work on attachments (for now ??)

            SceneObjectPart root = ParentGroup.RootPart;

            if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
                return;

            PhysicsActor pa = root.PhysActor;

            if (pa == null || !pa.IsPhysical)
                return;

            if (localGlobalTF)
            {
                pVel = pVel * GetWorldRotation();
            }

            ParentGroup.Velocity = pVel;
        }

        //      SetAngularVelocity for LSL llSetAngularVelocity..  may need revision if having other uses in future
        public void SetAngularVelocity(Vector3 pAngVel, bool localGlobalTF)
        {
            if (ParentGroup == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
                return;

            if (ParentGroup.IsAttachment)
                return;                         // don't work on attachments (for now ??)

            SceneObjectPart root = ParentGroup.RootPart;

            if (root.VehicleType != (int)Vehicle.TYPE_NONE) // don't mess with vehicles
                return;

            PhysicsActor pa = root.PhysActor;

            if (pa == null || !pa.IsPhysical)
                return;

            if (localGlobalTF)
            {
                pAngVel = pAngVel * GetWorldRotation();
            }

            root.AngularVelocity = pAngVel;
        }


        /// <summary>
        /// hook to the physics scene to apply angular impulse
        /// This is sent up to the group, which then finds the root prim
        /// and applies the force on the root prim of the group
        /// </summary>
        /// <param name="impulsei">Vector force</param>
        /// <param name="localGlobalTF">true for the local frame, false for the global frame</param>
        public void ApplyAngularImpulse(Vector3 impulsei, bool localGlobalTF)
        {
           if (ParentGroup == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
                return;

            Vector3 impulse = impulsei;

            if (localGlobalTF)
            {
                Quaternion grot = GetWorldRotation();
                Quaternion AXgrot = grot;
                Vector3 AXimpulsei = impulsei;
                Vector3 newimpulse = AXimpulsei * AXgrot;
                impulse = newimpulse;
            }

            ParentGroup.ApplyAngularImpulse(impulse);
        }

        /// <summary>
        /// hook to the physics scene to apply angular impulse
        /// This is sent up to the group, which then finds the root prim
        /// and applies the force on the root prim of the group
        /// </summary>
        /// <param name="impulsei">Vector force</param>
        /// <param name="localGlobalTF">true for the local frame, false for the global frame</param>

        // this is actualy Set Torque.. keeping naming so not to edit lslapi also
        public void SetAngularImpulse(Vector3 torquei, bool localGlobalTF)
        {
            Vector3 torque = torquei;

            if (localGlobalTF)
            {
                torque *= GetWorldRotation();
            }

            Torque = torque;
        }

        /// <summary>
        /// Apply physics to this part.
        /// </summary>
        /// <param name="rootObjectFlags"></param>
        /// <param name="VolumeDetectActive"></param>
        /// <param name="building"></param>

        public void ApplyPhysics(uint _ObjectFlags, bool _VolumeDetectActive, bool building)
        {
            VolumeDetectActive = _VolumeDetectActive;

            if (!ParentGroup.Scene.CollidablePrims)
                return;

            if (PhysicsShapeType == (byte)PhysShapeType.none)
                return;

            bool isPhysical = (_ObjectFlags & (uint) PrimFlags.Physics) != 0;
            bool isPhantom = (_ObjectFlags & (uint)PrimFlags.Phantom) != 0;

            if (_VolumeDetectActive)
                isPhantom = true;

            if (IsJoint())
            {
                DoPhysicsPropertyUpdate(isPhysical, true);
            }
            else
            {
                if ((!isPhantom || isPhysical || _VolumeDetectActive)
                        && !ParentGroup.IsAttachmentCheckFull()
                        && !(Shape.PathCurve == (byte)Extrusion.Flexible))
                {
                    AddToPhysics(isPhysical, isPhantom, building, isPhysical);
                    UpdatePhysicsSubscribedEvents(); // not sure if appliable here
                }
                else
                {
                    PhysActor = null; // just to be sure
                    RemFlag(PrimFlags.CameraDecoupled);
                }
            }
        }

        public byte ConvertScriptUintToByte(uint indata)
        {
            byte outdata = (byte)TextureAnimFlags.NONE;
            if ((indata & 1) != 0) outdata |= (byte)TextureAnimFlags.ANIM_ON;
            if ((indata & 2) != 0) outdata |= (byte)TextureAnimFlags.LOOP;
            if ((indata & 4) != 0) outdata |= (byte)TextureAnimFlags.REVERSE;
            if ((indata & 8) != 0) outdata |= (byte)TextureAnimFlags.PING_PONG;
            if ((indata & 16) != 0) outdata |= (byte)TextureAnimFlags.SMOOTH;
            if ((indata & 32) != 0) outdata |= (byte)TextureAnimFlags.ROTATE;
            if ((indata & 64) != 0) outdata |= (byte)TextureAnimFlags.SCALE;
            return outdata;
        }

        /// <summary>
        /// Duplicates this part.
        /// </summary>
        /// <param name="localID"></param>
        /// <param name="AgentID"></param>
        /// <param name="GroupID"></param>
        /// <param name="linkNum"></param>
        /// <param name="userExposed">True if the duplicate will immediately be in the scene, false otherwise</param>
        /// <returns></returns>
        public SceneObjectPart Copy(uint plocalID, UUID AgentID, UUID GroupID, int linkNum, bool userExposed)
        {
            // FIXME: This is dangerous since it's easy to forget to reset some references when necessary and end up
            // with bugs that only occur in some circumstances (e.g. crossing between regions on the same simulator
            // but not between regions on different simulators).  Really, all copying should be done explicitly.
            SceneObjectPart dupe = (SceneObjectPart)MemberwiseClone();

            dupe.m_shape = m_shape.Copy();
            dupe.m_regionHandle = m_regionHandle;
            if (userExposed)
                dupe.UUID = UUID.Random();

            dupe.PhysActor = null;

            dupe.OwnerID = AgentID;
            dupe.GroupID = GroupID;
            dupe.GroupPosition = GroupPosition;
            dupe.OffsetPosition = OffsetPosition;
            dupe.RotationOffset = RotationOffset;
            dupe.Velocity = Velocity;
            dupe.Acceleration = Acceleration;
            dupe.AngularVelocity = AngularVelocity;
            dupe.Flags = Flags;

            dupe.OwnershipCost = OwnershipCost;
            dupe.ObjectSaleType = ObjectSaleType;
            dupe.SalePrice = SalePrice;
            dupe.Category = Category;
            dupe.m_rezzed = m_rezzed;

            dupe.m_UndoRedo = null;
            dupe.m_isSelected = false;

            dupe.IgnoreUndoUpdate = false;
            dupe.Undoing = false;

            dupe.m_inventory = new SceneObjectPartInventory(dupe);
            dupe.m_inventory.Items = (TaskInventoryDictionary)m_inventory.Items.Clone();

            if (userExposed)
            {
                dupe.ResetIDs(linkNum);
                dupe.m_inventory.HasInventoryChanged = true;
            }
            else
            {
                dupe.m_inventory.HasInventoryChanged = m_inventory.HasInventoryChanged;
            }

            // Move afterwards ResetIDs as it clears the localID
            dupe.LocalId = plocalID;

            // This may be wrong...    it might have to be applied in SceneObjectGroup to the object that's being duplicated.
            if(OwnerID != GroupID)
                dupe.LastOwnerID = OwnerID;
            else
                dupe.LastOwnerID = LastOwnerID; // redundant ?

            dupe.RezzerID = RezzerID;

            byte[] extraP = new byte[Shape.ExtraParams.Length];
            Array.Copy(Shape.ExtraParams, extraP, extraP.Length);
            dupe.Shape.ExtraParams = extraP;

            dupe.m_sittingAvatars = new HashSet<ScenePresence>();
            dupe.SitTargetAvatar = UUID.Zero;
            // safeguard  actual copy is done in sog.copy
            dupe.KeyframeMotion = null;
            dupe.PayPrice = (int[])PayPrice.Clone();

            dupe.DynAttrs.CopyFrom(DynAttrs);

            if (userExposed)
            {
                bool UsePhysics = ((dupe.Flags & PrimFlags.Physics) != 0);
                dupe.DoPhysicsPropertyUpdate(UsePhysics, true);
            }

            if (dupe.PhysActor != null)
                dupe.PhysActor.LocalID = plocalID;

            ParentGroup.Scene.EventManager.TriggerOnSceneObjectPartCopy(dupe, this, userExposed);

//            m_log.DebugFormat("[SCENE OBJECT PART]: Clone of {0} {1} finished", Name, UUID);

            return dupe;
        }

        /// <summary>
        /// Do a physics property update for a NINJA joint.
        /// </summary>
        /// <param name="UsePhysics"></param>
        /// <param name="isNew"></param>
        protected void DoPhysicsPropertyUpdateForNinjaJoint(bool UsePhysics, bool isNew)
        {
            if (UsePhysics)
            {
                // by turning a joint proxy object physical, we cause creation of a joint in the ODE scene.
                // note that, as a special case, joints have no bodies or geoms in the physics scene, even though they are physical.

                PhysicsJointType jointType;
                if (IsHingeJoint())
                {
                    jointType = PhysicsJointType.Hinge;
                }
                else if (IsBallJoint())
                {
                    jointType = PhysicsJointType.Ball;
                }
                else
                {
                    jointType = PhysicsJointType.Ball;
                }

                List<string> bodyNames = new List<string>();
                string RawParams = Description;
                string[] jointParams = RawParams.Split(" ".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries);
                string trackedBodyName = null;
                if (jointParams.Length >= 2)
                {
                    for (int iBodyName = 0; iBodyName < 2; iBodyName++)
                    {
                        string bodyName = jointParams[iBodyName];
                        bodyNames.Add(bodyName);
                        if (bodyName != "NULL")
                        {
                            if (trackedBodyName == null)
                            {
                                trackedBodyName = bodyName;
                            }
                        }
                    }
                }

                SceneObjectPart trackedBody = ParentGroup.Scene.GetSceneObjectPart(trackedBodyName); // FIXME: causes a sequential lookup
                Quaternion localRotation = Quaternion.Identity;
                if (trackedBody != null)
                {
                    localRotation = Quaternion.Inverse(trackedBody.RotationOffset) * this.RotationOffset;
                }
                else
                {
                    // error, output it below
                }

                PhysicsJoint joint;

                joint = ParentGroup.Scene.PhysicsScene.RequestJointCreation(Name, jointType,
                    AbsolutePosition,
                    this.RotationOffset,
                    Description,
                    bodyNames,
                    trackedBodyName,
                    localRotation);

                if (trackedBody == null)
                {
                    ParentGroup.Scene.jointErrorMessage(joint, "warning: tracked body name not found! joint location will not be updated properly. joint: " + Name);
                }
            }
            else
            {
                if (isNew)
                {
                    // if the joint proxy is new, and it is not physical, do nothing. There is no joint in ODE to
                    // delete, and if we try to delete it, due to asynchronous processing, the deletion request
                    // will get processed later at an indeterminate time, which could cancel a later-arriving
                    // joint creation request.
                }
                else
                {
                    // here we turn off the joint object, so remove the joint from the physics scene
                    ParentGroup.Scene.PhysicsScene.RequestJointDeletion(Name); // FIXME: what if the name changed?

                    // make sure client isn't interpolating the joint proxy object
                    Stop();
                }
            }
        }

        /// <summary>
        /// Do a physics propery update for this part.
        /// now also updates phantom and volume detector
        /// </summary>
        /// <param name="UsePhysics"></param>
        /// <param name="isNew"></param>
        public void DoPhysicsPropertyUpdate(bool UsePhysics, bool isNew)
        {
            if (ParentGroup.Scene == null)
                return;

            if (!ParentGroup.Scene.PhysicalPrims && UsePhysics)
                return;

            if (IsJoint())
            {
                DoPhysicsPropertyUpdateForNinjaJoint(UsePhysics, isNew);
            }
            else
            {
                PhysicsActor pa = PhysActor;

                if (pa != null)
                {
                    if (UsePhysics != pa.IsPhysical || isNew)
                    {
                        if (pa.IsPhysical) // implies UsePhysics==false for this block
                        {
                            if (!isNew)  // implies UsePhysics==false for this block
                            {
                                ParentGroup.Scene.RemovePhysicalPrim(1);

                                Velocity = new Vector3(0, 0, 0);
                                Acceleration = new Vector3(0, 0, 0);
                                AngularVelocity = new Vector3(0, 0, 0);
                                APIDActive = false;

                                if (pa.Phantom && !VolumeDetectActive)
                                {
                                    RemoveFromPhysics();
                                    return;
                                }

                                pa.IsPhysical = UsePhysics;
                                pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
                                pa.OnOutOfBounds -= PhysicsOutOfBounds;
                                pa.delink();
                                if (ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
                                {
                                    // destroy all joints connected to this now deactivated body
                                    ParentGroup.Scene.PhysicsScene.RemoveAllJointsConnectedToActorThreadLocked(pa);
                                }
                            }
                        }

                        if (pa.IsPhysical != UsePhysics)
                            pa.IsPhysical = UsePhysics;

                        if (UsePhysics)
                        {
                            if (ParentGroup.RootPart.KeyframeMotion != null)
                                ParentGroup.RootPart.KeyframeMotion.Stop();
                            ParentGroup.RootPart.KeyframeMotion = null;
                            ParentGroup.Scene.AddPhysicalPrim(1);

                            PhysActor.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
                            PhysActor.OnOutOfBounds += PhysicsOutOfBounds;

                            if (_parentID != 0 && _parentID != LocalId)
                            {
                                PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;

                                if (parentPa != null)
                                {
                                    pa.link(parentPa);
                                }
                            }
                        }
                    }

                    bool phan = ((Flags & PrimFlags.Phantom) != 0);
                    if (pa.Phantom != phan)
                        pa.Phantom = phan;

// some engines dont' have this check still
//                    if (VolumeDetectActive != pa.IsVolumeDtc)
                    {
                        if (VolumeDetectActive)
                            pa.SetVolumeDetect(1);
                        else
                            pa.SetVolumeDetect(0);
                    }

                    // If this part is a sculpt then delay the physics update until we've asynchronously loaded the
                    // mesh data.
//                    if (Shape.SculptEntry)
//                        CheckSculptAndLoad();
//                    else
                        ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
                }
            }
        }

        /// <summary>
        /// Restore this part from the serialized xml representation.
        /// </summary>
        /// <param name="xmlReader"></param>
        /// <returns></returns>
        public static SceneObjectPart FromXml(XmlReader xmlReader)
        {
            SceneObjectPart part = SceneObjectSerializer.Xml2ToSOP(xmlReader);

            // for tempOnRez objects, we have to fix the Expire date.
            if ((part.Flags & PrimFlags.TemporaryOnRez) != 0)
                part.ResetExpire();

            return part;
        }

        public bool GetDieAtEdge()
        {
            if (ParentGroup.IsDeleted)
                return false;

            return ParentGroup.RootPart.DIE_AT_EDGE;
        }

        public bool GetReturnAtEdge()
        {
            if (ParentGroup.IsDeleted)
                return false;

            return ParentGroup.RootPart.RETURN_AT_EDGE;
        }

        public void SetReturnAtEdge(bool p)
        {
            if (ParentGroup.IsDeleted)
                return;

            ParentGroup.RootPart.RETURN_AT_EDGE = p;
        }

        public void SetStatusSandbox(bool p)
        {
            if (ParentGroup.IsDeleted)
                return;
            StatusSandboxPos = ParentGroup.RootPart.AbsolutePosition;
            ParentGroup.RootPart.StatusSandbox = p;
        }

        public bool GetStatusSandbox()
        {
            if (ParentGroup.IsDeleted)
                return false;

            return ParentGroup.RootPart.StatusSandbox;
        }

        public int GetAxisRotation(int axis)
        {
           if (!ParentGroup.IsDeleted)
                return ParentGroup.GetAxisRotation(axis);

            return 0;
        }

        public double GetDistanceTo(Vector3 a, Vector3 b)
        {
            float dx = a.X - b.X;
            float dy = a.Y - b.Y;
            float dz = a.Z - b.Z;
            return Math.Sqrt(dx * dx + dy * dy + dz * dz);
        }

        public uint GetEffectiveObjectFlags()
        {
            // Commenting this section of code out since it doesn't actually do anything, as enums are handled by
            // value rather than reference
//            PrimFlags f = _flags;
//            if (m_parentGroup == null || m_parentGroup.RootPart == this)
//                f &= ~(PrimFlags.Touch | PrimFlags.Money);

            return (uint)Flags | (uint)LocalFlags;
        }

        // some of this lines need be moved to other place later

        // effective permitions considering only this part inventory contents perms
        public uint AggregatedInnerOwnerPerms {get; private set; }
        public uint AggregatedInnerGroupPerms {get; private set; }
        public uint AggregatedInnerEveryonePerms {get; private set; }
        private object InnerPermsLock = new object();

        public void AggregateInnerPerms()
        {
            // assuming child prims permissions masks are irrelevant on a linkset
            // root part is handle at SOG since its masks are the sog masks
            const uint mask = (uint)PermissionMask.AllEffective;

            uint owner = mask;
            uint group = mask;
            uint everyone = mask;

            lock(InnerPermsLock) // do we really need this?
            {
                if(Inventory != null)
                    Inventory.AggregateInnerPerms(ref owner, ref group, ref everyone);
            
                AggregatedInnerOwnerPerms = owner & mask;
                AggregatedInnerGroupPerms = group & mask;
                AggregatedInnerEveryonePerms = everyone & mask;
            }
            if(ParentGroup != null)
                ParentGroup.InvalidateEffectivePerms();
        }

        // same as above but called during group Effective Permission validation
        public void AggregatedInnerPermsForGroup()
        {
            // assuming child prims permissions masks are irrelevant on a linkset
            // root part is handle at SOG since its masks are the sog masks
            const uint mask = (uint)PermissionMask.AllEffective;

            uint owner = mask;
            uint group = mask;
            uint everyone = mask;

            lock(InnerPermsLock) // do we really need this?
            {
                if(Inventory != null)
                    Inventory.AggregateInnerPerms(ref owner, ref group, ref everyone);
            
                AggregatedInnerOwnerPerms = owner & mask;
                AggregatedInnerGroupPerms = group & mask;
                AggregatedInnerEveryonePerms = everyone & mask;
            }
        }

        public Vector3 GetGeometricCenter()
        {
            // this is not real geometric center but a average of positions relative to root prim acording to
            // http://wiki.secondlife.com/wiki/llGetGeometricCenter
            // ignoring tortured prims details since sl also seems to ignore
            // so no real use in doing it on physics
            if (ParentGroup.IsDeleted)
                return new Vector3(0, 0, 0);

            return ParentGroup.GetGeometricCenter();
        }

        public float GetMass()
        {
            PhysicsActor pa = PhysActor;

            if (pa != null)
                return pa.Mass;
            else
                return 0;
        }

        public Vector3 GetCenterOfMass()
        {
            if (ParentGroup.RootPart == this)
            {
                if (ParentGroup.IsDeleted)
                    return AbsolutePosition;
                return ParentGroup.GetCenterOfMass();
            }

            PhysicsActor pa = PhysActor;

            if (pa != null)
            {
                Vector3 tmp = pa.CenterOfMass;
                return tmp;
            }
            else
                return AbsolutePosition;
        }

        public Vector3 GetPartCenterOfMass()
        {
            PhysicsActor pa = PhysActor;

            if (pa != null)
            {
                Vector3 tmp = pa.CenterOfMass;
                return tmp;
            }
            else
                return AbsolutePosition;
        }


        public Vector3 GetForce()
        {
            return Force;
        }

        /// <summary>
        /// Method for a prim to get it's world position from the group.
        /// </summary>
        /// <remarks>
        /// Remember, the Group Position simply gives the position of the group itself
        /// </remarks>
        /// <returns>A Linked Child Prim objects position in world</returns>
        public Vector3 GetWorldPosition()
        {
            Vector3 ret;
            if (_parentID == 0)
                // if a root SOP, my position is what it is
                ret = GroupPosition;
            else
            {
                // If a child SOP, my position is relative to the root SOP so take
                //    my info and add the root's position and rotation to
                //    get my world position.
                Quaternion parentRot = ParentGroup.RootPart.RotationOffset;
                Vector3 translationOffsetPosition = OffsetPosition * parentRot;
                ret = ParentGroup.AbsolutePosition + translationOffsetPosition;
            }
            return ret;
        }

        /// <summary>
        /// Gets the rotation of this prim offset by the group rotation
        /// </summary>
        /// <returns></returns>
        public Quaternion GetWorldRotation()
        {
            Quaternion newRot;

            if (this.LinkNum == 0 || this.LinkNum == 1)
            {
                newRot = RotationOffset;
            }
            else
            {
                // A child SOP's rotation is relative to the root SOP's rotation.
                // Combine them to get my absolute rotation.
                Quaternion parentRot = ParentGroup.RootPart.RotationOffset;
                Quaternion oldRot = RotationOffset;
                newRot = parentRot * oldRot;
            }

            return newRot;
        }

        public void MoveToTarget(Vector3 target, float tau)
        {
            if (tau > 0)
            {
                ParentGroup.MoveToTarget(target, tau);
            }
            else
            {
                StopMoveToTarget();
            }
        }

        /// <summary>
        /// Uses a PID to attempt to clamp the object on the Z axis at the given height over tau seconds.
        /// </summary>
        /// <param name="height">Height to hover.  Height of zero disables hover.</param>
        /// <param name="hoverType">Determines what the height is relative to </param>
        /// <param name="tau">Number of seconds over which to reach target</param>
        public void SetHoverHeight(float height, PIDHoverType hoverType, float tau)
        {
            ParentGroup.SetHoverHeight(height, hoverType, tau);
        }

        public void StopHover()
        {
            ParentGroup.SetHoverHeight(0f, PIDHoverType.Ground, 0f);
        }

        public virtual void OnGrab(Vector3 offsetPos, IClientAPI remoteClient)
        {
        }

        public bool CollisionFilteredOut(UUID objectID, string objectName)
        {
            if(CollisionFilter.Count == 0)
                return false;

            if (CollisionFilter.ContainsValue(objectID.ToString()) ||
                CollisionFilter.ContainsValue(objectID.ToString() + objectName) ||
                CollisionFilter.ContainsValue(UUID.Zero.ToString() + objectName))
            {
                if (CollisionFilter.ContainsKey(1))
                    return false;
                return true;
            }

            if (CollisionFilter.ContainsKey(1))
                return true;

            return false;
        }

        private DetectedObject CreateDetObject(SceneObjectPart obj)
        {
            DetectedObject detobj = new DetectedObject();
            detobj.keyUUID = obj.UUID;
            detobj.nameStr = obj.Name;
            detobj.ownerUUID = obj.OwnerID;
            detobj.posVector = obj.AbsolutePosition;
            detobj.rotQuat = obj.GetWorldRotation();
            detobj.velVector = obj.Velocity;
            detobj.colliderType = 0;
            detobj.groupUUID = obj.GroupID;
            detobj.linkNumber = LinkNum;
            return detobj;
        }

        private DetectedObject CreateDetObject(ScenePresence av)
        {
            DetectedObject detobj = new DetectedObject();
            detobj.keyUUID = av.UUID;
            detobj.nameStr = av.ControllingClient.Name;
            detobj.ownerUUID = av.UUID;
            detobj.posVector = av.AbsolutePosition;
            detobj.rotQuat = av.Rotation;
            detobj.velVector = av.Velocity;
            detobj.colliderType = av.IsNPC ? 0x20 : 0x1; // OpenSim\Region\ScriptEngine\Shared\Helpers.cs
            if(av.IsSatOnObject)
                detobj.colliderType |= 0x4; //passive
            else if(detobj.velVector != Vector3.Zero)
                detobj.colliderType |= 0x2; //active
            detobj.groupUUID = av.ControllingClient.ActiveGroupId;
            detobj.linkNumber = LinkNum;

            return detobj;
        }

        private DetectedObject CreateDetObjectForGround()
        {
            DetectedObject detobj = new DetectedObject();
            detobj.keyUUID = UUID.Zero;
            detobj.nameStr = "";
            detobj.ownerUUID = UUID.Zero;
            detobj.posVector = ParentGroup.RootPart.AbsolutePosition;
            detobj.rotQuat = Quaternion.Identity;
            detobj.velVector = Vector3.Zero;
            detobj.colliderType = 0;
            detobj.groupUUID = UUID.Zero;
            detobj.linkNumber = LinkNum; // pass my link number not sure needed.. but no harm

            return detobj;
        }

        private ColliderArgs CreateColliderArgs(SceneObjectPart dest, List<uint> colliders)
        {
            ColliderArgs colliderArgs = new ColliderArgs();
            List<DetectedObject> colliding = new List<DetectedObject>();
            Scene parentScene = ParentGroup.Scene;
            foreach (uint localId in colliders)
            {
                if (localId == 0)
                    continue;

                SceneObjectPart obj = parentScene.GetSceneObjectPart(localId);
                if (obj != null)
                {
                    if (!dest.CollisionFilteredOut(obj.UUID, obj.Name))
                        colliding.Add(CreateDetObject(obj));
                }
                else
                {
                    ScenePresence av = parentScene.GetScenePresence(localId);
                    if (av != null && (!av.IsChildAgent))
                    {
                        if (!dest.CollisionFilteredOut(av.UUID, av.Name))
                            colliding.Add(CreateDetObject(av));
                    }
                }
            }

            colliderArgs.Colliders = colliding;

            return colliderArgs;
        }

        private delegate void ScriptCollidingNotification(uint localID, ColliderArgs message);

        private void SendCollisionEvent(scriptEvents ev, List<uint> colliders, ScriptCollidingNotification notify)
        {
            bool sendToRoot = false;
            ColliderArgs CollidingMessage;

            if (colliders.Count > 0)
            {
                if ((ScriptEvents & ev) != 0)
                {
                    CollidingMessage = CreateColliderArgs(this, colliders);

                    if (CollidingMessage.Colliders.Count > 0)
                        notify(LocalId, CollidingMessage);

                    if (PassCollisions)
                        sendToRoot = true;
                }
                else
                {
                    if ((ParentGroup.RootPart.ScriptEvents & ev) != 0)
                        sendToRoot = true;
                }
                if (sendToRoot && ParentGroup.RootPart != this)
                {
                    CollidingMessage = CreateColliderArgs(ParentGroup.RootPart, colliders);
                    if (CollidingMessage.Colliders.Count > 0)
                        notify(ParentGroup.RootPart.LocalId, CollidingMessage);
                }
            }
        }

        private void SendLandCollisionEvent(scriptEvents ev, ScriptCollidingNotification notify)
        {
            bool sendToRoot = true;

            ColliderArgs LandCollidingMessage = new ColliderArgs();
            List<DetectedObject> colliding = new List<DetectedObject>();

            colliding.Add(CreateDetObjectForGround());
            LandCollidingMessage.Colliders = colliding;

            if (Inventory.ContainsScripts())
            {
                if (!PassCollisions)
                    sendToRoot = false;
            }
            if ((ScriptEvents & ev) != 0)
                notify(LocalId, LandCollidingMessage);

            if ((ParentGroup.RootPart.ScriptEvents & ev) != 0 && sendToRoot)
            {
                notify(ParentGroup.RootPart.LocalId, LandCollidingMessage);
            }
        }

        public void PhysicsCollision(EventArgs e)
        {
            if (ParentGroup.Scene == null || ParentGroup.IsDeleted || ParentGroup.inTransit)
                return;

            // this a thread from physics ( heartbeat )
            bool thisHitLand = false;
            bool startLand = false;
            bool endedLand = false;

            CollisionEventUpdate a = (CollisionEventUpdate)e;
            Dictionary<uint, ContactPoint> collissionswith = a.m_objCollisionList;
            List<uint> thisHitColliders = new List<uint>();
            List<uint> endedColliders = new List<uint>();
            List<uint> startedColliders = new List<uint>();

            if (collissionswith.Count == 0)
            {
                if (m_lastColliders.Count == 0 && !m_lastLandCollide)
                    return; // nothing to do

                endedLand = m_lastLandCollide;
                m_lastLandCollide = false;

                foreach (uint localID in m_lastColliders)
                {
                    endedColliders.Add(localID);
                }

                m_lastColliders.Clear();
            }
            else
            {
                List<CollisionForSoundInfo> soundinfolist = new List<CollisionForSoundInfo>();

                // calculate things that started colliding this time
                // and build up list of colliders this time
                if (!VolumeDetectActive && CollisionSoundType >= 0)
                {
                    CollisionForSoundInfo soundinfo;
                    ContactPoint curcontact;

                    foreach (uint id in collissionswith.Keys)
                    {
                        if(id == 0)
                        {
                            thisHitLand = true;
                            if (!m_lastLandCollide)
                            {
                                startLand = true;
                                curcontact = collissionswith[id];
                                if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
                                {
                                    soundinfo = new CollisionForSoundInfo();
                                    soundinfo.colliderID = id;
                                    soundinfo.position = curcontact.Position;
                                    soundinfo.relativeVel = curcontact.RelativeSpeed;
                                    soundinfolist.Add(soundinfo);
                                }
                            }
                        }
                        else
                        {
                            thisHitColliders.Add(id);
                            if (!m_lastColliders.Contains(id))
                            {
                                startedColliders.Add(id);

                                curcontact = collissionswith[id];
                                if (Math.Abs(curcontact.RelativeSpeed) > 0.2)
                                {
                                    soundinfo = new CollisionForSoundInfo();
                                    soundinfo.colliderID = id;
                                    soundinfo.position = curcontact.Position;
                                    soundinfo.relativeVel = curcontact.RelativeSpeed;
                                    soundinfolist.Add(soundinfo);
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (uint id in collissionswith.Keys)
                    {
                        if(id == 0)
                        {
                            thisHitLand = true;
                            if (!m_lastLandCollide)
                                startLand = true;
                        }
                        else
                        {
                            thisHitColliders.Add(id);
                            if (!m_lastColliders.Contains(id))
                                startedColliders.Add(id);
                        }
                    }
                }

                // calculate things that ended colliding
                foreach (uint localID in m_lastColliders)
                {
                    if (!thisHitColliders.Contains(localID))
                        endedColliders.Add(localID);
                }

                //add the items that started colliding this time to the last colliders list.
                foreach (uint localID in startedColliders)
                    m_lastColliders.Add(localID);

                // remove things that ended colliding from the last colliders list
                foreach (uint localID in endedColliders)
                    m_lastColliders.Remove(localID);

                if(m_lastLandCollide && !thisHitLand)
                    endedLand = true;

                m_lastLandCollide = thisHitLand;

                // play sounds.
                if (soundinfolist.Count > 0)
                    CollisionSounds.PartCollisionSound(this, soundinfolist);
            }
            
            EventManager eventmanager = ParentGroup.Scene.EventManager;

            SendCollisionEvent(scriptEvents.collision_start, startedColliders, eventmanager.TriggerScriptCollidingStart);
            if (!VolumeDetectActive)
                SendCollisionEvent(scriptEvents.collision  , m_lastColliders , eventmanager.TriggerScriptColliding);
            SendCollisionEvent(scriptEvents.collision_end  , endedColliders  , eventmanager.TriggerScriptCollidingEnd);

            if (!VolumeDetectActive)
            {
                if (startLand)
                    SendLandCollisionEvent(scriptEvents.land_collision_start, eventmanager.TriggerScriptLandCollidingStart);
                if (m_lastLandCollide)
                    SendLandCollisionEvent(scriptEvents.land_collision, eventmanager.TriggerScriptLandColliding);
                if (endedLand)
                    SendLandCollisionEvent(scriptEvents.land_collision_end, eventmanager.TriggerScriptLandCollidingEnd);
            }
        }

        // The Collision sounds code calls this
        public void SendCollisionSound(UUID soundID, double volume, Vector3 position)
        {
            if (soundID == UUID.Zero)
                return;

            ISoundModule soundModule = ParentGroup.Scene.RequestModuleInterface<ISoundModule>();
            if (soundModule == null)
                return;

            if (volume > 1)
                volume = 1;
            if (volume < 0)
                volume = 0;

            int now = Util.EnvironmentTickCount();
            if(Util.EnvironmentTickCountSubtract(now, LastColSoundSentTime) < 200)
                return;

            LastColSoundSentTime = now;

            UUID ownerID = OwnerID;
            UUID objectID = ParentGroup.RootPart.UUID;
            UUID parentID = ParentGroup.UUID;
            ulong regionHandle = ParentGroup.Scene.RegionInfo.RegionHandle;

            soundModule.TriggerSound(soundID, ownerID, objectID, parentID, volume, position, regionHandle, 0 );
        }

        public void PhysicsOutOfBounds(Vector3 pos)
        {
            // Note: This is only being called on the root prim at this time.

            m_log.ErrorFormat(
                "[SCENE OBJECT PART]: Physical object {0}, localID {1} went out of bounds at {2} in {3}.  Stopping at {4} and making non-physical.",
                Name, LocalId, pos, ParentGroup.Scene.Name, AbsolutePosition);

            RemFlag(PrimFlags.Physics);
            DoPhysicsPropertyUpdate(false, true);
        }

        public void PhysicsRequestingTerseUpdate()
        {
            PhysicsActor pa = PhysActor;

            if (pa != null)
            {
                Vector3 newpos = pa.Position;
                if (!ParentGroup.Scene.PositionIsInCurrentRegion(newpos))
                {
                    // Setting position outside current region will start region crossing
                    ParentGroup.AbsolutePosition = newpos;
                    return;
                }
                //ParentGroup.RootPart.m_groupPosition = newpos;
            }
/*
            if (pa != null && _parentID != 0 && ParentGroup != null)
            {
                // Special case where a child object is requesting property updates.
                // This happens when linksets are modified to use flexible links rather than
                //    the default links.
                // The simulator code presumes that child parts are only modified by scripts
                //    so the logic for changing position/rotation/etc does not take into
                //    account the physical object actually moving.
                // This code updates the offset position and rotation of the child and then
                //    lets the update code push the update to the viewer.
                // Since physics engines do not normally generate this event for linkset children,
                //    this code will not be active unless you have a specially configured
                //    physics engine.
                Quaternion invRootRotation = Quaternion.Normalize(Quaternion.Inverse(ParentGroup.RootPart.RotationOffset));
                m_offsetPosition = pa.Position - m_groupPosition;
                RotationOffset = pa.Orientation * invRootRotation;
                // m_log.DebugFormat("{0} PhysicsRequestingTerseUpdate child: pos={1}, rot={2}, offPos={3}, offRot={4}",
                //                     "[SCENE OBJECT PART]", pa.Position, pa.Orientation, m_offsetPosition, RotationOffset);
            }
*/
            ScheduleTerseUpdate();
        }

        public void RemFlag(PrimFlags flag)
        {
            // PrimFlags prevflag = Flags;
            if ((Flags & flag) != 0)
            {
                //m_log.Debug("Removing flag: " + ((PrimFlags)flag).ToString());
                Flags &= ~flag;
            }
            //m_log.Debug("prev: " + prevflag.ToString() + " curr: " + Flags.ToString());
            //ScheduleFullUpdate();
        }

        public void RemoveScriptEvents(UUID scriptid)
        {
            lock (m_scriptEvents)
            {
                if (m_scriptEvents.ContainsKey(scriptid))
                {
                    scriptEvents oldparts = scriptEvents.None;
                    oldparts = (scriptEvents) m_scriptEvents[scriptid];

                    // remove values from aggregated script events
                    AggregateScriptEvents &= ~oldparts;
                    m_scriptEvents.Remove(scriptid);
                    aggregateScriptEvents();
                }
            }
        }

        /// <summary>
        /// Reset UUIDs for this part.  This involves generate this part's own UUID and
        /// generating new UUIDs for all the items in the inventory.
        /// </summary>
        /// <param name="linkNum">Link number for the part</param>
        public void ResetIDs(int linkNum)
        {
            UUID = UUID.Random();
            LinkNum = linkNum;
            LocalId = 0;
            Inventory.ResetInventoryIDs();
        }

        /// <summary>
        /// Set the scale of this part.
        /// </summary>
        /// <remarks>
        /// Unlike the scale property, this checks the new size against scene limits and schedules a full property
        /// update to viewers.
        /// </remarks>
        /// <param name="scale"></param>
        public void Resize(Vector3 scale)
        {
            PhysicsActor pa = PhysActor;

            if (ParentGroup.Scene != null)
            {
                float minsize = ParentGroup.Scene.m_minNonphys;
                float maxsize = ParentGroup.Scene.m_maxNonphys;
                if (pa != null && pa.IsPhysical)
                    {
                    minsize = ParentGroup.Scene.m_minPhys;
                    maxsize = ParentGroup.Scene.m_maxPhys;
                    }
                scale.X = Util.Clamp(scale.X, minsize, maxsize);
                scale.Y = Util.Clamp(scale.Y, minsize, maxsize);
                scale.Z = Util.Clamp(scale.Z, minsize, maxsize);
            }
//            m_log.DebugFormat("[SCENE OBJECT PART]: Resizing {0} {1} to {2}", Name, LocalId, scale);

            Scale = scale;

            ParentGroup.HasGroupChanged = true;
            ScheduleFullUpdate();
        }

        public void RotLookAt(Quaternion target, float strength, float damping)
        {
            if(ParentGroup.IsDeleted)
                return;

            // for now we only handle physics case
            if(!ParentGroup.UsesPhysics || ParentGroup.IsAttachment)
                return;

            // physical is SOG
            if(ParentGroup.RootPart != this)
            {
                ParentGroup.RotLookAt(target, strength, damping);
                return;
            }

            APIDDamp = damping;
            APIDStrength = strength;
            APIDTarget = target;

            if (APIDStrength <= 0)
            {
                m_log.WarnFormat("[SceneObjectPart] Invalid rotation strength {0}",APIDStrength);
                return;
            }

            APIDActive = true;

            // Necessary to get the lookat deltas applied
            ParentGroup.QueueForUpdateCheck();
        }

        public void StartLookAt(Quaternion target, float strength, float damping)
        {
            if(ParentGroup.IsDeleted)
                return;

            // non physical is done on LSL
            if(ParentGroup.IsAttachment || !ParentGroup.UsesPhysics)
                return;

            // physical is SOG
            if(ParentGroup.RootPart != this)
                ParentGroup.RotLookAt(target, strength, damping);
            else
                RotLookAt(target,strength,damping);
        }

        public void StopLookAt()
        {
            if(ParentGroup.IsDeleted)
                return;

            if(ParentGroup.RootPart != this && ParentGroup.UsesPhysics)
                 ParentGroup.StopLookAt();

            // just in case do this always
            if(APIDActive)
                AngularVelocity = Vector3.Zero;

            APIDActive = false;
        }

        /// <summary>
        /// Schedules this prim for a full update
        /// </summary>
        public void ScheduleFullUpdate()
        {
//            m_log.DebugFormat("[SCENE OBJECT PART]: Scheduling full update for {0} {1}", Name, LocalId);

            if (ParentGroup == null)
                return;
            if (ParentGroup.Scene == null)
                return;

            if(ParentGroup.Scene.GetNumberOfClients() == 0)
                return;

            ParentGroup.QueueForUpdateCheck(); // just in case

            lock(UpdateFlagLock)
            {
                if(UpdateFlag != UpdateRequired.FULL)
                {
                    UpdateFlag = UpdateRequired.FULL;

                    //            m_log.DebugFormat(
                    //                "[SCENE OBJECT PART]: Scheduling full  update for {0}, {1} at {2}",
                    //                UUID, Name, TimeStampFull);

                }
            }
            ParentGroup.Scene.EventManager.TriggerSceneObjectPartUpdated(this, true);
        }

        /// <summary>
        /// Schedule a terse update for this prim.  Terse updates only send position,
        /// rotation, velocity and rotational velocity information. WRONG!!!!
        /// </summary>
        public void ScheduleTerseUpdate()
        {
            if (ParentGroup == null)
                return;
            if (ParentGroup.Scene == null)
                return;

            ParentGroup.HasGroupChanged = true;

            if(ParentGroup.Scene.GetNumberOfClients() == 0)
                return;

            // This was pulled from SceneViewer. Attachments always receive full updates.
            // This is needed because otherwise if only the root prim changes position, then
            // it looks as if the entire object has moved (including the other prims).
            if (ParentGroup.IsAttachment)
            {
                ScheduleFullUpdate();
                return;
            }

            ParentGroup.QueueForUpdateCheck();
            lock(UpdateFlagLock)
            {
                if (UpdateFlag == UpdateRequired.NONE)
                {
                    UpdateFlag = UpdateRequired.TERSE;

                    //            m_log.DebugFormat(
                    //                "[SCENE OBJECT PART]: Scheduling terse update for {0}, {1}",
                    //                UUID, Name);
                }
            }
            ParentGroup.Scene.EventManager.TriggerSceneObjectPartUpdated(this, false);
        }

        public void ScriptSetPhysicsStatus(bool UsePhysics)
        {
            ParentGroup.ScriptSetPhysicsStatus(UsePhysics);
        }

        /// <summary>
        /// Send a full update to the client for the given part
        /// </summary>
        /// <param name="remoteClient"></param>
        protected internal void SendFullUpdate(IClientAPI remoteClient)
        {
            if (ParentGroup == null)
                return;

//            m_log.DebugFormat(
//                "[SOG]: Sendinging part full update to {0} for {1} {2}", remoteClient.Name, part.Name, part.LocalId);


            if (ParentGroup.IsAttachment)
            {
                ScenePresence sp = ParentGroup.Scene.GetScenePresence(ParentGroup.AttachedAvatar);
                if (sp != null)
                {
                    sp.SendAttachmentUpdate(this, UpdateRequired.FULL);
                }
            }
            else
            {
                SendFullUpdateToClient(remoteClient);
            }
        }

        /// <summary>
        /// Send a full update for this part to all clients.
        /// </summary>
        public void SendFullUpdateToAllClientsInternal()
        {
            if (ParentGroup == null)
                return;

            // Update the "last" values
            lock(UpdateFlagLock)
            {
                m_lastPosition = AbsolutePosition;
                m_lastRotation = RotationOffset;
                m_lastVelocity = Velocity;
                m_lastAcceleration = Acceleration;
                m_lastAngularVelocity = AngularVelocity;
                m_lastUpdateSentTime = Util.GetTimeStampMS();
            }

            ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
            {
                SendFullUpdate(avatar.ControllingClient);
            });
        }

        public void SendFullUpdateToAllClients()
        {
            if (ParentGroup == null)
                return;

            // Update the "last" values
            lock(UpdateFlagLock)
            {
                m_lastPosition = AbsolutePosition;
                m_lastRotation = RotationOffset;
                m_lastVelocity = Velocity;
                m_lastAcceleration = Acceleration;
                m_lastAngularVelocity = AngularVelocity;
                m_lastUpdateSentTime = Util.GetTimeStampMS();
            }

            if (ParentGroup.IsAttachment)
            {
                ScenePresence sp = ParentGroup.Scene.GetScenePresence(ParentGroup.AttachedAvatar);
                if (sp != null)
                {
                    sp.SendAttachmentUpdate(this, UpdateRequired.FULL);
                }
            }
            else
            {
                ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
                {
                    SendFullUpdate(avatar.ControllingClient);
                });
            }
        }

        /// <summary>
        /// Sends a full update to the client
        /// </summary>
        /// <param name="remoteClient"></param>
        public void SendFullUpdateToClient(IClientAPI remoteClient)
        {
             if (ParentGroup == null || ParentGroup.IsDeleted)
                return;

            if (ParentGroup.IsAttachment
                && ParentGroup.AttachedAvatar != remoteClient.AgentId
                && ParentGroup.HasPrivateAttachmentPoint)
                return;

            if (remoteClient.AgentId == OwnerID)
            {
                if ((Flags & PrimFlags.CreateSelected) != 0)
                    Flags &= ~PrimFlags.CreateSelected;
            }
            //bool isattachment = IsAttachment;
            //if (LocalId != ParentGroup.RootPart.LocalId)
                //isattachment = ParentGroup.RootPart.IsAttachment;

            remoteClient.SendEntityUpdate(this, PrimUpdateFlags.FullUpdate);
            ParentGroup.Scene.StatsReporter.AddObjectUpdates(1);
        }

        private const float ROTATION_TOLERANCE = 0.01f;
        private const float VELOCITY_TOLERANCE = 0.1f;
        private const float ANGVELOCITY_TOLERANCE = 0.005f;
        private const float POSITION_TOLERANCE = 0.05f; // I don't like this, but I suppose it's necessary
        private const double TIME_MS_TOLERANCE = 200.0; //llSetPos has a 200ms delay. This should NOT be 3 seconds.
        
        /// <summary>
        /// Tell all the prims which have had updates scheduled
        /// </summary>
        public void SendScheduledUpdates(double now)
        {  
            bool sendterse = false;    
            bool sendfull = false;    

            lock(UpdateFlagLock)
            {
                switch (UpdateFlag)
                {
                    case UpdateRequired.NONE:
                        break;

                    case UpdateRequired.TERSE:
                        sendterse = true;

                        Vector3 curvel = Velocity;
                        Vector3 curacc = Acceleration;
                        Vector3 angvel = AngularVelocity;

                        while(true) // just to avoid ugly goto
                        {
                            double elapsed = now - m_lastUpdateSentTime;
                            if (elapsed > TIME_MS_TOLERANCE)
                                break;

                            if( Math.Abs(curacc.X - m_lastAcceleration.X) >  VELOCITY_TOLERANCE ||
                                Math.Abs(curacc.Y - m_lastAcceleration.Y) >  VELOCITY_TOLERANCE ||
                                Math.Abs(curacc.Z - m_lastAcceleration.Z) >  VELOCITY_TOLERANCE)
                                break;
                          
                            if( Math.Abs(curvel.X - m_lastVelocity.X) >  VELOCITY_TOLERANCE ||
                                Math.Abs(curvel.Y - m_lastVelocity.Y) >  VELOCITY_TOLERANCE ||
                                Math.Abs(curvel.Z - m_lastVelocity.Z) >  VELOCITY_TOLERANCE)
                                break;
                        
                            float vx = Math.Abs(curvel.X);
                            if(vx > 128.0)
                                break;
                            float vy = Math.Abs(curvel.Y);
                            if(vy > 128.0)
                                break;
                            float vz = Math.Abs(curvel.Z);
                            if(vz > 128.0)
                                break;

                            if (
                                vx <  VELOCITY_TOLERANCE &&
                                vy <  VELOCITY_TOLERANCE &&
                                vz <  VELOCITY_TOLERANCE
                                )
                            {
                                if(!AbsolutePosition.ApproxEquals(m_lastPosition, POSITION_TOLERANCE))
                                    break;
                            
                                if (vx <  1e-4 &&
                                    vy <  1e-4 &&
                                    vz <  1e-4 &&
                                    (
                                        Math.Abs(m_lastVelocity.X) > 1e-4 ||
                                        Math.Abs(m_lastVelocity.Y) > 1e-4 ||
                                        Math.Abs(m_lastVelocity.Z) > 1e-4
                                    ))
                                    break;
                            }

                            if( Math.Abs(angvel.X - m_lastAngularVelocity.X) >  ANGVELOCITY_TOLERANCE ||
                                Math.Abs(angvel.Y - m_lastAngularVelocity.Y) >  ANGVELOCITY_TOLERANCE ||
                                Math.Abs(angvel.Z - m_lastAngularVelocity.Z) >  ANGVELOCITY_TOLERANCE)
                                break;

                            // viewer interpolators have a limit of 64rad/s
                            float ax = Math.Abs(angvel.X);
                            if(ax > 64.0)
                                break;
                            float ay = Math.Abs(angvel.Y);
                            if(ay > 64.0)
                                break;
                            float az = Math.Abs(angvel.Z);
                            if(az > 64.0)
                                break;

                            if (
                                ax <  ANGVELOCITY_TOLERANCE &&
                                ay <  ANGVELOCITY_TOLERANCE &&
                                az <  ANGVELOCITY_TOLERANCE &&
                                !RotationOffset.ApproxEquals(m_lastRotation, ROTATION_TOLERANCE)
                                )
                                break;

                            sendterse = false;
                            break;
                        }

                        if(sendterse)
                        {
                            // Update the "last" values
                            m_lastPosition = AbsolutePosition;
                            m_lastRotation = RotationOffset;
                            m_lastVelocity = curvel;
                            m_lastAcceleration = curacc;
                            m_lastAngularVelocity = angvel;
                            m_lastUpdateSentTime = now;
                            ClearUpdateSchedule();
                        }
                        break;

                    case UpdateRequired.FULL:
                        m_lastPosition = AbsolutePosition;
                        m_lastRotation = RotationOffset;
                        m_lastVelocity = Velocity;
                        m_lastAcceleration = Acceleration;
                        m_lastAngularVelocity = AngularVelocity;
                        m_lastUpdateSentTime = now;
                        ClearUpdateSchedule();
                        sendfull = true;
                        break;
                }
            }
            if(sendterse)
            {
                ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
                {
                    SendTerseUpdateToClient(client);
                });
            }
            else if(sendfull)
            {
                ParentGroup.Scene.ForEachScenePresence(delegate(ScenePresence avatar)
                {
                    SendFullUpdate(avatar.ControllingClient);
                });
            }
        }

        /// <summary>
        /// Send a terse update to all clients
        /// </summary>
        public void SendTerseUpdateToAllClientsInternal()
        {
            if (ParentGroup == null || ParentGroup.Scene == null)
                return;
            lock(UpdateFlagLock)
            {
                if(UpdateFlag != UpdateRequired.NONE)
                    return;

                // Update the "last" values
                m_lastPosition = AbsolutePosition;
                m_lastRotation = RotationOffset;
                m_lastVelocity = Velocity;
                m_lastAcceleration = Acceleration;
                m_lastAngularVelocity = AngularVelocity;
                m_lastUpdateSentTime = Util.GetTimeStampMS();
            }

            ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
            {
                SendTerseUpdateToClient(client);
            });
        }

        public void SendTerseUpdateToAllClients()
        {
            if (ParentGroup == null || ParentGroup.Scene == null)
                return;

            lock(UpdateFlagLock)
            {
                if(UpdateFlag != UpdateRequired.NONE)
                    return;

                // Update the "last" values
                m_lastPosition = AbsolutePosition;
                m_lastRotation = RotationOffset;
                m_lastVelocity = Velocity;
                m_lastAcceleration = Acceleration;
                m_lastAngularVelocity = AngularVelocity;
                m_lastUpdateSentTime = Util.GetTimeStampMS();
            }

            if (ParentGroup.IsAttachment)
            {
                ScenePresence sp = ParentGroup.Scene.GetScenePresence(ParentGroup.AttachedAvatar);
                if (sp != null)
                {
                    sp.SendAttachmentUpdate(this, UpdateRequired.TERSE);
                }
            }
            else
            {
                ParentGroup.Scene.ForEachClient(delegate(IClientAPI client)
                {
                    SendTerseUpdateToClient(client);
                });
            }
        }

        public void SetAxisRotation(int axis, int rotate)
        {
            ParentGroup.SetAxisRotation(axis, rotate);

            //Cannot use ScriptBaseClass constants as no referance to it currently.
            if ((axis & (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_X) != 0)
                STATUS_ROTATE_X = rotate;

            if ((axis & (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_Y) != 0)
                STATUS_ROTATE_Y = rotate;

            if ((axis & (int)SceneObjectGroup.axisSelect.STATUS_ROTATE_Z) != 0)
                STATUS_ROTATE_Z = rotate;
        }

        public void SetBuoyancy(float fvalue)
        {
            Buoyancy = fvalue;
/*
            if (PhysActor != null)
            {
                PhysActor.Buoyancy = fvalue;
            }
 */
        }

        public void SetDieAtEdge(bool p)
        {
            if (ParentGroup.IsDeleted)
                return;

            ParentGroup.RootPart.DIE_AT_EDGE = p;
        }

        public void SetFloatOnWater(int floatYN)
        {
            PhysicsActor pa = PhysActor;

            if (pa != null)
                pa.FloatOnWater = (floatYN == 1);
        }

        public void SetForce(Vector3 force)
        {
            Force = force;
        }

        public PhysicsInertiaData PhysicsInertia
        {
            get
            {
                return m_physicsInertia;
            }
            set
            {
                m_physicsInertia = value;
            }
        }

        public SOPVehicle VehicleParams
        {
            get
            {
                return m_vehicleParams;
            }
            set
            {
                m_vehicleParams = value;

            }
        }

        public int VehicleType
        {
            get
            {
                if (m_vehicleParams == null)
                    return (int)Vehicle.TYPE_NONE;
                else
                    return (int)m_vehicleParams.Type;
            }
            set
            {
                SetVehicleType(value);
            }
        }

        public void SetVehicleType(int type)
        {
                m_vehicleParams = null;

                if (type == (int)Vehicle.TYPE_NONE)
                {
                    if (_parentID ==0 && PhysActor != null)
                        PhysActor.VehicleType = (int)Vehicle.TYPE_NONE;
                    return;
                }
                m_vehicleParams = new SOPVehicle();
                m_vehicleParams.ProcessTypeChange((Vehicle)type);
                {
                    if (_parentID ==0 && PhysActor != null)
                        PhysActor.VehicleType = type;
                    return;
                }
        }

        public void SetVehicleFlags(int param, bool remove)
        {
            if (m_vehicleParams == null)
                return;

            m_vehicleParams.ProcessVehicleFlags(param, remove);

            if (_parentID == 0 && PhysActor != null)
            {
                PhysActor.VehicleFlags(param, remove);
            }
        }

        public void SetVehicleFloatParam(int param, float value)
        {
            if (m_vehicleParams == null)
                return;

            m_vehicleParams.ProcessFloatVehicleParam((Vehicle)param, value);

            if (_parentID == 0 && PhysActor != null)
            {
                PhysActor.VehicleFloatParam(param, value);
            }
        }

        public void SetVehicleVectorParam(int param, Vector3 value)
        {
            if (m_vehicleParams == null)
                return;

            m_vehicleParams.ProcessVectorVehicleParam((Vehicle)param, value);

            if (_parentID == 0 && PhysActor != null)
            {
                PhysActor.VehicleVectorParam(param, value);
            }
        }

        public void SetVehicleRotationParam(int param, Quaternion rotation)
        {
            if (m_vehicleParams == null)
                return;

            m_vehicleParams.ProcessRotationVehicleParam((Vehicle)param, rotation);

            if (_parentID == 0 && PhysActor != null)
            {
                PhysActor.VehicleRotationParam(param, rotation);
            }
        }

        /// <summary>
        /// Set the color & alpha of prim faces
        /// </summary>
        /// <param name="face"></param>
        /// <param name="color"></param>
        /// <param name="alpha"></param>
        public void SetFaceColorAlpha(int face, Vector3 color, double ?alpha)
        {
            Vector3 clippedColor = Util.Clip(color, 0.0f, 1.0f);
            float clippedAlpha = alpha.HasValue ?
                Util.Clip((float)alpha.Value, 0.0f, 1.0f) : 0;

            // The only way to get a deep copy/ If we don't do this, we can
            // never detect color changes further down.
            Byte[] buf = Shape.Textures.GetBytes();
            Primitive.TextureEntry tex = new Primitive.TextureEntry(buf, 0, buf.Length);
            Color4 texcolor;
            int nsides = GetNumberOfSides();
            if (face >= 0 && face < nsides)
            {
                texcolor = tex.CreateFace((uint)face).RGBA;
                texcolor.R = clippedColor.X;
                texcolor.G = clippedColor.Y;
                texcolor.B = clippedColor.Z;
                if (alpha.HasValue)
                {
                    texcolor.A = clippedAlpha;
                }
                tex.FaceTextures[face].RGBA = texcolor;
                UpdateTextureEntry(tex.GetBytes());
                return;
            }
            else if (face == ALL_SIDES)
            {
                for (uint i = 0; i < nsides; i++)
                {
                    if (tex.FaceTextures[i] != null)
                    {
                        texcolor = tex.FaceTextures[i].RGBA;
                        texcolor.R = clippedColor.X;
                        texcolor.G = clippedColor.Y;
                        texcolor.B = clippedColor.Z;
                        if (alpha.HasValue)
                        {
                            texcolor.A = clippedAlpha;
                        }
                        tex.FaceTextures[i].RGBA = texcolor;
                    }
                    texcolor = tex.DefaultTexture.RGBA;
                    texcolor.R = clippedColor.X;
                    texcolor.G = clippedColor.Y;
                    texcolor.B = clippedColor.Z;
                    if (alpha.HasValue)
                    {
                        texcolor.A = clippedAlpha;
                    }
                    tex.DefaultTexture.RGBA = texcolor;
                }
                UpdateTextureEntry(tex.GetBytes());
                return;
            }
        }

        /// <summary>
        /// Get the number of sides that this part has.
        /// </summary>
        /// <returns></returns>
        public int GetNumberOfSides()
        {
            int ret = 0;

            if(Shape.SculptEntry)
            {
                if (Shape.SculptType != (byte)SculptType.Mesh)
                    return 1; // sculp

                //hack to detect new upload with faces data enconded on pbs              
                if ((Shape.ProfileCurve & 0xf0) != (byte)HollowShape.Triangle)
                    // old broken upload TODO
                    return 8;
            }

            PrimType primType = GetPrimType(true);

            switch (primType)
            {
                case PrimType.BOX:
                    ret = 6;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0) // cut case
                    {
                        // removed sides
                        int cut = (Shape.ProfileEnd + Shape.ProfileBegin);
                        if(cut > 50000) // range is 0 to 50000
                            cut = 50000;
                        cut /= 12500; // ie 1/4 
                        ret -= cut;
                        ret += 2; // both cut faces
                    }
                    break;
                case PrimType.PRISM:
                    ret = 5;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0) // cut case
                    {
                        // removed faces
                        int cut = (Shape.ProfileEnd + Shape.ProfileBegin);
                        if(cut >= 16667 ) // ie 1/3 
                            ret--;
                        if(cut >= 33333 ) // ie 2/3
                            ret--;
                        ret += 2; // both cut faces
                    }
                    break;
                case PrimType.CYLINDER:
                    ret = 3;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0) // cut
                        ret += 2;
                    break;
                case PrimType.SPHERE:
                    ret = 1;
                    // cut faces exist if cut or skew or unequal twist limits
                    if (Shape.PathBegin > 0 || Shape.PathEnd > 0 || Shape.PathSkew != 0 || (Shape.PathTwistBegin != Shape.PathTwist))
                        ret += 2;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0 || Shape.ProfileHollow > 0) // dimple faces also if hollow
                        ret += 2;
                    break;
                case PrimType.TORUS:
                    ret = 1;
                    if (Shape.PathBegin > 0 || Shape.PathEnd > 0 || Shape.PathSkew != 0
                            || Shape.PathTaperX != 0 || Shape.PathTaperY != 0 || Shape.PathRevolutions > 0
                            || Shape.PathRadiusOffset != 0 || (Shape.PathTwistBegin != Shape.PathTwist))
                        ret += 2;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0) // profile cut
                        ret += 2;
                    break;
                case PrimType.TUBE:
                    ret = 4;
                    if (Shape.PathBegin > 0 || Shape.PathEnd > 0 || Shape.PathSkew != 0
                            || Shape.PathTaperX != 0 || Shape.PathTaperY != 0 || Shape.PathRevolutions > 0
                            || Shape.PathRadiusOffset != 0 || (Shape.PathTwistBegin != Shape.PathTwist))
                        ret += 2;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0) // profile cut
                    {
                        // removed sides
                        int cut = (Shape.ProfileEnd + Shape.ProfileBegin);
                        if(cut > 50000)
                            cut = 50000;
                        cut /= 12500;
                        ret -= cut;
                        ret += 2; // both cut faces
                    }
                    break;
                case PrimType.RING:
                    ret = 3;
                    if (Shape.PathBegin > 0 || Shape.PathEnd > 0 || Shape.PathSkew != 0
                            || Shape.PathTaperX != 0 || Shape.PathTaperY != 0 || Shape.PathRevolutions > 0
                            || Shape.PathRadiusOffset != 0 || (Shape.PathTwistBegin != Shape.PathTwist))
                        ret += 2;
                    if (Shape.ProfileBegin > 0 || Shape.ProfileEnd > 0) // profile cut
                    {
                        // removed faces
                        int cut = (Shape.ProfileEnd + Shape.ProfileBegin);
                        if(cut >= 16667 )
                            ret--;
                        if(cut >= 33333 )
                            ret--;
                        ret += 2; // both cut faces
                    }
                    break;
            }

            // hollow face commum to all
            if (Shape.ProfileHollow > 0)
                ret += 1;

            return ret;
        }

        /// <summary>
        /// Tell us what type this prim is
        /// </summary>
        /// <param name="primShape"></param>
        /// <returns></returns>
        public PrimType GetPrimType(bool ignoreSculpt = false)
        {
            if (Shape.SculptEntry && !ignoreSculpt)
                return PrimType.SCULPT;

            if ((Shape.ProfileCurve & 0x07) == (byte)ProfileShape.Square)
            {
                if (Shape.PathCurve == (byte)Extrusion.Straight)
                    return PrimType.BOX;
                else if (Shape.PathCurve == (byte)Extrusion.Curve1)
                    return PrimType.TUBE;
            }
            else if ((Shape.ProfileCurve & 0x07) == (byte)ProfileShape.Circle)
            {
                if (Shape.PathCurve == (byte)Extrusion.Straight || Shape.PathCurve == (byte)Extrusion.Flexible)
                    return PrimType.CYLINDER;
                // ProfileCurve seems to combine hole shape and profile curve so we need to only compare against the lower 3 bits
                else if (Shape.PathCurve == (byte)Extrusion.Curve1)
                    return PrimType.TORUS;
            }
            else if ((Shape.ProfileCurve & 0x07) == (byte)ProfileShape.HalfCircle)
            {
                if (Shape.PathCurve == (byte)Extrusion.Curve1 || Shape.PathCurve == (byte)Extrusion.Curve2)
                    return PrimType.SPHERE;
            }
            else if ((Shape.ProfileCurve & 0x07) == (byte)ProfileShape.EquilateralTriangle)
            {
                if (Shape.PathCurve == (byte)Extrusion.Straight || Shape.PathCurve == (byte)Extrusion.Flexible)
                    return PrimType.PRISM;
                else if (Shape.PathCurve == (byte)Extrusion.Curve1)
                    return PrimType.RING;
            }

            return PrimType.BOX;
        }

        public void SetGroup(UUID groupID, IClientAPI client)
        {
            // Scene.AddNewPrims() calls with client == null so can't use this.
//            m_log.DebugFormat(
//                "[SCENE OBJECT PART]: Setting group for {0} to {1} for {2}",
//                Name, groupID, OwnerID);

            GroupID = groupID;
//            if (client != null)
//                SendPropertiesToClient(client);
            UpdateFlag = UpdateRequired.FULL;
        }

        /// <summary>
        /// Set the parent group of this prim.
        /// </summary>
        public void SetParent(SceneObjectGroup parent)
        {
            ParentGroup = parent;
        }

        // Use this for attachments!  LocalID should be avatar's localid
        public void SetParentLocalId(uint localID)
        {
            ParentID = localID;
        }

        public void SetPhysicsAxisRotation()
        {
            PhysicsActor pa = PhysActor;

            if (pa != null)
            {
                pa.LockAngularMotion(RotationAxisLocks);
                ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
            }
        }

        /// <summary>
        /// Set the events that this part will pass on to listeners.
        /// </summary>
        /// <param name="scriptid"></param>
        /// <param name="events"></param>
        public void SetScriptEvents(UUID scriptid, int events)
        {
//            m_log.DebugFormat(
//                "[SCENE OBJECT PART]: Set script events for script with id {0} on {1}/{2} to {3} in {4}",
//                scriptid, Name, ParentGroup.Name, events, ParentGroup.Scene.Name);

            // scriptEvents oldparts;
            lock (m_scriptEvents)
            {
                if (m_scriptEvents.ContainsKey(scriptid))
                {
                    // oldparts = m_scriptEvents[scriptid];

                    // remove values from aggregated script events
                    if (m_scriptEvents[scriptid] == (scriptEvents) events)
                        return;
                    m_scriptEvents[scriptid] = (scriptEvents) events;
                }
                else
                {
                    m_scriptEvents.Add(scriptid, (scriptEvents) events);
                }
            }
            aggregateScriptEvents();
        }

        /// <summary>
        /// Set the text displayed for this part.
        /// </summary>
        /// <param name="text"></param>
        public void SetText(string text)
        {
            Text = text;

            if (ParentGroup != null)
            {
                ParentGroup.HasGroupChanged = true;
                ScheduleFullUpdate();
            }
        }

        /// <summary>
        /// Set the text displayed for this part.
        /// </summary>
        /// <param name="text"></param>
        /// <param name="color"></param>
        /// <param name="alpha"></param>
        public void SetText(string text, Vector3 color, double alpha)
        {
            Color = Color.FromArgb((int) (alpha*0xff),
                                   (int) (color.X*0xff),
                                   (int) (color.Y*0xff),
                                   (int) (color.Z*0xff));
            SetText(text);
        }

        public void StopMoveToTarget()
        {
            ParentGroup.StopMoveToTarget();
        }

        public void StoreUndoState(ObjectChangeType change)
        {
            lock (m_UndoLock)
            {
                if (m_UndoRedo == null)
                    m_UndoRedo = new UndoRedoState(5);

                if (!Undoing && !IgnoreUndoUpdate && ParentGroup != null) // just to read better  - undo is in progress, or suspended
                {
                    m_UndoRedo.StoreUndo(this, change);
                }
            }
        }

        /// <summary>
        /// Return number of undos on the stack.  Here temporarily pending a refactor.
        /// </summary>
        public int UndoCount
        {
            get
            {
                if (m_UndoRedo == null)
                    return 0;
                return m_UndoRedo.Count;
            }
        }

        public void Undo()
        {
            lock (m_UndoLock)
            {
                if (m_UndoRedo == null || Undoing || ParentGroup == null)
                    return;

                Undoing = true;
                m_UndoRedo.Undo(this);
                Undoing = false;
            }
        }

        public void Redo()
        {
            lock (m_UndoLock)
            {
                if (m_UndoRedo == null || Undoing || ParentGroup == null)
                    return;

                Undoing = true;
                m_UndoRedo.Redo(this);
                Undoing = false;
            }
        }

        public void ClearUndoState()
        {
            lock (m_UndoLock)
            {
                if (m_UndoRedo == null || Undoing)
                    return;

                m_UndoRedo.Clear();
            }
        }

        public EntityIntersection TestIntersectionOBB(Ray iray, Quaternion parentrot, bool frontFacesOnly, bool faceCenters)
        {
            // In this case we're using a rectangular prism, which has 6 faces and therefore 6 planes
            // This breaks down into the ray---> plane equation.
            // TODO: Change to take shape into account
            Vector3[] vertexes = new Vector3[8];

            // float[] distance = new float[6];
            Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
            Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
            Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
            Vector3[] FaceD = new Vector3[6]; // vertex D for Facei

            Vector3[] normals = new Vector3[6]; // Normal for Facei
            Vector3[] AAfacenormals = new Vector3[6]; // Axis Aligned face normals

            AAfacenormals[0] = new Vector3(1, 0, 0);
            AAfacenormals[1] = new Vector3(0, 1, 0);
            AAfacenormals[2] = new Vector3(-1, 0, 0);
            AAfacenormals[3] = new Vector3(0, -1, 0);
            AAfacenormals[4] = new Vector3(0, 0, 1);
            AAfacenormals[5] = new Vector3(0, 0, -1);

            Vector3 AmBa = new Vector3(0, 0, 0); // Vertex A - Vertex B
            Vector3 AmBb = new Vector3(0, 0, 0); // Vertex B - Vertex C
            Vector3 cross = new Vector3();

            Vector3 pos = GetWorldPosition();
            Quaternion rot = GetWorldRotation();

            // Variables prefixed with AX are Axiom.Math copies of the LL variety.

            Quaternion AXrot = rot;
            AXrot.Normalize();

            Vector3 AXpos = pos;

            // tScale is the offset to derive the vertex based on the scale.
            // it's different for each vertex because we've got to rotate it
            // to get the world position of the vertex to produce the Oriented Bounding Box

            Vector3 tScale = Vector3.Zero;

            Vector3 AXscale = new Vector3(m_shape.Scale.X * 0.5f, m_shape.Scale.Y * 0.5f, m_shape.Scale.Z * 0.5f);

            //Vector3 pScale = (AXscale) - (AXrot.Inverse() * (AXscale));
            //Vector3 nScale = (AXscale * -1) - (AXrot.Inverse() * (AXscale * -1));

            // rScale is the rotated offset to find a vertex based on the scale and the world rotation.
            Vector3 rScale = new Vector3();

            // Get Vertexes for Faces Stick them into ABCD for each Face
            // Form: Face<vertex>[face] that corresponds to the below diagram
            #region ABCD Face Vertex Map Comment Diagram
            //                   A _________ B
            //                    |         |
            //                    |  4 top  |
            //                    |_________|
            //                   C           D

            //                   A _________ B
            //                    |  Back   |
            //                    |    3    |
            //                    |_________|
            //                   C           D

            //   A _________ B                     B _________ A
            //    |  Left   |                       |  Right  |
            //    |    0    |                       |    2    |
            //    |_________|                       |_________|
            //   C           D                     D           C

            //                   A _________ B
            //                    |  Front  |
            //                    |    1    |
            //                    |_________|
            //                   C           D

            //                   C _________ D
            //                    |         |
            //                    |  5 bot  |
            //                    |_________|
            //                   A           B
            #endregion

            #region Plane Decomposition of Oriented Bounding Box
            tScale = new Vector3(AXscale.X, -AXscale.Y, AXscale.Z);
            rScale = tScale * AXrot;
            vertexes[0] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));
               // vertexes[0].X = pos.X + vertexes[0].X;
            //vertexes[0].Y = pos.Y + vertexes[0].Y;
            //vertexes[0].Z = pos.Z + vertexes[0].Z;

            FaceA[0] = vertexes[0];
            FaceB[3] = vertexes[0];
            FaceA[4] = vertexes[0];

            tScale = AXscale;
            rScale = tScale * AXrot;
            vertexes[1] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

               // vertexes[1].X = pos.X + vertexes[1].X;
               // vertexes[1].Y = pos.Y + vertexes[1].Y;
            //vertexes[1].Z = pos.Z + vertexes[1].Z;

            FaceB[0] = vertexes[1];
            FaceA[1] = vertexes[1];
            FaceC[4] = vertexes[1];

            tScale = new Vector3(AXscale.X, -AXscale.Y, -AXscale.Z);
            rScale = tScale * AXrot;

            vertexes[2] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

            //vertexes[2].X = pos.X + vertexes[2].X;
            //vertexes[2].Y = pos.Y + vertexes[2].Y;
            //vertexes[2].Z = pos.Z + vertexes[2].Z;

            FaceC[0] = vertexes[2];
            FaceD[3] = vertexes[2];
            FaceC[5] = vertexes[2];

            tScale = new Vector3(AXscale.X, AXscale.Y, -AXscale.Z);
            rScale = tScale * AXrot;
            vertexes[3] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

            //vertexes[3].X = pos.X + vertexes[3].X;
               // vertexes[3].Y = pos.Y + vertexes[3].Y;
               // vertexes[3].Z = pos.Z + vertexes[3].Z;

            FaceD[0] = vertexes[3];
            FaceC[1] = vertexes[3];
            FaceA[5] = vertexes[3];

            tScale = new Vector3(-AXscale.X, AXscale.Y, AXscale.Z);
            rScale = tScale * AXrot;
            vertexes[4] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

               // vertexes[4].X = pos.X + vertexes[4].X;
               // vertexes[4].Y = pos.Y + vertexes[4].Y;
               // vertexes[4].Z = pos.Z + vertexes[4].Z;

            FaceB[1] = vertexes[4];
            FaceA[2] = vertexes[4];
            FaceD[4] = vertexes[4];

            tScale = new Vector3(-AXscale.X, AXscale.Y, -AXscale.Z);
            rScale = tScale * AXrot;
            vertexes[5] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

               // vertexes[5].X = pos.X + vertexes[5].X;
               // vertexes[5].Y = pos.Y + vertexes[5].Y;
               // vertexes[5].Z = pos.Z + vertexes[5].Z;

            FaceD[1] = vertexes[5];
            FaceC[2] = vertexes[5];
            FaceB[5] = vertexes[5];

            tScale = new Vector3(-AXscale.X, -AXscale.Y, AXscale.Z);
            rScale = tScale * AXrot;
            vertexes[6] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

               // vertexes[6].X = pos.X + vertexes[6].X;
               // vertexes[6].Y = pos.Y + vertexes[6].Y;
               // vertexes[6].Z = pos.Z + vertexes[6].Z;

            FaceB[2] = vertexes[6];
            FaceA[3] = vertexes[6];
            FaceB[4] = vertexes[6];

            tScale = new Vector3(-AXscale.X, -AXscale.Y, -AXscale.Z);
            rScale = tScale * AXrot;
            vertexes[7] = (new Vector3((pos.X + rScale.X), (pos.Y + rScale.Y), (pos.Z + rScale.Z)));

               // vertexes[7].X = pos.X + vertexes[7].X;
               // vertexes[7].Y = pos.Y + vertexes[7].Y;
               // vertexes[7].Z = pos.Z + vertexes[7].Z;

            FaceD[2] = vertexes[7];
            FaceC[3] = vertexes[7];
            FaceD[5] = vertexes[7];
            #endregion

            // Get our plane normals
            for (int i = 0; i < 6; i++)
            {
                //m_log.Info("[FACECALCULATION]: FaceA[" + i + "]=" + FaceA[i] + " FaceB[" + i + "]=" + FaceB[i] + " FaceC[" + i + "]=" + FaceC[i] + " FaceD[" + i + "]=" + FaceD[i]);

                // Our Plane direction
                AmBa = FaceA[i] - FaceB[i];
                AmBb = FaceB[i] - FaceC[i];

                cross = Vector3.Cross(AmBb, AmBa);

                // normalize the cross product to get the normal.
                normals[i] = cross / cross.Length();

                //m_log.Info("[NORMALS]: normals[ " + i + "]" + normals[i].ToString());
                //distance[i] = (normals[i].X * AmBa.X + normals[i].Y * AmBa.Y + normals[i].Z * AmBa.Z) * -1;
            }

            EntityIntersection result = new EntityIntersection();

            result.distance = 1024;
            float c = 0;
            float a = 0;
            float d = 0;
            Vector3 q = new Vector3();

            #region OBB Version 2 Experiment
            //float fmin = 999999;
            //float fmax = -999999;
            //float s = 0;

            //for (int i=0;i<6;i++)
            //{
                //s = iray.Direction.Dot(normals[i]);
                //d = normals[i].Dot(FaceB[i]);

                //if (s == 0)
                //{
                    //if (iray.Origin.Dot(normals[i]) > d)
                    //{
                        //return result;
                    //}
                   // else
                    //{
                        //continue;
                    //}
                //}
                //a = (d - iray.Origin.Dot(normals[i])) / s;
                //if (iray.Direction.Dot(normals[i]) < 0)
                //{
                    //if (a > fmax)
                    //{
                        //if (a > fmin)
                        //{
                            //return result;
                        //}
                        //fmax = a;
                    //}

                //}
                //else
                //{
                    //if (a < fmin)
                    //{
                        //if (a < 0 || a < fmax)
                        //{
                            //return result;
                        //}
                        //fmin = a;
                    //}
                //}
            //}
            //if (fmax > 0)
            //    a= fmax;
            //else
               //     a=fmin;

            //q = iray.Origin + a * iray.Direction;
            #endregion

            // Loop over faces (6 of them)
            for (int i = 0; i < 6; i++)
            {
                AmBa = FaceA[i] - FaceB[i];
                AmBb = FaceB[i] - FaceC[i];
                d = Vector3.Dot(normals[i], FaceB[i]);

                //if (faceCenters)
                //{
                //    c = normals[i].Dot(normals[i]);
                //}
                //else
                //{
                c = Vector3.Dot(iray.Direction, normals[i]);
                //}
                if (c == 0)
                    continue;

                a = (d - Vector3.Dot(iray.Origin, normals[i])) / c;

                if (a < 0)
                    continue;

                // If the normal is pointing outside the object
                if (Vector3.Dot(iray.Direction, normals[i]) < 0 || !frontFacesOnly)
                {
                    //if (faceCenters)
                    //{   //(FaceA[i] + FaceB[i] + FaceC[1] + FaceD[i]) / 4f;
                    //    q =  iray.Origin + a * normals[i];
                    //}
                    //else
                    //{
                        q = iray.Origin + iray.Direction * a;
                    //}

                    float distance2 = (float)GetDistanceTo(q, AXpos);
                    // Is this the closest hit to the object's origin?
                    //if (faceCenters)
                    //{
                    //    distance2 = (float)GetDistanceTo(q, iray.Origin);
                    //}

                    if (distance2 < result.distance)
                    {
                        result.distance = distance2;
                        result.HitTF = true;
                        result.ipoint = q;
                        result.face = i;
                        //m_log.Info("[FACE]:" + i.ToString());
                        //m_log.Info("[POINT]: " + q.ToString());
                        //m_log.Info("[DIST]: " + distance2.ToString());
                        if (faceCenters)
                        {
                            result.normal = AAfacenormals[i] * AXrot;

                            Vector3 scaleComponent = AAfacenormals[i];
                            float ScaleOffset = 0.5f;
                            if (scaleComponent.X != 0) ScaleOffset = AXscale.X;
                            if (scaleComponent.Y != 0) ScaleOffset = AXscale.Y;
                            if (scaleComponent.Z != 0) ScaleOffset = AXscale.Z;
                            ScaleOffset = Math.Abs(ScaleOffset);
                            Vector3 offset = result.normal * ScaleOffset;
                            result.ipoint = AXpos + offset;

                            ///pos = (intersectionpoint + offset);
                        }
                        else
                        {
                            result.normal = normals[i];
                        }
                        result.AAfaceNormal = AAfacenormals[i];
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// Serialize this part to xml.
        /// </summary>
        /// <param name="xmlWriter"></param>
        public void ToXml(XmlTextWriter xmlWriter)
        {
            SceneObjectSerializer.SOPToXml2(xmlWriter, this, new Dictionary<string, object>());
        }

        public void TriggerScriptChangedEvent(Changed val)
        {
            if (ParentGroup != null && ParentGroup.Scene != null)
                ParentGroup.Scene.EventManager.TriggerOnScriptChangedEvent(LocalId, (uint)val);
        }

        public void TrimPermissions()
        {
            BaseMask &= (uint)(PermissionMask.All | PermissionMask.Export);
            OwnerMask &= (uint)(PermissionMask.All | PermissionMask.Export);
            GroupMask &= (uint)PermissionMask.All;
            EveryoneMask &= (uint)(PermissionMask.All | PermissionMask.Export);
            NextOwnerMask &= (uint)PermissionMask.All;
        }

        public void UpdateExtraParam(ushort type, bool inUse, byte[] data)
        {
            m_shape.ReadInUpdateExtraParam(type, inUse, data);

            if (ParentGroup != null)
            {
                ParentGroup.HasGroupChanged = true;
                ScheduleFullUpdate();
            }
        }

        public void UpdateGroupPosition(Vector3 newPos)
        {
            Vector3 oldPos = GroupPosition;

            if ((newPos.X != oldPos.X) ||
                (newPos.Y != oldPos.Y) ||
                (newPos.Z != oldPos.Z))
            {
                GroupPosition = newPos;
                ScheduleTerseUpdate();
            }
        }

        /// <summary>
        /// Update this part's offset position.
        /// </summary>
        /// <param name="pos"></param>
        public void UpdateOffSet(Vector3 newPos)
        {
            Vector3 oldPos = OffsetPosition;

            if ((newPos.X != oldPos.X) ||
                (newPos.Y != oldPos.Y) ||
                (newPos.Z != oldPos.Z))
            {
                if (ParentGroup.RootPart.GetStatusSandbox())
                {
                    if (Util.GetDistanceTo(ParentGroup.RootPart.StatusSandboxPos, newPos) > 10)
                    {
                        ParentGroup.RootPart.ScriptSetPhysicsStatus(false);
                        newPos = OffsetPosition;
                        ParentGroup.Scene.SimChat(Utils.StringToBytes("Hit Sandbox Limit"),
                              ChatTypeEnum.DebugChannel, 0x7FFFFFFF, ParentGroup.RootPart.AbsolutePosition, Name, UUID, false);
                    }
                }

                OffsetPosition = newPos;
                ScheduleTerseUpdate();
            }
        }

        /// <summary>
        /// Update permissions on the SOP. Should only be called from SOG.UpdatePermissions because the SOG
        /// will handle the client notifications once all of its parts are updated.
        /// </summary>
        /// <param name="AgentID"></param>
        /// <param name="field"></param>
        /// <param name="localID"></param>
        /// <param name="mask"></param>
        /// <param name="addRemTF"></param>
        public void UpdatePermissions(UUID AgentID, byte field, uint localID, uint mask, byte addRemTF)
        {
            bool set = addRemTF == 1;
            bool god = ParentGroup.Scene.Permissions.IsGod(AgentID);

            uint baseMask = BaseMask;
            if (god)
                baseMask = 0x7ffffff0;

            bool canChange = (AgentID == OwnerID) || god;
            if(!canChange)
                canChange = ParentGroup.Scene.Permissions.CanEditObjectPermissions(ParentGroup, AgentID);

            if (canChange)
            {
                switch (field)
                {
                    case 1:
                        if (god)
                        {
                            BaseMask = ApplyMask(BaseMask, set, mask);
                            Inventory.ApplyGodPermissions(BaseMask);
                        }

                        break;
                    case 2:
                        OwnerMask = ApplyMask(OwnerMask, set, mask) &
                                baseMask;
                        break;
                    case 4:
                        GroupMask = ApplyMask(GroupMask, set, mask) &
                                baseMask;
                        break;
                    case 8:
                        // Trying to set export permissions - extra checks
                        if (set && (mask & (uint)PermissionMask.Export) != 0)
                        {
                            if ((OwnerMask & (uint)PermissionMask.Export) == 0 || (BaseMask & (uint)PermissionMask.Export) == 0 || (NextOwnerMask & (uint)PermissionMask.All) != (uint)PermissionMask.All)
                                mask &= ~(uint)PermissionMask.Export;
                        }
                        EveryoneMask = ApplyMask(EveryoneMask, set, mask) &
                                baseMask;
                        break;
                    case 16:
                        // Force full perm if export
                        if ((EveryoneMask & (uint)PermissionMask.Export) != 0)
                        {
                            NextOwnerMask = (uint)PermissionMask.All;
                            break;
                        }
                        NextOwnerMask = ApplyMask(NextOwnerMask, set, mask) &
                                baseMask;
                        // Prevent the client from creating no copy, no transfer
                        // objects
                        if ((NextOwnerMask & (uint)PermissionMask.Copy) == 0)
                            NextOwnerMask |= (uint)PermissionMask.Transfer;

                        NextOwnerMask |= (uint)PermissionMask.Move;

                        break;
                }
                AggregateInnerPerms();
                SendFullUpdateToAllClients();
            }
        }

        public void ClonePermissions(SceneObjectPart source)
        {
            uint prevOwnerMask = OwnerMask;
            uint prevGroupMask = GroupMask;
            uint prevEveryoneMask = EveryoneMask;
            uint prevNextOwnerMask = NextOwnerMask;

            OwnerMask = source.OwnerMask & BaseMask;
            GroupMask = source.GroupMask & BaseMask;
            EveryoneMask = source.EveryoneMask & BaseMask;
            NextOwnerMask = source.NextOwnerMask & BaseMask;

            AggregateInnerPerms();

            if (OwnerMask != prevOwnerMask ||
                GroupMask != prevGroupMask ||
                EveryoneMask != prevEveryoneMask ||
                NextOwnerMask != prevNextOwnerMask)
                SendFullUpdateToAllClients();
        }

        public bool IsHingeJoint()
        {
            // For now, we use the NINJA naming scheme for identifying joints.
            // In the future, we can support other joint specification schemes such as a
            // custom checkbox in the viewer GUI.
            if (ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
            {
                string hingeString = "hingejoint";
                return (Name.Length >= hingeString.Length && Name.Substring(0, hingeString.Length) == hingeString);
            }
            else
            {
                return false;
            }
        }

        public bool IsBallJoint()
        {
            // For now, we use the NINJA naming scheme for identifying joints.
            // In the future, we can support other joint specification schemes such as a
            // custom checkbox in the viewer GUI.
            if (ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
            {
                string ballString = "balljoint";
                return (Name.Length >= ballString.Length && Name.Substring(0, ballString.Length) == ballString);
            }
            else
            {
                return false;
            }
        }

        public bool IsJoint()
        {
            // For now, we use the NINJA naming scheme for identifying joints.
            // In the future, we can support other joint specification schemes such as a
            // custom checkbox in the viewer GUI.
            if (ParentGroup.Scene != null && ParentGroup.Scene.PhysicsScene != null && ParentGroup.Scene.PhysicsScene.SupportsNINJAJoints)
            {
                return IsHingeJoint() || IsBallJoint();
            }
            else
            {
                return false;
            }
        }

        public void UpdateExtraPhysics(ExtraPhysicsData physdata)
        {
            if (physdata.PhysShapeType == PhysShapeType.invalid || ParentGroup == null)
                return;

            byte newtype = (byte)physdata.PhysShapeType;
            if (PhysicsShapeType != newtype)
                PhysicsShapeType = newtype;

            if(Density != physdata.Density)
                Density = physdata.Density;

            if(GravityModifier != physdata.GravitationModifier)
                GravityModifier = physdata.GravitationModifier;

            if(Friction != physdata.Friction)
                Friction = physdata.Friction;

            if(Restitution != physdata.Bounce)
                Restitution = physdata.Bounce;
        }
        /// <summary>
        /// Update the flags on this prim.  This covers properties such as phantom, physics and temporary.
        /// </summary>
        /// <param name="UsePhysics"></param>
        /// <param name="SetTemporary"></param>
        /// <param name="SetPhantom"></param>
        /// <param name="SetVD"></param>
        public void UpdatePrimFlags(bool UsePhysics, bool SetTemporary, bool SetPhantom, bool SetVD, bool building)
        {
            bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0);
            bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0);
            bool wasPhantom = ((Flags & PrimFlags.Phantom) != 0);
            bool wasVD = VolumeDetectActive;

            if ((UsePhysics == wasUsingPhysics) && (wasTemporary == SetTemporary) && (wasPhantom == SetPhantom) && (SetVD == wasVD))
                return;

            VolumeDetectActive = SetVD;

            // volume detector implies phantom we need to decouple this mess
            if (SetVD)
                SetPhantom = true;
            else if(wasVD)
                SetPhantom = false;

            if (UsePhysics)
                AddFlag(PrimFlags.Physics);
            else
                RemFlag(PrimFlags.Physics);

            if (SetPhantom)
                AddFlag(PrimFlags.Phantom);
            else
                RemFlag(PrimFlags.Phantom);

            if (SetTemporary)
                AddFlag(PrimFlags.TemporaryOnRez);
            else
                RemFlag(PrimFlags.TemporaryOnRez);

            if (ParentGroup.Scene == null)
                return;

            PhysicsActor pa = PhysActor;

            if (pa != null && building && pa.Building != building)
                pa.Building = building;

            if ((SetPhantom && !UsePhysics && !SetVD) ||  ParentGroup.IsAttachment || PhysicsShapeType == (byte)PhysShapeType.none
                || (Shape.PathCurve == (byte)Extrusion.Flexible))
            {
                if (pa != null)
                {
                    if(wasUsingPhysics)
                        ParentGroup.Scene.RemovePhysicalPrim(1);
                    RemoveFromPhysics();
                }

                Stop();
            }

            else
            {
                if (ParentGroup.Scene.CollidablePrims)
                {
                    if (pa == null)
                    {
                        AddToPhysics(UsePhysics, SetPhantom, building, false);
                        pa = PhysActor;

                        if (pa != null)
                        {
                            pa.SetMaterial(Material);
                            DoPhysicsPropertyUpdate(UsePhysics, true);
                        }
                    }
                    else // it already has a physical representation
                    {

                        DoPhysicsPropertyUpdate(UsePhysics, false); // Update physical status.

                        if(UsePhysics && !SetPhantom &&  m_localId == ParentGroup.RootPart.LocalId &&
                            m_vehicleParams != null && m_vehicleParams.CameraDecoupled)
                        AddFlag(PrimFlags.CameraDecoupled);
                        else
                            RemFlag(PrimFlags.CameraDecoupled);

                        if (pa.Building != building)
                            pa.Building = building;
                    }

                    UpdatePhysicsSubscribedEvents();
                }
            }

            // and last in case we have a new actor and not building

            if (ParentGroup != null)
            {
                ParentGroup.HasGroupChanged = true;
                ScheduleFullUpdate();
            }

//            m_log.DebugFormat("[SCENE OBJECT PART]: Updated PrimFlags on {0} {1} to {2}", Name, LocalId, Flags);
        }

        /// <summary>
        /// Adds this part to the physics scene.
        /// and sets the PhysActor property
        /// </summary>
        /// <param name="isPhysical">Add this prim as physical.</param>
        /// <param name="isPhantom">Add this prim as phantom.</param>
        /// <param name="building">tells physics to delay full construction of object</param>
        /// <param name="applyDynamics">applies velocities, force and torque</param>
        private void AddToPhysics(bool isPhysical, bool isPhantom, bool building, bool applyDynamics)
        {
            PhysicsActor pa;

            Vector3 velocity = Velocity;
            Vector3 rotationalVelocity = AngularVelocity;;

            try
            {
                pa = ParentGroup.Scene.PhysicsScene.AddPrimShape(
                                 string.Format("{0}/{1}", Name, UUID),
                                 Shape,
                                 AbsolutePosition,
                                 Scale,
                                 GetWorldRotation(),
                                 isPhysical,
                                 isPhantom,
                                 PhysicsShapeType,
                                 m_localId);
            }
            catch (Exception e)
            {
                m_log.ErrorFormat("[SCENE]: caught exception meshing object {0}. Object set to phantom. e={1}", m_uuid, e);
                pa = null;
            }

            if (pa != null)
            {
                pa.SOPName = this.Name; // save object into the PhysActor so ODE internals know the joint/body info
                pa.SetMaterial(Material);

                pa.Density = Density;
                pa.GravModifier = GravityModifier;
                pa.Friction = Friction;
                pa.Restitution = Restitution;
                pa.Buoyancy = Buoyancy;

                if(LocalId == ParentGroup.RootPart.LocalId)
                {
                    pa.LockAngularMotion(RotationAxisLocks);
                }

                if (VolumeDetectActive) // change if not the default only
                    pa.SetVolumeDetect(1);
 
                bool isroot = (m_localId == ParentGroup.RootPart.LocalId);

                if(isroot && m_physicsInertia != null)
                    pa.SetInertiaData(m_physicsInertia);

                if (isroot && m_vehicleParams != null )
                {
                    m_vehicleParams.SetVehicle(pa);
                    if(isPhysical && !isPhantom && m_vehicleParams.CameraDecoupled)
                        AddFlag(PrimFlags.CameraDecoupled);
                    else
                        RemFlag(PrimFlags.CameraDecoupled);
                }
                else
                    RemFlag(PrimFlags.CameraDecoupled);
                // we are going to tell rest of code about physics so better have this here
                PhysActor = pa;

                //                DoPhysicsPropertyUpdate(isPhysical, true);
                // lets expand it here just with what it really needs to do

                if (isPhysical)
                {
                    if (ParentGroup.RootPart.KeyframeMotion != null)
                        ParentGroup.RootPart.KeyframeMotion.Stop();
                    ParentGroup.RootPart.KeyframeMotion = null;
                    ParentGroup.Scene.AddPhysicalPrim(1);

                    pa.OnRequestTerseUpdate += PhysicsRequestingTerseUpdate;
                    pa.OnOutOfBounds += PhysicsOutOfBounds;

                    if (_parentID != 0 && _parentID != LocalId)
                    {
                        PhysicsActor parentPa = ParentGroup.RootPart.PhysActor;

                        if (parentPa != null)
                        {
                            pa.link(parentPa);
                        }
                    }
                }

                if (applyDynamics && LocalId == ParentGroup.RootPart.LocalId)
                    // do independent of isphysical so parameters get setted (at least some)
                {
                    Velocity = velocity;
                    AngularVelocity = rotationalVelocity;

                    // if not vehicle and root part apply force and torque
                    if ((m_vehicleParams == null || m_vehicleParams.Type == Vehicle.TYPE_NONE))
                    {
                        pa.Force = Force;
                        pa.Torque = Torque;
                    }
                }

//                if (Shape.SculptEntry)
//                    CheckSculptAndLoad();
//                else
                    ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);

                if (!building)
                    pa.Building = false;
            }

            PhysActor = pa;

            ParentGroup.Scene.EventManager.TriggerObjectAddedToPhysicalScene(this);
        }

        /// <summary>
        /// This removes the part from the physics scene.
        /// </summary>
        /// <remarks>
        /// This isn't the same as turning off physical, since even without being physical the prim has a physics
        /// representation for collision detection.
        /// </remarks>
        public void RemoveFromPhysics()
        {
            PhysicsActor pa = PhysActor;
            if (pa != null)
            {
                pa.OnCollisionUpdate -= PhysicsCollision;
                pa.OnRequestTerseUpdate -= PhysicsRequestingTerseUpdate;
                pa.OnOutOfBounds -= PhysicsOutOfBounds;

                ParentGroup.Scene.PhysicsScene.RemovePrim(pa);

                ParentGroup.Scene.EventManager.TriggerObjectRemovedFromPhysicalScene(this);
            }
            RemFlag(PrimFlags.CameraDecoupled);
            PhysActor = null;
        }

        /// <summary>
        /// This updates the part's rotation and sends out an update to clients if necessary.
        /// </summary>
        /// <param name="rot"></param>
        public void UpdateRotation(Quaternion rot)
        {
            if (rot != RotationOffset)
            {
                RotationOffset = rot;

                if (ParentGroup != null)
                {
                    ParentGroup.HasGroupChanged = true;
                    ScheduleTerseUpdate();
                }
            }
        }

        /// <summary>
        /// Update the shape of this part.
        /// </summary>
        /// <param name="shapeBlock"></param>
        public void UpdateShape(ObjectShapePacket.ObjectDataBlock shapeBlock)
        {
            m_shape.PathBegin = shapeBlock.PathBegin;
            m_shape.PathEnd = shapeBlock.PathEnd;
            m_shape.PathScaleX = shapeBlock.PathScaleX;
            m_shape.PathScaleY = shapeBlock.PathScaleY;
            m_shape.PathShearX = shapeBlock.PathShearX;
            m_shape.PathShearY = shapeBlock.PathShearY;
            m_shape.PathSkew = shapeBlock.PathSkew;
            m_shape.ProfileBegin = shapeBlock.ProfileBegin;
            m_shape.ProfileEnd = shapeBlock.ProfileEnd;
            m_shape.PathCurve = shapeBlock.PathCurve;
            m_shape.ProfileCurve = shapeBlock.ProfileCurve;
            m_shape.ProfileHollow = shapeBlock.ProfileHollow;
            m_shape.PathRadiusOffset = shapeBlock.PathRadiusOffset;
            m_shape.PathRevolutions = shapeBlock.PathRevolutions;
            m_shape.PathTaperX = shapeBlock.PathTaperX;
            m_shape.PathTaperY = shapeBlock.PathTaperY;
            m_shape.PathTwist = shapeBlock.PathTwist;
            m_shape.PathTwistBegin = shapeBlock.PathTwistBegin;

            PhysicsActor pa = PhysActor;

            if (pa != null)
            {
                pa.Shape = m_shape;
                ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(pa);
            }

            // This is what makes vehicle trailers work
            // A script in a child prim re-issues
            // llSetPrimitiveParams(PRIM_TYPE) every few seconds. That
            // prevents autoreturn. This is not well known. It also works
            // in SL.
            //
            if (ParentGroup.RootPart != this)
                ParentGroup.RootPart.Rezzed = DateTime.UtcNow;

            ParentGroup.HasGroupChanged = true;
            TriggerScriptChangedEvent(Changed.SHAPE);
            ScheduleFullUpdate();
        }

        public void UpdateSlice(float begin, float end)
        {
            if (end < begin)
            {
                float temp = begin;
                begin = end;
                end = temp;
            }
            end = Math.Min(1f, Math.Max(0f, end));
            begin = Math.Min(Math.Min(1f, Math.Max(0f, begin)), end - 0.02f);
            if (begin < 0.02f && end < 0.02f)
            {
                begin = 0f;
                end = 0.02f;
            }

            ushort uBegin = (ushort)(50000.0 * begin);
            ushort uEnd = (ushort)(50000.0 * (1f - end));
            bool updatePossiblyNeeded = false;
            PrimType primType = GetPrimType();
            if (primType == PrimType.SPHERE || primType == PrimType.TORUS || primType == PrimType.TUBE || primType == PrimType.RING)
            {
                if (m_shape.ProfileBegin != uBegin || m_shape.ProfileEnd != uEnd)
                {
                    m_shape.ProfileBegin = uBegin;
                    m_shape.ProfileEnd = uEnd;
                    updatePossiblyNeeded = true;
                }
            }
            else if (m_shape.PathBegin != uBegin || m_shape.PathEnd != uEnd)
            {
                m_shape.PathBegin = uBegin;
                m_shape.PathEnd = uEnd;
                updatePossiblyNeeded = true;
            }

            if (updatePossiblyNeeded && ParentGroup != null)
            {
                ParentGroup.HasGroupChanged = true;
            }
            if (updatePossiblyNeeded && PhysActor != null)
            {
                PhysActor.Shape = m_shape;
                ParentGroup.Scene.PhysicsScene.AddPhysicsActorTaint(PhysActor);
            }
            if (updatePossiblyNeeded)
            {
                ScheduleFullUpdate();
            }
        }

        /// <summary>
        /// Update the texture entry for this part.
        /// </summary>
        /// <param name="serializedTextureEntry"></param>
        public void UpdateTextureEntry(byte[] serializedTextureEntry)
        {
            UpdateTextureEntry(new Primitive.TextureEntry(serializedTextureEntry, 0, serializedTextureEntry.Length));
        }

        /// <summary>
        /// Update the texture entry for this part.
        /// </summary>
        /// <param name="newTex"></param>
        public void UpdateTextureEntry(Primitive.TextureEntry newTex)
        {
            Primitive.TextureEntry oldTex = Shape.Textures;

            Changed changeFlags = 0;

            Primitive.TextureEntryFace defaultNewFace = newTex.DefaultTexture;
            Primitive.TextureEntryFace defaultOldFace = oldTex.DefaultTexture;

            // On Incoming packets, sometimes newText.DefaultTexture is null.  The assumption is that all
            // other prim-sides are set, but apparently that's not always the case.  Lets assume packet/data corruption at this point.
            if (defaultNewFace == null)
            {
                defaultNewFace = new Primitive.TextureEntry(Util.BLANK_TEXTURE_UUID).CreateFace(0);
                newTex.DefaultTexture = defaultNewFace;
            }
            if (defaultOldFace == null)
            {
                defaultOldFace = new Primitive.TextureEntry(Util.BLANK_TEXTURE_UUID).CreateFace(0);
                oldTex.DefaultTexture = defaultOldFace;
            }

            // Materials capable viewers can send a ObjectImage packet
            // when nothing in TE has changed. MaterialID should be updated
            // by the RenderMaterials CAP handler, so updating it here may cause a
            // race condtion. Therefore, if no non-materials TE fields have changed,
            // we should ignore any changes and not update Shape.TextureEntry

            bool otherFieldsChanged = false;
            int nsides = GetNumberOfSides();
            for (int i = 0 ; i < nsides; i++)
            {
                Primitive.TextureEntryFace newFace = defaultNewFace;
                Primitive.TextureEntryFace oldFace = defaultOldFace;
                if (oldTex.FaceTextures[i] != null)
                    oldFace = oldTex.FaceTextures[i];
                if (newTex.FaceTextures[i] != null)
                    newFace = newTex.FaceTextures[i];

                if (oldFace.TextureID != newFace.TextureID)
                    changeFlags |= Changed.TEXTURE;

                Color4 oldRGBA = oldFace.RGBA;
                Color4 newRGBA = newFace.RGBA;

                if (oldRGBA.R != newRGBA.R ||
                    oldRGBA.G != newRGBA.G ||
                    oldRGBA.B != newRGBA.B ||
                    oldRGBA.A != newRGBA.A)
                    changeFlags |= Changed.COLOR;

                // Max change, skip the rest of testing
                if (changeFlags == (Changed.TEXTURE | Changed.COLOR))
                    break;

                if (!otherFieldsChanged)
                {
                    if (oldFace.Bump != newFace.Bump) otherFieldsChanged = true;
                    if (oldFace.Fullbright != newFace.Fullbright) otherFieldsChanged = true;
                    if (oldFace.Glow != newFace.Glow) otherFieldsChanged = true;
                    if (oldFace.MediaFlags != newFace.MediaFlags) otherFieldsChanged = true;
                    if (oldFace.OffsetU != newFace.OffsetU) otherFieldsChanged = true;
                    if (oldFace.OffsetV != newFace.OffsetV) otherFieldsChanged = true;
                    if (oldFace.RepeatU != newFace.RepeatU) otherFieldsChanged = true;
                    if (oldFace.RepeatV != newFace.RepeatV) otherFieldsChanged = true;
                    if (oldFace.Rotation != newFace.Rotation) otherFieldsChanged = true;
                    if (oldFace.Shiny != newFace.Shiny) otherFieldsChanged = true;
                    if (oldFace.TexMapType != newFace.TexMapType) otherFieldsChanged = true;
                    if(otherFieldsChanged)
                        changeFlags |= Changed.TEXTURE;
                }
            }

            if (changeFlags == 0)
				return;
            m_shape.TextureEntry = newTex.GetBytes();
            TriggerScriptChangedEvent(changeFlags);
            ParentGroup.HasGroupChanged = true;
            ScheduleFullUpdate();
        }

        internal void UpdatePhysicsSubscribedEvents()
        {
            PhysicsActor pa = PhysActor;
            if (pa == null)
                return;

            pa.OnCollisionUpdate -= PhysicsCollision;

            bool hassound = (!VolumeDetectActive && CollisionSoundType >= 0 && ((Flags & PrimFlags.Physics) != 0));

            scriptEvents CombinedEvents = AggregateScriptEvents;

            // merge with root part
            if (ParentGroup != null && ParentGroup.RootPart != null)
                CombinedEvents |= ParentGroup.RootPart.AggregateScriptEvents;

            // submit to this part case
            if (VolumeDetectActive)
                CombinedEvents &= PhyscicsVolumeDtcSubsEvents;
            else if ((Flags & PrimFlags.Phantom) != 0)
                CombinedEvents &= PhyscicsPhantonSubsEvents;
            else
                CombinedEvents &= PhysicsNeededSubsEvents;

            if (hassound || CombinedEvents != 0)
            {
                // subscribe to physics updates.
                pa.OnCollisionUpdate += PhysicsCollision;
                pa.SubscribeEvents(50); // 20 reports per second
            }
            else
            {
                pa.UnSubscribeEvents();
            }
        }


        public void aggregateScriptEvents()
        {
            if (ParentGroup == null || ParentGroup.RootPart == null)
                return;

            AggregateScriptEvents = 0;

            // Aggregate script events
            lock (m_scriptEvents)
            {
                foreach (scriptEvents s in m_scriptEvents.Values)
                {
                    AggregateScriptEvents |= s;
                }
            }

            uint objectflagupdate = 0;

            if (
                ((AggregateScriptEvents & scriptEvents.touch) != 0) ||
                ((AggregateScriptEvents & scriptEvents.touch_end) != 0) ||
                ((AggregateScriptEvents & scriptEvents.touch_start) != 0)
                )
            {
                objectflagupdate |= (uint) PrimFlags.Touch;
            }

            if ((AggregateScriptEvents & scriptEvents.money) != 0)
            {
                objectflagupdate |= (uint) PrimFlags.Money;
            }

            if (AllowedDrop)
            {
                objectflagupdate |= (uint) PrimFlags.AllowInventoryDrop;
            }

            LocalFlags = (PrimFlags)objectflagupdate;

            if (ParentGroup != null && ParentGroup.RootPart == this)
            {
                ParentGroup.aggregateScriptEvents();
            }
            else
            {
//                m_log.DebugFormat(
//                    "[SCENE OBJECT PART]: Scheduling part {0} {1} for full update in aggregateScriptEvents()", Name, LocalId);
                UpdatePhysicsSubscribedEvents();
                ScheduleFullUpdate();
            }
        }

        public void SetCameraAtOffset(Vector3 v)
        {
            m_cameraAtOffset = v;
        }

        public void SetCameraEyeOffset(Vector3 v)
        {
            m_cameraEyeOffset = v;
        }

        public void SetForceMouselook(bool force)
        {
            m_forceMouselook = force;
        }

        public Vector3 GetCameraAtOffset()
        {
            return m_cameraAtOffset;
        }

        public Vector3 GetCameraEyeOffset()
        {
            return m_cameraEyeOffset;
        }

        public bool GetForceMouselook()
        {
            return m_forceMouselook;
        }

        public override string ToString()
        {
            return String.Format("{0} {1} (parent {2}))", Name, UUID, ParentGroup);
        }

        #endregion Public Methods

        public void SendTerseUpdateToClient(IClientAPI remoteClient)
        {
            if (ParentGroup.IsDeleted)
                return;

            if (ParentGroup.IsAttachment
                && (ParentGroup.RootPart != this
                    || ParentGroup.AttachedAvatar != remoteClient.AgentId && ParentGroup.HasPrivateAttachmentPoint))
                return;

            // Causes this thread to dig into the Client Thread Data.
            // Remember your locking here!
            remoteClient.SendEntityUpdate(
                this,
                PrimUpdateFlags.Position | PrimUpdateFlags.Rotation | PrimUpdateFlags.Velocity
                    | PrimUpdateFlags.Acceleration | PrimUpdateFlags.AngularVelocity);

            ParentGroup.Scene.StatsReporter.AddObjectUpdates(1);
        }

        public void AddScriptLPS(int count)
        {
            ParentGroup.AddScriptLPS(count);
        }

        /// <summary>
        /// Sets a prim's owner and permissions when it's rezzed.
        /// </summary>
        /// <param name="item">The inventory item from which the item was rezzed</param>
        /// <param name="userInventory">True: the item is being rezzed from the user's inventory. False: from a prim's inventory.</param>
        /// <param name="scene">The scene the prim is being rezzed into</param>
        public void ApplyPermissionsOnRez(InventoryItemBase item, bool userInventory, Scene scene)
        {
            if ((OwnerID != item.Owner) || ((item.CurrentPermissions & (uint)PermissionMask.Slam) != 0) || ((item.Flags & (uint)InventoryItemFlags.ObjectSlamPerm) != 0))
            {
                if (scene.Permissions.PropagatePermissions())
                {
                    if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0)
                    {
                        // Apply the item's permissions to the object
                        //LogPermissions("Before applying item permissions");
                        if (userInventory)
                        {
                            EveryoneMask = item.EveryOnePermissions;
                            NextOwnerMask = item.NextPermissions;
                        }
                        else
                        {
                            if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteEveryone) != 0)
                                EveryoneMask = item.EveryOnePermissions;
                            if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteNextOwner) != 0)
                                NextOwnerMask = item.NextPermissions;
                            if ((item.Flags & (uint)InventoryItemFlags.ObjectOverwriteGroup) != 0)
                                GroupMask = item.GroupPermissions;
                        }
                        //LogPermissions("After applying item permissions");
                    }
                }

                GroupMask = 0; // DO NOT propagate here
            }

            if (OwnerID != item.Owner)
            {
                if(OwnerID != GroupID)
                    LastOwnerID = OwnerID;
                OwnerID = item.Owner;
                Inventory.ChangeInventoryOwner(item.Owner);

                if (scene.Permissions.PropagatePermissions())
                    ApplyNextOwnerPermissions();
            }
        }

        /// <summary>
        /// Logs the prim's permissions. Useful when debugging permission problems.
        /// </summary>
        /// <param name="message"></param>
        private void LogPermissions(String message)
        {
            PermissionsUtil.LogPermissions(Name, message, BaseMask, OwnerMask, NextOwnerMask);
        }

        public void ApplyNextOwnerPermissions()
        {
            // Export needs to be preserved in the base and everyone
            // mask, but removed in the owner mask as a next owner
            // can never change the export status
            BaseMask &= (NextOwnerMask | (uint)PermissionMask.Export);
            OwnerMask &= NextOwnerMask;
            EveryoneMask &= (NextOwnerMask | (uint)PermissionMask.Export);
            GroupMask = 0; // Giving an object zaps group permissions

            Inventory.ApplyNextOwnerPermissions();
            AggregateInnerPerms();
        }

        public void UpdateLookAt()
        {
            try
            {
                if (APIDActive)
                {
                    PhysicsActor pa = ParentGroup.RootPart.PhysActor;
                    if (pa == null || !pa.IsPhysical || APIDStrength < 0.04)
                    {
                        StopLookAt();
                        return;
                    }

                    Quaternion currRot = GetWorldRotation();
                    currRot.Normalize();

                    // difference between current orientation and desired orientation
                    Quaternion dR = currRot / APIDTarget;

                    // find axis and angle of rotation to rotate to desired orientation
                    Vector3 axis = Vector3.UnitX;
                    float angle;
                    dR.GetAxisAngle(out axis, out angle);
                    axis = axis * currRot;

                    // clamp strength to avoid overshoot
                    float strength = 1.0f / APIDStrength;
                    if (strength > 1.0) strength = 1.0f;

                    // set angular velocity to rotate to desired orientation
                    // with velocity proportional to strength and angle
                    AngularVelocity = axis * angle * strength * (float)Math.PI;

                    // This ensures that we'll check this object on the next iteration
                    ParentGroup.QueueForUpdateCheck();
                }
            }
            catch (Exception ex)
            {
                m_log.Error("[Physics] " + ex);
            }
        }

        public Color4 GetTextColor()
        {
            Color color = Color;
            return new Color4(color.R, color.G, color.B, (byte)(0xFF - color.A));
        }

        public void ResetOwnerChangeFlag()
        {
            List<UUID> inv = Inventory.GetInventoryList();

            foreach (UUID itemID in inv)
            {
                TaskInventoryItem item = Inventory.GetInventoryItem(itemID);
                item.OwnerChanged = false;
                Inventory.UpdateInventoryItem(item, false, false);
            }
            AggregateInnerPerms();
        }

        /// <summary>
        /// Record an avatar sitting on this part.
        /// </summary>
        /// <remarks>This is called for all the sitting avatars whether there is a sit target set or not.</remarks>
        /// <returns>
        /// true if the avatar was not already recorded, false otherwise.
        /// </returns>
        /// <param name='avatarId'></param>
        protected internal bool AddSittingAvatar(ScenePresence sp)
        {
            lock (ParentGroup.m_sittingAvatars)
            {
                if (IsSitTargetSet && SitTargetAvatar == UUID.Zero)
                    SitTargetAvatar = sp.UUID;

                if (m_sittingAvatars == null)
                    m_sittingAvatars = new HashSet<ScenePresence>();

                if (m_sittingAvatars.Add(sp))
                {
                    if(!ParentGroup.m_sittingAvatars.Contains(sp))
                        ParentGroup.m_sittingAvatars.Add(sp);

                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Remove an avatar recorded as sitting on this part.
        /// </summary>
        /// <remarks>This applies to all sitting avatars whether there is a sit target set or not.</remarks>
        /// <returns>
        /// true if the avatar was present and removed, false if it was not present.
        /// </returns>
        /// <param name='avatarId'></param>
        protected internal bool RemoveSittingAvatar(ScenePresence sp)
        {
            lock (ParentGroup.m_sittingAvatars)
            {
                if (SitTargetAvatar == sp.UUID)
                    SitTargetAvatar = UUID.Zero;

                if (m_sittingAvatars == null)
                    return false;

                if (m_sittingAvatars.Remove(sp))
                {
                    if (m_sittingAvatars.Count == 0)
                        m_sittingAvatars = null;

                    ParentGroup.m_sittingAvatars.Remove(sp);

                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Get a copy of the list of sitting avatars.
        /// </summary>
        /// <remarks>This applies to all sitting avatars whether there is a sit target set or not.</remarks>
        /// <returns>A hashset of the sitting avatars.  Returns null if there are no sitting avatars.</returns>
        public HashSet<ScenePresence> GetSittingAvatars()
        {
            lock (ParentGroup.m_sittingAvatars)
            {
                if (m_sittingAvatars == null)
                    return null;
                else
                    return new HashSet<ScenePresence>(m_sittingAvatars);
            }
        }

        /// <summary>
        /// Gets the number of sitting avatars.
        /// </summary>
        /// <remarks>This applies to all sitting avatars whether there is a sit target set or not.</remarks>
        /// <returns></returns>
        public int GetSittingAvatarsCount()
        {
            lock (ParentGroup.m_sittingAvatars)
            {
                if (m_sittingAvatars == null)
                    return 0;
                else
                    return m_sittingAvatars.Count;
            }
        }

        public void Stop()
        {
            Velocity = Vector3.Zero;
            AngularVelocity = Vector3.Zero;
            Acceleration = Vector3.Zero;
            APIDActive = false;
        }

        // handle osVolumeDetect
        public void ScriptSetVolumeDetect(bool makeVolumeDetect)
        {
            if(_parentID == 0)
            {
                // if root prim do it via SOG
                ParentGroup.ScriptSetVolumeDetect(makeVolumeDetect);
                return;
            }

            bool wasUsingPhysics = ((Flags & PrimFlags.Physics) != 0);
            bool wasTemporary = ((Flags & PrimFlags.TemporaryOnRez) != 0);
            bool wasPhantom = ((Flags & PrimFlags.Phantom) != 0);

            if(PhysActor != null)
                PhysActor.Building = true;
            UpdatePrimFlags(wasUsingPhysics,wasTemporary,wasPhantom,makeVolumeDetect,false);
        }
    }
}